Skip to content
Python

Merge main: OpenShell guided setup (openworker#699) into the Sandbox page

Rohit C Prasadff54ceaf739c
diff --cc coworker/sandbox/registry.py
index 28071387,b301b271..559d35ff
--- a/coworker/sandbox/registry.py
+++ b/coworker/sandbox/registry.py
@@@ -12,8 -12,8 +12,9 @@@ gone (a crash, a kill) so they do not p
from __future__ import annotations
import json
+ import logging
import os
+import sys
import sqlite3
import threading
import time
diff --cc coworker/sandbox/settings.py
index db1cf2b5,e568c14b..a9a9f59b
--- a/coworker/sandbox/settings.py
+++ b/coworker/sandbox/settings.py
@@@ -9,49 -9,38 +9,55 @@@ import sy
from typing import Any, Optional
from .. import config as app_config
-from . import credentials, network_profiles
-from .workspace import DIRECT, OPENSHELL, SEATBELT
+from . import credentials, network_profiles, toolchains
+from .workspace import DIRECT, OPENSHELL, SEATBELT, WINDOWS
- 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:
+ if sys.platform == "win32": # its Windows driver is a preview; the setup command here sets up the Windows sandbox
- return False, "OpenShell is not available on Windows yet."
++ return False, "OpenShell is not available on Windows yet.", "unavailable"
+ from .providers.openshell import is_image_problem
from .selection import openshell_problem
problem = openshell_problem()
- return (problem is None), (problem or "")
+ if problem is None:
+ return True, "", "ready"
+ return False, problem, ("needs_download" if is_image_problem(problem) else "unavailable")
+ if name == WINDOWS:
+ if sys.platform != "win32":
- return False, "Windows only"
++ return False, "Windows only", "unavailable"
+ from .providers import windows
+
+ try:
+ windows.preflight()
- return True, ""
++ return True, "", "ready"
+ except windows.WindowsUnavailable as exc:
- return False, str(exc)
- return False, "unknown"
++ return False, str(exc), "unavailable"
+ return False, "unknown", "unavailable"
+def native_sandbox() -> str:
+ """The operating system's own sandbox provider: the middle option on the page."""
+ return WINDOWS if sys.platform == "win32" else SEATBELT
+
+
def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:
cfg = cfg or app_config.load_config()
from .selection import select
@@@ -62,9 -51,9 +68,9 @@@
except Exception as exc: # an explicit choice that cannot be used: sessions are refused
effective, refused = "", str(exc)
providers = []
- for name in (DIRECT, SEATBELT, OPENSHELL):
+ for name in (DIRECT, native_sandbox(), 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
@@@ -82,19 -69,21 +88,31 @@@
}
+def _windows_setup_info() -> Optional[dict[str, Any]]:
+ """The Windows setup's state for the page (UX-053): None off Windows."""
+ if sys.platform != "win32":
+ return None
+ from .providers import windows_setup
+
+ return windows_setup.info()
+
+
+ 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 changed
- them, so the app can show them in the user's language; a user's own text is kept."""
+ them, so the app can show them in the user's language; a user's own text is kept.
+ `kind` says what the path is on this machine: file, folder, or "" when it is missing."""
shipped = {e["name"]: e for e in credentials.DEFAULT_ENTRIES}
out = []
for row in rows:
diff --cc coworker/sandbox/setup_cmd.py
index 0e21776a,6ca244c1..7b83c684
--- a/coworker/sandbox/setup_cmd.py
+++ b/coworker/sandbox/setup_cmd.py
@@@ -163,20 -391,45 +462,47 @@@ def status(print_fn: Callable[[str], No
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, tool = openshell.sandbox_image(), openshell.image_tool() or "docker"
+ 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 {tool} pull {image}")
+ if not confirm("Download it now? (10 to 20 minutes on a slow connection)"):
+ return 1
+ if subprocess.run([tool, "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 sys.platform == "win32":
+ return windows_setup_command(confirm=confirm, print_fn=print_fn)
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"]:
+ 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"]:
- 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 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 = 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:
diff --cc coworker/sandbox/workspace.py
index 64cb8377,81f3a5e6..713eba50
--- a/coworker/sandbox/workspace.py
+++ b/coworker/sandbox/workspace.py
@@@ -131,30 -138,16 +138,32 @@@ class RunnerWorkspace(Workspace)
wanted = [{"path": str(r.path), "writable": bool(r.writable)} for r in self._live_roots]
if not wanted or _same_roots(wanted, getattr(self.provider, "roots", [])):
return None
- self.client.detach()
- # Reserve the replacement's name before it exists, for the same reason as at start:
- # a concurrent build's reap() must not take it for an orphan.
- regrant(wanted, before_create=lambda: self._record(state="creating"))
- self.client.connect() # a new runner: the client notes the restart
+ restarts = getattr(self.provider, "restarts_on_regrant", True)
+ if restarts:
+ self.client.detach()
- regrant(wanted)
- if restarts:
++ # Reserve the replacement's name before it exists, for the same reason as at
++ # start: a concurrent build's reap() must not take it for an orphan.
++ regrant(wanted, before_create=lambda: self._record(state="creating"))
+ self.client.connect() # a new runner: the client notes the restart
+ self._after_connect()
+ else:
++ regrant(wanted) # the same sandbox, re-granted in place (Windows: entries on folders)
+ verify = getattr(self.provider, "verify", None)
+ if verify is not None:
+ verify(self.client)
+ self._record()
+ return RESTART_NOTICE if restarts else REGRANT_NOTICE
+
+ def _after_connect(self) -> None:
+ """What a provider does once it can talk to its runner: prove the wall is up, then
+ put in what it could not put in before the runner existed (copies that must be
+ owned by the sandbox's own account)."""
verify = getattr(self.provider, "verify", None)
if verify is not None:
- verify(self.client)
- self._record()
- return RESTART_NOTICE
+ verify(self.client) # e.g. every folder is really reachable inside
+ provision = getattr(self.provider, "provision", None)
+ if provision is not None:
+ provision(self.client)
@property
def executor(self) -> Executor:
diff --cc coworker/server/app.py
index 7677e7d6,a5a365e0..f83d73e1
--- a/coworker/server/app.py
+++ b/coworker/server/app.py
@@@ -2400,22 -2403,40 +2403,55 @@@ def create_app(manager: SessionManager
def settings_set_sandbox(body: dict) -> dict[str, Any]:
from ..sandbox import settings as sandbox_settings
- return sandbox_settings.update(body or {})
+ result = sandbox_settings.update(body or {})
+ if result.get("ok") and "provider" in (body or {}):
+ # Live sessions built under the old rule are rebuilt on their next connection;
+ # the app reconnects the one on screen (see App.tsx, onSandboxProviderChanged).
+ result["rebuilt_sessions"] = manager.apply_sandbox_setting()
+ return result
+
+ @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() -> dict[str, Any]:
+ 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/sandbox/windows/setup")
++ def settings_sandbox_windows_setup() -> dict[str, Any]:
+ # UX-053: the Windows setup dialog. Runs the elevated setup (Windows shows its own
- # prompt), proves the wall in a throwaway sandbox, then makes it the choice.
++ # prompt), proves the wall in a throwaway sandbox, then makes it the choice. Blocks
++ # until Windows answers, unlike the OpenShell setup job above.
+ from ..sandbox import settings as sandbox_settings
+
+ return sandbox_settings.run_windows_setup()
+
- @app.post("/v1/settings/sandbox/remove")
- def settings_sandbox_remove() -> dict[str, Any]:
++ @app.post("/v1/settings/sandbox/windows/remove")
++ def settings_sandbox_windows_remove() -> dict[str, Any]:
+ from ..sandbox import settings as sandbox_settings
+
+ return sandbox_settings.run_windows_remove()
+
@app.post("/v1/settings/compaction")
def settings_set_compaction(body: dict) -> dict[str, Any]:
# Auto-compaction overrides (OPE-27): threshold % of the context window, the
diff --cc surfaces/gui/src/api.ts
index 600bda47,5f6094fe..8115f4d9
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@@ -2121,8 -2102,9 +2121,10 @@@ 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" }[];
+ windows_setup: WindowsSetupInfo | null;
network_profile: string;
network_profiles: { name: string; hosts: string[] }[];
credentials: SandboxCredentialEntry[];
@@@ -2136,9 -2117,11 +2138,11 @@@ export async function getSandboxSetting
}
export async function setSandboxSettings(
- patch: Partial<Pick<SandboxSettings, "provider" | "network_profile" | "credentials">>,
+ patch: Partial<Pick<SandboxSettings, "provider" | "network_profile" | "credentials" | "toolchains">>,
machineId?: string | null,
- ): Promise<{ ok: boolean; error?: string } & Partial<SandboxSettings>> {
+ ): Promise<{ ok: boolean; error?: string; rebuilt_sessions?: string[] } & Partial<SandboxSettings>> {
+ // `rebuilt_sessions`: after a provider change, the sessions whose engine the server
+ // dropped so their next connection rebuilds them under the new rule.
const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox`, {
method: "POST",
headers: { "Content-Type": "application/json" },
@@@ -2147,21 -2130,53 +2151,69 @@@
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; // 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;
+ 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();
+ }
+
+// UX-053: "Set up now" in the Windows setup dialog. The server runs the elevated setup
+// (Windows shows its own prompt), proves the wall in a throwaway sandbox, and makes the
- // Windows sandbox the machine's choice. Blocks until Windows answers.
++// Windows sandbox the machine's choice. Blocks until Windows answers, unlike the OpenShell
++// setup job above, which is polled.
+export async function runSandboxSetup(
+ machineId?: string | null,
+): Promise<{ ok: boolean; error?: string; said?: string; checked?: string } & Partial<SandboxSettings>> {
- const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/setup`, { method: "POST" });
++ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/windows/setup`, { method: "POST" });
+ return res.json();
+}
+
+export async function runSandboxRemove(machineId?: string | null): Promise<{ ok: boolean; error?: string; said?: string } & Partial<SandboxSettings>> {
- const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/remove`, { method: "POST" });
++ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/windows/remove`, { 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 --cc surfaces/gui/src/components/SandboxSection.tsx
index 6fa0fc09,00000000..7b2b6315
mode 100644,000000..100644
--- a/surfaces/gui/src/components/SandboxSection.tsx
+++ b/surfaces/gui/src/components/SandboxSection.tsx
@@@ -1,737 -1,0 +1,964 @@@
- // Settings ▸ Sandbox (UX-051 A, UX-053 v3): one switch first; on reveals the sandbox type;
- // a ready type reveals only its own options (network, the files an agent may be given,
- // the tool folders the sandbox may read). Choosing the Windows sandbox opens its setup
- // dialog, which runs the one-time elevated setup and proves the wall before the choice
- // takes effect. Everything here is machine-level (the machine's config.toml through
- // /v1/settings/sandbox); nothing is per project.
- import { useEffect, useState } from "react";
++// Settings ▸ Sandbox (UX-051 A, UX-053 v3, OPE-207): one switch first; on reveals the
++// sandbox type; a ready type reveals only its own options (network, the files an agent may
++// be given, the tool folders the sandbox may read). Choosing the Windows sandbox opens its
++// setup dialog, which runs the one-time elevated setup and proves the wall before the
++// choice takes effect. OpenShell shows its readiness checklist with the guided "Set up
++// sandbox" job (fixes what the app may fix, never as root; hands the rest over as
++// commands; downloads the image with progress). Everything here is machine-level (the
++// machine's config.toml through /v1/settings/sandbox); nothing is per project. A provider
++// change rebuilds live sessions under the new rule (onProviderChanged carries their ids).
++import { useEffect, useRef, useState } from "react";
+import { useTranslation } from "react-i18next";
+import {
++ cancelSandboxSetup,
++ getSandboxReadiness,
+ getSandboxSettings,
++ getSandboxSetup,
+ runSandboxRemove,
+ runSandboxSetup,
+ setSandboxSettings,
++ startSandboxSetup,
+ type Machine,
+ type SandboxCredentialEntry,
++ type SandboxReadiness,
++ type SandboxReadinessStep,
+ type SandboxSettings,
++ type SandboxSetupRowState,
++ type SandboxSetupState,
+ type SandboxToolchainEntry,
+} from "../api";
+import { chooseFolder } from "../tauri";
+import { Toggle } from "./Toggle";
+import { PanelHead } from "./IntegrationsView";
+
+const CARD = "rounded-xl2 border border-line bg-panel";
+const FIELD_LABEL = "text-ui font-medium text-ink";
+const FIELD_HELP = "text-meta text-muted mt-1.5 leading-relaxed";
+const INPUT =
+ "flex-1 min-w-0 px-3 py-2 rounded-lg border border-line bg-paper text-ui text-ink outline-none focus:border-accent";
+const BTN_ACCENT = "text-ui px-3 py-2 rounded-lg bg-accent text-white shrink-0 disabled:opacity-40";
+const BTN_BORDERED = "text-ui px-3 py-2 rounded-lg border border-line bg-paper hover:border-lineStrong shrink-0";
+const TAG = "inline-flex items-center rounded px-1.5 text-label font-medium leading-5";
+
+type SetupStage = "ask" | "working" | "done" | "failed";
+
+function Chevron({ open }: { open: boolean }) {
+ return (
+ <svg
+ viewBox="0 0 20 20"
+ fill="none"
+ stroke="currentColor"
+ strokeWidth="1.6"
+ className={"w-5 h-5 text-faint transition-transform shrink-0 " + (open ? "rotate-90" : "")}
+ aria-hidden="true"
+ >
+ <path d="M8 5l5 5-5 5" />
+ </svg>
+ );
+}
+
+// A card that is one line until opened: chevron, title, one sentence, and a summary on
+// the right. The body is the card's own list plus a foot with its action.
+function DisclosureCard({
+ id,
+ open,
+ onToggle,
+ title,
+ desc,
+ summary,
+ children,
+}: {
+ id: string;
+ open: boolean;
+ onToggle: () => void;
+ title: string;
+ desc: string;
+ summary: React.ReactNode;
+ children: React.ReactNode;
+}) {
+ return (
+ <div className={CARD + " mb-2.5"} data-testid={`sandbox-card-${id}`}>
+ <button
+ type="button"
+ className={"w-full text-left flex items-center gap-3 px-4 py-3 hover:bg-chrome rounded-xl2 " + (open ? "border-b border-line rounded-b-none" : "")}
+ onClick={onToggle}
+ aria-expanded={open}
+ data-testid={`sandbox-card-${id}-toggle`}
+ >
+ <Chevron open={open} />
+ <span className="flex-1 min-w-0">
+ <span className="block text-ui font-medium text-ink">{title}</span>
+ <span className="block text-meta text-muted">{desc}</span>
+ </span>
+ <span className="text-meta text-faint text-right shrink-0 max-w-[360px] flex flex-wrap justify-end gap-1.5">{summary}</span>
+ </button>
+ {open ? <div data-testid={`sandbox-card-${id}-body`}>{children}</div> : null}
+ </div>
+ );
+}
+
+function Chip({ on, children }: { on: boolean; children: React.ReactNode }) {
+ return (
+ <span className={"inline-flex items-center gap-1.5 rounded-full border px-2 py-px text-meta whitespace-nowrap " + (on ? "border-lineStrong text-muted" : "border-dashed border-lineStrong text-faint")}>
+ {on ? <span className="w-1.5 h-1.5 rounded-full bg-ok" /> : null}
+ {children}
+ </span>
+ );
+}
+
+function Modal({ children, testid }: { children: React.ReactNode; testid: string }) {
+ return (
+ <div className="fixed inset-0 z-50" role="dialog" aria-modal="true" data-testid={testid}>
+ <div className="absolute inset-0 bg-black/30 backdrop-blur-[1px]" />
+ <div className="absolute left-1/2 top-[12vh] -translate-x-1/2 w-[640px] max-w-[94vw] max-h-[80vh] rounded-xl2 border border-line bg-panel shadow-2xl overflow-auto p-6">
+ {children}
+ </div>
+ </div>
+ );
+}
+
+const SETUP_CHANGES = ["accounts", "rules", "folder", "record"] as const;
+
- export function SandboxSection({ machine }: { machine?: Machine | null }) {
++export function SandboxSection({ machine, onProviderChanged }: { machine?: Machine | null; onProviderChanged?: (sessionIds: string[]) => void }) {
+ const { t } = useTranslation();
+ const mid = machine?.id ?? null;
+ const [cfg, setCfg] = useState<SandboxSettings | null>(null);
+ const [error, setError] = useState<string>("");
++ const [readiness, setReadiness] = useState<SandboxReadiness | null>(null);
++ const [job, setJob] = useState<SandboxSetupState | null>(null);
++ const [copied, setCopied] = useState<string>("");
++ const notifiedRef = useRef(false);
+ const [wantOn, setWantOn] = useState(false); // the switch is on, no type is ready yet
+ const [openCard, setOpenCard] = useState<"files" | "tools" | null>(null);
+ const [editing, setEditing] = useState<string | null>(null); // credential name being edited, "" = new
+ const [addingTool, setAddingTool] = useState(false); // the "Add a folder" editor of the toolchain list
+ const [toolTitle, setToolTitle] = useState("");
+ const [toolPath, setToolPath] = useState("~/");
+ const [setupStage, setSetupStage] = useState<SetupStage | null>(null);
+ const [setupOutcome, setSetupOutcome] = useState<{ checked?: string; error?: string }>({});
+ const [removing, setRemoving] = useState(false);
+ const [removeBusy, setRemoveBusy] = useState(false);
+
+ useEffect(() => {
+ getSandboxSettings(mid).then(setCfg).catch(() => setCfg(null));
+ }, [mid]);
+
+ const save = async (patch: Parameters<typeof setSandboxSettings>[0]) => {
+ const res = await setSandboxSettings(patch, mid);
+ if (!res.ok) {
+ setError(res.error || "could not save");
+ return;
+ }
+ setError("");
+ setCfg(res as SandboxSettings);
++ if ("provider" in patch) onProviderChanged?.(res.rebuilt_sessions ?? []);
++ };
++
++ // OpenShell's readiness checklist (Seatbelt and the Windows sandbox need none of this):
++ // loaded when OpenShell is the choice, and again after a setup run.
++ const openshellChosen = Boolean(cfg) && (cfg!.provider || cfg!.effective_provider || "direct") === "openshell";
++ const loadReadiness = () => {
++ if (!cfg || !openshellChosen) return;
++ setReadiness(null);
++ getSandboxReadiness(mid)
++ .then(setReadiness)
++ .catch(() => setReadiness({ platform: cfg.platform, supported: false, steps: [], all_ok: false }));
++ };
++ useEffect(loadReadiness, [mid, openshellChosen, 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 (!openshellChosen) return;
++ getSandboxSetup(mid)
++ .then((s) => setJob(s.status === "idle" ? null : s))
++ .catch(() => {});
++ }, [mid, openshellChosen]);
++ // 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 (!job || job.status !== "running") return;
++ const timer = window.setInterval(() => {
++ getSandboxSetup(mid)
++ .then((s) => {
++ setJob(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);
++ }, [job?.status, mid]); // eslint-disable-line react-hooks/exhaustive-deps
++ const startJob = 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) setJob(s);
++ };
++ const cancelJob = async () => {
++ const s = await cancelSandboxSetup(mid).catch(() => null);
++ if (s) setJob(s);
++ };
++ const copy = (text: string) => {
++ navigator.clipboard
++ ?.writeText(text)
++ .then(() => {
++ setCopied(text);
++ window.setTimeout(() => setCopied(""), 1500);
++ })
++ .catch(() => {});
+ };
+
+ if (!cfg) return null;
+ const isWindows = cfg.platform === "win32";
+ const isMac = cfg.platform === "darwin";
+ const providerNames: Record<string, [string, string]> = {
+ seatbelt: [t("settingsx.sandbox.provider_seatbelt"), t("settingsx.sandbox.provider_seatbelt_desc")],
+ windows: [t("settingsx.sandbox.provider_windows"), t("settingsx.sandbox.provider_windows_desc")],
+ openshell: [t("settingsx.sandbox.provider_openshell"), t("settingsx.sandbox.provider_openshell_desc")],
+ };
+ const chosen = cfg.provider || cfg.effective_provider || "direct";
- const active = chosen !== "direct"; // a type is the machine's choice
++ const active = chosen !== "direct"; // a type is the machine's choice (OpenShell counts even while its image downloads)
+ const on = active || wantOn;
+ const setup = cfg.windows_setup;
+ const setupReady = setup?.state === "ready";
+ const types = cfg.providers.filter((p) => p.name !== "direct" && (p.name !== "seatbelt" || isMac) && (p.name !== "windows" || isWindows));
+ const anyType = types.some((p) => p.usable || (p.name === "windows" && setup?.can_elevate));
+ const shipped = (name: string, key: "title" | "does", fallback?: string) => {
+ const k = `settingsx.sandbox.${key}_${name}`;
+ const v = t(k);
+ return v === k ? fallback || "" : v;
+ };
+ const updateCredentials = (rows: SandboxCredentialEntry[]) =>
+ save({ credentials: rows.map(({ kind: _k, shipped: _s, ...row }) => row) });
+ const updateToolchains = (rows: SandboxToolchainEntry[]) =>
+ save({ toolchains: rows.map(({ exists: _e, shipped: _s, ...row }) => row) });
+
+ const switchStatus = !on
+ ? t("settingsx.sandbox.switch_off")
+ : active
+ ? t("settingsx.sandbox.switch_on", { type: providerNames[chosen]?.[0] ?? chosen })
+ : anyType
+ ? t("settingsx.sandbox.switch_choose")
+ : t("settingsx.sandbox.switch_none");
+
+ const flip = (next: boolean) => {
+ if (next) {
+ setWantOn(true);
+ return;
+ }
+ setWantOn(false);
+ if (active) void save({ provider: "direct" });
+ };
+
+ const chooseType = (name: string) => {
+ if (name === "windows" && !setupReady) {
+ if (setup?.can_elevate) {
+ setSetupOutcome({});
+ setSetupStage("ask");
+ }
+ return;
+ }
+ void save({ provider: name });
+ };
+
+ const runSetup = async () => {
+ setSetupStage("working");
+ const res = await runSandboxSetup(mid);
+ if (res.ok) {
+ setCfg(res as SandboxSettings);
+ setWantOn(false);
+ setSetupOutcome({ checked: res.checked });
+ setSetupStage("done");
+ } else {
+ if (res.platform) setCfg(res as SandboxSettings);
+ setSetupOutcome({ error: res.error || "setup did not finish" });
+ setSetupStage("failed");
+ }
+ };
+
+ const runRemove = async () => {
+ setRemoveBusy(true);
+ const res = await runSandboxRemove(mid);
+ setRemoveBusy(false);
+ if (res.ok) {
+ setCfg(res as SandboxSettings);
+ setWantOn(false);
+ setRemoving(false);
+ } else {
+ setError(res.error || "could not remove the setup");
+ setRemoving(false);
+ }
+ };
+
+ const setUpOn = setup?.set_up_at ? new Date(setup.set_up_at) : null;
+ const setUpOnText = setUpOn && !Number.isNaN(setUpOn.getTime()) ? setUpOn.toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : "";
+
+ // The network list: Open first where it is the default (Windows).
+ const profiles = isWindows ? [...cfg.network_profiles].sort((a, b) => (a.name === "open" ? -1 : b.name === "open" ? 1 : 0)) : cfg.network_profiles;
+ const showTools = cfg.platform !== "linux" && chosen !== "openshell" && Boolean(cfg.toolchains);
+ const toolsOn = (cfg.toolchains || []).filter((x) => x.enabled);
+
+ return (
+ <section data-testid="sandbox-section">
+ <PanelHead
+ title={t("settingsx.sandbox.title")}
+ sub={machine ? t("settingsx.sandbox.sub_machine", { name: machine.name }) : isWindows ? t("settingsx.sandbox.sub_windows") : t("settingsx.sandbox.sub")}
+ />
+ {error ? <div className="mb-3 text-meta text-danger">{error}</div> : null}
+
+ {/* 1. The switch */}
+ <div className={CARD + " mb-1"}>
+ <div className="flex items-start gap-3.5 px-4 py-3.5">
+ <span className="mt-0.5">
+ <Toggle checked={on} onChange={flip} title={t("settingsx.sandbox.switch_title")} />
+ </span>
+ <span className="flex-1 min-w-0">
+ <span className="block text-ui font-medium text-ink">{t("settingsx.sandbox.switch_title")}</span>
+ <span className="block text-meta text-muted max-w-[640px]">{t("settingsx.sandbox.switch_desc")}</span>
+ </span>
+ <span
+ className={"text-meta shrink-0 whitespace-nowrap pt-0.5 " + (active ? "text-ok" : on && !anyType ? "text-warnInk" : "text-faint")}
+ data-testid="sandbox-switch-status"
+ >
+ {switchStatus}
+ </span>
+ </div>
+ </div>
+ {!on ? <div className={FIELD_HELP + " mb-4"}>{t("settingsx.sandbox.switch_help_off")}</div> : <div className="mb-4" />}
+ {cfg.refused ? <div className="mb-4 text-meta text-danger">{t("settingsx.sandbox.refused", { why: cfg.refused })}</div> : null}
+
+ {/* 2. The type, once the switch is on */}
+ {on ? (
+ <>
+ <div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.type")}</div>
+ <div className={CARD + " mb-1 divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.type")}>
+ {types.map((p) => {
+ const [label, desc] = providerNames[p.name] ?? [p.name, ""];
+ const isActive = chosen === p.name;
+ const win = p.name === "windows";
- const canPick = p.usable || (win && Boolean(setup?.can_elevate));
- const why = !p.usable ? (win && setup && !setup.can_elevate ? t("settingsx.sandbox.needs_admin_why", { command: setup.command }) : win && setup?.can_elevate ? "" : p.why) : "";
++ const needsDownload = p.state === "needs_download"; // OpenShell in place except the base image: still choosable
++ const canPick = p.usable || needsDownload || (win && Boolean(setup?.can_elevate));
++ const why = !p.usable && !needsDownload ? (win && setup && !setup.can_elevate ? t("settingsx.sandbox.needs_admin_why", { command: setup.command }) : win && setup?.can_elevate ? "" : p.why) : "";
+ const status = win
+ ? setupReady
+ ? t("settingsx.sandbox.status_ready")
+ : setup?.can_elevate
+ ? t("settingsx.sandbox.status_setup")
+ : t("settingsx.sandbox.status_needs_admin")
- : 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");
+ return (
+ <label key={p.name} className={"flex items-start gap-3 px-4 py-3 " + (canPick ? "cursor-pointer" : "opacity-60")}>
+ <input
+ type="radio"
+ name="sandbox-provider"
+ className="mt-1"
+ checked={isActive}
+ disabled={!canPick && !isActive}
+ onChange={() => chooseType(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>
+ {why ? (
+ <span className="block text-meta text-warnInk mt-1" data-testid={`sandbox-provider-${p.name}-why`}>
+ {why}
+ </span>
+ ) : null}
++ {needsDownload ? (
++ <span className="block text-meta text-warnInk mt-1" data-testid={`sandbox-provider-${p.name}-hint`}>
++ {t("settingsx.sandbox.needs_download_hint")}
++ </span>
++ ) : null}
+ {win && setupReady ? (
+ <span className="block text-meta text-muted mt-1.5" data-testid="sandbox-windows-setup-line">
+ {setUpOnText ? t("settingsx.sandbox.set_up_on", { date: setUpOnText }) : t("settingsx.sandbox.set_up")}
+ <span className="mx-1.5 text-faint">·</span>
+ <button type="button" className="text-accent hover:underline" onClick={() => setRemoving(true)} data-testid="sandbox-remove-setup">
+ {t("settingsx.sandbox.remove_setup")}
+ </button>
+ </span>
+ ) : null}
+ </span>
- <span className={"text-meta shrink-0 whitespace-nowrap pt-0.5 " + (win && !setupReady && setup && !setup.can_elevate ? "text-warnInk" : isActive || (win ? setupReady : p.usable) ? "text-ok" : "text-faint")}>
++ <span
++ className={"text-meta shrink-0 whitespace-nowrap pt-0.5 " + ((win && !setupReady && setup && !setup.can_elevate) || needsDownload ? "text-warnInk" : isActive || (win ? setupReady : p.usable) ? "text-ok" : "text-faint")}
++ data-testid={`sandbox-provider-${p.name}-status`}
++ >
+ {status}
+ </span>
+ </label>
+ );
+ })}
+ </div>
+ <div className={FIELD_HELP + " mb-4"}>
+ {!active ? (anyType ? t("settingsx.sandbox.type_help") : t("settingsx.sandbox.type_help_admin")) : ""}
+ </div>
+ </>
+ ) : null}
+
++ {/* 2b. OpenShell: the readiness checklist and the guided setup job (OPE-207) */}
++ {active && chosen === "openshell" ? <OpenShellReadiness t={t} readiness={readiness} job={job} onStart={startJob} onCancel={cancelJob} copy={copy} copied={copied} /> : null}
++
+ {/* 3. The type's own options */}
+ {active ? (
+ <>
+ <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")}>
+ {profiles.map((np) => (
+ <label key={np.name} className="flex items-start gap-3 px-4 py-2.5 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 flex items-baseline gap-3">
+ <span className="text-ui text-ink">{t(`settingsx.sandbox.profile_${np.name}`)}</span>
+ <span className="text-meta text-muted ml-auto text-right">
+ {t(`settingsx.sandbox.profile_${np.name}_desc`)}
+ {np.name === "open" && isWindows ? " " + t("settingsx.sandbox.profile_open_default") : ""}
+ </span>
+ </span>
+ </label>
+ ))}
+ </div>
+ <div className={FIELD_HELP + " mb-5"}>
+ {chosen === "windows" ? t("settingsx.sandbox.network_help_windows") : chosen === "openshell" ? t("settingsx.sandbox.network_help_openshell") : t("settingsx.sandbox.network_help")}
+ </div>
+
+ <div className={FIELD_LABEL}>{t("settingsx.sandbox.credentials")}</div>
+ <div className={FIELD_HELP + " mb-2.5 mt-0.5"}>{t("settingsx.sandbox.credentials_intro")}</div>
+ <DisclosureCard
+ id="files"
+ open={openCard === "files"}
+ onToggle={() => setOpenCard(openCard === "files" ? null : "files")}
+ title={isWindows ? t("settingsx.sandbox.files_title_windows") : isMac ? t("settingsx.sandbox.files_title_mac") : t("settingsx.sandbox.files_title")}
+ desc={t("settingsx.sandbox.files_desc")}
+ summary={
+ cfg.credentials.length ? (
+ cfg.credentials.map((c) => (
+ <Chip key={c.name} on={c.enabled}>
+ {c.title || shipped(c.name, "title", c.name)}
+ </Chip>
+ ))
+ ) : (
+ <span>{t("settingsx.sandbox.none_yet")}</span>
+ )
+ }
+ >
+ <div className="divide-y divide-line">
+ {cfg.credentials.map((c) => (
+ <div key={c.name} className="flex items-start gap-3 pl-6 pr-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="flex items-center flex-wrap gap-2 text-ui text-ink">
+ {c.title || shipped(c.name, "title", c.name)}
+ <code className="text-meta text-muted font-mono">{c.path}</code>
+ {c.kind ? (
+ <span className={TAG + " bg-accentSoft text-accent"} data-testid={`sandbox-credential-${c.name}-kind`}>
+ {t(c.kind === "folder" ? "settingsx.sandbox.kind_folder" : "settingsx.sandbox.kind_file")}
+ </span>
+ ) : (
+ <span className="text-meta text-faint">{t("settingsx.sandbox.credential_missing")}</span>
+ )}
+ <span className={TAG + " " + (c.label === "configuration" ? "bg-paper text-muted" : "bg-warnSoft text-warnInk")}>
+ {t(c.label === "configuration" ? "settingsx.sandbox.label_configuration" : "settingsx.sandbox.label_credential")}
+ </span>
+ </span>
+ <span className="block text-meta text-muted">
+ {c.does ? c.does : shipped(c.name, "does")}{" "}
+ {c.hosts && c.hosts.length && cfg.network_profile !== "open" ? (
+ <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="flex items-center gap-3.5 pl-6 pr-4 py-3 bg-chrome border-t border-line rounded-b-xl2">
+ <span className="text-meta text-faint flex-1">
+ {t("settingsx.sandbox.files_foot")} {isWindows ? t("settingsx.sandbox.credman_note") : isMac ? t("settingsx.sandbox.keychain_note") : ""}
+ </span>
+ <button className={BTN_BORDERED + " text-meta px-2.5 py-1"} onClick={() => setEditing("")} data-testid="sandbox-credential-add">
+ {t("settingsx.sandbox.add")}
+ </button>
+ </div>
+ </DisclosureCard>
+ {editing !== null ? (
+ <CredentialEditor
+ entry={editing ? cfg.credentials.find((c) => c.name === editing) ?? null : null}
+ onCancel={() => setEditing(null)}
+ onSave={(row) => {
+ const rows = editing ? cfg.credentials.map((x) => (x.name === editing ? row : x)) : [...cfg.credentials, row];
+ setEditing(null);
+ updateCredentials(rows);
+ }}
+ />
+ ) : null}
+
+ {showTools ? (
+ <>
+ <div className={FIELD_LABEL + " mt-5 mb-2"}>{t("settingsx.sandbox.tools")}</div>
+ <DisclosureCard
+ id="tools"
+ open={openCard === "tools"}
+ onToggle={() => setOpenCard(openCard === "tools" ? null : "tools")}
+ title={t("settingsx.sandbox.toolchains")}
+ desc={t("settingsx.sandbox.tools_desc")}
+ summary={
+ <span data-testid="sandbox-tools-summary">
+ {t("settingsx.sandbox.tools_count", { on: toolsOn.length, total: (cfg.toolchains || []).length })}
+ {toolsOn.length ? " · " + toolsOn.slice(0, 6).map((x) => x.title || x.name).join(", ") + (toolsOn.length > 6 ? "…" : "") : ""}
+ </span>
+ }
+ >
+ <div className="divide-y divide-line">
+ {cfg.toolchains.map((tc) => (
+ <div key={tc.name} className="flex items-start gap-3 pl-6 pr-4 py-2.5" data-testid={`sandbox-toolchain-${tc.name}`}>
+ <input
+ type="checkbox"
+ className="mt-1"
+ checked={tc.enabled}
+ onChange={(e) => updateToolchains(cfg.toolchains.map((x) => (x.name === tc.name ? { ...x, enabled: e.target.checked } : x)))}
+ aria-label={tc.title || tc.name}
+ />
+ <span className="flex-1 min-w-0">
+ <span className={"block text-ui " + (tc.exists === false ? "text-muted" : "text-ink")}>
+ {tc.title || tc.name}
+ {tc.exists === false ? <span className="text-meta text-faint"> · {t("settingsx.sandbox.toolchain_missing")}</span> : null}
+ {!tc.shipped ? <span className="text-meta text-faint"> · {t("settingsx.sandbox.added_by_you")}</span> : null}
+ </span>
+ </span>
+ <code className="text-meta text-muted font-mono shrink-0">{tc.path}</code>
+ {!tc.shipped ? (
+ <button className="text-meta text-muted hover:text-ink shrink-0" onClick={() => updateToolchains(cfg.toolchains.filter((x) => x.name !== tc.name))}>
+ {t("settingsx.sandbox.remove")}
+ </button>
+ ) : null}
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center gap-3.5 pl-6 pr-4 py-3 bg-chrome border-t border-line rounded-b-xl2">
+ <span className="text-meta text-faint flex-1">{isWindows ? t("settingsx.sandbox.tools_foot_windows") : t("settingsx.sandbox.toolchains_help")}</span>
+ <button className={BTN_BORDERED + " text-meta px-2.5 py-1"} onClick={() => setAddingTool(true)} data-testid="sandbox-toolchain-add">
+ {t("settingsx.sandbox.add_toolchain")}
+ </button>
+ </div>
+ </DisclosureCard>
+ {addingTool ? (
+ <div className={CARD + " p-4 mt-3"} data-testid="sandbox-toolchain-editor">
+ <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={toolTitle} onChange={(e) => setToolTitle(e.target.value)} />
+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_toolchain_path")}</label>
+ <div className="flex gap-2">
+ <input className={INPUT + " font-mono"} value={toolPath} onChange={(e) => setToolPath(e.target.value)} />
+ <button
+ className={BTN_BORDERED}
+ onClick={async () => {
+ const picked = await chooseFolder();
+ if (picked) setToolPath(picked);
+ }}
+ >
+ {t("settingsx.sandbox.browse")}
+ </button>
+ </div>
+ </div>
+ <div className="flex justify-end gap-2 mt-3">
+ <button className={BTN_BORDERED} onClick={() => setAddingTool(false)}>
+ {t("settingsx.sandbox.cancel")}
+ </button>
+ <button
+ className={BTN_ACCENT}
+ disabled={!validPath(toolPath)}
+ onClick={() => {
+ const slug = (toolTitle || toolPath).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
+ setAddingTool(false);
+ setToolTitle("");
+ setToolPath("~/");
+ updateToolchains([...cfg.toolchains, { name: slug, title: toolTitle || undefined, path: toolPath, enabled: true }]);
+ }}
+ >
+ {t("settingsx.sandbox.done")}
+ </button>
+ </div>
+ </div>
+ ) : null}
+ </>
+ ) : null}
+ <div className={FIELD_HELP + " mt-4"}>{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div>
+ </>
+ ) : null}
+
+ {/* The Windows setup dialog */}
+ {setupStage ? (
+ <Modal testid="sandbox-setup-dialog">
+ {setupStage === "ask" ? (
+ <>
+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_intro")}</p>
+ <div className="text-label font-medium text-faint mb-1.5">{t("settingsx.sandbox.setup_changes")}</div>
+ <div className="grid gap-2.5">
+ {SETUP_CHANGES.map((k) => (
+ <div key={k} className="text-ui leading-relaxed">
+ {t(`settingsx.sandbox.setup_change_${k}`)}
+ <div className="text-meta text-muted">{t(`settingsx.sandbox.setup_change_${k}_desc`)}</div>
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center gap-2 mt-4">
+ <span className="text-meta text-faint max-w-[320px] leading-relaxed">{t("settingsx.sandbox.setup_not_now_note")}</span>
+ <span className="flex-1" />
+ <button
+ className={BTN_BORDERED}
+ onClick={() => {
+ setSetupStage(null);
+ setWantOn(false);
+ }}
+ data-testid="sandbox-setup-not-now"
+ >
+ {t("settingsx.sandbox.not_now")}
+ </button>
+ <button className={BTN_ACCENT} onClick={runSetup} data-testid="sandbox-setup-now">
+ {t("settingsx.sandbox.set_up_now")}
+ </button>
+ </div>
+ </>
+ ) : setupStage === "working" ? (
+ <>
+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_working_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_working_intro")}</p>
+ <div className="rounded-lg border border-line bg-paper px-3 py-2.5 text-ui text-muted flex items-center gap-2.5">
+ <span className="w-4 h-4 rounded-full border-2 border-lineStrong border-t-accent animate-spin shrink-0" />
+ {t("settingsx.sandbox.setup_waiting")}
+ </div>
+ </>
+ ) : setupStage === "done" ? (
+ <>
+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_done_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_done_intro")}</p>
+ <div className="rounded-lg border border-okLine bg-okSoft px-3 py-2.5 text-ui text-ok leading-relaxed" data-testid="sandbox-setup-done-box">
+ {t("settingsx.sandbox.setup_done_box", { checked: setupOutcome.checked || "" })}
+ </div>
+ <div className="flex justify-end mt-4">
+ <button className={BTN_ACCENT} onClick={() => setSetupStage(null)} data-testid="sandbox-setup-done">
+ {t("settingsx.sandbox.done")}
+ </button>
+ </div>
+ </>
+ ) : (
+ <>
+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_failed_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_failed_intro")}</p>
+ <div className="rounded-lg border border-line bg-paper px-3 py-2.5 text-meta text-danger font-mono whitespace-pre-wrap break-words" data-testid="sandbox-setup-error">
+ {setupOutcome.error}
+ </div>
+ <div className="flex justify-end gap-2 mt-4">
+ <button
+ className={BTN_BORDERED}
+ onClick={() => {
+ setSetupStage(null);
+ setWantOn(false);
+ }}
+ >
+ {t("settingsx.sandbox.close")}
+ </button>
+ <button className={BTN_ACCENT} onClick={() => setSetupStage("ask")}>
+ {t("settingsx.sandbox.try_again")}
+ </button>
+ </div>
+ </>
+ )}
+ </Modal>
+ ) : null}
+
+ {/* The Remove setup confirmation */}
+ {removing ? (
+ <Modal testid="sandbox-remove-dialog">
+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.remove_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.remove_intro")}</p>
+ <div className="text-label font-medium text-faint mb-1.5">{t("settingsx.sandbox.remove_what")}</div>
+ <div className="grid gap-2.5">
+ {SETUP_CHANGES.map((k) => (
+ <div key={k} className="text-ui leading-relaxed">
+ {t(`settingsx.sandbox.setup_change_${k}`)}
+ <div className="text-meta text-muted">{t(`settingsx.sandbox.remove_change_${k}_desc`)}</div>
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center gap-2 mt-4">
+ <span className="text-meta text-faint max-w-[320px] leading-relaxed">{t("settingsx.sandbox.remove_keep_note")}</span>
+ <span className="flex-1" />
+ <button className={BTN_BORDERED} onClick={() => setRemoving(false)} disabled={removeBusy}>
+ {t("settingsx.sandbox.cancel")}
+ </button>
+ <button className={BTN_ACCENT} onClick={runRemove} disabled={removeBusy} data-testid="sandbox-remove-confirm">
+ {removeBusy ? t("settingsx.sandbox.setup_waiting") : t("settingsx.sandbox.remove")}
+ </button>
+ </div>
+ </Modal>
+ ) : null}
+ </section>
+ );
+}
+
++// OpenShell's checklist: the rows `openworker machine sandbox status` prints, each with a
++// key and whether the app may fix it itself; the live job's rows while it runs or just ran.
++function OpenShellReadiness({
++ t,
++ readiness,
++ job,
++ onStart,
++ onCancel,
++ copy,
++ copied,
++}: {
++ t: (k: string, o?: Record<string, unknown>) => string;
++ readiness: SandboxReadiness | null;
++ job: SandboxSetupState | null;
++ onStart: () => void;
++ onCancel: () => void;
++ copy: (text: string) => void;
++ copied: string;
++}) {
++ const rows: (SandboxReadinessStep & { state?: SandboxSetupRowState })[] = job && job.status !== "idle" ? job.rows : readiness?.steps ?? [];
++ const missing = rows.filter((r) => !r.ok && r.state !== "fixed").length;
++ const running = job?.status === "running";
++ const elapsed = (s: number) => (s >= 60 ? `${Math.floor(s / 60)} min ${s % 60} s` : `${s} s`);
++ return (
++ <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 font-medium text-ink">{t("settingsx.sandbox.readiness")}</span>
++ <span className={"block text-meta " + (rows.length && missing === 0 ? "text-ok" : "text-muted")}>
++ {!readiness && !job
++ ? 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>
++ {running ? (
++ <button className={BTN_BORDERED} onClick={onCancel} data-testid="sandbox-setup-cancel">
++ {t("settingsx.sandbox.setup_cancel")}
++ </button>
++ ) : (
++ <button
++ className={BTN_ACCENT}
++ disabled={!rows.length || (missing === 0 && job?.status !== "needs_you" && job?.status !== "failed")}
++ onClick={onStart}
++ data-testid="sandbox-setup-start"
++ >
++ {job && job.status !== "idle" ? t("settingsx.sandbox.setup_again") : t("settingsx.sandbox.setup_start")}
++ </button>
++ )}
++ </div>
++ <ul className="divide-y divide-line">
++ {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");
++ 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-ok" : 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 === "openshell" && running && state === "fixing" && job?.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(job.progress.elapsed_s) })}
++ {job.progress.last_line ? ` · ${job.progress.last_line}` : ""}
++ </div>
++ ) : null}
++ {r.key === "image" && running && state === "fixing" && job?.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: job.progress.layers_total ? `${Math.round((100 * job.progress.layers_done) / job.progress.layers_total)}%` : "5%" }}
++ />
++ </div>
++ <div className="text-meta text-muted mt-1">
++ {job.progress.layers_total
++ ? t("settingsx.sandbox.download_progress", { done: job.progress.layers_done, total: job.progress.layers_total, elapsed: elapsed(job.progress.elapsed_s) })
++ : t("settingsx.sandbox.download_progress_unknown", { elapsed: elapsed(job.progress.elapsed_s) })}
++ </div>
++ </div>
++ ) : null}
++ {!good && r.hint ? <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}
++ {!good && r.docs ? (
++ <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>
++ );
++ })}
++ </ul>
++ {job && job.status !== "idle" && job.status !== "running" ? (
++ <div className={"px-4 py-3 border-t border-line text-ui " + (job.status === "done" ? "text-ok" : "text-warnInk")} data-testid={`sandbox-setup-${job.status}`}>
++ {job.status === "done"
++ ? t("settingsx.sandbox.setup_done", { provider: t("settingsx.sandbox.provider_openshell") })
++ : job.status === "needs_you"
++ ? t("settingsx.sandbox.setup_needs_you")
++ : job.status === "cancelled"
++ ? t("settingsx.sandbox.setup_cancelled")
++ : t("settingsx.sandbox.setup_failed", { error: job.error })}
++ </div>
++ ) : null}
++ <div className={FIELD_HELP + " px-4 pb-3"}>{t("settingsx.sandbox.setup_never_root")}</div>
++ </div>
++ );
++}
++
+function validPath(path: string): boolean {
+ return (path.startsWith("~/") || path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path)) && path.length >= 3;
+}
+
+// Add or edit one entry: a file or a folder under the home folder, what is in it, the
+// hosts its tool needs, and what it lets the agent do.
+export function CredentialEditor({
+ entry,
+ onCancel,
+ onSave,
+}: {
+ entry: SandboxCredentialEntry | null;
+ onCancel: () => void;
+ onSave: (row: SandboxCredentialEntry) => void;
+}) {
+ const { t } = useTranslation();
+ const [title, setTitle] = useState(entry?.title ?? "");
+ const [name, setName] = useState(entry?.name ?? "");
+ const [path, setPath] = useState(entry?.path ?? "~/");
+ const [hosts, setHosts] = useState((entry?.hosts ?? []).join("\n"));
+ const [does, setDoes] = useState(entry?.does ?? "");
+ const [label, setLabel] = useState<"credential" | "configuration">(entry?.label === "configuration" ? "configuration" : "credential");
+ const slug = entry?.name || name || title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");
+ const valid = Boolean(slug) && validPath(path);
+ return (
+ <div className={CARD + " p-4 mt-3"} data-testid="sandbox-credential-editor">
+ <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("");
+ }}
+ />
+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_path")}</label>
+ <div className="flex gap-2">
+ <input className={INPUT + " font-mono"} value={path} onChange={(e) => setPath(e.target.value)} />
+ <button
+ className={BTN_BORDERED}
+ onClick={async () => {
+ const picked = await chooseFolder();
+ if (picked) setPath(picked);
+ }}
+ >
+ {t("settingsx.sandbox.browse")}
+ </button>
+ </div>
+ <label className="text-ui text-muted self-start pt-2">{t("settingsx.sandbox.field_label")}</label>
+ <div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label={t("settingsx.sandbox.field_label")}>
+ {(["credential", "configuration"] as const).map((k) => (
+ <label key={k} className={"flex items-start gap-2.5 rounded-lg border px-3 py-2 cursor-pointer " + (label === k ? "border-accent bg-accentSoft" : "border-line")}>
+ <input type="radio" name="sandbox-credential-label" className="mt-1" checked={label === k} onChange={() => setLabel(k)} data-testid={`sandbox-credential-label-${k}`} />
+ <span>
+ <span className="block text-ui text-ink">{t(`settingsx.sandbox.label_${k}_title`)}</span>
+ <span className="block text-meta text-muted">{t(`settingsx.sandbox.label_${k}_desc`)}</span>
+ </span>
+ </label>
+ ))}
+ </div>
+ <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)} />
+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_does")}</label>
+ <input className={INPUT} value={does} onChange={(e) => setDoes(e.target.value)} />
+ </div>
+ <div className="flex items-center gap-2 mt-3">
+ <span className="text-meta text-faint">{t("settingsx.sandbox.editor_note")}</span>
+ <span className="flex-1" />
+ <button className={BTN_BORDERED} onClick={onCancel}>
+ {t("settingsx.sandbox.cancel")}
+ </button>
+ <button
+ className={BTN_ACCENT}
+ disabled={!valid}
+ onClick={() =>
+ onSave({
+ name: slug,
+ title: title || undefined,
+ path,
+ hosts: hosts
+ .split(/\s+/)
+ .map((h) => h.trim())
+ .filter(Boolean),
+ does: does || undefined,
+ label,
+ enabled: entry?.enabled ?? true,
+ })
+ }
+ >
+ {t("settingsx.sandbox.done")}
+ </button>
+ </div>
+ </div>
+ );
+}
diff --cc surfaces/gui/src/components/SettingsView.sandbox.test.tsx
index a4a64b50,447c6c9b..bbec6b9f
--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
@@@ -1,9 -1,7 +1,10 @@@
- // Settings ▸ Sandbox (UX-051 A, UX-053 v3): one switch first; on reveals the type; a ready
- // type reveals its options. The page shows what the machine reports and writes back the
- // changes: provider, network profile, credential list, toolchain list. On Windows, choosing
- // the sandbox opens the setup dialog, which calls the setup route.
-// 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.
++// Settings ▸ Sandbox (UX-051 A, UX-053 v3, OPE-207): one switch first; on reveals the type;
++// a ready type reveals its options. The page shows what the machine reports and writes back
++// the changes: provider, network profile, credential list, toolchain list. On Windows,
++// choosing the sandbox opens the setup dialog, which calls the Windows setup route. Under
++// OpenShell the readiness checklist and the guided setup job show.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
const base = {
platform: "darwin",
@@@ -33,11 -24,29 +34,28 @@@
],
config_path: "/Users/sam/.config/coworker/config.toml",
};
-let snapshot: any = base;
+let snapshot: any = { ...base };
+
- const setSandboxSettings = vi.fn(async (patch: any) => ({ ok: true, ...snapshot, ...patch }));
+ 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, 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 };
+
-// Like the backend: each save returns the whole (updated) snapshot.
-const setSandboxSettings = vi.fn(async (patch: any) => {
- snapshot = { ...snapshot, ...patch };
- // Like the backend: a provider change names the sessions it dropped for a rebuild.
- return { ok: true, ...snapshot, ...("provider" in patch ? { rebuilt_sessions: ["s-open"] } : {}) };
-});
++// Like the backend: a provider change names the sessions it dropped for a rebuild.
++const setSandboxSettings = vi.fn(async (patch: any) => ({ ok: true, ...snapshot, ...patch, ...("provider" in patch ? { rebuilt_sessions: ["s-open"] } : {}) }));
+ const onSandboxProviderChanged = vi.fn();
+ const startSandboxSetup = vi.fn(async () => setupState);
+const runSandboxSetup = vi.fn(async () => ({ ok: true, checked: "the wall held", ...snapshot, provider: "windows", windows_setup: { ...snapshot.windows_setup, state: "ready", set_up_at: "2026-09-28T10:00:00Z" } }));
+const runSandboxRemove = vi.fn(async () => ({ ok: true, ...snapshot, provider: "direct", windows_setup: { ...snapshot.windows_setup, state: "not_set_up", set_up_at: "" } }));
vi.mock("../api", async (importOriginal) => {
const actual = await importOriginal<typeof import("../api")>();
@@@ -45,8 -54,10 +63,12 @@@
...actual,
getSandboxSettings: vi.fn(async () => snapshot),
setSandboxSettings: (patch: any) => setSandboxSettings(patch),
+ runSandboxSetup: () => runSandboxSetup(),
+ runSandboxRemove: () => runSandboxRemove(),
+ 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 () => []),
@@@ -58,79 -69,166 +80,178 @@@
import { SettingsView } from "./SettingsView";
+const stripDisplay = (rows: any[]) => rows.map(({ kind: _k, shipped: _s, ...row }) => row);
+
describe("Settings ▸ Sandbox", () => {
beforeEach(() => {
+ snapshot = { ...base };
setSandboxSettings.mockClear();
+ runSandboxSetup.mockClear();
+ runSandboxRemove.mockClear();
+ startSandboxSetup.mockClear();
- snapshot = base;
++ onSandboxProviderChanged.mockClear();
+ setupState = { status: "idle", rows: [], progress: null, error: "", elapsed_s: 0 };
});
afterEach(cleanup);
- 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-switch") as HTMLInputElement).checked).toBe(false);
- 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.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 () => {
+ it("off: one switch and nothing else; on reveals the type card only", async () => {
- render(<SettingsView initialTab="sandbox" />);
+ render(<SettingsView initialTab="sandbox" onSandboxProviderChanged={onSandboxProviderChanged} />);
await screen.findByTestId("sandbox-section");
- fireEvent.click(screen.getByTestId("sandbox-switch"));
+ const sw = screen.getByRole("switch");
+ expect(sw.getAttribute("aria-checked")).toBe("false");
+ expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("off");
+ expect(screen.queryByTestId("sandbox-provider-seatbelt")).toBeNull();
+ expect(screen.queryByTestId("sandbox-network-strict")).toBeNull();
+ expect(screen.queryByTestId("sandbox-card-files")).toBeNull();
+ fireEvent.click(sw);
+ expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("choose a type");
+ expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).disabled).toBe(true);
+ expect(screen.getByTestId("sandbox-provider-openshell-why").textContent).toBe("OpenShell is not installed");
+ expect(screen.queryByTestId("sandbox-network-strict")).toBeNull(); // no type is ready yet
+ expect(setSandboxSettings).not.toHaveBeenCalled();
+ fireEvent.click(screen.getByTestId("sandbox-provider-seatbelt"));
await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ provider: "seatbelt" }));
- await waitFor(() => expect(onSandboxProviderChanged).toHaveBeenCalledWith(["s-open"])); // the app reconnects that session
- // 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"));
- await waitFor(() =>
- expect(setSandboxSettings).toHaveBeenLastCalledWith({
- credentials: [
- { name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], enabled: true },
- { name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], enabled: true },
- ],
- }),
- );
- fireEvent.click(screen.getByTestId("sandbox-switch"));
- await waitFor(() => expect(setSandboxSettings).toHaveBeenLastCalledWith({ provider: "" })); // cleared, not "direct"
++ await waitFor(() => expect(onSandboxProviderChanged).toHaveBeenCalledWith(["s-open"])); // live sessions rebuilt under the new rule
+ });
+
- it("with OpenShell on Linux: the readiness checklist, its hints, and the setup button", async () => {
++ it("OpenShell on Linux: the readiness checklist, its hints, the handover command 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: 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-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
++ expect(screen.getByRole("switch").getAttribute("aria-checked")).toBe("true");
++ expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("on · OpenShell (NVIDIA)");
++ expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).checked).toBe(true);
+ await screen.findByTestId("sandbox-readiness-row-openshell");
+ 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
+ // 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);
++ expect(screen.queryByTestId("sandbox-card-tools")).toBeNull(); // OpenShell mounts no home folder: no tools card
++ expect(screen.getByTestId("sandbox-card-files")).toBeTruthy();
+ });
+
- it("running the setup: the job's rows, the download progress, and the handover verdict", async () => {
++ it("OpenShell: a running setup job shows its rows and progress; needs_you offers Check again", 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], ok: true, state: "ok" },
+ { ...readiness.steps[3], 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();
+
- // 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: "",
+ elapsed_s: 3,
+ };
+ render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-setup-needs_you");
+ 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"));
+ await waitFor(() => expect(startSandboxSetup).toHaveBeenCalled());
+ });
+
- 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" }] };
++ it("OpenShell with the base image missing is still choosable and says needs download", async () => {
++ snapshot = {
++ ...base,
++ platform: "linux",
++ providers: [
++ { name: "direct", usable: true, why: "", state: "ready" },
++ { name: "openshell", usable: false, why: "the base image is missing", state: "needs_download" },
++ ],
++ };
+ 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/);
++ fireEvent.click(screen.getByRole("switch"));
++ expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).disabled).toBe(false);
++ expect(screen.getByTestId("sandbox-provider-openshell-status").textContent).toBe("needs download");
++ expect(screen.getByTestId("sandbox-provider-openshell-hint").textContent).toMatch(/about 5 GB/);
++ expect(screen.queryByTestId("sandbox-provider-openshell-why")).toBeNull();
++ fireEvent.click(screen.getByTestId("sandbox-provider-openshell"));
++ await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ provider: "openshell" }));
});
- it("adds a credential through the editor and removes one (when the sandbox is on)", async () => {
+ it("a ready type shows its options; switching off writes direct", async () => {
snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };
render(<SettingsView initialTab="sandbox" />);
- await screen.findByTestId("sandbox-credentials-section");
+ await screen.findByTestId("sandbox-section");
+ expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("on · macOS sandbox");
+ expect((screen.getByTestId("sandbox-network-strict") as HTMLInputElement).checked).toBe(true);
+ fireEvent.click(screen.getByTestId("sandbox-network-standard"));
+ await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ network_profile: "standard" }));
+ // the files card is one line until opened; its chips name the entries
+ expect(screen.getByTestId("sandbox-card-files")).toBeTruthy();
+ expect(screen.queryByTestId("sandbox-card-files-body")).toBeNull();
+ expect(within(screen.getByTestId("sandbox-card-files-toggle")).getByText("SSH keys")).toBeTruthy();
+ expect(screen.getByTestId("sandbox-tools-summary").textContent).toContain("2 of 2 on");
+ expect(screen.getByText(/config\.toml/)).toBeTruthy();
+ fireEvent.click(screen.getByRole("switch"));
+ await waitFor(() => expect(setSandboxSettings).toHaveBeenLastCalledWith({ provider: "direct" }));
+ });
+
+ it("the files card: switch, kind and label tags, add through the editor with a label, remove", async () => {
+ snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };
+ render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-section");
+ fireEvent.click(screen.getByTestId("sandbox-card-files-toggle"));
+ const body = screen.getByTestId("sandbox-card-files-body");
+ expect(screen.getByTestId("sandbox-credential-ssh-kind").textContent).toBe("folder");
+ expect(screen.getByTestId("sandbox-credential-aws-kind").textContent).toBe("file");
+ expect(within(screen.getByTestId("sandbox-credential-gh")).getByText("not on this machine")).toBeTruthy();
+ expect(within(screen.getByTestId("sandbox-credential-aws")).getByText("configuration")).toBeTruthy();
+ expect(within(body).getByText(/Also allows github.com:22/)).toBeTruthy();
+ fireEvent.click(screen.getByLabelText("SSH keys"));
+ await waitFor(() =>
+ expect(setSandboxSettings).toHaveBeenLastCalledWith({
+ credentials: stripDisplay([{ ...base.credentials[0], enabled: true }, base.credentials[1], base.credentials[2]]),
+ }),
+ );
fireEvent.click(screen.getByTestId("sandbox-credential-add"));
const editor = screen.getByTestId("sandbox-credential-editor");
- const inputs = editor.querySelectorAll("input, textarea");
+ const inputs = editor.querySelectorAll("input[type=text], input:not([type]), textarea");
fireEvent.change(inputs[0], { target: { value: "npm token" } });
fireEvent.change(inputs[1], { target: { value: "~/.npmrc" } });
+ fireEvent.click(screen.getByTestId("sandbox-credential-label-configuration"));
fireEvent.change(inputs[2], { target: { value: "registry.npmjs.org:443" } });
- fireEvent.click(screen.getByText("Done"));
+ fireEvent.click(within(editor).getByText("Done"));
await waitFor(() =>
expect(setSandboxSettings).toHaveBeenLastCalledWith({
credentials: [
diff --cc surfaces/gui/src/locales/en.json
index 96c33c7a,db992d5b..c805e649
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@@ -2269,128 -2270,92 +2270,166 @@@
},
"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_windows": "Where agents run their commands and file tools on this PC. Applies to every session on this machine; a project cannot change it.",
- "sub_machine": "On ⌂ {{name}} — where its agents run commands and file tools. Applies to every session on that machine; a project cannot change it.",
- "sub": "Where agents run their commands and file tools on this machine. Applies to every session here (one in the middle of a turn switches when the turn ends); a project cannot change it.",
++ "sub": "Where agents run their commands and file tools on this Mac. Applies to every session here (one in the middle of a turn switches when the turn ends); a project cannot change it.",
++ "sub_windows": "Where agents run their commands and file tools on this PC. Applies to every session here (one in the middle of a turn switches when the turn ends); 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 (one in the middle of a turn switches when the turn ends); a project cannot change it.",
- "switch": "Run agents in a sandbox",
- "switch_off_desc": "Off: commands run directly on this machine, with the same access as your user account. Your network and credential settings are kept for when you switch back on.",
- "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",
+ "switch_title": "Run agents in a sandbox",
+ "switch_desc": "Commands run where they cannot see your files, your keys or OpenWorker's own state. Off, they run as you, with no limits.",
+ "switch_off": "off",
+ "switch_choose": "choose a type",
+ "switch_on": "on · {{type}}",
+ "switch_none": "no type can be used yet",
+ "switch_help_off": "Turn it on to choose how agents are isolated on this machine.",
+ "type": "Sandbox type",
+ "type_help": "Nothing changes until a type is ready. Its options appear here once it is.",
+ "type_help_admin": "Once an administrator has run the setup, come back here and choose the Windows sandbox.",
+ "provider_seatbelt": "macOS sandbox",
+ "provider_seatbelt_desc": "The Seatbelt profile built into macOS. Nothing to install.",
+ "provider_windows": "Windows sandbox",
+ "provider_windows_desc": "Commands run as a hidden Windows account that cannot see your profile. One-time setup, with one administrator prompt.",
+ "provider_openshell": "OpenShell (NVIDIA)",
+ "provider_openshell_desc": "One Linux container per agent, with the session's folders mounted. Needs OpenShell and Docker.",
+ "status_ready": "ready",
+ "status_unavailable": "not available on this machine",
+ "status_setup": "one-time setup",
+ "status_needs_admin": "needs an administrator",
+ "needs_admin_why": "Needs an administrator to set up. Ask one to run this once on this PC: {{command}}",
+ "set_up_on": "Set up on {{date}}",
+ "set_up": "Set up",
+ "remove_setup": "Remove setup…",
+ "refused": "Sessions on this machine are refused until this is fixed: {{why}}",
+ "network": "Network",
+ "profile_strict": "Strict",
+ "profile_strict_desc": "GitHub, GitLab and the package registries (PyPI, npm, crates, Go).",
+ "profile_standard": "Standard",
+ "profile_standard_desc": "Strict plus the search APIs.",
+ "profile_open": "Open",
+ "profile_open_desc": "Any host. Files stay isolated.",
+ "profile_open_default": "The default on Windows.",
+ "network_help": "Credentials below add the hosts their tools need.",
+ "network_help_windows": "Strict and Standard run commands as the closed account: Windows blocks its traffic, and only the allow list gets through. Credentials below add the hosts their tools need.",
+ "network_help_openshell": "Enforced by the container's policy. Credentials below add the hosts their tools need.",
+ "credentials": "Credentials an agent may be given",
+ "credentials_intro": "A sandbox holds none of your logins unless you say so. An agent is told what it can do, never where a credential is kept.",
+ "files_title": "Files from this machine",
+ "files_title_mac": "Files from this Mac",
+ "files_title_windows": "Files from this PC",
+ "files_desc": "Files or folders copied into the sandbox for the session and deleted with it. Each is marked configuration or credential.",
+ "files_foot": "A file or a whole folder, copied in at session start and deleted with it. Your real files are never touched.",
+ "credman_note": "Logins in Windows' credential manager are not files and cannot be added.",
+ "keychain_note": "Logins kept in the macOS Keychain (git over HTTPS) are not files and cannot be added. Use an SSH remote, or the GitHub connector.",
+ "none_yet": "none yet",
+ "add": "Add a file or folder…",
+ "also_allows": "Also allows {{hosts}}.",
+ "edit": "Edit",
+ "remove": "Remove",
+ "done": "Done",
+ "cancel": "Cancel",
+ "close": "Close",
+ "try_again": "Try again",
+ "browse": "Browse…",
+ "kind_file": "file",
+ "kind_folder": "folder",
+ "credential_missing": "not on this machine",
+ "label_credential": "credential",
+ "label_configuration": "configuration",
+ "field_title": "Name",
+ "field_path": "Path (a file or a folder under your home folder)",
+ "field_label": "What is in it",
+ "label_credential_title": "A credential",
+ "label_credential_desc": "A key, a token, a password. The agent gets it only while this entry is on.",
+ "label_configuration_title": "Configuration only",
+ "label_configuration_desc": "Host names, profiles, options. No secret inside.",
+ "field_hosts": "Hosts it needs (host:port, one per line; added to the allow list when this entry is on)",
+ "field_does": "Lets the agent",
+ "editor_note": "A folder is copied whole, including anything added to it later. Prefer the one file a tool needs.",
+ "tools": "Tools from your profile",
+ "toolchains": "Tools from your profile the sandbox may read",
+ "tools_desc": "Read only, never written. The rest of your profile stays invisible; the session inherits your PATH.",
+ "tools_count": "{{on}} of {{total}} on",
+ "toolchains_help": "Tools installed under your home folder are hidden with the rest of it. These folders are readable, never writable, so the agent can run them.",
+ "tools_foot_windows": "Folders outside your profile, such as D:\\work, are readable as for any local account.",
+ "toolchain_missing": "not on this machine",
+ "added_by_you": "added by you",
+ "add_toolchain": "Add a folder…",
+ "field_toolchain_path": "Folder (under your home folder)",
+ "setup_title": "Set up the Windows sandbox",
+ "setup_intro": "Agents' commands will run as a hidden Windows account that cannot see your profile: not your documents, not your keys, not OpenWorker's own state. Setting that up is one step, and Windows will ask for administrator permission once.",
+ "setup_changes": "What setup changes on this PC",
+ "setup_change_accounts": "Two hidden local accounts, OWSandboxOpenNet and OWSandboxClosedNet, with passwords nobody sees",
+ "setup_change_accounts_desc": "Hidden from the sign-in screen. They cannot log on remotely or over the network.",
+ "setup_change_rules": "One firewall rule and four loopback filters on the closed account",
+ "setup_change_rules_desc": "It reaches the network only through OpenWorker's allow-list proxy. The open account has no rules.",
+ "setup_change_folder": "A folder under C:\\ProgramData\\OpenWorker",
+ "setup_change_folder_desc": "The accounts' passwords, readable by you and administrators only, and each session's private folder.",
+ "setup_change_record": "A record of every change",
+ "setup_change_record_desc": "Undo all of it any time with \"Remove setup\" on this page.",
+ "setup_not_now_note": "\"Not now\" turns the sandbox off again. You can choose it any time.",
+ "not_now": "Not now",
+ "set_up_now": "Set up now",
+ "setup_working_title": "Setting up the Windows sandbox",
+ "setup_working_intro": "Windows is asking for administrator permission in its own prompt. Then the accounts, the rule and the filters are written, and the wall is tried from inside a throwaway sandbox. About ten seconds.",
+ "setup_waiting": "Waiting for Windows…",
+ "setup_done_title": "The Windows sandbox is ready",
+ "setup_done_intro": "Every session on this PC now runs its commands as a hidden account. Your profile is out of reach. The network is open by default; the options for this type are now on this page.",
+ "setup_done_box": "Accounts created · firewall rule written · loopback filters written · checked from inside a throwaway sandbox: {{checked}}",
+ "setup_failed_title": "Setup did not finish",
+ "setup_failed_intro": "Nothing is chosen until setup finishes and the wall is proved. Windows said:",
+ "remove_title": "Remove the Windows sandbox setup",
+ "remove_intro": "The sandbox turns off and this PC goes back to running commands as you. Windows will ask for administrator permission once. Nothing of yours is touched; only what setup made is removed:",
+ "remove_what": "What is removed",
+ "remove_change_accounts_desc": "Hidden from the sign-in screen. They cannot log on remotely or over the network.",
+ "remove_change_rules_desc": "The closed account's rule and filters.",
+ "remove_change_folder_desc": "The accounts' passwords and every session's private folder.",
+ "remove_change_record_desc": "The record itself is the last thing to go.",
+ "remove_keep_note": "Your network, credential and tool choices are kept for the next time.",
+ "does_ssh": "Push and pull over SSH, and log in to servers, as you.",
+ "does_gh": "Use gh as you: pull requests, issues, releases.",
+ "does_aws": "Use aws with your profiles: regions and profile names. ~/.aws/credentials stays out unless you add it.",
+ "does_kube": "Use kubectl with your clusters.",
+ "title_ssh": "SSH keys",
+ "title_gh": "GitHub CLI",
+ "title_aws": "AWS profiles",
+ "title_kube": "Kubernetes",
- "saved_in": "Saved in {{path}}"
++ "saved_in": "Saved in {{path}}",
+ "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 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": "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",
+ "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 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)",
- "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. 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",
- "profile_strict": "Strict",
- "profile_strict_desc": "GitHub, GitLab and the package registries (PyPI, npm, crates, Go).",
- "profile_standard": "Standard",
- "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 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",
- "remove": "Remove",
- "done": "Done",
- "cancel": "Cancel",
- "field_title": "Name",
- "field_path": "Path (under your home folder)",
- "field_hosts": "Hosts it needs (host:port, one per line)",
- "field_does": "Lets the agent",
- "credentials_help": "Switched-on entries are copied into every sandbox on this machine for the session, and deleted with it. Your real files are never touched.",
- "keychain_note": "Logins kept in the macOS Keychain (git over HTTPS) are not files and cannot be shared. Use an SSH remote, or the GitHub connector.",
- "does_ssh": "Push and pull over SSH, and log in to servers, as you.",
- "does_gh": "Use gh as you: pull requests, issues, releases.",
- "does_aws": "Use aws with your profiles.",
- "does_kube": "Use kubectl with your clusters.",
- "title_ssh": "SSH keys",
- "title_gh": "GitHub CLI",
- "title_aws": "AWS",
- "title_kube": "Kubernetes",
- "saved_in": "This setting is stored in {{path}}"
++ "field_does_example": "Publish packages to npm as you"
}
},
"misc": {
diff --cc surfaces/gui/src/locales/zh.json
index f846f025,4f5c822d..1d4ebb3e
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@@ -2229,128 -2230,92 +2230,166 @@@
},
"sandbox": {
"title": "沙箱",
- "sub": "同事在这台 Mac 上运行命令和文件工具的位置。适用于这台机器上的每个会话;项目无法更改。",
- "sub_windows": "同事在这台 PC 上运行命令和文件工具的位置。适用于这台机器上的每个会话;项目无法更改。",
- "sub_machine": "在 ⌂ {{name}} 上 —— 它的同事运行命令和文件工具的位置。适用于那台机器上的每个会话;项目无法更改。",
- "sub": "同事在这台机器上运行命令和文件工具的位置。适用于这里的每个会话(正在进行回合的会话会在回合结束后切换);项目无法更改。",
++ "sub": "同事在这台 Mac 上运行命令和文件工具的位置。适用于这里的每个会话(正在进行中的会话会在本轮结束后切换);项目无法更改。",
++ "sub_windows": "同事在这台 PC 上运行命令和文件工具的位置。适用于这里的每个会话(正在进行中的会话会在本轮结束后切换);项目无法更改。",
+ "sub_machine": "在 ⌂ {{name}} 上 —— 它的同事运行命令和文件工具的位置。适用于那台机器上的每个会话(正在进行回合的会话会在回合结束后切换);项目无法更改。",
- "run_in": "在哪里运行同事",
- "switch": "在沙箱中运行同事",
- "switch_off_desc": "关闭:命令直接在这台机器上运行,权限与你的用户账户相同。你的网络和凭据设置会保留,以便再次开启时使用。",
- "switch_on_desc": "开启:命令和文件工具在一道墙后运行,墙内只有会话的文件夹和网络允许列表。",
- "current": "当前",
- "windows_hint": "沙箱需要一台 Linux 机器。请在 设置 ▸ 机器 中添加一台;这台电脑上的 WSL Ubuntu 即可。",
- "provider_label": "沙箱",
+ "switch_title": "在沙箱中运行同事",
+ "switch_desc": "命令在看不到你的文件、密钥和 OpenWorker 自身状态的地方运行。关闭时,命令以你的身份运行,没有限制。",
+ "switch_off": "关闭",
+ "switch_choose": "选择一种类型",
+ "switch_on": "开启 · {{type}}",
+ "switch_none": "目前没有可用的类型",
+ "switch_help_off": "开启后可选择这台机器上隔离同事的方式。",
+ "type": "沙箱类型",
+ "type_help": "在某种类型就绪之前不会有任何变化。就绪后它的选项会显示在这里。",
+ "type_help_admin": "管理员完成设置后,回到这里选择 Windows 沙箱。",
+ "provider_seatbelt": "macOS 沙箱",
+ "provider_seatbelt_desc": "macOS 内置的 Seatbelt 配置。无需安装。",
+ "provider_windows": "Windows 沙箱",
+ "provider_windows_desc": "命令以一个看不到你的用户配置文件的隐藏 Windows 账户运行。一次性设置,只需一次管理员确认。",
+ "provider_openshell": "OpenShell(NVIDIA)",
+ "provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要 OpenShell 和 Docker。",
+ "status_ready": "就绪",
+ "status_unavailable": "这台机器上不可用",
+ "status_setup": "一次性设置",
+ "status_needs_admin": "需要管理员",
+ "needs_admin_why": "需要管理员进行设置。请管理员在这台 PC 上运行一次:{{command}}",
+ "set_up_on": "设置于 {{date}}",
+ "set_up": "已设置",
+ "remove_setup": "移除设置…",
+ "refused": "在修复此问题前,这台机器上的会话将被拒绝:{{why}}",
+ "network": "网络",
+ "profile_strict": "严格",
+ "profile_strict_desc": "GitHub、GitLab 和软件包源(PyPI、npm、crates、Go)。",
+ "profile_standard": "标准",
+ "profile_standard_desc": "严格模式加上搜索 API。",
+ "profile_open": "开放",
+ "profile_open_desc": "任意主机。文件仍然隔离。",
+ "profile_open_default": "Windows 上的默认值。",
+ "network_help": "下方的凭据会加入其工具所需的主机。",
+ "network_help_windows": "严格和标准模式以封闭账户运行命令:Windows 阻断它的流量,只有允许列表能通过。下方的凭据会加入其工具所需的主机。",
+ "network_help_openshell": "由容器策略强制执行。下方的凭据会加入其工具所需的主机。",
+ "credentials": "可提供给同事的凭据",
+ "credentials_intro": "除非你明确允许,沙箱不持有你的任何登录信息。同事只被告知它能做什么,从不被告知凭据存放在哪里。",
+ "files_title": "来自这台机器的文件",
+ "files_title_mac": "来自这台 Mac 的文件",
+ "files_title_windows": "来自这台 PC 的文件",
+ "files_desc": "在会话期间复制到沙箱中、随沙箱一起删除的文件或文件夹。每一项都标记为配置或凭据。",
+ "files_foot": "单个文件或整个文件夹,在会话开始时复制进去,随会话删除。你的真实文件不会被改动。",
+ "credman_note": "Windows 凭据管理器中的登录信息不是文件,无法添加。",
+ "keychain_note": "保存在 macOS 钥匙串中的登录信息(HTTPS 方式的 git)不是文件,无法添加。请使用 SSH 远程地址,或 GitHub 连接器。",
+ "none_yet": "暂无",
+ "add": "添加文件或文件夹…",
+ "also_allows": "同时允许 {{hosts}}。",
+ "edit": "编辑",
+ "remove": "移除",
+ "done": "完成",
+ "cancel": "取消",
+ "close": "关闭",
+ "try_again": "重试",
+ "browse": "浏览…",
+ "kind_file": "文件",
+ "kind_folder": "文件夹",
+ "credential_missing": "这台机器上没有",
+ "label_credential": "凭据",
+ "label_configuration": "配置",
+ "field_title": "名称",
+ "field_path": "路径(你主目录下的文件或文件夹)",
+ "field_label": "内容类型",
+ "label_credential_title": "凭据",
+ "label_credential_desc": "密钥、令牌或密码。只有此条目开启时同事才能获得。",
+ "label_configuration_title": "仅配置",
+ "label_configuration_desc": "主机名、配置文件、选项。不含机密。",
+ "field_hosts": "所需主机(host:port,每行一个;此条目开启时加入允许列表)",
+ "field_does": "让同事可以",
+ "editor_note": "文件夹会整个复制,包括以后加入其中的内容。优先选择工具所需的单个文件。",
+ "tools": "来自你用户配置文件的工具",
+ "toolchains": "沙箱可读取的、来自你用户配置文件的工具",
+ "tools_desc": "只读,从不写入。你配置文件的其余部分仍不可见;会话继承你的 PATH。",
+ "tools_count": "{{total}} 项中 {{on}} 项已开启",
+ "toolchains_help": "安装在你主目录下的工具会随主目录一起被隐藏。这些文件夹只读、不可写,以便同事运行它们。",
+ "tools_foot_windows": "用户配置文件之外的文件夹(如 D:\\work)对任何本地账户都可读。",
+ "toolchain_missing": "这台机器上没有",
+ "added_by_you": "由你添加",
+ "add_toolchain": "添加文件夹…",
+ "field_toolchain_path": "文件夹(在你的主目录下)",
+ "setup_title": "设置 Windows 沙箱",
+ "setup_intro": "同事的命令将以一个看不到你的用户配置文件的隐藏 Windows 账户运行:看不到你的文档、你的密钥,也看不到 OpenWorker 自身的状态。设置只需一步,Windows 会请求一次管理员权限。",
+ "setup_changes": "设置会在这台 PC 上做出的更改",
+ "setup_change_accounts": "两个隐藏的本地账户 OWSandboxOpenNet 和 OWSandboxClosedNet,密码无人可见",
+ "setup_change_accounts_desc": "不在登录界面显示。不能远程登录,也不能通过网络登录。",
+ "setup_change_rules": "封闭账户上的一条防火墙规则和四条回环过滤器",
+ "setup_change_rules_desc": "它只能通过 OpenWorker 的允许列表代理访问网络。开放账户没有规则。",
+ "setup_change_folder": "C:\\ProgramData\\OpenWorker 下的一个文件夹",
+ "setup_change_folder_desc": "账户密码(只有你和管理员可读)以及每个会话的私有文件夹。",
+ "setup_change_record": "每项更改的记录",
+ "setup_change_record_desc": "随时可以通过本页的“移除设置”全部撤销。",
+ "setup_not_now_note": "“暂不”会再次关闭沙箱。你可以随时再选择它。",
+ "not_now": "暂不",
+ "set_up_now": "立即设置",
+ "setup_working_title": "正在设置 Windows 沙箱",
+ "setup_working_intro": "Windows 正在通过它自己的提示请求管理员权限。随后会写入账户、规则和过滤器,并在一个临时沙箱内验证隔离墙。大约十秒。",
+ "setup_waiting": "正在等待 Windows…",
+ "setup_done_title": "Windows 沙箱已就绪",
+ "setup_done_intro": "这台 PC 上的每个会话现在都以隐藏账户运行命令。你的用户配置文件不可访问。网络默认开放;此类型的选项现已显示在本页。",
+ "setup_done_box": "已创建账户 · 已写入防火墙规则 · 已写入回环过滤器 · 已在临时沙箱内检查:{{checked}}",
+ "setup_failed_title": "设置未完成",
+ "setup_failed_intro": "在设置完成并验证隔离墙之前,不会选择任何类型。Windows 的输出:",
+ "remove_title": "移除 Windows 沙箱设置",
+ "remove_intro": "沙箱将关闭,这台 PC 恢复为以你的身份运行命令。Windows 会请求一次管理员权限。不会改动你的任何东西;只移除设置所创建的内容:",
+ "remove_what": "将被移除的内容",
+ "remove_change_accounts_desc": "不在登录界面显示。不能远程登录,也不能通过网络登录。",
+ "remove_change_rules_desc": "封闭账户的规则和过滤器。",
+ "remove_change_folder_desc": "账户密码和每个会话的私有文件夹。",
+ "remove_change_record_desc": "记录本身最后移除。",
+ "remove_keep_note": "你的网络、凭据和工具选择会保留到下次使用。",
+ "does_ssh": "以你的身份通过 SSH 推送和拉取,并登录服务器。",
+ "does_gh": "以你的身份使用 gh:拉取请求、议题、发布。",
+ "does_aws": "使用你的配置文件运行 aws:区域和配置文件名。除非你添加,~/.aws/credentials 不会包含在内。",
+ "does_kube": "使用你的集群运行 kubectl。",
+ "title_ssh": "SSH 密钥",
+ "title_gh": "GitHub CLI",
+ "title_aws": "AWS 配置文件",
+ "title_kube": "Kubernetes",
- "saved_in": "保存在 {{path}}"
++ "saved_in": "保存在 {{path}}",
+ "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": "应用会尽量自行完成每一步。需要管理员权限的步骤通过系统自带的密码提示完成;没有该提示的环境(WSL)会显示一条命令由你运行。应用绝不会看到或保存你的密码,也绝不会自行关闭沙箱。",
+ "run_in_terminal": "在这台机器的终端里运行:",
+ "guide": "指南",
+ "install_progress": "正在安装 OpenShell… 已用 {{elapsed}}",
+ "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 沙箱",
- "provider_seatbelt_desc": "命令只能读写会话的文件夹,只能访问允许列表中的网络主机。你的其他文件和登录信息被隐藏。",
- "provider_openshell": "OpenShell(NVIDIA)",
- "provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要这台机器上装有 OpenShell 和 Docker。",
- "status_default": "默认",
- "status_ready": "就绪",
+ "status_needs_download": "需要下载",
+ "needs_download_hint": "沙箱基础镜像(约 5 GB,仅下载一次)尚未下载到这台机器。点击下方的“设置沙箱”进行下载;下载完成前第一个会话无法启动。",
- "status_unavailable": "不可用",
- "refused": "在修复此问题前,这台机器上的会话将被拒绝:{{why}}",
- "network": "网络允许列表",
- "profile_strict": "严格",
- "profile_strict_desc": "GitHub、GitLab 和软件包源(PyPI、npm、crates、Go)。",
- "profile_standard": "标准",
- "profile_standard_desc": "严格模式加上搜索 API。",
- "network_help": "下方共享的凭据会加入其工具所需的主机。",
- "credentials": "可提供给同事的凭据",
- "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": "编辑",
- "remove": "移除",
- "done": "完成",
- "cancel": "取消",
- "field_title": "名称",
- "field_path": "路径(在你的主目录下)",
- "field_hosts": "所需主机(host:port,每行一个)",
- "field_does": "让同事可以",
- "credentials_help": "已开启的条目会在会话期间复制到这台机器上的每个沙箱中,并随沙箱一起删除。你的真实文件不会被改动。",
- "keychain_note": "保存在 macOS 钥匙串中的登录信息(HTTPS 方式的 git)不是文件,无法共享。请使用 SSH 远程地址,或 GitHub 连接器。",
- "does_ssh": "以你的身份通过 SSH 推送和拉取,并登录服务器。",
- "does_gh": "以你的身份使用 gh:拉取请求、议题、发布。",
- "does_aws": "使用你的配置文件运行 aws。",
- "does_kube": "使用你的集群运行 kubectl。",
- "title_ssh": "SSH 密钥",
- "title_gh": "GitHub CLI",
- "title_aws": "AWS",
- "title_kube": "Kubernetes",
- "saved_in": "此设置存储在 {{path}}"
++ "field_does_example": "以你的身份向 npm 发布包"
}
},
"misc": {
diff --cc tests/test_sandbox_openshell.py
index 68fe0b22,e4b87337..d72cda9b
--- a/tests/test_sandbox_openshell.py
+++ b/tests/test_sandbox_openshell.py
@@@ -8,8 -8,9 +8,10 @@@ messages. The second half needs a machi
from __future__ import annotations
import os
+ import shutil
+ import tempfile
import subprocess
+import sys
import threading
import time
from pathlib import Path
diff --cc tests/test_sandbox_settings.py
index f33ac07b,b60f621b..93d9e76c
--- a/tests/test_sandbox_settings.py
+++ b/tests/test_sandbox_settings.py
@@@ -91,60 -60,6 +91,60 @@@ def test_update_refuses_bad_input_witho
assert not config_file.exists()
+def test_a_label_is_written_and_read_back(config_file):
+ out = settings.update({"credentials": [{"name": "aws", "enabled": True, "path": "~/.aws", "label": "credential"}, {"name": "npmrc", "enabled": True, "path": "~/.npmrc", "label": "configuration"}]})
+ assert out["ok"], out
+ by = {e["name"]: e for e in settings.snapshot()["credentials"]}
+ assert by["aws"]["label"] == "credential" and by["aws"]["path"] == "~/.aws" and by["npmrc"]["label"] == "configuration"
+ assert by["gh"]["label"] == "credential" and by["gh"]["shipped"] and not by["npmrc"]["shipped"]
+
+
+def test_windows_setup_runs_checks_and_only_then_chooses_the_sandbox(config_file, monkeypatch):
+ """UX-053: "Set up now" runs the elevated setup, proves the wall in a throwaway sandbox,
+ and makes the Windows sandbox the choice; a failed check leaves the choice alone."""
+ from types import SimpleNamespace
+
+ from coworker.sandbox import selection
+ from coworker.sandbox.providers import windows_setup
+
+ monkeypatch.setattr(settings.sys, "platform", "win32")
+ # Off Windows the provider module cannot even import; the snapshot's two probes are stubbed.
- monkeypatch.setattr(settings, "_availability", lambda name: (True, ""))
++ monkeypatch.setattr(settings, "_availability", lambda name: (True, "", "ready"))
+ monkeypatch.setattr(selection, "select", lambda name=None: SimpleNamespace(provider=name or "direct"))
+ monkeypatch.setattr(windows_setup, "info", lambda: {"state": "ready", "set_up_at": "2026-09-28T10:00:00Z", "problem": "", "can_elevate": True, "command": "x"})
+ monkeypatch.setattr(windows_setup, "run_setup", lambda: (True, "ok S-1 S-2"))
+ monkeypatch.setattr(settings, "_throwaway_check", lambda: (False, "the home folder can be listed from inside"))
+ out = settings.run_windows_setup()
+ assert not out["ok"] and "throwaway sandbox failed" in out["error"] and "sandbox_provider" not in (config_file.read_text() if config_file.exists() else "")
+ monkeypatch.setattr(settings, "_throwaway_check", lambda: (True, "proved"))
+ out = settings.run_windows_setup()
+ assert out["ok"] and out["checked"] == "proved" and out["provider"] == "windows" and out["windows_setup"]["state"] == "ready"
+ monkeypatch.setattr(windows_setup, "run_setup", lambda: (False, "The operation was canceled by the user."))
+ out = settings.run_windows_setup()
+ assert not out["ok"] and "canceled" in out["error"] and out["provider"] == "windows" # the earlier choice stands
+ monkeypatch.setattr(windows_setup, "run_remove", lambda: (True, "removed"))
+ out = settings.run_windows_remove()
+ assert out["ok"] and out["provider"] == "direct"
+ monkeypatch.setattr(settings.sys, "platform", "darwin")
+ assert not settings.run_windows_setup()["ok"] and not settings.run_windows_remove()["ok"]
+
+
+def test_windows_setup_info_states(monkeypatch):
+ from coworker.sandbox.providers import windows_setup
+
+ monkeypatch.setattr(windows_setup, "can_elevate", lambda: True)
+ monkeypatch.setattr(windows_setup, "state", lambda: None)
+ assert windows_setup.info()["state"] == "not_set_up"
+ monkeypatch.setattr(windows_setup, "state", lambda: {"version": 1})
+ assert windows_setup.info()["state"] == "older"
+ monkeypatch.setattr(windows_setup, "state", lambda: {"version": windows_setup.SETUP_VERSION, "set_up_at": "2026-09-28T10:00:00Z"})
+ monkeypatch.setattr(windows_setup, "problem", lambda: "the sandbox account for the open network mode is not usable by this user")
+ info = windows_setup.info()
+ assert info["state"] == "broken" and info["set_up_at"] == "2026-09-28T10:00:00Z" and info["can_elevate"] and info["command"]
+ monkeypatch.setattr(windows_setup, "problem", lambda: None)
+ assert windows_setup.info()["state"] == "ready"
+
+
def test_removing_a_shipped_entry_and_going_back_to_the_default_rule(config_file):
settings.update({"provider": "direct", "credentials": [{"name": "ssh", "enabled": True}]})
assert 'sandbox_provider = "direct"' in config_file.read_text()