Skip to content
Python

Sandbox settings v5: one-button setup, two network choices, CLI login presets

Rohit C Prasad6b7cae8d5f10
diff --git a/coworker/agent.py b/coworker/agent.py
index 52a7be72..d7e0b88f 100644
--- a/coworker/agent.py
+++ b/coworker/agent.py
@@ -348,6 +348,7 @@ def build_engine(
agent=agent.name,
credentials=config.sandbox_credentials,
network_profile=config.sandbox_network_profile,
+ extra_hosts=config.sandbox_network_extra_hosts,
toolchains=config.sandbox_toolchains,
)
if ws is not None
diff --git a/coworker/config.py b/coworker/config.py
index d3e2b885..8e6f391d 100644
--- a/coworker/config.py
+++ b/coworker/config.py
@@ -125,8 +125,10 @@ class Config:
# coworker/sandbox/credentials.py; an entry here edits or adds by name.
sandbox_credentials: list[dict[str, Any]] = field(default_factory=list)
# Which hosts a sandbox may reach: a profile name from coworker/sandbox/network_profiles.py
- # ("strict" when unset). Machine-level, like the provider.
+ # ("standard" when unset, "open" on Windows). Machine-level, like the provider.
sandbox_network_profile: Optional[str] = None
+ # The machine's own additions to that list, "host:port" (a bare host means 443).
+ sandbox_network_extra_hosts: list[str] = field(default_factory=list)
# Developer tool folders under the home folder a sandbox may read (design doc, Windows
# 3d.4): `[[sandbox_toolchains]]` tables with name, path, enabled, editing or adding to
# the shipped list in coworker/sandbox/toolchains.py by name. Machine-level.
@@ -143,6 +145,7 @@ _FIELDS = {
"sandbox_provider",
"sandbox_credentials",
"sandbox_network_profile",
+ "sandbox_network_extra_hosts",
"sandbox_toolchains",
"compaction_cap_tokens",
"compaction_summary_max_tokens",
@@ -170,6 +173,7 @@ _GLOBAL_ONLY_FIELDS = {
"sandbox_provider",
"sandbox_credentials",
"sandbox_network_profile",
+ "sandbox_network_extra_hosts",
"sandbox_toolchains",
"allowed_commands",
"auto_allow",
@@ -199,6 +203,32 @@ def set_global_value(key: str, value: str, *, path: Optional[Path] = None) -> Pa
return target
+def set_global_list(key: str, values: list[str], *, path: Optional[Path] = None) -> Path:
+ """Set one top-level list-of-strings key in the machine's config.toml, like
+ set_global_value; an empty list removes the key. A hand-written array spread over
+ several lines is removed whole."""
+ if key not in _FIELDS:
+ raise ValueError(f"not a config key: {key}")
+ target = Path(path) if path is not None else global_config_path()
+ target.parent.mkdir(parents=True, exist_ok=True)
+ lines = target.read_text(encoding="utf-8").splitlines() if target.is_file() else []
+ kept: list[str] = []
+ inside = False
+ for line in lines:
+ if inside:
+ inside = "]" not in line
+ continue
+ if re.match(rf"\s*{re.escape(key)}\s*=", line):
+ inside = "[" in line and "]" not in line
+ continue
+ kept.append(line)
+ if values:
+ items = ", ".join('"' + v.replace("\\", "\\\\").replace('"', '\\"') + '"' for v in values)
+ kept = [f"{key} = [{items}]", *kept]
+ target.write_text("\n".join(kept) + "\n", encoding="utf-8")
+ return target
+
+
def set_global_tables(key: str, rows: list[dict[str, Any]], *, path: Optional[Path] = None) -> Path:
"""Replace every `[[key]]` table in the machine's config.toml with `rows`, keeping the
rest of the file. Values may be strings, booleans, integers and lists of strings."""
diff --git a/coworker/sandbox/credentials.py b/coworker/sandbox/credentials.py
index 7b79a0e0..6ca97f17 100644
--- a/coworker/sandbox/credentials.py
+++ b/coworker/sandbox/credentials.py
@@ -28,10 +28,13 @@ CREDENTIAL = "credential"
CONFIGURATION = "configuration"
LABELS = (CREDENTIAL, CONFIGURATION)
-# What ships. `hosts` are "host:port"; a port of 22 is an SSH tunnel through the proxy.
-# `.ssh` and `gh` are folders (their tools write beside the files); AWS ships as the
-# profiles file only, so `~/.aws/credentials` stays out unless the user adds it; the
-# kubeconfig is one file.
+# What ships: the presets of the page's "A CLI's login" picker (UX-053 v5). None is on, or
+# even listed, until the user adds it. `hosts` are "host:port"; a port of 22 is an SSH
+# tunnel through the proxy. `.ssh` and `gh` are folders (their tools write beside the
+# files); AWS profiles and AWS credentials are two entries, so the keys stay out unless the
+# user adds them; the kubeconfig is one file. `env`: variables the tool reads to find its
+# copy, `{path}` being the copy's path inside and `{dir}` the folder holding it.
+# `windows_path`: where the tool keeps it on Windows, when that differs.
DEFAULT_ENTRIES: list[dict[str, Any]] = [
{
"name": "ssh",
@@ -69,7 +72,61 @@ DEFAULT_ENTRIES: list[dict[str, Any]] = [
"label": CREDENTIAL,
"enabled": False,
},
+ {
+ "name": "aws-credentials",
+ "title": "AWS credentials",
+ "path": "~/.aws/credentials",
+ "hosts": ["*.amazonaws.com:443"],
+ "does": "use aws with your access keys",
+ "label": CREDENTIAL,
+ "enabled": False,
+ },
+ {
+ "name": "npm",
+ "title": "npm",
+ "path": "~/.npmrc",
+ "hosts": ["registry.npmjs.org:443"],
+ "does": "install and publish private packages as you",
+ "label": CREDENTIAL,
+ "env": {"NPM_CONFIG_USERCONFIG": "{path}"},
+ "enabled": False,
+ },
+ {
+ "name": "docker",
+ "title": "Docker registries",
+ "path": "~/.docker/config.json",
+ "hosts": ["registry-1.docker.io:443", "auth.docker.io:443", "production.cloudflare.docker.com:443", "ghcr.io:443"],
+ "does": "push and pull images with the logins saved in this file",
+ "label": CREDENTIAL,
+ "env": {"DOCKER_CONFIG": "{dir}"},
+ "enabled": False,
+ },
+ {
+ "name": "gcloud",
+ "title": "gcloud",
+ "path": "~/.config/gcloud",
+ "windows_path": "~/AppData/Roaming/gcloud",
+ "hosts": ["*.googleapis.com:443", "accounts.google.com:443"],
+ "does": "use gcloud with your accounts and projects",
+ "label": CREDENTIAL,
+ "env": {"CLOUDSDK_CONFIG": "{path}"},
+ "enabled": False,
+ },
+ {
+ "name": "terraform",
+ "title": "Terraform Cloud",
+ "path": "~/.terraform.d/credentials.tfrc.json",
+ "windows_path": "~/AppData/Roaming/terraform.d/credentials.tfrc.json",
+ "hosts": ["app.terraform.io:443", "registry.terraform.io:443", "releases.hashicorp.com:443"],
+ "does": "run terraform against Terraform Cloud as you",
+ "label": CREDENTIAL,
+ "enabled": False,
+ },
]
+for _entry in DEFAULT_ENTRIES: # a shipped entry's path is the one for this platform
+ if sys.platform == "win32" and _entry.get("windows_path"):
+ _entry["path"] = _entry["windows_path"]
+ _entry.pop("windows_path", None)
# Git's own settings are not a credential, but a sandbox whose HOME is redirected must still
# see them (git refuses to commit without an identity). Always copied when present.
@@ -86,6 +143,7 @@ class Grant:
does: str = ""
label: str = CREDENTIAL # credential | configuration
kind: str = "folder" # file | folder, from what the path is on this machine
+ env: dict[str, str] = field(default_factory=dict) # templates: {path}, {dir}
@dataclass
@@ -102,6 +160,18 @@ class CopiedCredentials:
return [{"name": g.name, "title": g.title, "path": g.path, "does": g.does} for g in self.grants]
+def listed(configured: Optional[Sequence[dict[str, Any]]]) -> list[dict[str, Any]]:
+ """The entries the user added (UX-053 v5): those named in the machine's config, in
+ that order, whether switched on or not. A shipped entry nobody added is a preset only."""
+ names = []
+ for raw in configured or []:
+ name = str(raw.get("name") or "").strip() if isinstance(raw, dict) else ""
+ if name and name not in names:
+ names.append(name)
+ by_name = {e["name"]: e for e in entries(configured)}
+ return [by_name[n] for n in names if n in by_name]
+
+
def entries(configured: Optional[Sequence[dict[str, Any]]]) -> list[dict[str, Any]]:
"""The machine's list: the shipped entries, with the user's edits and additions applied
by name. Unknown keys in a user entry are kept, missing ones default."""
@@ -160,6 +230,7 @@ def granted(configured: Optional[Sequence[dict[str, Any]]], *, home: Optional[st
Grant(
name=str(e["name"]), title=str(e.get("title") or e["name"]), path=real, relative=relative, hosts=hosts,
does=str(e.get("does") or ""), label=str(e.get("label") or CREDENTIAL), kind="folder" if os.path.isdir(real) else "file",
+ env={str(k): str(v) for k, v in (e.get("env") or {}).items()} if isinstance(e.get("env"), dict) else {},
)
) # fmt: skip
return out
@@ -259,6 +330,8 @@ def copy_in(
env["AWS_SHARED_CREDENTIALS_FILE"] = inside
elif g.name == "kube":
env["KUBECONFIG"] = os.path.join(inside, "config") if g.kind == "folder" else inside
+ for variable, template in g.env.items():
+ env[variable] = template.replace("{path}", inside).replace("{dir}", os.path.dirname(inside))
return CopiedCredentials(home=sandbox_home, env=env, hosts=sorted(set(hosts)), grants=list(grants), path_dirs=path_dirs)
diff --git a/coworker/sandbox/network_profiles.py b/coworker/sandbox/network_profiles.py
index 0c5f6405..7bad984c 100644
--- a/coworker/sandbox/network_profiles.py
+++ b/coworker/sandbox/network_profiles.py
@@ -4,6 +4,10 @@ proxy, Windows into the account it runs as. HTTPS (port 443) only.
`open` is the profile with no list at all: files stay isolated, the network is the
machine's own (ruling of 2026-09-25). It is the default on Windows for now.
+
+`strict` (code hosts and registries, no search) was folded into `standard` (UX-053 v5): the
+name is still accepted and means `standard`. A machine may add its own hosts to the list
+(`sandbox_network_extra_hosts`, see `clean_host`).
"""
from __future__ import annotations
@@ -16,19 +20,18 @@ SEARCH_APIS = ["api.search.brave.com", "api.tavily.com", "html.duckduckgo.com",
# name of the group -> hosts, per profile
PROFILES: dict[str, dict[str, list[str]]] = {
- # git and package registries: enough to clone, install and push.
- "strict": {"code-hosts": CODE_HOSTS, "package-registries": PACKAGE_REGISTRIES},
- # plus the search APIs.
+ # git, the package registries and the search APIs: enough to clone, install, push and search.
"standard": {"code-hosts": CODE_HOSTS, "package-registries": PACKAGE_REGISTRIES, "search-apis": SEARCH_APIS},
# any host: no proxy, no list. Files are still confined.
"open": {},
}
OPEN = "open"
-DEFAULT_PROFILE = "strict"
+DEFAULT_PROFILE = "standard"
+ALIASES = {"strict": "standard"}
def default_profile(platform: str = sys.platform) -> str:
- """The profile a machine uses until it chooses one: `open` on Windows, `strict` elsewhere."""
+ """The profile a machine uses until it chooses one: `open` on Windows, `standard` elsewhere."""
return OPEN if platform == "win32" else DEFAULT_PROFILE
@@ -37,10 +40,41 @@ def is_open(profile: str) -> bool:
def check(profile: str) -> str:
+ """The profile's name, with an old name mapped to its current one."""
+ profile = ALIASES.get(profile, profile)
if profile not in PROFILES:
raise ValueError(f"unknown network profile {profile!r} (known: {', '.join(sorted(PROFILES))})")
return profile
+def clean_host(item: str) -> str:
+ """One entry of a machine's own host list as "host:port": a bare host means port 443,
+ `*.example.com` any subdomain. Raises ValueError for anything else."""
+ text = str(item or "").strip().lower().rstrip(".")
+ if "://" in text:
+ text = text.split("://", 1)[1].split("/", 1)[0]
+ host, sep, port = text.rpartition(":")
+ if not sep:
+ host, port = text, "443"
+ name = host[2:] if host.startswith("*.") else host
+ labels = name.split(".")
+ if not port.isdigit() or not 0 < int(port) < 65536 or len(labels) < 2 or not all(l and all(c.isalnum() or c == "-" for c in l) for l in labels):
+ raise ValueError(f"not a host name: {item!r} (for example api.example.com:443)")
+ return f"{host}:{int(port)}"
+
+
+def clean_hosts(items) -> list[str]:
+ """A machine's own host list, cleaned and without repeats; bad entries are dropped."""
+ out: list[str] = []
+ for item in items or []:
+ try:
+ host = clean_host(item)
+ except ValueError:
+ continue
+ if host not in out:
+ out.append(host)
+ return out
+
+
def hosts(profile: str) -> list[str]:
return [h for group in PROFILES[check(profile)].values() for h in group]
diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.py
index bed71e55..0e4d27c4 100644
--- a/coworker/sandbox/providers/openshell.py
+++ b/coworker/sandbox/providers/openshell.py
@@ -214,14 +214,17 @@ class OpenShellProvider:
image: Optional[str] = None,
label: str = "",
credentials: Sequence[creds.Grant] = (),
+ extra_hosts: Sequence[str] = (),
) -> None:
"""`roots`: [{"path", "writable"}], primary first. `label`: who this sandbox is for
- (session and agent), stored on the sandbox so leftovers can be found."""
+ (session and agent), stored on the sandbox so leftovers can be found. `extra_hosts`:
+ the machine's own additions to the network list ("host:port")."""
if not roots:
raise ValueError("an OpenShell sandbox needs at least one folder")
self.roots = [{"path": str(Path(r["path"]).expanduser().resolve()), "writable": bool(r.get("writable"))} for r in roots]
self.cwd = str(Path(cwd).expanduser().resolve()) if cwd else self.roots[0]["path"]
- self.profile = profile
+ self.profile = policy.network_profiles.check(profile)
+ self.extra_hosts = list(extra_hosts)
self.image = image or sandbox_image()
# A label value may hold letters, digits, '-', '_' and '.', and at most 63 characters.
self.label = "".join(c if c.isalnum() or c in "-_." else "-" for c in label)[:63].strip("-_.")
@@ -268,7 +271,7 @@ class OpenShellProvider:
# git's settings, and HOME stays the runtime folder.
self.copied = creds.copy_in(self.grants, self._tmp) if self.grants else None
home = self.copied.home if self.copied is not None else None
- extra_hosts = self.copied.hosts if self.copied is not None else []
+ extra_hosts = sorted({*self.extra_hosts, *(self.copied.hosts if self.copied is not None else [])})
policy_file = Path(self._tmp) / "policy.yaml"
policy_file.write_text(yaml.safe_dump(policy.render(self.roots, profile=self.profile, uid=uid, gid=gid, home=home, extra_hosts=extra_hosts), sort_keys=False), encoding="utf-8")
driver_config = json.dumps(policy.mounts(self.roots, str(self._runner.parent), home))
diff --git a/coworker/sandbox/providers/openshell_policy.py b/coworker/sandbox/providers/openshell_policy.py
index d4f91e3f..abb7e86a 100644
--- a/coworker/sandbox/providers/openshell_policy.py
+++ b/coworker/sandbox/providers/openshell_policy.py
@@ -66,8 +66,7 @@ def render(
"""`roots`: [{"path": absolute path, "writable": bool}], primary first. `home`: the
sandbox's private home folder with the copied credentials (section 11b), read-write.
`extra_hosts`: "host:port" entries the grants need; `*.example.com` is a wildcard."""
- if profile not in PROFILES:
- raise ValueError(f"unknown network profile {profile!r} (known: {', '.join(sorted(PROFILES))})")
+ profile = network_profiles.check(profile)
read_write = [RUNTIME_DIR, "/dev/null", "/dev/pts", *([home] if home else []), *[str(r["path"]) for r in roots if r.get("writable")]]
read_only = [*_SYSTEM_READ_ONLY, *_IMAGE_TOOLS_READ_ONLY, RUNNER_MOUNT, *[str(r["path"]) for r in roots if not r.get("writable")]]
policy: dict[str, Any] = {
diff --git a/coworker/sandbox/providers/seatbelt.py b/coworker/sandbox/providers/seatbelt.py
index 8e0a8840..40ca25c8 100644
--- a/coworker/sandbox/providers/seatbelt.py
+++ b/coworker/sandbox/providers/seatbelt.py
@@ -92,8 +92,11 @@ class SeatbeltProvider:
runner_path: Optional[Path] = None,
relay_silence_seconds: Optional[float] = None,
credentials: Sequence[creds.Grant] = (),
+ extra_hosts: Sequence[str] = (),
) -> None:
- """`credentials`: the grants (credentials.granted) to copy into the sandbox."""
+ """`credentials`: the grants (credentials.granted) to copy into the sandbox.
+ `extra_hosts`: the machine's own additions to the network list ("host:port")."""
+ self.extra_hosts = list(extra_hosts)
self.roots = [{"path": seatbelt_profile.real(r["path"]), "writable": bool(r.get("writable"))} for r in roots]
self.grants = list(credentials)
self.copied: Optional[creds.CopiedCredentials] = None
@@ -161,8 +164,8 @@ class SeatbeltProvider:
preflight()
os.makedirs(os.path.join(self._dir, "tmp", "cache"), exist_ok=True)
if self.network and not network_profiles.is_open(self.profile):
- hosts = sorted({h for g in self.grants for h in g.hosts})
- # A session with grants gets its own proxy, because its allow list is its own.
+ hosts = sorted({*self.extra_hosts, *(h for g in self.grants for h in g.hosts)})
+ # A session with grants or added hosts gets its own proxy: its allow list is its own.
self._proxy = netproxy.AllowListProxy(self.profile, extra_hosts=hosts) if hosts else netproxy.shared(self.profile)
else:
self._proxy = None # `open`: the profile lets everything out, nothing to route
diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.py
index f686ec2a..a755a523 100644
--- a/coworker/sandbox/providers/windows.py
+++ b/coworker/sandbox/providers/windows.py
@@ -88,9 +88,12 @@ class WindowsProvider:
relay_silence_seconds: Optional[float] = None,
credentials: Sequence[creds.Grant] = (),
tool_dirs: Sequence[str] = (),
+ extra_hosts: Sequence[str] = (),
) -> None:
"""`credentials`: the grants (credentials.granted) to copy into the sandbox.
- `tool_dirs`: developer tool folders under the profile the account may read."""
+ `tool_dirs`: developer tool folders under the profile the account may read.
+ `extra_hosts`: the machine's own additions to the network list ("host:port")."""
+ self.extra_hosts = list(extra_hosts)
self.roots = _clean_roots(roots)
self.grants = list(credentials)
self.tool_dirs = [os.path.realpath(p) for p in tool_dirs]
@@ -152,7 +155,7 @@ class WindowsProvider:
preflight()
from .. import winsec
- hosts = sorted({h for g in self.grants for h in g.hosts})
+ hosts = sorted({*self.extra_hosts, *(h for g in self.grants for h in g.hosts)})
if self.network and not self.open_network:
self._proxy = netproxy.AllowListProxy(self.profile, extra_hosts=hosts) if hosts else netproxy.shared(self.profile)
for entry in self._wanted_entries():
diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.py
index a9a9f59b..78321584 100644
--- a/coworker/sandbox/settings.py
+++ b/coworker/sandbox/settings.py
@@ -78,16 +78,33 @@ def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:
"refused": refused,
"providers": providers,
"windows_setup": _windows_setup_info(),
- "network_profile": (cfg.sandbox_network_profile or network_profiles.default_profile()),
+ "network_profile": _profile_for_display(cfg.sandbox_network_profile),
"network_profiles": [
{"name": name, "hosts": network_profiles.hosts(name)} for name in network_profiles.PROFILES
],
- "credentials": _for_display(credentials.entries(cfg.sandbox_credentials)),
+ "network_extra_hosts": network_profiles.clean_hosts(cfg.sandbox_network_extra_hosts),
+ "credentials": _for_display(credentials.listed(cfg.sandbox_credentials)),
+ "credential_presets": _presets(cfg.sandbox_credentials),
"toolchains": toolchains.for_display(cfg.sandbox_toolchains),
"config_path": str(app_config.global_config_path()),
}
+def _profile_for_display(configured: Optional[str]) -> str:
+ """The machine's profile by its current name (an old `strict` shows as `standard`)."""
+ try:
+ return network_profiles.check((configured or "").strip().lower() or network_profiles.default_profile())
+ except ValueError:
+ return str(configured)
+
+
+def _presets(configured: Optional[list]) -> list[dict[str, Any]]:
+ """The "A CLI's login" picker: the shipped entries not yet added, each saying whether
+ its file or folder is on this machine (`kind` empty when it is not)."""
+ added = {e["name"] for e in credentials.listed(configured)}
+ return [row for row in _for_display([dict(e) for e in credentials.DEFAULT_ENTRIES]) if row["name"] not in added]
+
+
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":
@@ -198,10 +215,23 @@ def update(body: dict[str, Any]) -> dict[str, Any]:
if "network_profile" in body:
profile = str(body.get("network_profile") or "").strip().lower()
try:
- network_profiles.check(profile)
+ profile = network_profiles.check(profile)
except ValueError as exc:
return {"ok": False, "error": str(exc)}
app_config.set_global_value("sandbox_network_profile", profile)
+ if "network_extra_hosts" in body:
+ items = body.get("network_extra_hosts")
+ if not isinstance(items, list):
+ return {"ok": False, "error": "network_extra_hosts must be a list"}
+ added: list[str] = []
+ for item in items:
+ try:
+ host = network_profiles.clean_host(str(item))
+ except ValueError as exc:
+ return {"ok": False, "error": str(exc)}
+ if host not in added:
+ added.append(host)
+ app_config.set_global_list("sandbox_network_extra_hosts", added)
if "credentials" in body:
rows = body.get("credentials")
if not isinstance(rows, list):
@@ -228,17 +258,13 @@ def update(body: dict[str, Any]) -> dict[str, Any]:
row["hosts"] = [h.strip() for h in hosts]
cleaned.append(row)
# Keep only what differs from the shipped entry, so the file stays small and the
- # shipped defaults can still improve underneath.
+ # shipped defaults can still improve underneath. A shipped entry with nothing
+ # changed keeps its name: being in the file is what lists it (UX-053 v5).
shipped = {e["name"]: e for e in credentials.DEFAULT_ENTRIES}
slim: list[dict[str, Any]] = []
for row in cleaned:
base = shipped.get(row["name"])
- if base is None:
- slim.append(row)
- continue
- diff = {k: v for k, v in row.items() if k == "name" or base.get(k) != v}
- if len(diff) > 1:
- slim.append(diff)
+ slim.append(row if base is None else {k: v for k, v in row.items() if k == "name" or base.get(k) != v})
app_config.set_global_tables("sandbox_credentials", slim)
if "toolchains" in body:
rows = body.get("toolchains")
diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.py
index 7b83c684..e6e12a84 100644
--- a/coworker/sandbox/setup_cmd.py
+++ b/coworker/sandbox/setup_cmd.py
@@ -84,7 +84,14 @@ class Step:
def _run(argv: list[str], timeout: float = 600) -> subprocess.CompletedProcess:
- return subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout)
+ """A command that hangs past `timeout` (`docker info` does while Docker Desktop is
+ installed but not running) or cannot start counts as failed, never as an error."""
+ try:
+ return subprocess.run(argv, stdin=subprocess.DEVNULL, capture_output=True, text=True, timeout=timeout)
+ except subprocess.TimeoutExpired:
+ return subprocess.CompletedProcess(argv, 124, "", f"timed out after {timeout:g} s")
+ except OSError as exc:
+ return subprocess.CompletedProcess(argv, 127, "", str(exc))
def _openshell_home() -> Path:
@@ -166,7 +173,7 @@ def steps() -> list[Step]:
docker_ok = bool(docker) and _run(["docker", "info", "--format", "{{.ServerVersion}}"], 30).returncode == 0
out.append(Step("docker", ROWS["docker"], docker_ok, "" if docker_ok else "install Docker, then add this user to the `docker` group and log in again", docs="" if docker_ok else DOCKER_INSTALL_URL))
exe = shutil.which("openshell")
- version = _run([exe, "--version"], 15).stdout.strip().split()[-1] if exe else ""
+ version = (_run([exe, "--version"], 15).stdout.split() or [""])[-1] if exe else ""
openshell_ok = version == PINNED_VERSION
# The app installs it when it can run as an administrator without a password (or
# needs none, on a Mac); otherwise the row carries the one command to run.
diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.py
index 713eba50..5cef561e 100644
--- a/coworker/sandbox/workspace.py
+++ b/coworker/sandbox/workspace.py
@@ -218,10 +218,12 @@ def open_workspace(
credentials: Optional[list] = None,
network_profile: Optional[str] = None,
toolchains: Optional[list] = None,
+ extra_hosts: Optional[list] = None,
) -> Workspace:
"""The session's workspace for the configured provider. `credentials`: the machine's
`sandbox_credentials` setting; the enabled entries are copied into the sandbox
(design doc, section 11b). Ignored in `direct` mode, where nothing is hidden anyway. `direct` unless told otherwise.
+ `extra_hosts`: the machine's `sandbox_network_extra_hosts`, joined to the network list.
`toolchains`: the machine's `sandbox_toolchains` setting; the switched-on folders that
exist are readable inside (Seatbelt, Windows full mode).
`roots`: the session's RootDir list (primary first); without it the workspace folder is
@@ -239,9 +241,10 @@ def open_workspace(
from .credentials import granted
grants = granted(credentials)
- from .network_profiles import check, default_profile
+ from .network_profiles import check, clean_hosts, default_profile
profile = check((network_profile or "").strip().lower() or default_profile())
+ added = clean_hosts(extra_hosts)
from . import toolchains as toolchain_list
tool_dirs = toolchain_list.granted(toolchains)
@@ -250,7 +253,7 @@ def open_workspace(
from .registry import SandboxRegistry
return RunnerWorkspace(
- SeatbeltProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile, tool_dirs=tool_dirs),
+ SeatbeltProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile, tool_dirs=tool_dirs, extra_hosts=added),
cwd=cwd,
registry=SandboxRegistry(),
session_id=session_id,
@@ -263,7 +266,7 @@ def open_workspace(
label = "-".join(part for part in (session_id[:24], agent[:24]) if part)
return RunnerWorkspace(
- OpenShellProvider(roots=listed, cwd=str(cwd), label=label, credentials=grants, profile=profile),
+ OpenShellProvider(roots=listed, cwd=str(cwd), label=label, credentials=grants, profile=profile, extra_hosts=added),
cwd=cwd,
registry=SandboxRegistry(),
session_id=session_id,
@@ -275,7 +278,7 @@ def open_workspace(
from .registry import SandboxRegistry
return RunnerWorkspace(
- WindowsProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile, tool_dirs=tool_dirs),
+ WindowsProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile, tool_dirs=tool_dirs, extra_hosts=added),
cwd=cwd,
registry=SandboxRegistry(),
session_id=session_id,
diff --git a/docs/config.example.toml b/docs/config.example.toml
index 15fcea64..672b871c 100644
--- a/docs/config.example.toml
+++ b/docs/config.example.toml
@@ -36,21 +36,25 @@ port = 8765
# the default), "openshell" (one NVIDIA OpenShell container per agent) or "seatbelt"
# (the sandbox built into macOS). See docs/openshell.md and docs/macos-sandbox.md.
# sandbox_provider = "openshell"
-# Network allow list inside a sandbox: "strict" (code hosts and package registries),
-# "standard" (plus the search APIs) or "open" (any host; the files are still confined).
-# The default is "strict", or "open" on Windows.
-# sandbox_network_profile = "strict"
-# Credentials an agent may be given, copied into the sandbox for the session and deleted
-# with it. All off unless enabled here or in Settings ▸ Sandbox. An entry is a single
-# file or a whole folder (the path decides), labelled "credential" or "configuration".
+# Network inside a sandbox: "standard" (code hosts, package registries and the search
+# APIs) or "open" (any host; the files are still confined). The default is "standard", or
+# "open" on Windows. "strict" is an older name for "standard".
+# sandbox_network_profile = "standard"
+# Hosts of your own added to "standard" (host:port; a bare host means 443).
+# sandbox_network_extra_hosts = ["registry.acme.dev:443"]
+# Config and keys exposed to agents, copied into the sandbox for the session and deleted
+# with it. Only the entries named here are listed in Settings ▸ Sandbox; the shipped ones
+# (ssh, gh, aws, aws-credentials, kube, npm, docker, gcloud, terraform) are added by name.
+# An entry is a single file or a whole folder (the path decides), labelled "credential"
+# or "configuration".
# [[sandbox_credentials]]
# name = "ssh"
# enabled = true
# [[sandbox_credentials]]
-# name = "aws-keys"
-# path = "~/.aws/credentials"
+# name = "acme-token"
+# path = "~/.config/acme/token"
# label = "credential"
-# hosts = ["*.amazonaws.com:443"]
+# hosts = ["api.acme.dev:443"]
# enabled = true
# Developer tool folders under your home folder a sandbox may read (never write). The
# shipped list per platform is in Settings ▸ Sandbox; an entry here switches one off or
diff --git a/docs/macos-sandbox.md b/docs/macos-sandbox.md
index 5bd95937..06b39c82 100644
--- a/docs/macos-sandbox.md
+++ b/docs/macos-sandbox.md
@@ -31,7 +31,8 @@ Settings ▸ Sandbox ▸ "macOS sandbox", or in `config.toml`:
```toml
sandbox_provider = "seatbelt" # or "direct": commands run in the OpenWorker process
-sandbox_network_profile = "strict" # or "standard", or "open" (any host; files still confined)
+sandbox_network_profile = "standard" # or "open" (any host; files still confined)
+sandbox_network_extra_hosts = ["registry.acme.dev:443"] # optional, your own additions
```
The setting is per machine; a project's own config cannot change it.
@@ -60,30 +61,40 @@ follow the proxy variables; a program that ignores them has no network at all.
## The network allow list
-Three profiles, shared with the OpenShell and Windows sandboxes:
+Two choices, shared with the other sandboxes:
-- **strict** (default): GitHub, GitLab, and the package registries — PyPI, npm, crates.io,
- the Go proxy.
-- **standard**: strict plus the search APIs (Brave, Tavily, DuckDuckGo).
-- **open**: any host, no proxy. The files are still the wall.
+- **Package registries and search** (`standard`, the default): GitHub, GitLab, the package
+ registries — PyPI, npm, crates.io, the Go proxy — and the search APIs (Brave, Tavily,
+ DuckDuckGo). **Customize…** adds hosts of your own; the shipped ones stay.
+- **Allow everything** (`open`): any host, no proxy. The files are still the wall.
-Credentials shared on purpose (below) add the hosts their tools need.
+`strict`, the list without the search APIs, was folded into `standard`; a machine set to it
+now uses `standard`. A credential entry (below) adds the hosts its tool needs.
## Sharing a credential on purpose
By default the sandbox has none of your logins, which also means `git push` over SSH has
-nothing to push with. Settings ▸ Sandbox lists files you can share, all off by default:
-
-| Entry | Copied from | Lets the agent | Hosts added to the allow list |
-|---|---|---|---|
-| `ssh` | `~/.ssh` | push and pull over SSH, and log in to servers, as you | `github.com:22`, `gitlab.com:22` |
-| `gh` | `~/.config/gh` | use `gh` as you: pull requests, issues, releases | `api.github.com:443`, `github.com:443` |
-| `aws` | `~/.aws/config` | use `aws` with your profiles; `~/.aws/credentials` stays out unless you add it | `*.amazonaws.com:443` |
-| `kube` | `~/.kube/config` | use `kubectl` with your clusters | the servers named in the kubeconfig |
-
-An entry is a single file or a whole folder, your choice; each is labelled *credential* or
-*configuration*. Settings ▸ Sandbox shows them once the sandbox is on: one switch first,
-then the type, then the type's own options.
+nothing to push with. Settings ▸ Sandbox ▸ **Explicit config and keys exposed to Agent**
+lists only what you added, each with a switch; nothing is copied until you add it.
+**Add… ▸ A CLI's login** offers these, marked found or not found on this machine:
+
+| Entry | Copied from | What it is | Lets the agent | Hosts added to the allow list |
+|---|---|---|---|---|
+| SSH keys | `~/.ssh` | folder, credential | push and pull over SSH, and log in to servers, as you | `github.com:22`, `gitlab.com:22` |
+| GitHub CLI | `~/.config/gh` | folder, credential | pull requests, issues and releases as you | `api.github.com:443`, `github.com:443` |
+| AWS profiles | `~/.aws/config` | file, configuration | regions and profile names, no keys | `*.amazonaws.com:443` |
+| AWS credentials | `~/.aws/credentials` | file, credential | your access keys | `*.amazonaws.com:443` |
+| kubectl | `~/.kube/config` | file, credential | your clusters | the servers named in the kubeconfig |
+| npm | `~/.npmrc` | file, credential | install and publish private packages | `registry.npmjs.org:443` |
+| Docker registries | `~/.docker/config.json` | file, credential | push and pull images with the logins saved in the file (not those kept by a credential helper) | Docker Hub, `ghcr.io` |
+| gcloud | `~/.config/gcloud` | folder, credential | your Google Cloud accounts and projects | `*.googleapis.com:443`, `accounts.google.com:443` |
+| Terraform Cloud | `~/.terraform.d/credentials.tfrc.json` | file, credential | runs and state in Terraform Cloud as you | `app.terraform.io:443`, `registry.terraform.io:443`, `releases.hashicorp.com:443` |
+
+Each one also sets the variable its tool reads to find the copy (`GH_CONFIG_DIR`,
+`AWS_CONFIG_FILE`, `AWS_SHARED_CREDENTIALS_FILE`, `KUBECONFIG`, `NPM_CONFIG_USERCONFIG`,
+`DOCKER_CONFIG`, `CLOUDSDK_CONFIG`). **Add… ▸ A file or folder** adds anything else under
+your home folder: a single file or a whole folder, labelled *credential* (a secret inside)
+or *configuration* (host names, profiles, options), with the hosts its tool needs.
An enabled entry is **copied** into the sandbox's private home when the sandbox starts,
owner-only, and deleted with the sandbox; the real files are never opened for writing.
@@ -121,7 +132,7 @@ itself, outside every sandbox, with their own tokens.
(macOS does not nest them). `openworker machine sandbox status` says why.
- **A tool cannot be found inside the sandbox** — it lives somewhere under your home folder
that is not on the toolchain list.
-- **A host is refused** — it is not on the profile; switch to `standard` if it is a search
- API, or share the credential entry whose hosts include it.
+- **A host is refused** — it is not on the list; add it with **Customize…**, or add the
+ credential entry whose hosts include it.
- **`git push` says permission denied inside the sandbox** — no credential is shared.
Switch the `ssh` (or `gh`) entry on in Settings ▸ Sandbox.
diff --git a/docs/openshell.md b/docs/openshell.md
index d13e0d4a..8fd1311c 100644
--- a/docs/openshell.md
+++ b/docs/openshell.md
@@ -78,8 +78,8 @@ OpenShell, and downloads the base image sandboxes are built from.
The base image is about 5 GB and is downloaded once. Until it is on the machine, Settings ▸
Sandbox shows OpenShell as **needs download** and a session is refused with the same
-message, rather than hanging on the download. `setup` and the page's **Set up sandbox**
-download it with Docker's own progress; the command is also `docker pull` of the image
+message, rather than hanging on the download. `setup` and the **Set up** button on the
+OpenShell row download it with Docker's own progress; the command is also `docker pull` of the image
named in the refusal.
Settings ▸ Sandbox does the same from the app: one switch, **Run agents in a sandbox**,
@@ -101,7 +101,8 @@ The setting is per machine, in Settings ▸ Sandbox or in `config.toml`:
```toml
sandbox_provider = "openshell" # or "direct": commands run in the OpenWorker process
-sandbox_network_profile = "strict" # or "standard", or "open" (any host; files still confined)
+sandbox_network_profile = "standard" # or "open" (any host; files still confined)
+sandbox_network_extra_hosts = ["registry.acme.dev:443"] # optional, your own additions
```
A project's own config cannot change it. When a machine is set to OpenShell and OpenShell
@@ -126,30 +127,42 @@ the agent is told.
## The network allow list
-Two profiles:
+Two choices, shared with the other sandboxes:
-- **strict** (default): GitHub, GitLab, and the package registries — PyPI, npm, crates.io,
- the Go proxy.
-- **standard**: strict plus the search APIs (Brave, Tavily, DuckDuckGo).
-- **open**: any host, no allow list. The files are still the wall.
+- **Package registries and search** (`standard`, the default): GitHub, GitLab, the package
+ registries — PyPI, npm, crates.io, the Go proxy — and the search APIs (Brave, Tavily,
+ DuckDuckGo). **Customize…** adds hosts of your own; the shipped ones stay.
+- **Allow everything** (`open`): any host, no allow list. The files are still the wall.
-OpenShell enforces the list in the container. Credentials shared on purpose (next
-section) add the hosts their tools need.
+`strict`, the list without the search APIs, was folded into `standard`; a machine set to it
+now uses `standard`. A credential entry (below) adds the hosts its tool needs.
-## Sharing a credential on purpose
-
-By default a sandbox has none of your logins, which also means `git push` over SSH has
-nothing to push with. If you want a tool to work inside as it does outside, you can share
-specific files. Settings ▸ Sandbox lists them, all off by default:
+OpenShell enforces the list in the container.
-| Entry | Copied from | Lets the agent | Hosts added to the allow list |
-|---|---|---|---|
-| `ssh` | `~/.ssh` | push and pull over SSH, and log in to servers, as you | `github.com:22`, `gitlab.com:22` |
-| `gh` | `~/.config/gh` | use `gh` as you: pull requests, issues, releases | `api.github.com:443`, `github.com:443` |
-| `aws` | `~/.aws` | use `aws` with your profiles | `*.amazonaws.com:443` |
-| `kube` | `~/.kube` | use `kubectl` with your clusters | the servers named in the kubeconfig |
+## Sharing a credential on purpose
-You can add your own entries (a name, a path under your home folder, the hosts it needs).
+By default the sandbox has none of your logins, which also means `git push` over SSH has
+nothing to push with. Settings ▸ Sandbox ▸ **Explicit config and keys exposed to Agent**
+lists only what you added, each with a switch; nothing is copied until you add it.
+**Add… ▸ A CLI's login** offers these, marked found or not found on this machine:
+
+| Entry | Copied from | What it is | Lets the agent | Hosts added to the allow list |
+|---|---|---|---|---|
+| SSH keys | `~/.ssh` | folder, credential | push and pull over SSH, and log in to servers, as you | `github.com:22`, `gitlab.com:22` |
+| GitHub CLI | `~/.config/gh` | folder, credential | pull requests, issues and releases as you | `api.github.com:443`, `github.com:443` |
+| AWS profiles | `~/.aws/config` | file, configuration | regions and profile names, no keys | `*.amazonaws.com:443` |
+| AWS credentials | `~/.aws/credentials` | file, credential | your access keys | `*.amazonaws.com:443` |
+| kubectl | `~/.kube/config` | file, credential | your clusters | the servers named in the kubeconfig |
+| npm | `~/.npmrc` | file, credential | install and publish private packages | `registry.npmjs.org:443` |
+| Docker registries | `~/.docker/config.json` | file, credential | push and pull images with the logins saved in the file (not those kept by a credential helper) | Docker Hub, `ghcr.io` |
+| gcloud | `~/.config/gcloud` | folder, credential | your Google Cloud accounts and projects | `*.googleapis.com:443`, `accounts.google.com:443` |
+| Terraform Cloud | `~/.terraform.d/credentials.tfrc.json` | file, credential | runs and state in Terraform Cloud as you | `app.terraform.io:443`, `registry.terraform.io:443`, `releases.hashicorp.com:443` |
+
+Each one also sets the variable its tool reads to find the copy (`GH_CONFIG_DIR`,
+`AWS_CONFIG_FILE`, `AWS_SHARED_CREDENTIALS_FILE`, `KUBECONFIG`, `NPM_CONFIG_USERCONFIG`,
+`DOCKER_CONFIG`, `CLOUDSDK_CONFIG`). **Add… ▸ A file or folder** adds anything else under
+your home folder: a single file or a whole folder, labelled *credential* (a secret inside)
+or *configuration* (host names, profiles, options), with the hosts its tool needs.
An enabled entry is **copied** into a private home that is mounted into the sandbox when
it starts, owner-only, and deleted with the sandbox; the real files are never opened for
@@ -185,7 +198,7 @@ enabled = true
- **"The sandbox base image is not downloaded yet"** — the one-time 5 GB download has
not happened. Run `openworker machine sandbox setup` and accept the download, or run the
`docker pull` command from the message; then start the session again.
-- **A host is refused** — it is not on the profile; switch to `standard` if it is a search
- API, or share the credential entry whose hosts include it.
+- **A host is refused** — it is not on the list; add it with **Customize…**, or add the
+ credential entry whose hosts include it.
- **`git push` says permission denied inside the sandbox** — no credential is shared.
Switch the `ssh` (or `gh`) entry on in Settings ▸ Sandbox.
diff --git a/docs/windows-sandbox.md b/docs/windows-sandbox.md
index ac07658b..96396e3b 100644
--- a/docs/windows-sandbox.md
+++ b/docs/windows-sandbox.md
@@ -60,19 +60,20 @@ A few things are true by design:
## Turn it on
Settings ▸ Sandbox has one switch, "Run agents in a sandbox". Turning it on shows the
-sandbox types this PC can use; choosing "Windows sandbox" shows what the one-time setup
-changes and runs it on one administrator prompt. Once the type is ready its options
-appear: the network mode, the files an agent may be given, and the tools from your profile
-the sandbox may read. In `config.toml`:
+sandbox types this PC can use. Until the one-time setup has run, "Windows sandbox" looks
+disabled with a **Set up** button, which shows what setup changes and runs it on one
+administrator prompt. Once the type is chosen its options appear: the network, the config
+and keys exposed to agents, and the tools shown to agents with read-only access. In `config.toml`:
```toml
sandbox_provider = "windows" # or "direct": commands run in the OpenWorker process
-sandbox_network_profile = "open" # the Windows default; or "strict", "standard"
+sandbox_network_profile = "open" # the Windows default; or "standard"
+sandbox_network_extra_hosts = ["registry.acme.dev:443"] # optional, for "standard"
```
The setting is per machine; a project's own config cannot change it.
-Choosing the Windows sandbox is choosing to set it up (the command line form is
+Setting up the Windows sandbox also chooses it (the command line form is
`openworker machine sandbox setup`). Setup ends by opening a throwaway sandbox and proving
the wall from inside; only then does the choice take effect. Until setup has run, the type
cannot be chosen and the switch goes back off. There is no weaker mode. If setup is later
@@ -110,7 +111,7 @@ One elevated PowerShell script, one prompt. It:
│
┌────────────────────────┴────────────────────────┐
│ │
- Open (default) Strict / Standard
+ Allow everything (default) Package registries and search
│ │
▼ ▼
runs as OWSandboxOpenNet runs as OWSandboxClosedNet
@@ -130,14 +131,15 @@ One elevated PowerShell script, one prompt. It:
only listed hosts
```
-- **Open** — any host. Nothing to configure. The files are still the wall. This is the
- default on Windows.
-- **Strict** — GitHub, GitLab and the package registries (PyPI, npm, crates.io, the Go
- proxy), through the proxy. A program that ignores the proxy variables has no network at
- all, because the account's direct traffic is blocked in the kernel.
-- **Standard** — Strict plus the search APIs.
+- **Allow everything** (`open`) — any host. Nothing to configure. The files are still the
+ wall. This is the default on Windows, and the page shows it in amber.
+- **Package registries and search** (`standard`) — GitHub, GitLab, the package registries
+ (PyPI, npm, crates.io, the Go proxy) and the search APIs, through the proxy.
+ **Customize…** adds hosts of your own. A program that ignores the proxy variables has no
+ network at all, because the account's direct traffic is blocked in the kernel.
-Credentials shared on purpose (below) add the hosts their tools need.
+`strict`, the list without the search APIs, was folded into `standard`. A credential entry
+(below) adds the hosts its tool needs.
Choosing a mode never touches the firewall. The rules are written once at setup; OpenWorker
picks the account. In the closed mode a sandbox can still **listen** on a local port (a dev
@@ -180,17 +182,27 @@ Not readable:
## Sharing a credential on purpose
By default the sandbox has none of your logins, which also means `git push` over SSH has
-nothing to push with. Settings ▸ Sandbox lists files you can share, all off by default:
+nothing to push with. Settings ▸ Sandbox ▸ **Explicit config and keys exposed to Agent**
+lists only what you added, each with a switch; nothing is copied until you add it.
+**Add… ▸ A CLI's login** offers these, marked found or not found on this machine:
| Entry | Copied from | What it is | Lets the agent | Hosts added to the allow list |
|---|---|---|---|---|
-| `ssh` | `~/.ssh` | folder, credential | push and pull over SSH, and log in to servers, as you | `github.com:22`, `gitlab.com:22` |
-| `gh` | `~/.config/gh` | folder, credential | use `gh` as you: pull requests, issues, releases | `api.github.com:443`, `github.com:443` |
-| `aws` | `~/.aws/config` | file, configuration | use `aws` with your profiles; `~/.aws/credentials` stays out unless you add it | `*.amazonaws.com:443` |
-| `kube` | `~/.kube/config` | file, credential | use `kubectl` with your clusters | the servers named in the kubeconfig |
-
-An entry is a single file or a whole folder, your choice; you can add either, and each is
-labelled *credential* (a secret inside) or *configuration* (host names, profiles, options).
+| SSH keys | `~/.ssh` | folder, credential | push and pull over SSH, and log in to servers, as you | `github.com:22`, `gitlab.com:22` |
+| GitHub CLI | `~/.config/gh` | folder, credential | pull requests, issues and releases as you | `api.github.com:443`, `github.com:443` |
+| AWS profiles | `~/.aws/config` | file, configuration | regions and profile names, no keys | `*.amazonaws.com:443` |
+| AWS credentials | `~/.aws/credentials` | file, credential | your access keys | `*.amazonaws.com:443` |
+| kubectl | `~/.kube/config` | file, credential | your clusters | the servers named in the kubeconfig |
+| npm | `~/.npmrc` | file, credential | install and publish private packages | `registry.npmjs.org:443` |
+| Docker registries | `~/.docker/config.json` | file, credential | push and pull images with the logins saved in the file (not those kept by a credential helper) | Docker Hub, `ghcr.io` |
+| gcloud | `~/AppData/Roaming/gcloud` | folder, credential | your Google Cloud accounts and projects | `*.googleapis.com:443`, `accounts.google.com:443` |
+| Terraform Cloud | `~/AppData/Roaming/terraform.d/credentials.tfrc.json` | file, credential | runs and state in Terraform Cloud as you | `app.terraform.io:443`, `registry.terraform.io:443`, `releases.hashicorp.com:443` |
+
+Each one also sets the variable its tool reads to find the copy (`GH_CONFIG_DIR`,
+`AWS_CONFIG_FILE`, `AWS_SHARED_CREDENTIALS_FILE`, `KUBECONFIG`, `NPM_CONFIG_USERCONFIG`,
+`DOCKER_CONFIG`, `CLOUDSDK_CONFIG`). **Add… ▸ A file or folder** adds anything else under
+your home folder: a single file or a whole folder, labelled *credential* (a secret inside)
+or *configuration* (host names, profiles, options), with the hosts its tool needs.
A copy is written into the sandbox account's own profile by the runner, so that Windows
OpenSSH accepts the key's permissions, and removed when the runner leaves. In the closed
@@ -225,4 +237,4 @@ expire on their own limit what that is worth.
| Install | one administrator prompt | nothing | OpenShell and Docker |
| Files | session folders; profile invisible except the tool list; outside-profile folders readable | session folders; home invisible except the tool list | session folders; nothing else |
| Network | open (default), or the allow list through the proxy | the allow list through the proxy, or open | the allow list in the policy, or open |
-| Default | open | strict | strict |
+| Default | open | standard | standard |
diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.ts
index 8115f4d9..04053efe 100644
--- a/surfaces/gui/src/api.ts
+++ b/surfaces/gui/src/api.ts
@@ -2125,9 +2125,11 @@ export interface SandboxSettings {
// 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_profile: string; // an old "strict" comes back as "standard"
network_profiles: { name: string; hosts: string[] }[];
- credentials: SandboxCredentialEntry[];
+ network_extra_hosts: string[]; // the machine's own additions, "host:port"
+ credentials: SandboxCredentialEntry[]; // only the entries the user added (UX-053 v5)
+ credential_presets: SandboxCredentialEntry[]; // the "A CLI's login" picker: shipped, not yet added
toolchains: SandboxToolchainEntry[];
config_path: string;
}
@@ -2138,7 +2140,7 @@ export async function getSandboxSettings(machineId?: string | null): Promise<San
}
export async function setSandboxSettings(
- patch: Partial<Pick<SandboxSettings, "provider" | "network_profile" | "credentials" | "toolchains">>,
+ patch: Partial<Pick<SandboxSettings, "provider" | "network_profile" | "network_extra_hosts" | "credentials" | "toolchains">>,
machineId?: string | null,
): Promise<{ ok: boolean; error?: string; rebuilt_sessions?: string[] } & Partial<SandboxSettings>> {
// `rebuilt_sessions`: after a provider change, the sessions whose engine the server
diff --git a/surfaces/gui/src/components/SandboxSection.tsx b/surfaces/gui/src/components/SandboxSection.tsx
index 7b2b6315..ed5c0654 100644
--- a/surfaces/gui/src/components/SandboxSection.tsx
+++ b/surfaces/gui/src/components/SandboxSection.tsx
@@ -1,12 +1,13 @@
-// 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).
+// Settings ▸ Sandbox (UX-051 A, UX-053 v5, OPE-207): one switch first; on reveals the
+// sandbox type; a type that is the machine's choice reveals its options: the network
+// (package registries and search, with the machine's own hosts; or everything), the config
+// and keys copied into sandboxes, and the tool folders agents may read. A type that is not
+// set up yet looks disabled and carries one "Set up" button: the Windows sandbox's opens its
+// one-time elevated setup, OpenShell's opens the guided setup 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 {
@@ -31,53 +32,60 @@ import { chooseFolder } from "../tauri";
import { Toggle } from "./Toggle";
import { PanelHead } from "./IntegrationsView";
+type T = (k: string, o?: Record<string, unknown>) => string;
+
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 BTN_BORDERED = "text-ui px-3 py-2 rounded-lg border border-line bg-paper hover:border-lineStrong shrink-0 disabled:opacity-40";
+const BTN_SMALL = "text-meta px-2.5 py-1 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";
+const FOOT = "flex items-center gap-3.5 pl-6 pr-4 py-3 bg-chrome border-t border-line rounded-b-xl2";
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"
- >
+ <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({
+const KEY_ICON = (
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
+ <circle cx="8" cy="15" r="4" />
+ <path d="M11 12l9-9M17 6l3 3M14 9l2 2" />
+ </svg>
+);
+const TOOL_ICON = (
+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
+ <path d="M14.7 6.3a4 4 0 0 0-5.4 5.4L3 18l3 3 6.3-6.3a4 4 0 0 0 5.4-5.4l-2.4 2.4-2-2z" />
+ </svg>
+);
+
+// A panel that is one line until opened: chevron, icon, title and a one-line summary.
+function Panel({
id,
open,
onToggle,
+ icon,
title,
- desc,
summary,
children,
}: {
id: string;
open: boolean;
onToggle: () => void;
+ icon: React.ReactNode;
title: string;
- desc: string;
- summary: React.ReactNode;
+ summary: string;
children: React.ReactNode;
}) {
return (
- <div className={CARD + " mb-2.5"} data-testid={`sandbox-card-${id}`}>
+ <div className={CARD + " mb-2.5 relative"} 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" : "")}
@@ -86,39 +94,64 @@ function DisclosureCard({
data-testid={`sandbox-card-${id}-toggle`}
>
<Chevron open={open} />
+ <span className={"w-[34px] h-[34px] rounded-[9px] flex items-center justify-center shrink-0 " + (open ? "bg-accentSoft text-accent" : "bg-paper text-muted")}>{icon}</span>
<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 className="block text-meta text-muted" data-testid={`sandbox-card-${id}-summary`}>
+ {summary}
+ </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 }) {
+function Modal({ children, testid, wide }: { children: React.ReactNode; testid: string; wide?: boolean }) {
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">
+ <div className={"absolute left-1/2 top-[10vh] -translate-x-1/2 max-w-[94vw] max-h-[80vh] rounded-xl2 border border-line bg-panel shadow-2xl overflow-auto p-6 " + (wide ? "w-[680px]" : "w-[640px]")}>
{children}
</div>
</div>
);
}
+// The small square before an entry: the tool's own mark for a known CLI, else a file or folder.
+const BADGES: Record<string, [string, string]> = {
+ gh: ["gh", "bg-[#24292f] text-white"],
+ aws: ["aws", "bg-[#232f3e] text-[#ff9900]"],
+ "aws-credentials": ["aws", "bg-[#232f3e] text-[#ff9900]"],
+ kube: ["K8s", "bg-[#326ce5] text-white"],
+ npm: ["npm", "bg-[#cb3837] text-white"],
+ docker: ["dkr", "bg-[#1d63ed] text-white"],
+ gcloud: ["G", "bg-white text-[#4285f4] border border-lineStrong"],
+ terraform: ["tf", "bg-[#7b42bc] text-white"],
+};
+function Badge({ name }: { name: string }) {
+ const known = BADGES[name];
+ if (known) {
+ return <span className={"w-[26px] h-[26px] rounded-[7px] inline-flex items-center justify-center text-[9.5px] font-bold shrink-0 " + known[1]}>{known[0]}</span>;
+ }
+ return (
+ <span className="w-[26px] h-[26px] rounded-[7px] inline-flex items-center justify-center shrink-0 bg-paper text-muted border border-line">
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" aria-hidden="true">
+ <path d="M3 7a2 2 0 0 1 2-2h4l2 2h8a2 2 0 0 1 2 2v9a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2z" />
+ </svg>
+ </span>
+ );
+}
+
const SETUP_CHANGES = ["accounts", "rules", "folder", "record"] as const;
+// "a, b and c", or "a, b, c and 5 more" past `max`.
+function listText(t: T, names: string[], max: number): string {
+ if (names.length <= 1) return names.join("");
+ if (names.length > max) return t("settingsx.sandbox.list_more", { list: names.slice(0, max).join(", "), count: names.length - max });
+ return t("settingsx.sandbox.list_and", { list: names.slice(0, -1).join(", "), last: names[names.length - 1] });
+}
+
export function SandboxSection({ machine, onProviderChanged }: { machine?: Machine | null; onProviderChanged?: (sessionIds: string[]) => void }) {
const { t } = useTranslation();
const mid = machine?.id ?? null;
@@ -128,14 +161,19 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
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 [wantOn, setWantOn] = useState(false); // the switch is on, no type is the choice yet
+ const [openFiles, setOpenFiles] = useState(false);
+ const [openTools, setOpenTools] = useState(false);
+ const [menu, setMenu] = useState(false); // the "Add…" menu of the files panel
+ const [picking, setPicking] = useState(false); // the "A CLI's login" picker
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 [hostsOpen, setHostsOpen] = useState(false);
+ const [addingTool, setAddingTool] = useState(false);
const [toolTitle, setToolTitle] = useState("");
const [toolPath, setToolPath] = useState("~/");
const [setupStage, setSetupStage] = useState<SetupStage | null>(null);
const [setupOutcome, setSetupOutcome] = useState<{ checked?: string; error?: string }>({});
+ const [openshellDialog, setOpenshellDialog] = useState(false);
const [removing, setRemoving] = useState(false);
const [removeBusy, setRemoveBusy] = useState(false);
@@ -147,33 +185,33 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
const res = await setSandboxSettings(patch, mid);
if (!res.ok) {
setError(res.error || "could not save");
- return;
+ return false;
}
setError("");
setCfg(res as SandboxSettings);
if ("provider" in patch) onProviderChanged?.(res.rebuilt_sessions ?? []);
+ return true;
};
- // 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";
+ // OpenShell's checklist, loaded when its setup dialog opens and again after a run.
const loadReadiness = () => {
- if (!cfg || !openshellChosen) return;
setReadiness(null);
getSandboxReadiness(mid)
.then(setReadiness)
- .catch(() => setReadiness({ platform: cfg.platform, supported: false, steps: [], all_ok: false }));
+ .catch(() => setReadiness({ platform: cfg?.platform ?? "", supported: false, steps: [], all_ok: false }));
};
- useEffect(loadReadiness, [mid, openshellChosen, cfg?.platform]); // eslint-disable-line react-hooks/exhaustive-deps
+ useEffect(() => {
+ if (openshellDialog) loadReadiness();
+ }, [openshellDialog, mid]); // 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;
+ if (!cfg || cfg.platform === "win32") return;
getSandboxSetup(mid)
.then((s) => setJob(s.status === "idle" ? null : s))
.catch(() => {});
- }, [mid, openshellChosen]);
+ }, [mid, cfg?.platform]); // eslint-disable-line react-hooks/exhaustive-deps
// 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.
+ // (the job writes the config line last) and say so once.
useEffect(() => {
if (!job || job.status !== "running") return;
const timer = window.setInterval(() => {
@@ -229,32 +267,23 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
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")],
+ openshell: [t("settingsx.sandbox.provider_openshell"), isMac ? t("settingsx.sandbox.provider_openshell_desc_mac") : 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 (OpenShell counts even while its image downloads)
+ const active = chosen !== "direct"; // a type is the machine's choice
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 titleOf = (c: SandboxCredentialEntry) => c.title || shipped(c.name, "title", c.name);
+ const doesOf = (c: SandboxCredentialEntry) => c.does || shipped(c.name, "does");
+ 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 flip = (next: boolean) => {
if (next) {
@@ -265,15 +294,9 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
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 openWindowsSetup = () => {
+ setSetupOutcome({});
+ setSetupStage("ask");
};
const runSetup = async () => {
@@ -308,21 +331,56 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
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 extraHosts = cfg.network_extra_hosts ?? [];
+ const presets = cfg.credential_presets ?? [];
const showTools = cfg.platform !== "linux" && chosen !== "openshell" && Boolean(cfg.toolchains);
const toolsOn = (cfg.toolchains || []).filter((x) => x.enabled);
+ const filesOn = cfg.credentials.filter((c) => c.enabled);
+ const filesSummary = filesOn.length ? t("settingsx.sandbox.files_sum", { list: listText(t, filesOn.map(titleOf), 3) }) : t("settingsx.sandbox.files_sum_none");
+ const toolsSummary = toolsOn.length ? t("settingsx.sandbox.tools_sum", { list: listText(t, toolsOn.map((x) => x.title || x.name), 3) }) : t("settingsx.sandbox.tools_sum_none");
+ const keyNote = isWindows ? t("settingsx.sandbox.credman_note") : isMac ? t("settingsx.sandbox.keychain_note") : t("settingsx.sandbox.files_foot");
+ const addMenu = (
+ <span className="relative">
+ <button className={BTN_SMALL} onClick={() => setMenu(!menu)} aria-expanded={menu} data-testid="sandbox-credential-add">
+ {t("settingsx.sandbox.add_menu")}
+ </button>
+ {menu ? (
+ <>
+ <span className="fixed inset-0 z-10" onClick={() => setMenu(false)} />
+ <span className="absolute right-0 bottom-9 z-20 w-[300px] rounded-xl border border-line bg-panel shadow-xl p-1.5 text-left" role="menu" data-testid="sandbox-add-menu">
+ {(
+ [
+ ["cli", () => setPicking(true)],
+ ["file", () => setEditing("")],
+ ] as const
+ ).map(([k, go]) => (
+ <button
+ key={k}
+ role="menuitem"
+ className="block w-full text-left px-3 py-2 rounded-lg hover:bg-chrome"
+ onClick={() => {
+ setMenu(false);
+ go();
+ }}
+ data-testid={`sandbox-add-${k}`}
+ >
+ <span className="block text-ui font-medium text-ink">{t(`settingsx.sandbox.add_${k}`)}</span>
+ <span className="block text-meta text-muted">{t(`settingsx.sandbox.add_${k}_desc`)}</span>
+ </button>
+ ))}
+ </span>
+ </>
+ ) : null}
+ </span>
+ );
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")}
- />
+ <PanelHead title={t("settingsx.sandbox.title")} sub={machine ? t("settingsx.sandbox.sub_machine", { name: machine.name }) : 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={CARD + " mb-5"}>
<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")} />
@@ -331,258 +389,193 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
<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}
+ {cfg.refused ? <div className="-mt-3 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")}>
+ <div className={CARD + " mb-5 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 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")
- : needsDownload
- ? t("settingsx.sandbox.status_needs_download")
- : p.usable
- ? t("settingsx.sandbox.status_ready")
- : t("settingsx.sandbox.status_unavailable");
+ const os = p.name === "openshell";
+ // Ready to choose: usable, and for Windows set up. Otherwise the row looks
+ // disabled and its one button sets it up, where this machine can.
+ const ready = win ? setupReady && p.usable : p.usable;
+ const canSetUp = win ? !setupReady && Boolean(setup?.can_elevate) : os && !isWindows && !p.usable;
+ const why = ready || canSetUp ? "" : win && setup && !setup.can_elevate ? t("settingsx.sandbox.needs_admin_why", { command: setup.command }) : p.why;
+ const osRunning = os && job?.status === "running";
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) || needsDownload ? "text-warnInk" : isActive || (win ? setupReady : p.usable) ? "text-ok" : "text-faint")}
- data-testid={`sandbox-provider-${p.name}-status`}
- >
- {status}
- </span>
- </label>
+ <div key={p.name} className="flex items-start gap-3 px-4 py-3" data-testid={`sandbox-type-${p.name}`}>
+ <label className={"flex items-start gap-3 flex-1 min-w-0 " + (ready ? "cursor-pointer" : "")}>
+ <input
+ type="radio"
+ name="sandbox-provider"
+ className={"mt-1 " + (ready || isActive ? "" : "opacity-50")}
+ checked={isActive}
+ disabled={!ready && !isActive}
+ onChange={() => void save({ provider: p.name })}
+ data-testid={`sandbox-provider-${p.name}`}
+ />
+ <span className="flex-1 min-w-0">
+ <span className={"block text-ui " + (ready || isActive ? "text-ink" : "text-ink/50")}>{label}</span>
+ <span className={"block text-meta " + (ready || isActive ? "text-muted" : "text-muted/60")}>{desc}</span>
+ {why ? (
+ <span className="block text-meta text-warnInk mt-1" data-testid={`sandbox-provider-${p.name}-why`}>
+ {why}
+ </span>
+ ) : null}
+ {isActive && os && p.state === "needs_download" ? (
+ <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_done")}
+ <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>
+ </label>
+ {canSetUp ? (
+ <button
+ className={BTN_SMALL + " self-center"}
+ onClick={() => (win ? openWindowsSetup() : setOpenshellDialog(true))}
+ data-testid={`sandbox-setup-${p.name}`}
+ >
+ {osRunning ? t("settingsx.sandbox.setup_running") : t("settingsx.sandbox.set_up")}
+ </button>
+ ) : null}
+ </div>
);
})}
</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">
+ <div className={CARD + " mb-5 divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.network")}>
+ {(["standard", "open"] as const).map((name) => (
+ <label key={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}`}
+ checked={cfg.network_profile === name}
+ onChange={() => save({ network_profile: name })}
+ data-testid={`sandbox-network-${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 className="flex-1 min-w-0">
+ <span className={"block text-ui " + (name === "open" ? "text-warnInk" : "text-ink")}>{t(`settingsx.sandbox.profile_${name}`)}</span>
+ <span className="block text-meta text-muted">
+ {t(`settingsx.sandbox.profile_${name}_desc`)}
+ {name === "standard" ? (
+ <>
+ <button
+ type="button"
+ className="ml-1.5 text-accent hover:underline"
+ onClick={(e) => {
+ e.preventDefault();
+ setHostsOpen(true);
+ }}
+ data-testid="sandbox-network-customize"
+ >
+ {t("settingsx.sandbox.customize")}
+ </button>
+ {extraHosts.length ? <span className="text-faint"> · {t("settingsx.sandbox.hosts_added", { count: extraHosts.length })}</span> : null}
+ </>
+ ) : null}
</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")}
+ <Panel id="files" open={openFiles} onToggle={() => setOpenFiles(!openFiles)} icon={KEY_ICON} title={t("settingsx.sandbox.files_panel")} summary={filesSummary}>
+ {cfg.credentials.length ? (
+ <div className="divide-y divide-line">
+ {cfg.credentials.map((c) => (
+ <div key={c.name} className="group flex items-start gap-3 pl-6 pr-4 py-3" data-testid={`sandbox-credential-${c.name}`}>
+ <span className="mt-0.5">
+ <Toggle checked={c.enabled} onChange={(next) => updateCredentials(cfg.credentials.map((x) => (x.name === c.name ? { ...x, enabled: next } : x)))} title={titleOf(c)} />
+ </span>
+ <Badge name={c.name} />
+ <span className="flex-1 min-w-0">
+ <span className="flex items-center flex-wrap gap-2 text-ui text-ink">
+ {titleOf(c)}
+ <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 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 className="block text-meta text-muted">
+ {doesOf(c)}{" "}
+ {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="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 className="text-meta text-muted shrink-0 whitespace-nowrap opacity-0 group-hover:opacity-100 focus-within:opacity-100 transition-opacity">
+ <button className="hover:text-ink" onClick={() => setEditing(c.name)} data-testid={`sandbox-credential-${c.name}-edit`}>
+ {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))} data-testid={`sandbox-credential-${c.name}-remove`}>
+ {t("settingsx.sandbox.remove")}
+ </button>
</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>
+ ))}
+ </div>
+ ) : (
+ <div className="px-6 py-4 text-ui text-muted" data-testid="sandbox-files-empty">
+ {t("settingsx.sandbox.files_empty")}
+ </div>
+ )}
+ <div className={FOOT}>
+ <span className="text-meta text-faint flex-1">{cfg.credentials.length ? keyNote : t("settingsx.sandbox.files_foot")}</span>
+ {addMenu}
</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}
+ </Panel>
{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>
+ <Panel id="tools" open={openTools} onToggle={() => setOpenTools(!openTools)} icon={TOOL_ICON} title={t("settingsx.sandbox.tools_panel")} summary={toolsSummary}>
+ <div className="divide-y divide-line">
+ {cfg.toolchains.map((tc) => (
+ <div key={tc.name} className="flex items-center gap-3 pl-6 pr-4 py-2" data-testid={`sandbox-toolchain-${tc.name}`}>
+ <Toggle checked={tc.enabled} onChange={(next) => updateToolchains(cfg.toolchains.map((x) => (x.name === tc.name ? { ...x, enabled: next } : x)))} title={tc.title || tc.name} />
+ <span className="flex-1 min-w-0 text-ui 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>
+ <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>
{addingTool ? (
- <div className={CARD + " p-4 mt-3"} data-testid="sandbox-toolchain-editor">
+ <div className="pl-6 pr-4 py-3 border-t border-line" 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)} />
@@ -615,17 +608,133 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
updateToolchains([...cfg.toolchains, { name: slug, title: toolTitle || undefined, path: toolPath, enabled: true }]);
}}
>
- {t("settingsx.sandbox.done")}
+ {t("settingsx.sandbox.add_button")}
</button>
</div>
</div>
) : null}
- </>
+ <div className={FOOT}>
+ <span className="text-meta text-faint flex-1">{t("settingsx.sandbox.tools_foot")}</span>
+ <button className={BTN_SMALL} onClick={() => setAddingTool(true)} data-testid="sandbox-toolchain-add">
+ {t("settingsx.sandbox.add_toolchain")}
+ </button>
+ </div>
+ </Panel>
) : null}
- <div className={FIELD_HELP + " mt-4"}>{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div>
+ <div className="text-meta text-faint mt-5">{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div>
</>
) : null}
+ {/* Customize: the machine's own hosts */}
+ {hostsOpen ? (
+ <HostsDialog
+ t={t}
+ hosts={extraHosts}
+ builtin={cfg.network_profiles.find((n) => n.name === "standard")?.hosts ?? []}
+ onCancel={() => setHostsOpen(false)}
+ onSave={async (next) => {
+ if (await save({ network_extra_hosts: next })) setHostsOpen(false);
+ }}
+ error={error}
+ />
+ ) : null}
+
+ {/* Add a CLI's login */}
+ {picking ? (
+ <Modal testid="sandbox-cli-picker" wide>
+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.cli_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.cli_intro")}</p>
+ <div className="rounded-lg border border-line divide-y divide-line">
+ {presets.length ? (
+ [...presets]
+ .sort((a, b) => Number(!a.kind) - Number(!b.kind))
+ .map((p) => (
+ <div key={p.name} className="flex items-center gap-3 px-3 py-2.5" data-testid={`sandbox-preset-${p.name}`} data-found={p.kind ? "yes" : "no"}>
+ <Badge name={p.name} />
+ <span className="flex-1 min-w-0">
+ <span className={"block text-ui font-medium " + (p.kind ? "text-ink" : "text-faint")}>{titleOf(p)}</span>
+ <span className={"block text-meta " + (p.kind ? "text-muted" : "text-faint")}>
+ {p.kind ? `${p.path} · ${doesOf(p).replace(/\.$/, "")}` : isMac ? t("settingsx.sandbox.not_on_mac") : isWindows ? t("settingsx.sandbox.not_on_pc") : t("settingsx.sandbox.credential_missing")}
+ </span>
+ </span>
+ {p.kind ? (
+ <button
+ className={BTN_SMALL}
+ onClick={() => updateCredentials([...cfg.credentials, { name: p.name, enabled: true }])}
+ data-testid={`sandbox-preset-${p.name}-add`}
+ >
+ {t("settingsx.sandbox.add_button")}
+ </button>
+ ) : (
+ <span className="text-meta text-faint">{t("settingsx.sandbox.not_found")}</span>
+ )}
+ </div>
+ ))
+ ) : (
+ <div className="px-3 py-3 text-ui text-muted">{t("settingsx.sandbox.cli_all_added")}</div>
+ )}
+ </div>
+ <div className="flex items-center gap-2 mt-4">
+ <span className="text-meta text-faint">{t("settingsx.sandbox.cli_not_listed")}</span>
+ <span className="flex-1" />
+ <button
+ className={BTN_BORDERED}
+ onClick={() => {
+ setPicking(false);
+ setEditing("");
+ }}
+ >
+ {t("settingsx.sandbox.cli_file_button")}
+ </button>
+ <button
+ className={BTN_ACCENT}
+ onClick={() => {
+ setPicking(false);
+ setOpenFiles(true);
+ }}
+ data-testid="sandbox-cli-done"
+ >
+ {t("settingsx.sandbox.done")}
+ </button>
+ </div>
+ </Modal>
+ ) : null}
+
+ {/* Add or edit a file or folder */}
+ {editing !== null ? (
+ <CredentialEditor
+ entry={editing ? cfg.credentials.find((c) => c.name === editing) ?? null : null}
+ titleOf={titleOf}
+ doesOf={doesOf}
+ onCancel={() => setEditing(null)}
+ onSave={(row) => {
+ const rows = editing ? cfg.credentials.map((x) => (x.name === editing ? row : x)) : [...cfg.credentials, row];
+ setEditing(null);
+ setOpenFiles(true);
+ updateCredentials(rows);
+ }}
+ />
+ ) : null}
+
+ {/* OpenShell's setup dialog */}
+ {openshellDialog ? (
+ <OpenShellDialog
+ t={t}
+ readiness={readiness}
+ job={job}
+ ready={Boolean(cfg.providers.find((p) => p.name === "openshell")?.usable) && chosen === "openshell"}
+ onStart={startJob}
+ onCancel={cancelJob}
+ onCheck={() => {
+ setJob(null);
+ loadReadiness();
+ }}
+ onClose={() => setOpenshellDialog(false)}
+ copy={copy}
+ copied={copied}
+ />
+ ) : null}
+
{/* The Windows setup dialog */}
{setupStage ? (
<Modal testid="sandbox-setup-dialog">
@@ -738,131 +847,251 @@ export function SandboxSection({ machine, onProviderChanged }: { machine?: Machi
);
}
-// 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({
+// "Customize…": the hosts this machine adds to "Package registries and search", which the
+// user adds and removes, above the shipped ones, which are read-only.
+function HostsDialog({
+ t,
+ hosts,
+ builtin,
+ onCancel,
+ onSave,
+ error,
+}: {
+ t: T;
+ hosts: string[];
+ builtin: string[];
+ onCancel: () => void;
+ onSave: (hosts: string[]) => void;
+ error: string;
+}) {
+ const [list, setList] = useState<string[]>(hosts);
+ const [draft, setDraft] = useState("");
+ const [bad, setBad] = useState(false);
+ const add = () => {
+ const host = cleanHost(draft);
+ if (!host) {
+ setBad(true);
+ return;
+ }
+ setBad(false);
+ setDraft("");
+ if (!list.includes(host)) setList([...list, host]);
+ };
+ const rows: string[][] = [];
+ for (let i = 0; i < builtin.length; i += 4) rows.push(builtin.slice(i, i + 4));
+ return (
+ <Modal testid="sandbox-hosts-dialog" wide>
+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.hosts_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.hosts_intro")}</p>
+ <div className="text-label font-medium text-faint mb-1.5">{t("settingsx.sandbox.hosts_yours")}</div>
+ {list.length ? (
+ <div className="rounded-lg border border-line divide-y divide-line mb-2">
+ {list.map((h) => (
+ <div key={h} className="flex items-center gap-2.5 px-3 py-1.5 text-meta font-mono text-ink" data-testid={`sandbox-host-${h}`}>
+ {h}
+ <button className="ml-auto text-meta font-sans text-muted hover:text-ink" onClick={() => setList(list.filter((x) => x !== h))}>
+ {t("settingsx.sandbox.remove")}
+ </button>
+ </div>
+ ))}
+ </div>
+ ) : null}
+ <div className="flex gap-2 mb-1">
+ <input
+ className={INPUT + " font-mono" + (bad ? " border-danger" : "")}
+ value={draft}
+ placeholder={t("settingsx.sandbox.hosts_placeholder")}
+ onChange={(e) => {
+ setDraft(e.target.value);
+ setBad(false);
+ }}
+ onKeyDown={(e) => {
+ if (e.key === "Enter") add();
+ }}
+ data-testid="sandbox-host-input"
+ />
+ <button className={BTN_BORDERED} onClick={add} disabled={!draft.trim()} data-testid="sandbox-host-add">
+ {t("settingsx.sandbox.add_button")}
+ </button>
+ </div>
+ {bad ? <div className="text-meta text-danger mb-1">{t("settingsx.sandbox.hosts_bad")}</div> : null}
+ {error ? <div className="text-meta text-danger mb-1">{error}</div> : null}
+ <div className="text-label font-medium text-faint mt-3.5 mb-1.5">{t("settingsx.sandbox.hosts_builtin")}</div>
+ <div className="rounded-lg border border-line divide-y divide-line">
+ {rows.map((r) => (
+ <div key={r.join()} className="px-3 py-1.5 text-meta font-mono text-muted">
+ {r.join(" · ")}
+ </div>
+ ))}
+ </div>
+ <div className="flex items-center gap-2 mt-4">
+ <span className="text-meta text-faint max-w-[340px]">{t("settingsx.sandbox.hosts_note")}</span>
+ <span className="flex-1" />
+ <button className={BTN_BORDERED} onClick={onCancel}>
+ {t("settingsx.sandbox.cancel")}
+ </button>
+ <button className={BTN_ACCENT} onClick={() => onSave(list)} data-testid="sandbox-hosts-save">
+ {t("settingsx.sandbox.save")}
+ </button>
+ </div>
+ </Modal>
+ );
+}
+
+// The same rule as the server's network_profiles.clean_host: "host:port", 443 when bare.
+export function cleanHost(text: string): string {
+ let s = text.trim().toLowerCase().replace(/\.$/, "");
+ if (s.includes("://")) s = s.split("://", 2)[1].split("/", 1)[0];
+ let host = s;
+ let port = "443";
+ const at = s.lastIndexOf(":");
+ if (at >= 0) {
+ host = s.slice(0, at);
+ port = s.slice(at + 1);
+ }
+ const name = host.startsWith("*.") ? host.slice(2) : host;
+ const labels = name.split(".");
+ if (!/^\d+$/.test(port) || Number(port) < 1 || Number(port) > 65535 || labels.length < 2 || !labels.every((l) => /^[a-z0-9-]+$/.test(l))) return "";
+ return `${host}:${Number(port)}`;
+}
+
+// OpenShell's setup (OPE-207, UX-053 v5): the steps first, then the job's rows with its
+// progress. A command with Copy shows only where the app cannot do the step itself.
+function OpenShellDialog({
t,
readiness,
job,
+ ready,
onStart,
onCancel,
+ onCheck,
+ onClose,
copy,
copied,
}: {
- t: (k: string, o?: Record<string, unknown>) => string;
+ t: T;
readiness: SandboxReadiness | null;
job: SandboxSetupState | null;
+ ready: boolean;
onStart: () => void;
onCancel: () => void;
+ onCheck: () => void;
+ onClose: () => 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 done = job?.status === "done" || (ready && !job);
+ const needsYou = job?.status === "needs_you";
+ const stopped = job?.status === "failed" || job?.status === "cancelled";
const elapsed = (s: number) => (s >= 60 ? `${Math.floor(s / 60)} min ${s % 60} s` : `${s} s`);
+ const [title, intro] = done
+ ? [t("settingsx.sandbox.os_done_title"), t("settingsx.sandbox.os_done_intro")]
+ : running
+ ? [t("settingsx.sandbox.os_running_title"), t("settingsx.sandbox.os_running_intro")]
+ : needsYou
+ ? [t("settingsx.sandbox.os_needs_you_title"), t("settingsx.sandbox.os_needs_you_intro")]
+ : stopped
+ ? [t("settingsx.sandbox.os_stopped_title"), job?.status === "cancelled" ? t("settingsx.sandbox.setup_cancelled") : t("settingsx.sandbox.setup_failed", { error: job?.error })]
+ : [t("settingsx.sandbox.os_title"), t("settingsx.sandbox.os_intro")];
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}` : ""}
+ <Modal testid="sandbox-openshell-dialog">
+ <h3 className="text-heading font-semibold mb-1.5">{title}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed" data-testid={job && job.status !== "idle" ? `sandbox-setup-${job.status}` : undefined}>
+ {intro}
+ </p>
+ {!running && !done && !job ? <div className="text-label font-medium text-faint mb-1.5">{t("settingsx.sandbox.os_steps")}</div> : null}
+ {!readiness && !job ? (
+ <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.readiness_loading")}
+ </div>
+ ) : (
+ <ul className="rounded-lg border border-line divide-y divide-line" data-testid="sandbox-readiness">
+ {rows.map((r) => {
+ const state: SandboxSetupRowState = r.state ?? (r.ok ? "ok" : "pending");
+ const good = state === "ok" || state === "fixed";
+ const showCommand = !good && r.command && (!r.fixable || state === "needs_you" || state === "failed");
+ return (
+ <li key={r.key} className="px-3 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-accent" : state === "pending" ? "text-faint" : "text-warnInk")} aria-hidden>
+ {good ? "✓" : state === "fixing" ? "⟳" : state === "pending" ? "○" : "!"}
+ </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_${!job && state === "pending" ? "todo" : state}`)}</span>
</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%" }}
- />
+ {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>
- <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) })}
+ ) : 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>
- </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">
+ ) : null}
+ {!good && r.hint ? <div className="mt-1 ml-6 text-meta text-muted">{r.hint}</div> : null}
+ {showCommand ? (
+ <div className="mt-1.5 ml-6 flex items-start gap-2 rounded-lg border border-line bg-paper px-2.5 py-1.5" data-testid={`sandbox-readiness-command-${r.key}`}>
<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>
+ ) : 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}`}>
+ {r.key === "docker" ? t("settingsx.sandbox.get_docker") : t("settingsx.sandbox.guide")}
+ </a>
+ ) : null}
+ </li>
+ );
+ })}
+ </ul>
+ )}
+ <div className="flex items-center gap-2 mt-4">
+ <span className="text-meta text-faint max-w-[340px] leading-relaxed">{done ? "" : running ? t("settingsx.sandbox.os_close_note") : t("settingsx.sandbox.setup_never_root")}</span>
+ <span className="flex-1" />
+ {done ? (
+ <button className={BTN_ACCENT} onClick={onClose} data-testid="sandbox-openshell-done">
+ {t("settingsx.sandbox.done")}
+ </button>
+ ) : running ? (
+ <>
+ <button className={BTN_BORDERED} onClick={onCancel} data-testid="sandbox-setup-cancel">
+ {t("settingsx.sandbox.setup_cancel")}
+ </button>
+ <button className={BTN_ACCENT} onClick={onClose}>
+ {t("settingsx.sandbox.close")}
+ </button>
+ </>
+ ) : (
+ <>
+ <button className={BTN_BORDERED} onClick={onClose} data-testid="sandbox-openshell-close">
+ {job ? t("settingsx.sandbox.close") : t("settingsx.sandbox.cancel")}
+ </button>
+ {job ? (
+ <button className={BTN_BORDERED} onClick={onCheck} data-testid="sandbox-setup-check">
+ {t("settingsx.sandbox.setup_again")}
+ </button>
+ ) : null}
+ <button className={BTN_ACCENT} onClick={onStart} disabled={!rows.length} data-testid="sandbox-setup-start">
+ {job ? t("settingsx.sandbox.try_again") : t("settingsx.sandbox.set_up")}
+ </button>
+ </>
+ )}
+ </div>
+ </Modal>
);
}
@@ -874,66 +1103,77 @@ function validPath(path: string): boolean {
// hosts its tool needs, and what it lets the agent do.
export function CredentialEditor({
entry,
+ titleOf,
+ doesOf,
onCancel,
onSave,
}: {
entry: SandboxCredentialEntry | null;
+ titleOf?: (c: SandboxCredentialEntry) => string;
+ doesOf?: (c: SandboxCredentialEntry) => string;
onCancel: () => void;
onSave: (row: SandboxCredentialEntry) => void;
}) {
const { t } = useTranslation();
- const [title, setTitle] = useState(entry?.title ?? "");
- const [name, setName] = useState(entry?.name ?? "");
+ const [title, setTitle] = useState(entry ? (titleOf ? titleOf(entry) : entry.title ?? "") : "");
const [path, setPath] = useState(entry?.path ?? "~/");
const [hosts, setHosts] = useState((entry?.hosts ?? []).join("\n"));
- const [does, setDoes] = useState(entry?.does ?? "");
+ const [does, setDoes] = useState(entry ? (doesOf ? doesOf(entry) : 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 slug = entry?.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>
- ))}
+ <Modal testid="sandbox-credential-editor" wide>
+ <h3 className="text-heading font-semibold mb-1.5">{entry ? t("settingsx.sandbox.file_title_edit") : t("settingsx.sandbox.file_title")}</h3>
+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.file_intro")}</p>
+ <div className="grid gap-3">
+ <label className="block">
+ <span className="block text-meta text-muted mb-1">
+ {t("settingsx.sandbox.field_path")} <span className="text-faint">{t("settingsx.sandbox.field_path_hint")}</span>
+ </span>
+ <span className="flex gap-2">
+ <input className={INPUT + " font-mono"} value={path} onChange={(e) => setPath(e.target.value)} data-testid="sandbox-credential-path" />
+ <button
+ className={BTN_BORDERED}
+ onClick={async (e) => {
+ e.preventDefault();
+ const picked = await chooseFolder();
+ if (picked) setPath(picked);
+ }}
+ >
+ {t("settingsx.sandbox.browse")}
+ </button>
+ </span>
+ </label>
+ <label className="block">
+ <span className="block text-meta text-muted mb-1">{t("settingsx.sandbox.field_title")}</span>
+ <input className={INPUT + " w-full"} value={title} onChange={(e) => setTitle(e.target.value)} placeholder={t("settingsx.sandbox.field_title_example")} data-testid="sandbox-credential-title" />
+ </label>
+ <div>
+ <span className="block text-meta text-muted mb-1">{t("settingsx.sandbox.field_label")}</span>
+ <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 font-medium">{t(`settingsx.sandbox.label_${k}_title`)}</span>
+ <span className="block text-meta text-muted">{t(`settingsx.sandbox.label_${k}_desc`)}</span>
+ </span>
+ </label>
+ ))}
+ </div>
</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)} />
+ <label className="block">
+ <span className="block text-meta text-muted mb-1">{t("settingsx.sandbox.field_hosts")}</span>
+ <textarea className={INPUT + " w-full font-mono"} rows={2} value={hosts} onChange={(e) => setHosts(e.target.value)} placeholder={t("settingsx.sandbox.field_hosts_example")} />
+ </label>
+ <label className="block">
+ <span className="block text-meta text-muted mb-1">{t("settingsx.sandbox.field_does")}</span>
+ <input className={INPUT + " w-full"} value={does} onChange={(e) => setDoes(e.target.value)} placeholder={t("settingsx.sandbox.field_does_example")} />
+ </label>
</div>
- <div className="flex items-center gap-2 mt-3">
- <span className="text-meta text-faint">{t("settingsx.sandbox.editor_note")}</span>
+ <div className="flex items-center gap-2 mt-4">
+ <span className="text-meta text-faint max-w-[340px]">{t("settingsx.sandbox.editor_note")}</span>
<span className="flex-1" />
<button className={BTN_BORDERED} onClick={onCancel}>
{t("settingsx.sandbox.cancel")}
@@ -941,24 +1181,25 @@ export function CredentialEditor({
<button
className={BTN_ACCENT}
disabled={!valid}
+ data-testid="sandbox-credential-save"
onClick={() =>
onSave({
name: slug,
- title: title || undefined,
+ title: title && title !== (entry && titleOf ? titleOf({ ...entry, title: undefined }) : "") ? title : entry?.title,
path,
hosts: hosts
- .split(/\s+/)
- .map((h) => h.trim())
+ .split(/[\s,]+/)
+ .map((h) => cleanHost(h) || h.trim())
.filter(Boolean),
- does: does || undefined,
+ does: does && does !== (entry && doesOf ? doesOf({ ...entry, does: undefined }) : "") ? does : entry?.does,
label,
enabled: entry?.enabled ?? true,
})
}
>
- {t("settingsx.sandbox.done")}
+ {entry ? t("settingsx.sandbox.save") : t("settingsx.sandbox.add_button")}
</button>
</div>
- </div>
+ </Modal>
);
}
diff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
index bbec6b9f..cbadd7ba 100644
--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
@@ -1,8 +1,9 @@
-// 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.
+// Settings ▸ Sandbox (UX-051 A, UX-053 v5, OPE-207): one switch first; on reveals the type;
+// a chosen type reveals its options. The page shows what the machine reports and writes back
+// the changes: provider, network profile and the machine's own hosts, the credential list,
+// the toolchain list. A type that is not set up looks disabled with one "Set up" button: on
+// Windows it opens the setup dialog, which calls the Windows setup route; for OpenShell it
+// opens the dialog with the readiness checklist and the guided setup job.
import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";
import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";
@@ -17,16 +18,20 @@ const base = {
{ name: "openshell", usable: false, why: "OpenShell is not installed" },
],
windows_setup: null as any,
- network_profile: "strict",
+ network_profile: "standard",
network_profiles: [
- { name: "strict", hosts: ["github.com"] },
- { name: "standard", hosts: ["github.com", "api.tavily.com"] },
+ { name: "standard", hosts: ["github.com", "pypi.org", "api.tavily.com"] },
{ name: "open", hosts: [] },
],
+ network_extra_hosts: [] as string[],
credentials: [
- { name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], label: "credential", enabled: false, kind: "folder", shipped: true },
- { name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], label: "credential", enabled: true, kind: "", shipped: true },
- { name: "aws", path: "~/.aws/config", hosts: ["*.amazonaws.com:443"], label: "configuration", enabled: false, kind: "file", shipped: true },
+ { name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], label: "credential", enabled: true, kind: "folder", shipped: true },
+ { name: "aws", path: "~/.aws/config", hosts: ["*.amazonaws.com:443"], label: "configuration", enabled: true, kind: "file", shipped: true },
+ { name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], label: "credential", enabled: false, kind: "", shipped: true },
+ ],
+ credential_presets: [
+ { name: "npm", path: "~/.npmrc", hosts: ["registry.npmjs.org:443"], label: "credential", enabled: false, kind: "file", shipped: true },
+ { name: "gcloud", path: "~/.config/gcloud", hosts: ["*.googleapis.com:443"], label: "credential", enabled: false, kind: "", shipped: true },
],
toolchains: [
{ name: "nvm", title: "nvm (Node versions)", path: "~/.nvm", enabled: true, exists: true, shipped: true },
@@ -54,7 +59,7 @@ let setupState: any = { status: "idle", rows: [], progress: null, error: "", ela
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 runSandboxSetup = vi.fn(async () => ({ ok: true, checked: "the wall held", ...snapshot, provider: "windows", providers: snapshot.providers.map((p: any) => (p.name === "windows" ? { ...p, usable: true, why: "" } : p)), 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) => {
@@ -79,8 +84,15 @@ vi.mock("../api", async (importOriginal) => {
});
import { SettingsView } from "./SettingsView";
+import { cleanHost } from "./SandboxSection";
const stripDisplay = (rows: any[]) => rows.map(({ kind: _k, shipped: _s, ...row }) => row);
+const lastPatch = () => {
+ const calls = setSandboxSettings.mock.calls;
+ return calls[calls.length - 1]?.[0];
+};
+const masterSwitch = () => within(screen.getByTestId("sandbox-section")).getAllByRole("switch")[0];
+const chosenSeatbelt = () => ({ ...base, provider: "seatbelt", effective_provider: "seatbelt" });
describe("Settings ▸ Sandbox", () => {
beforeEach(() => {
@@ -94,61 +106,62 @@ describe("Settings ▸ Sandbox", () => {
});
afterEach(cleanup);
- it("off: one switch and nothing else; on reveals the type card only", async () => {
+ it("off: one switch and one line; on reveals the types, OpenShell disabled with one Set up button", async () => {
render(<SettingsView initialTab="sandbox" onSandboxProviderChanged={onSandboxProviderChanged} />);
await screen.findByTestId("sandbox-section");
- const sw = screen.getByRole("switch");
- expect(sw.getAttribute("aria-checked")).toBe("false");
- expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("off");
+ expect(screen.getByText("Manage environment restrictions for your Agent.")).toBeTruthy();
+ expect(screen.getByText("Agents can only use the folders you open. The rest of your computer stays private.")).toBeTruthy();
+ expect(masterSwitch().getAttribute("aria-checked")).toBe("false");
+ expect(screen.queryByTestId("sandbox-switch-status")).toBeNull(); // the switch is its own cue
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");
+ fireEvent.click(masterSwitch());
+ expect(screen.getByText("Built into macOS.")).toBeTruthy();
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(screen.getByTestId("sandbox-setup-openshell").textContent).toBe("Set up");
+ expect(screen.queryByTestId("sandbox-provider-openshell-why")).toBeNull(); // the button says it all
+ expect(screen.queryByTestId("sandbox-network-standard")).toBeNull(); // no type is chosen 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"])); // live sessions rebuilt under the new rule
});
- it("OpenShell on Linux: the readiness checklist, its hints, the handover command and the setup button", async () => {
+ it("OpenShell's Set up opens its dialog: the steps first, the handover command with Copy, then the job", 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: "openshell", usable: false, why: "OpenShell is not installed", state: "unavailable" },
],
};
render(<SettingsView initialTab="sandbox" />);
- await screen.findByTestId("sandbox-readiness");
- 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();
+ await screen.findByTestId("sandbox-section");
+ fireEvent.click(masterSwitch());
+ expect(screen.getByText("One Linux container per agent. Needs Docker.")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("sandbox-setup-openshell"));
+ const dialog = await screen.findByTestId("sandbox-openshell-dialog");
+ await within(dialog).findByTestId("sandbox-readiness-row-openshell");
+ expect(within(dialog).getByText("Set up OpenShell")).toBeTruthy();
expect(screen.getByTestId("sandbox-readiness-row-docker").getAttribute("data-state")).toBe("ok");
expect(screen.getByTestId("sandbox-readiness-row-openshell").getAttribute("data-state")).toBe("pending");
- expect(screen.getByText("curl -LsSf https://example/install.sh | sh")).toBeTruthy(); // the command to run
+ expect(within(screen.getByTestId("sandbox-readiness-row-image")).getByText("to do")).toBeTruthy();
// 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(within(dialog).getByText("curl -LsSf https://example/install.sh | sh")).toBeTruthy();
+ expect(within(dialog).getAllByText("Copy").length).toBe(1);
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();
+ expect(screen.queryByTestId("sandbox-readiness")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("sandbox-setup-start"));
+ await waitFor(() => expect(startSandboxSetup).toHaveBeenCalled());
+ fireEvent.click(screen.getByTestId("sandbox-openshell-close"));
+ expect(screen.queryByTestId("sandbox-openshell-dialog")).toBeNull();
});
- 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" }] };
+ it("OpenShell: a running job shows progress in the dialog; needs_you offers Check again and Try again", async () => {
+ snapshot = { ...base, platform: "linux", providers: [{ name: "direct", usable: true, why: "", state: "ready" }, { name: "openshell", usable: false, why: "", state: "needs_download" }] };
setupState = {
status: "running",
rows: [
@@ -162,7 +175,12 @@ describe("Settings ▸ Sandbox", () => {
elapsed_s: 75,
};
render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-section");
+ fireEvent.click(masterSwitch());
+ await waitFor(() => expect(screen.getByTestId("sandbox-setup-openshell").textContent).toBe("Setting up…")); // the job was adopted
+ fireEvent.click(screen.getByTestId("sandbox-setup-openshell"));
await screen.findByTestId("sandbox-download-progress");
+ expect(screen.getByText("Setting up OpenShell")).toBeTruthy();
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");
@@ -181,18 +199,24 @@ describe("Settings ▸ Sandbox", () => {
elapsed_s: 3,
};
render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-section");
+ fireEvent.click(masterSwitch());
+ await waitFor(() => expect(screen.getByTestId("sandbox-setup-openshell")).toBeTruthy());
+ fireEvent.click(screen.getByTestId("sandbox-setup-openshell"));
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.getByText("One step needs you")).toBeTruthy();
expect(screen.getByTestId("sandbox-readiness-row-openshell").getAttribute("data-state")).toBe("needs_you");
- expect(screen.getByTestId("sandbox-setup-start").textContent).toBe("Check again");
+ expect(screen.getByTestId("sandbox-setup-check").textContent).toBe("Check again");
fireEvent.click(screen.getByTestId("sandbox-setup-start"));
await waitFor(() => expect(startSandboxSetup).toHaveBeenCalled());
});
- it("OpenShell with the base image missing is still choosable and says needs download", async () => {
+ it("OpenShell chosen with the base image missing: selected, with the hint and the Set up button", async () => {
snapshot = {
...base,
platform: "linux",
+ provider: "openshell",
+ effective_provider: "",
providers: [
{ name: "direct", usable: true, why: "", state: "ready" },
{ name: "openshell", usable: false, why: "the base image is missing", state: "needs_download" },
@@ -200,35 +224,55 @@ describe("Settings ▸ Sandbox", () => {
};
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
- 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") as HTMLInputElement).checked).toBe(true);
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" }));
+ expect(screen.getByTestId("sandbox-setup-openshell")).toBeTruthy();
+ expect(screen.queryByTestId("sandbox-card-tools")).toBeNull(); // OpenShell mounts no home folder: no tools panel
+ expect(screen.getByTestId("sandbox-card-files")).toBeTruthy();
});
- it("a ready type shows its options; switching off writes direct", async () => {
- snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };
+ it("a chosen type shows two network choices, Customize, and two closed panels; off writes direct", async () => {
+ snapshot = chosenSeatbelt();
render(<SettingsView initialTab="sandbox" />);
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(document.querySelectorAll('input[name="sandbox-network"]').length).toBe(2);
+ expect((screen.getByTestId("sandbox-network-standard") as HTMLInputElement).checked).toBe(true);
+ expect(screen.getByText("Package registries and search")).toBeTruthy();
+ expect(screen.getByText("Allow everything").className).toContain("text-warnInk");
+ fireEvent.click(screen.getByTestId("sandbox-network-open"));
+ await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ network_profile: "open" }));
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.getByTestId("sandbox-card-files-summary").textContent).toBe("SSH keys and AWS profiles. Copies are deleted when the session ends.");
+ expect(screen.queryByTestId("sandbox-card-tools-body")).toBeNull();
+ expect(screen.getByTestId("sandbox-card-tools-summary").textContent).toBe("nvm (Node versions) and My tools. Agents can run them, not change them.");
expect(screen.getByText(/config\.toml/)).toBeTruthy();
- fireEvent.click(screen.getByRole("switch"));
+ fireEvent.click(masterSwitch());
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" };
+ it("Customize: add a host, refuse a bad one, remove one, save the machine's list", async () => {
+ snapshot = { ...chosenSeatbelt(), network_extra_hosts: ["sentry.io:443"] };
+ render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-section");
+ expect(screen.getByText(/1 added/)).toBeTruthy();
+ fireEvent.click(screen.getByTestId("sandbox-network-customize"));
+ const dialog = screen.getByTestId("sandbox-hosts-dialog");
+ expect(within(dialog).getByText(/github\.com · pypi\.org · api\.tavily\.com/)).toBeTruthy(); // the shipped list, read-only
+ const input = screen.getByTestId("sandbox-host-input");
+ fireEvent.change(input, { target: { value: "not a host" } });
+ fireEvent.click(screen.getByTestId("sandbox-host-add"));
+ expect(within(dialog).getByText(/That is not a host name/)).toBeTruthy();
+ fireEvent.change(input, { target: { value: "Registry.Acme.dev" } });
+ fireEvent.keyDown(input, { key: "Enter" });
+ expect(screen.getByTestId("sandbox-host-registry.acme.dev:443")).toBeTruthy();
+ fireEvent.click(within(screen.getByTestId("sandbox-host-sentry.io:443")).getByText("Remove"));
+ fireEvent.click(screen.getByTestId("sandbox-hosts-save"));
+ await waitFor(() => expect(setSandboxSettings).toHaveBeenLastCalledWith({ network_extra_hosts: ["registry.acme.dev:443"] }));
+ await waitFor(() => expect(screen.queryByTestId("sandbox-hosts-dialog")).toBeNull());
+ });
+
+ it("the files panel lists only added entries: switch, tags, remove; Add… offers a CLI's login or a file", async () => {
+ snapshot = chosenSeatbelt();
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
fireEvent.click(screen.getByTestId("sandbox-card-files-toggle"));
@@ -238,45 +282,69 @@ describe("Settings ▸ Sandbox", () => {
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]]),
- }),
- );
+ expect(within(body).getByText("Logins kept in the macOS Keychain are not files and cannot be added.")).toBeTruthy();
+ expect(screen.queryByTestId("sandbox-credential-npm")).toBeNull(); // a preset is not listed until added
+ fireEvent.click(within(screen.getByTestId("sandbox-credential-ssh")).getByRole("switch"));
+ await waitFor(() => expect(lastPatch()).toEqual({ credentials: stripDisplay([{ ...base.credentials[0], enabled: false }, base.credentials[1], base.credentials[2]]) }));
+ fireEvent.click(screen.getByTestId("sandbox-credential-gh-remove"));
+ await waitFor(() => expect(lastPatch().credentials.map((c: any) => c.name)).toEqual(["ssh", "aws"]));
+
+ // A CLI's login: found presets can be added, missing ones say so
+ fireEvent.click(screen.getByTestId("sandbox-credential-add"));
+ fireEvent.click(screen.getByTestId("sandbox-add-cli"));
+ const picker = screen.getByTestId("sandbox-cli-picker");
+ expect(screen.getByTestId("sandbox-preset-npm").getAttribute("data-found")).toBe("yes");
+ expect(within(screen.getByTestId("sandbox-preset-npm")).getByText("~/.npmrc · Install and publish private packages")).toBeTruthy();
+ expect(within(screen.getByTestId("sandbox-preset-gcloud")).getByText("not found")).toBeTruthy();
+ expect(within(screen.getByTestId("sandbox-preset-gcloud")).getByText("not on this Mac")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("sandbox-preset-npm-add"));
+ await waitFor(() => expect(lastPatch().credentials[lastPatch().credentials.length - 1]).toEqual({ name: "npm", enabled: true }));
+ fireEvent.click(within(picker).getByTestId("sandbox-cli-done"));
+ expect(screen.queryByTestId("sandbox-cli-picker")).toBeNull();
+
+ // A file or folder: the modal, with a label
fireEvent.click(screen.getByTestId("sandbox-credential-add"));
+ fireEvent.click(screen.getByTestId("sandbox-add-file"));
const editor = screen.getByTestId("sandbox-credential-editor");
- 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" } });
+ expect(within(editor).getByText("Add a file or folder")).toBeTruthy();
+ fireEvent.change(screen.getByTestId("sandbox-credential-path"), { target: { value: "~/.config/acme/token" } });
+ fireEvent.change(screen.getByTestId("sandbox-credential-title"), { target: { value: "Acme CLI token" } });
fireEvent.click(screen.getByTestId("sandbox-credential-label-configuration"));
- fireEvent.change(inputs[2], { target: { value: "registry.npmjs.org:443" } });
- fireEvent.click(within(editor).getByText("Done"));
+ fireEvent.change(editor.querySelector("textarea")!, { target: { value: "api.acme.dev" } });
+ fireEvent.click(screen.getByTestId("sandbox-credential-save"));
await waitFor(() =>
- expect(setSandboxSettings).toHaveBeenLastCalledWith({
- credentials: [
- ...stripDisplay([{ ...base.credentials[0], enabled: true }, base.credentials[1], base.credentials[2]]),
- { name: "npm-token", title: "npm token", path: "~/.npmrc", hosts: ["registry.npmjs.org:443"], does: undefined, label: "configuration", enabled: true },
- ],
+ expect(lastPatch().credentials[lastPatch().credentials.length - 1]).toEqual({
+ name: "acme-cli-token",
+ title: "Acme CLI token",
+ path: "~/.config/acme/token",
+ hosts: ["api.acme.dev:443"],
+ does: undefined,
+ label: "configuration",
+ enabled: true,
}),
);
- fireEvent.click(within(screen.getByTestId("sandbox-credential-ssh")).getByText("Remove"));
- await waitFor(() => {
- const calls = setSandboxSettings.mock.calls;
- const last = calls[calls.length - 1]?.[0];
- expect(last.credentials.map((c: any) => c.name)).toEqual(["gh", "aws", "npm-token"]);
- });
});
- it("the tools card: switch a folder off and add one, without the display-only fields", async () => {
- snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };
+ it("nothing added yet: the panel says so in one line and offers Add…", async () => {
+ snapshot = { ...chosenSeatbelt(), credentials: [] };
+ render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-section");
+ expect(screen.getByTestId("sandbox-card-files-summary").textContent).toBe("Nothing is copied into sandboxes.");
+ fireEvent.click(screen.getByTestId("sandbox-card-files-toggle"));
+ expect(screen.getByTestId("sandbox-files-empty").textContent).toContain("Add a CLI's login");
+ expect(screen.getByTestId("sandbox-credential-add").textContent).toBe("Add…");
+ });
+
+ it("the tools panel: switch a folder off and add one, without the display-only fields", async () => {
+ snapshot = chosenSeatbelt();
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
fireEvent.click(screen.getByTestId("sandbox-card-tools-toggle"));
- expect(screen.getByText(/not on this machine/)).toBeTruthy();
- fireEvent.click(screen.getByLabelText("nvm (Node versions)"));
+ expect(screen.getByText("Tools shown to Agent with read-only access")).toBeTruthy();
+ expect(within(screen.getByTestId("sandbox-toolchain-mytools")).getByText(/not on this machine/)).toBeTruthy();
+ fireEvent.click(within(screen.getByTestId("sandbox-toolchain-nvm")).getByRole("switch"));
await waitFor(() =>
- expect(setSandboxSettings).toHaveBeenLastCalledWith({
+ expect(lastPatch()).toEqual({
toolchains: [
{ name: "nvm", title: "nvm (Node versions)", path: "~/.nvm", enabled: false },
{ name: "mytools", title: "My tools", path: "~/tools", enabled: true },
@@ -288,32 +356,31 @@ describe("Settings ▸ Sandbox", () => {
const inputs = editor.querySelectorAll("input");
fireEvent.change(inputs[0], { target: { value: "JDKs" } });
fireEvent.change(inputs[1], { target: { value: "~/.jdks" } });
- fireEvent.click(within(editor).getByText("Done"));
- await waitFor(() => {
- const calls = setSandboxSettings.mock.calls;
- const last = calls[calls.length - 1]?.[0];
- expect(last.toolchains[last.toolchains.length - 1]).toEqual({ name: "jdks", title: "JDKs", path: "~/.jdks", enabled: true });
- });
+ fireEvent.click(within(editor).getByText("Add"));
+ await waitFor(() => expect(lastPatch().toolchains[lastPatch().toolchains.length - 1]).toEqual({ name: "jdks", title: "JDKs", path: "~/.jdks", enabled: true }));
});
- it("Windows: choosing the sandbox opens the setup dialog; Set up now calls the route; Done shows the options", async () => {
+ it("Windows: Set up opens the setup dialog; Set up now calls the route; Done shows the options", async () => {
snapshot = {
...base,
platform: "win32",
providers: [
{ name: "direct", usable: true, why: "" },
{ name: "windows", usable: false, why: "the one-time setup has not run on this PC" },
- { name: "openshell", usable: false, why: "OpenShell is not available on Windows" },
+ { name: "openshell", usable: false, why: "OpenShell is not available on Windows yet." },
],
windows_setup: { state: "not_set_up", set_up_at: "", problem: "not run", can_elevate: true, command: "openworker machine sandbox setup" },
network_profile: "open",
};
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
- fireEvent.click(screen.getByRole("switch"));
- expect(screen.getByText("one-time setup")).toBeTruthy();
+ fireEvent.click(masterSwitch());
+ expect(screen.getByText("Built into Windows.")).toBeTruthy();
+ expect((screen.getByTestId("sandbox-provider-windows") as HTMLInputElement).disabled).toBe(true);
expect(screen.queryByTestId("sandbox-provider-windows-why")).toBeNull(); // an administrator sees no warning
- fireEvent.click(screen.getByTestId("sandbox-provider-windows"));
+ expect(screen.queryByTestId("sandbox-setup-openshell")).toBeNull(); // nothing to set up for OpenShell on Windows
+ expect(screen.getByTestId("sandbox-provider-openshell-why").textContent).toBe("OpenShell is not available on Windows yet.");
+ fireEvent.click(screen.getByTestId("sandbox-setup-windows"));
const dialog = screen.getByTestId("sandbox-setup-dialog");
expect(within(dialog).getByText("Set up the Windows sandbox")).toBeTruthy();
expect(setSandboxSettings).not.toHaveBeenCalled();
@@ -323,50 +390,55 @@ describe("Settings ▸ Sandbox", () => {
expect(screen.getByTestId("sandbox-setup-done-box").textContent).toContain("the wall held");
fireEvent.click(screen.getByTestId("sandbox-setup-done"));
expect(screen.queryByTestId("sandbox-setup-dialog")).toBeNull();
- expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("on · Windows sandbox");
+ expect((screen.getByTestId("sandbox-provider-windows") as HTMLInputElement).checked).toBe(true);
expect(screen.getByTestId("sandbox-windows-setup-line").textContent).toContain("Set up on");
- // Open is first and chosen on Windows; the options are visible now
- const radios = document.querySelectorAll('input[name="sandbox-network"]');
- expect(radios[0].getAttribute("data-testid")).toBe("sandbox-network-open");
expect((screen.getByTestId("sandbox-network-open") as HTMLInputElement).checked).toBe(true);
expect(screen.getByTestId("sandbox-card-files")).toBeTruthy();
expect(screen.getByTestId("sandbox-card-tools")).toBeTruthy();
+ fireEvent.click(screen.getByTestId("sandbox-card-files-toggle"));
+ expect(screen.getByText("Logins kept in Windows Credential Manager are not files and cannot be added.")).toBeTruthy();
// Remove setup: confirm, the route runs, the page collapses
fireEvent.click(screen.getByTestId("sandbox-remove-setup"));
fireEvent.click(screen.getByTestId("sandbox-remove-confirm"));
await waitFor(() => expect(runSandboxRemove).toHaveBeenCalled());
- await waitFor(() => expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("off"));
+ await waitFor(() => expect(masterSwitch().getAttribute("aria-checked")).toBe("false"));
expect(screen.queryByTestId("sandbox-card-files")).toBeNull();
});
- it("Windows, not an administrator: the row is disabled with the command; Not now turns the switch off", async () => {
+ it("Windows, not an administrator: the row is disabled with the command and no button; Not now turns the switch off", async () => {
snapshot = {
...base,
platform: "win32",
providers: [
{ name: "direct", usable: true, why: "" },
{ name: "windows", usable: false, why: "the one-time setup has not run on this PC" },
- { name: "openshell", usable: false, why: "OpenShell is not available on Windows" },
+ { name: "openshell", usable: false, why: "OpenShell is not available on Windows yet." },
],
windows_setup: { state: "not_set_up", set_up_at: "", problem: "not run", can_elevate: false, command: "openworker machine sandbox setup" },
};
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
- fireEvent.click(screen.getByRole("switch"));
- expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("no type can be used yet");
+ fireEvent.click(masterSwitch());
expect((screen.getByTestId("sandbox-provider-windows") as HTMLInputElement).disabled).toBe(true);
expect(screen.getByTestId("sandbox-provider-windows-why").textContent).toContain("openworker machine sandbox setup");
- expect(screen.getByText("needs an administrator")).toBeTruthy();
+ expect(screen.queryByTestId("sandbox-setup-windows")).toBeNull();
// an administrator, but "Not now"
snapshot = { ...snapshot, windows_setup: { ...snapshot.windows_setup, can_elevate: true } };
cleanup();
render(<SettingsView initialTab="sandbox" />);
await screen.findByTestId("sandbox-section");
- fireEvent.click(screen.getByRole("switch"));
- fireEvent.click(screen.getByTestId("sandbox-provider-windows"));
+ fireEvent.click(masterSwitch());
+ fireEvent.click(screen.getByTestId("sandbox-setup-windows"));
fireEvent.click(screen.getByTestId("sandbox-setup-not-now"));
expect(screen.queryByTestId("sandbox-setup-dialog")).toBeNull();
- expect(screen.getByRole("switch").getAttribute("aria-checked")).toBe("false");
+ expect(masterSwitch().getAttribute("aria-checked")).toBe("false");
expect(runSandboxSetup).not.toHaveBeenCalled();
});
+
+ it("cleanHost follows the server's rule", () => {
+ expect(cleanHost("Registry.Acme.dev")).toBe("registry.acme.dev:443");
+ expect(cleanHost("https://api.acme.dev/v1")).toBe("api.acme.dev:443");
+ expect(cleanHost("*.acme.dev:8443")).toBe("*.acme.dev:8443");
+ for (const bad of ["", "localhost", "acme dev", "api.acme.dev:0", "a..b"]) expect(cleanHost(bad)).toBe("");
+ });
});
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index c805e649..14bbcaa0 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -2270,56 +2270,30 @@
},
"sandbox": {
"title": "Sandbox",
- "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.",
+ "sub": "Manage environment restrictions for your Agent.",
+ "sub_machine": "Manage environment restrictions for agents on ⌂ {{name}}.",
"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.",
+ "switch_desc": "Agents can only use the folders you open. The rest of your computer stays private.",
"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_seatbelt_desc": "Built into macOS.",
"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_windows_desc": "Built into Windows.",
"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",
+ "provider_openshell_desc": "One Linux container per agent. Needs Docker.",
"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…",
+ "profile_standard": "Package registries and search",
+ "profile_standard_desc": "GitHub, GitLab, PyPI, npm, crates, Go and the search APIs.",
+ "profile_open": "Allow everything",
+ "profile_open_desc": "Any site. Your files stay private.",
+ "files_foot": "Copies are deleted when the session ends.",
+ "credman_note": "Logins kept in Windows Credential Manager are not files and cannot be added.",
+ "keychain_note": "Logins kept in the macOS Keychain are not files and cannot be added.",
"also_allows": "Also allows {{hosts}}.",
"edit": "Edit",
"remove": "Remove",
@@ -2334,21 +2308,15 @@
"label_credential": "credential",
"label_configuration": "configuration",
"field_title": "Name",
- "field_path": "Path (a file or a folder under your home folder)",
+ "field_path": "Path",
"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_credential_desc": "A key, a token, a password.",
"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)",
+ "label_configuration_desc": "No secret inside.",
+ "field_hosts": "Hosts it needs",
"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.",
+ "editor_note": "A folder is copied whole. Prefer the one file a tool needs.",
"toolchain_missing": "not on this machine",
"added_by_you": "added by you",
"add_toolchain": "Add a folder…",
@@ -2384,29 +2352,21 @@
"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.",
+ "does_gh": "Pull requests, issues and releases as you.",
+ "does_aws": "Regions and profile names, no keys.",
+ "does_kube": "Your clusters.",
"title_ssh": "SSH keys",
"title_gh": "GitHub CLI",
"title_aws": "AWS profiles",
- "title_kube": "Kubernetes",
+ "title_kube": "kubectl",
"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",
@@ -2421,15 +2381,73 @@
"copied": "Copied",
"notify_title": "Sandbox ready",
"notify_body": "You can start a new session now; its commands will run in the sandbox.",
- "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.",
- "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"
+ "needs_download_hint": "The base image (about 5 GB, downloaded once) is not on this machine yet. Click Set up to download it; the first session cannot start until it is.",
+ "field_title_example": "Acme CLI token",
+ "field_hosts_example": "api.acme.dev:443",
+ "field_does_example": "Use the acme CLI as you",
+ "add_button": "Add",
+ "add_cli": "A CLI's login",
+ "add_cli_desc": "gh, aws, gcloud, kubectl, npm, docker…",
+ "add_file": "A file or folder",
+ "add_file_desc": "Any path under your home folder.",
+ "add_menu": "Add…",
+ "cli_all_added": "Every known login is already added.",
+ "cli_file_button": "A file or folder…",
+ "cli_intro": "A copy goes into each sandbox for the session, and the agent is told what it can do with it.",
+ "cli_not_listed": "Not listed? Add it as a file or folder.",
+ "cli_title": "Add a CLI's login",
+ "customize": "Customize…",
+ "does_aws-credentials": "Your access keys.",
+ "does_docker": "Push and pull images with the logins in this file.",
+ "does_gcloud": "Your Google Cloud accounts and projects.",
+ "does_npm": "Install and publish private packages.",
+ "does_terraform": "Runs and state in Terraform Cloud as you.",
+ "field_path_hint": "(under your home folder)",
+ "file_intro": "Copied into each sandbox at session start and deleted with the session. Your real file is never changed.",
+ "file_title": "Add a file or folder",
+ "file_title_edit": "Edit this entry",
+ "files_empty": "Add a CLI's login, such as gh or aws, or any file or folder an agent needs.",
+ "files_panel": "Explicit config and keys exposed to Agent",
+ "files_sum": "{{list}}. Copies are deleted when the session ends.",
+ "files_sum_none": "Nothing is copied into sandboxes.",
+ "get_docker": "Get Docker",
+ "hosts_added": "{{count}} added",
+ "hosts_bad": "That is not a host name. For example: api.example.com:443",
+ "hosts_builtin": "Always allowed with this choice",
+ "hosts_intro": "Everything else is blocked. Changes apply to new sessions.",
+ "hosts_note": "Hosts a CLI's login needs come with it and are not listed here.",
+ "hosts_placeholder": "host:port, for example api.example.com:443",
+ "hosts_title": "Hosts agents may reach",
+ "hosts_yours": "Added by you",
+ "list_and": "{{list}} and {{last}}",
+ "list_more": "{{list}} and {{count}} more",
+ "not_found": "not found",
+ "not_on_mac": "not on this Mac",
+ "not_on_pc": "not on this PC",
+ "os_close_note": "You can close this dialog. Setup continues, and this page shows when it is ready.",
+ "os_done_intro": "New sessions on this machine run their commands in an OpenShell container. The network choice and the files you add apply inside it.",
+ "os_done_title": "OpenShell is ready",
+ "os_intro": "Each agent will run in its own Linux container that holds only the session's folders.",
+ "os_needs_you_intro": "Run the command below in a terminal on this machine, then check again.",
+ "os_needs_you_title": "One step needs you",
+ "os_running_intro": "Each step runs on this machine.",
+ "os_running_title": "Setting up OpenShell",
+ "os_steps": "What setup does",
+ "os_stopped_title": "Setup stopped",
+ "os_title": "Set up OpenShell",
+ "provider_openshell_desc_mac": "One Linux container per agent. Needs Docker Desktop.",
+ "save": "Save",
+ "set_up_done": "Set up",
+ "step_todo": "to do",
+ "title_aws-credentials": "AWS credentials",
+ "title_docker": "Docker registries",
+ "title_gcloud": "gcloud",
+ "title_npm": "npm",
+ "title_terraform": "Terraform Cloud",
+ "tools_foot": "Agents can run these but not change them. The rest of your home folder stays private.",
+ "tools_panel": "Tools shown to Agent with read-only access",
+ "tools_sum": "{{list}}. Agents can run them, not change them.",
+ "tools_sum_none": "None. Agents see no tools from your home folder."
}
},
"misc": {
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 1d4ebb3e..d20db0f9 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -2230,56 +2230,30 @@
},
"sandbox": {
"title": "沙箱",
- "sub": "同事在这台 Mac 上运行命令和文件工具的位置。适用于这里的每个会话(正在进行中的会话会在本轮结束后切换);项目无法更改。",
- "sub_windows": "同事在这台 PC 上运行命令和文件工具的位置。适用于这里的每个会话(正在进行中的会话会在本轮结束后切换);项目无法更改。",
- "sub_machine": "在 ⌂ {{name}} 上 —— 它的同事运行命令和文件工具的位置。适用于那台机器上的每个会话(正在进行回合的会话会在回合结束后切换);项目无法更改。",
+ "sub": "管理同事运行环境的限制。",
+ "sub_machine": "管理 ⌂ {{name}} 上同事运行环境的限制。",
"switch_title": "在沙箱中运行同事",
- "switch_desc": "命令在看不到你的文件、密钥和 OpenWorker 自身状态的地方运行。关闭时,命令以你的身份运行,没有限制。",
- "switch_off": "关闭",
- "switch_choose": "选择一种类型",
- "switch_on": "开启 · {{type}}",
- "switch_none": "目前没有可用的类型",
- "switch_help_off": "开启后可选择这台机器上隔离同事的方式。",
+ "switch_desc": "同事只能使用你打开的文件夹。电脑上的其他内容保持私密。",
"type": "沙箱类型",
- "type_help": "在某种类型就绪之前不会有任何变化。就绪后它的选项会显示在这里。",
- "type_help_admin": "管理员完成设置后,回到这里选择 Windows 沙箱。",
"provider_seatbelt": "macOS 沙箱",
- "provider_seatbelt_desc": "macOS 内置的 Seatbelt 配置。无需安装。",
+ "provider_seatbelt_desc": "macOS 内置。",
"provider_windows": "Windows 沙箱",
- "provider_windows_desc": "命令以一个看不到你的用户配置文件的隐藏 Windows 账户运行。一次性设置,只需一次管理员确认。",
+ "provider_windows_desc": "Windows 内置。",
"provider_openshell": "OpenShell(NVIDIA)",
- "provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要 OpenShell 和 Docker。",
- "status_ready": "就绪",
- "status_unavailable": "这台机器上不可用",
- "status_setup": "一次性设置",
- "status_needs_admin": "需要管理员",
+ "provider_openshell_desc": "每个同事一个 Linux 容器。需要 Docker。",
"needs_admin_why": "需要管理员进行设置。请管理员在这台 PC 上运行一次:{{command}}",
"set_up_on": "设置于 {{date}}",
- "set_up": "已设置",
+ "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": "添加文件或文件夹…",
+ "profile_standard": "软件包仓库和搜索",
+ "profile_standard_desc": "GitHub、GitLab、PyPI、npm、crates、Go 和搜索 API。",
+ "profile_open": "允许所有网站",
+ "profile_open_desc": "任何网站。你的文件仍然私密。",
+ "files_foot": "副本会在会话结束时删除。",
+ "credman_note": "保存在 Windows 凭据管理器中的登录不是文件,无法添加。",
+ "keychain_note": "保存在 macOS 钥匙串中的登录不是文件,无法添加。",
"also_allows": "同时允许 {{hosts}}。",
"edit": "编辑",
"remove": "移除",
@@ -2294,21 +2268,15 @@
"label_credential": "凭据",
"label_configuration": "配置",
"field_title": "名称",
- "field_path": "路径(你主目录下的文件或文件夹)",
- "field_label": "内容类型",
+ "field_path": "路径",
+ "field_label": "其中包含什么",
"label_credential_title": "凭据",
- "label_credential_desc": "密钥、令牌或密码。只有此条目开启时同事才能获得。",
+ "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)对任何本地账户都可读。",
+ "label_configuration_desc": "不含机密信息。",
+ "field_hosts": "需要的主机",
+ "field_does": "允许同事",
+ "editor_note": "文件夹会被整体复制。尽量只选工具需要的那个文件。",
"toolchain_missing": "这台机器上没有",
"added_by_you": "由你添加",
"add_toolchain": "添加文件夹…",
@@ -2344,29 +2312,21 @@
"remove_change_record_desc": "记录本身最后移除。",
"remove_keep_note": "你的网络、凭据和工具选择会保留到下次使用。",
"does_ssh": "以你的身份通过 SSH 推送和拉取,并登录服务器。",
- "does_gh": "以你的身份使用 gh:拉取请求、议题、发布。",
- "does_aws": "使用你的配置文件运行 aws:区域和配置文件名。除非你添加,~/.aws/credentials 不会包含在内。",
- "does_kube": "使用你的集群运行 kubectl。",
+ "does_gh": "以你的身份处理拉取请求、议题和发布。",
+ "does_aws": "区域和配置文件名称,不含密钥。",
+ "does_kube": "你的集群。",
"title_ssh": "SSH 密钥",
"title_gh": "GitHub CLI",
"title_aws": "AWS 配置文件",
- "title_kube": "Kubernetes",
+ "title_kube": "kubectl",
"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": "等待中",
@@ -2381,15 +2341,73 @@
"copied": "已复制",
"notify_title": "沙箱已就绪",
"notify_body": "现在可以开始新会话了;其命令将在沙箱中运行。",
- "status_needs_download": "需要下载",
- "needs_download_hint": "沙箱基础镜像(约 5 GB,仅下载一次)尚未下载到这台机器。点击下方的“设置沙箱”进行下载;下载完成前第一个会话无法启动。",
- "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 发布包"
+ "needs_download_hint": "这台机器上还没有基础镜像(约 5 GB,只需下载一次)。点击“设置”开始下载;下载完成前无法启动第一个会话。",
+ "field_title_example": "Acme CLI 令牌",
+ "field_hosts_example": "api.acme.dev:443",
+ "field_does_example": "以你的身份使用 acme CLI",
+ "add_button": "添加",
+ "add_cli": "CLI 的登录",
+ "add_cli_desc": "gh、aws、gcloud、kubectl、npm、docker…",
+ "add_file": "文件或文件夹",
+ "add_file_desc": "主目录下的任意路径。",
+ "add_menu": "添加…",
+ "cli_all_added": "所有已知的登录都已添加。",
+ "cli_file_button": "文件或文件夹…",
+ "cli_intro": "每个沙箱在会话期间获得一份副本,并告知同事可以用它做什么。",
+ "cli_not_listed": "没有列出?请作为文件或文件夹添加。",
+ "cli_title": "添加 CLI 的登录",
+ "customize": "自定义…",
+ "does_aws-credentials": "你的访问密钥。",
+ "does_docker": "使用此文件中的登录推送和拉取镜像。",
+ "does_gcloud": "你的 Google Cloud 账号和项目。",
+ "does_npm": "安装和发布私有软件包。",
+ "does_terraform": "以你的身份在 Terraform Cloud 中运行和管理状态。",
+ "field_path_hint": "(在你的主目录下)",
+ "file_intro": "在会话开始时复制到每个沙箱,并随会话一起删除。你的原始文件不会被更改。",
+ "file_title": "添加文件或文件夹",
+ "file_title_edit": "编辑此条目",
+ "files_empty": "添加一个 CLI 的登录(例如 gh 或 aws),或同事需要的任意文件或文件夹。",
+ "files_panel": "明确提供给同事的配置和密钥",
+ "files_sum": "{{list}}。副本会在会话结束时删除。",
+ "files_sum_none": "不会向沙箱复制任何内容。",
+ "get_docker": "获取 Docker",
+ "hosts_added": "已添加 {{count}} 个",
+ "hosts_bad": "这不是有效的主机名。例如:api.example.com:443",
+ "hosts_builtin": "此选项始终允许",
+ "hosts_intro": "其他主机一律拦截。更改对新会话生效。",
+ "hosts_note": "CLI 登录所需的主机会随之一起允许,不在此列出。",
+ "hosts_placeholder": "主机:端口,例如 api.example.com:443",
+ "hosts_title": "同事可以访问的主机",
+ "hosts_yours": "你添加的",
+ "list_and": "{{list}}和{{last}}",
+ "list_more": "{{list}}等另外 {{count}} 项",
+ "not_found": "未找到",
+ "not_on_mac": "这台 Mac 上没有",
+ "not_on_pc": "这台 PC 上没有",
+ "os_close_note": "你可以关闭此对话框。设置会继续进行,完成后此页面会显示。",
+ "os_done_intro": "这台机器上的新会话会在 OpenShell 容器中运行命令。网络选项和你添加的文件在容器内生效。",
+ "os_done_title": "OpenShell 已就绪",
+ "os_intro": "每个同事将在自己的 Linux 容器中运行,容器中只有该会话的文件夹。",
+ "os_needs_you_intro": "请在这台机器的终端中运行下面的命令,然后重新检查。",
+ "os_needs_you_title": "有一步需要你操作",
+ "os_running_intro": "每一步都在这台机器上运行。",
+ "os_running_title": "正在设置 OpenShell",
+ "os_steps": "设置会做什么",
+ "os_stopped_title": "设置已停止",
+ "os_title": "设置 OpenShell",
+ "provider_openshell_desc_mac": "每个同事一个 Linux 容器。需要 Docker Desktop。",
+ "save": "保存",
+ "set_up_done": "已设置",
+ "step_todo": "待完成",
+ "title_aws-credentials": "AWS 凭据",
+ "title_docker": "Docker 镜像仓库",
+ "title_gcloud": "gcloud",
+ "title_npm": "npm",
+ "title_terraform": "Terraform Cloud",
+ "tools_foot": "同事可以运行这些工具,但不能修改。主目录的其他内容保持私密。",
+ "tools_panel": "以只读方式提供给同事的工具",
+ "tools_sum": "{{list}}。同事可以运行它们,但不能修改。",
+ "tools_sum_none": "无。同事看不到你主目录中的任何工具。"
}
},
"misc": {
diff --git a/tests/test_sandbox_credentials.py b/tests/test_sandbox_credentials.py
index 0e9d90b9..8e393dea 100644
--- a/tests/test_sandbox_credentials.py
+++ b/tests/test_sandbox_credentials.py
@@ -41,7 +41,8 @@ def _home(tmp_path) -> Path:
def test_nothing_is_granted_unless_switched_on(tmp_path):
home = _home(tmp_path)
assert creds.granted(None, home=str(home)) == []
- assert [e["enabled"] for e in creds.entries(None)] == [False] * 4
+ assert [e["enabled"] for e in creds.entries(None)] == [False] * len(creds.DEFAULT_ENTRIES)
+ assert creds.listed(None) == []
def test_a_user_entry_edits_or_adds_by_name(tmp_path):
@@ -253,3 +254,22 @@ def test_a_failed_creation_leaves_no_copied_credential_behind(tmp_path, monkeypa
with pytest.raises(seatbelt.SeatbeltUnavailable):
provider.create()
assert not os.path.exists(folder)
+
+
[email protected](sys.platform == "win32", reason="gcloud and Terraform keep theirs under AppData on Windows")
+def test_a_presets_variables_point_at_its_copy(tmp_path):
+ """UX-053 v5: a preset from the "A CLI's login" picker tells its tool where the copy is."""
+ home = _home(tmp_path)
+ (home / ".npmrc").write_text("//registry.npmjs.org/:_authToken=npm_x\n")
+ (home / ".docker").mkdir()
+ (home / ".docker" / "config.json").write_text('{"auths": {}}\n')
+ (home / ".config" / "gcloud").mkdir(parents=True)
+ grants = creds.granted([{"name": n, "enabled": True} for n in ("npm", "docker", "gcloud", "terraform")], home=str(home))
+ assert [g.name for g in grants] == ["npm", "docker", "gcloud"] # no Terraform Cloud login on this machine
+ run = tmp_path / "run"
+ copied = creds.copy_in(grants, str(run), home=str(home))
+ inside = Path(copied.home)
+ assert copied.env["NPM_CONFIG_USERCONFIG"] == str(inside / ".npmrc")
+ assert copied.env["DOCKER_CONFIG"] == str(inside / ".docker")
+ assert copied.env["CLOUDSDK_CONFIG"] == str(inside / ".config" / "gcloud")
+ assert "registry-1.docker.io:443" in copied.hosts and "*.googleapis.com:443" in copied.hosts
diff --git a/tests/test_sandbox_openshell.py b/tests/test_sandbox_openshell.py
index d72cda9b..11c0cea1 100644
--- a/tests/test_sandbox_openshell.py
+++ b/tests/test_sandbox_openshell.py
@@ -44,12 +44,13 @@ def test_policy_is_plain_yaml_without_shared_objects():
def test_network_profiles():
- strict = policy.render(ROOTS, profile="strict")["network_policies"]
standard = policy.render(ROOTS, profile="standard")["network_policies"]
hosts = lambda p: {e["host"] for entry in p.values() for e in entry["endpoints"]} # noqa: E731
- assert {"github.com", "pypi.org", "registry.npmjs.org"} <= hosts(strict)
- assert "api.tavily.com" not in hosts(strict) and "api.tavily.com" in hosts(standard)
- assert all(entry["binaries"] for entry in strict.values()) # OpenShell requires the field
+ assert {"github.com", "pypi.org", "registry.npmjs.org", "api.tavily.com"} <= hosts(standard)
+ assert policy.render(ROOTS, profile="strict")["network_policies"] == standard # the old name
+ assert all(entry["binaries"] for entry in standard.values()) # OpenShell requires the field
+ added = policy.render(ROOTS, profile="standard", extra_hosts=["registry.acme.dev:443"])["network_policies"]
+ assert {"host": "registry.acme.dev", "port": 443} in added["credentials"]["endpoints"]
opened = policy.render(ROOTS, profile="open")["network_policies"]
assert [e["host"] for e in opened["open"]["endpoints"]] == ["*"] # any host; unproved against a gateway
with pytest.raises(ValueError):
diff --git a/tests/test_sandbox_seatbelt.py b/tests/test_sandbox_seatbelt.py
index 2daa8f94..0eab6582 100644
--- a/tests/test_sandbox_seatbelt.py
+++ b/tests/test_sandbox_seatbelt.py
@@ -151,16 +151,32 @@ def test_proxy_tunnels_a_listed_host(monkeypatch):
def test_every_profile_has_hosts_and_an_unknown_one_is_refused():
- assert "github.com" in network_profiles.hosts("strict")
- assert set(network_profiles.hosts("strict")) < set(network_profiles.hosts("standard"))
+ assert {"github.com", "pypi.org", "api.tavily.com"} <= set(network_profiles.hosts("standard"))
+ assert network_profiles.check("strict") == "standard" # folded in (UX-053 v5), the name still works
with pytest.raises(ValueError):
netproxy.AllowListProxy("wide-open")
+def test_a_machines_own_hosts_are_cleaned_and_join_the_list():
+ clean = network_profiles.clean_host
+ assert clean("Registry.Acme.dev") == "registry.acme.dev:443"
+ assert clean("sentry.io:8443") == "sentry.io:8443" and clean("*.acme.dev") == "*.acme.dev:443"
+ assert clean("https://api.acme.dev/v1") == "api.acme.dev:443"
+ for bad in ("", "localhost", "acme dev", "api.acme.dev:0", "api.acme.dev:http", "a..b"):
+ with pytest.raises(ValueError):
+ clean(bad)
+ assert network_profiles.clean_hosts(["a.dev", "A.dev:443", "nope"]) == ["a.dev:443"]
+ proxy = netproxy.AllowListProxy("standard", extra_hosts=["registry.acme.dev:443"])
+ try:
+ assert proxy.allows("registry.acme.dev", 443) and not proxy.allows("other.acme.dev", 443)
+ finally:
+ proxy.close()
+
+
def test_the_open_profile_has_no_list_and_is_the_default_on_windows_only(tmp_path):
assert network_profiles.hosts("open") == [] and network_profiles.is_open("open")
assert network_profiles.default_profile("win32") == "open"
- assert network_profiles.default_profile("darwin") == "strict" and network_profiles.default_profile("linux") == "strict"
+ assert network_profiles.default_profile("darwin") == "standard" and network_profiles.default_profile("linux") == "standard"
# Seatbelt: the files stay confined, the network clause opens
text = seatbelt_profile.render([{"path": str(tmp_path), "writable": True}], runtime_dir=str(tmp_path), open_network=True, home=str(tmp_path))
assert "(allow network*)" in text and "localhost:" not in text and "(deny default)" in text
diff --git a/tests/test_sandbox_settings.py b/tests/test_sandbox_settings.py
index 93d9e76c..293ed22e 100644
--- a/tests/test_sandbox_settings.py
+++ b/tests/test_sandbox_settings.py
@@ -27,10 +27,13 @@ def test_snapshot_reports_the_default_rule_and_the_shipped_entries(config_file):
assert next(p for p in snap["providers"] if p["name"] == "direct")["usable"]
from coworker.sandbox import network_profiles
- assert snap["network_profile"] == network_profiles.default_profile() # strict; `open` on Windows
- assert [n["name"] for n in snap["network_profiles"]] == ["strict", "standard", "open"]
- assert [(e["name"], e["enabled"]) for e in snap["credentials"]] == [("ssh", False), ("gh", False), ("aws", False), ("kube", False)]
- assert all(e["shipped"] and "kind" in e and e["label"] in ("credential", "configuration") for e in snap["credentials"])
+ assert snap["network_profile"] == network_profiles.default_profile() # standard; `open` on Windows
+ assert [n["name"] for n in snap["network_profiles"]] == ["standard", "open"] and snap["network_extra_hosts"] == []
+ assert snap["credentials"] == [] # nothing is listed until added (UX-053 v5)
+ from coworker.sandbox import credentials
+
+ assert [e["name"] for e in snap["credential_presets"]] == [e["name"] for e in credentials.DEFAULT_ENTRIES]
+ assert all(e["shipped"] and "kind" in e and e["label"] in ("credential", "configuration") for e in snap["credential_presets"])
assert snap["config_path"] == str(config_file)
assert (snap["windows_setup"] is None) == (sys.platform != "win32")
from coworker.sandbox import toolchains
@@ -73,12 +76,31 @@ def test_update_writes_only_what_differs_from_the_shipped_entries(config_file):
assert out["ok"], out
text = config_file.read_text()
assert 'sandbox_network_profile = "standard"' in text
- assert text.count("[[sandbox_credentials]]") == 3 # gh is untouched, so not written
- assert 'path = "~/.aws-work"' in text and 'hosts = ["registry.npmjs.org:443"]' in text
+ assert text.count("[[sandbox_credentials]]") == 4 # gh is listed, switched off, by name only
+ assert 'path = "~/.aws-work"' in text and 'hosts = ["registry.npmjs.org:443"]' not in text # npm's own hosts
snap = settings.snapshot()
by = {e["name"]: e for e in snap["credentials"]}
- assert by["ssh"]["enabled"] and not by["gh"]["enabled"] and by["aws"]["path"] == "~/.aws-work" and by["npm"]["title"] == "npm"
+ assert [e["name"] for e in snap["credentials"]] == ["ssh", "gh", "aws", "npm"]
+ assert by["ssh"]["enabled"] and not by["gh"]["enabled"] and by["aws"]["path"] == "~/.aws-work" and by["npm"]["shipped"]
+ assert {e["name"] for e in snap["credential_presets"]}.isdisjoint(by) # an added one leaves the picker
assert app_config.load_config().sandbox_credentials[0] == {"name": "ssh", "enabled": True}
+ assert settings.update({"credentials": [{"name": "gh", "enabled": False}]})["credentials"][0]["name"] == "gh"
+ assert [e["name"] for e in settings.snapshot()["credentials"]] == ["gh"] # removing is leaving it out
+
+
+def test_network_choice_and_the_machines_own_hosts(config_file):
+ out = settings.update({"network_profile": "strict", "network_extra_hosts": ["Registry.Acme.dev", "sentry.io:443", "sentry.io"]})
+ assert out["ok"], out
+ assert out["network_profile"] == "standard" and out["network_extra_hosts"] == ["registry.acme.dev:443", "sentry.io:443"]
+ text = config_file.read_text()
+ assert 'sandbox_network_profile = "standard"' in text
+ assert 'sandbox_network_extra_hosts = ["registry.acme.dev:443", "sentry.io:443"]' in text
+ assert app_config.load_config().sandbox_network_extra_hosts == ["registry.acme.dev:443", "sentry.io:443"]
+ assert settings.update({"network_extra_hosts": ["not a host"]})["ok"] is False
+ assert settings.update({"network_extra_hosts": []})["network_extra_hosts"] == []
+ assert "sandbox_network_extra_hosts" not in config_file.read_text()
+ config_file.write_text('sandbox_network_profile = "strict"\n') # a machine set before v5
+ assert settings.snapshot()["network_profile"] == "standard"
def test_update_refuses_bad_input_without_writing(config_file):
@@ -96,7 +118,7 @@ def test_a_label_is_written_and_read_back(config_file):
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"]
+ assert "gh" not in by and not by["npmrc"]["shipped"] and by["aws"]["shipped"]
def test_windows_setup_runs_checks_and_only_then_chooses_the_sandbox(config_file, monkeypatch):
diff --git a/tests/test_sandbox_setup_job.py b/tests/test_sandbox_setup_job.py
index e853d012..23f414b0 100644
--- a/tests/test_sandbox_setup_job.py
+++ b/tests/test_sandbox_setup_job.py
@@ -49,6 +49,23 @@ def test_steps_carry_keys_and_say_which_the_app_may_fix(monkeypatch):
assert [(w, ok) for w, ok, _ in setup_cmd.checks()] == [(s.what, s.ok) for s in setup_cmd.steps()]
+def test_a_hung_check_counts_as_not_ok_instead_of_failing_the_checklist(monkeypatch):
+ """`docker info` hangs while Docker Desktop is installed but not running (seen on a Mac,
+ 2026-09-28): the row says Docker is missing, and the checklist still loads."""
+ import subprocess
+
+ def hang(argv, **kwargs):
+ raise subprocess.TimeoutExpired(argv, kwargs.get("timeout"))
+
+ monkeypatch.setattr(setup_cmd.shutil, "which", lambda name: f"/usr/local/bin/{name}")
+ monkeypatch.setattr(setup_cmd.subprocess, "run", hang)
+ monkeypatch.setattr(setup_cmd.sys, "platform", "darwin")
+ monkeypatch.setattr(setup_cmd, "openshell_problem", lambda fresh=False: "OpenShell is not installed")
+ rows = {s.key: s for s in setup_cmd.steps()}
+ assert not rows["docker"].ok and not rows["openshell"].ok
+ assert setup_cmd._run(["docker", "info"], 1).returncode == 124
+
+
def test_on_linux_the_install_is_the_apps_when_it_can_run_as_an_administrator(monkeypatch):
monkeypatch.setattr(setup_cmd.shutil, "which", lambda name: None)
monkeypatch.setattr(setup_cmd.sys, "platform", "linux")