Python
Settings ▸ Sandbox: one switch, then the type, then its options; the Windows setup dialog
Rohit C Prasadf0cc63023c34
diff --git a/coworker/sandbox/credentials.py b/coworker/sandbox/credentials.pyindex ea0947d0..7b79a0e0 100644--- a/coworker/sandbox/credentials.py+++ b/coworker/sandbox/credentials.py@@ -1,12 +1,15 @@-"""Credential grants: files from the home folder a user chooses to share with a sandbox.--Design doc rulings 30 to 33 and section 11b. Nothing is shared unless the user switched an-entry on in the MACHINE config (`[[sandbox_credentials]]`); a repository's own config cannot-add one. Each granted entry is COPIED into the sandbox's private folder for the session-(tools like `ssh`, `aws` and `gh` write beside their credentials, and Windows OpenSSH refuses-a key another user can read), and the copy dies with the sandbox. The real files are never-opened for writing. Each entry also names the hosts its tool needs; those join the session's-network allow list.+"""Credential grants: files and folders from the home folder a user chooses to share with+a sandbox.++Design doc rulings 30 to 33, section 11b and 11d ruling 6. Nothing is shared unless the user+switched an entry on in the MACHINE config (`[[sandbox_credentials]]`); a repository's own+config cannot add one. An entry is a single file or a whole folder, the user's choice; the+path decides which. Each granted entry is COPIED into the sandbox's private folder for the+session (tools like `ssh`, `aws` and `gh` write beside their credentials, and Windows+OpenSSH refuses a key another user can read), and the copy dies with the sandbox. The real+files are never opened for writing. Each entry names the hosts its tool needs; those join+the session's network allow list. Each entry carries a label: `credential` (a secret is+inside) or `configuration` (host names, profiles, options; no secret).Logins kept in a keychain or credential manager are not files and cannot be shared."""@@ -21,7 +24,14 @@ from dataclasses import dataclass, fieldfrom pathlib import Pathfrom typing import Any, Optional, Sequence+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.DEFAULT_ENTRIES: list[dict[str, Any]] = [{"name": "ssh",@@ -29,6 +39,7 @@ DEFAULT_ENTRIES: list[dict[str, Any]] = ["path": "~/.ssh","hosts": ["github.com:22", "gitlab.com:22"],"does": "push and pull over SSH, and log in to servers, as you",+ "label": CREDENTIAL,"enabled": False,},{@@ -37,22 +48,25 @@ DEFAULT_ENTRIES: list[dict[str, Any]] = ["path": "~/.config/gh","hosts": ["api.github.com:443", "github.com:443"],"does": "use gh as you: pull requests, issues, releases",+ "label": CREDENTIAL,"enabled": False,},{"name": "aws",- "title": "AWS",- "path": "~/.aws",+ "title": "AWS profiles",+ "path": "~/.aws/config","hosts": ["*.amazonaws.com:443"],- "does": "use aws with your profiles",+ "does": "use aws with your profiles (regions and profile names; no keys unless you add ~/.aws/credentials)",+ "label": CONFIGURATION,"enabled": False,},{"name": "kube","title": "Kubernetes",- "path": "~/.kube",+ "path": "~/.kube/config","hosts": [], # read from the kubeconfig at grant time"does": "use kubectl with your clusters",+ "label": CREDENTIAL,"enabled": False,},]@@ -70,6 +84,8 @@ class Grant:relative: str # the path under the home folder, e.g. ".ssh"hosts: list[str] = field(default_factory=list)does: str = ""+ label: str = CREDENTIAL # credential | configuration+ kind: str = "folder" # file | folder, from what the path is on this machine@dataclass@@ -94,14 +110,27 @@ def entries(configured: Optional[Sequence[dict[str, Any]]]) -> list[dict[str, Anif not isinstance(raw, dict) or not str(raw.get("name") or "").strip():continuename = str(raw["name"]).strip()- base = by_name.get(name, {"name": name, "title": name, "path": "", "hosts": [], "does": "", "enabled": False})+ base = by_name.get(name, {"name": name, "title": name, "path": "", "hosts": [], "does": "", "label": CREDENTIAL, "enabled": False})merged = {**base, **{k: v for k, v in raw.items() if v is not None}}merged["hosts"] = [str(h) for h in (merged.get("hosts") or [])]merged["enabled"] = bool(merged.get("enabled"))+ merged["label"] = merged.get("label") if merged.get("label") in LABELS else CREDENTIALby_name[name] = mergedreturn list(by_name.values())+def kind_of(path: str, *, home: Optional[str] = None) -> str:+ """"file", "folder", or "" when the path does not exist on this machine."""+ if not path:+ return ""+ real = _real(str(path), home or os.path.expanduser("~"))+ if os.path.isdir(real):+ return "folder"+ if os.path.isfile(real):+ return "file"+ return ""++def _real(path: str, home: str) -> str:text = str(path)if text == "~" or text.startswith("~/"):@@ -127,18 +156,24 @@ def granted(configured: Optional[Sequence[dict[str, Any]]], *, home: Optional[sthosts = list(e.get("hosts") or [])if e["name"] == "kube" and not hosts:hosts = _kubeconfig_hosts(real)- out.append(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 "")))+ out.append(+ 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",+ )+ ) # fmt: skipreturn out-def _kubeconfig_hosts(kube_dir: str) -> list[str]:- """`server:` lines of the kubeconfig, as host:port. Plain text scan, no YAML needed."""+def _kubeconfig_hosts(kube_path: str) -> list[str]:+ """`server:` lines of the kubeconfig (the file, or a folder holding `config`), as+ host:port. Plain text scan, no YAML needed."""from urllib.parse import urlsplithosts: list[str] = []- for name in ("config",):+ for path in ([os.path.join(kube_path, "config")] if os.path.isdir(kube_path) else [kube_path]):try:- text = Path(kube_dir, name).read_text(encoding="utf-8", errors="replace")+ text = Path(path).read_text(encoding="utf-8", errors="replace")except OSError:continuefor line in text.splitlines():@@ -214,10 +249,16 @@ def copy_in(elif g.name == "gh":env["GH_CONFIG_DIR"] = insideelif g.name == "aws":- env["AWS_CONFIG_FILE"] = os.path.join(inside, "config")- env["AWS_SHARED_CREDENTIALS_FILE"] = os.path.join(inside, "credentials")+ # The shipped entry is the profiles file; a user may point it at the folder.+ if g.kind == "folder":+ env["AWS_CONFIG_FILE"] = os.path.join(inside, "config")+ env["AWS_SHARED_CREDENTIALS_FILE"] = os.path.join(inside, "credentials")+ else:+ env["AWS_CONFIG_FILE"] = inside+ elif g.name == "aws-credentials":+ env["AWS_SHARED_CREDENTIALS_FILE"] = insideelif g.name == "kube":- env["KUBECONFIG"] = os.path.join(inside, "config")+ env["KUBECONFIG"] = os.path.join(inside, "config") if g.kind == "folder" else insidereturn CopiedCredentials(home=sandbox_home, env=env, hosts=sorted(set(hosts)), grants=list(grants), path_dirs=path_dirs)@@ -288,5 +329,6 @@ def context_lines(copied: Optional[CopiedCredentials]) -> str:return ""lines = ["Credentials shared with this sandbox (copies, deleted when the session ends):"]for g in copied.grants:- lines.append(f"- {g.title} ({g.relative}): you can {g.does}.")+ what = "folder" if g.kind == "folder" else "file"+ lines.append(f"- {g.title} ({g.relative}, {what}): you can {g.does}.")return "\n".join(lines)diff --git a/coworker/sandbox/providers/windows_setup.py b/coworker/sandbox/providers/windows_setup.pyindex 084a4e3c..b359babd 100644--- a/coworker/sandbox/providers/windows_setup.py+++ b/coworker/sandbox/providers/windows_setup.py@@ -142,6 +142,7 @@ $changed += "sandboxes-folder"# 6. The record.@{ version = $Version; user_sid = $UserSid; firewall_rule = $Rule; changed = $changed;+ set_up_at = (Get-Date).ToUniversalTime().ToString("yyyy-MM-ddTHH:mm:ssZ");accounts = @{ open = @{ name = $OpenAccount; sid = $openSid }; closed = @{ name = $ClosedAccount; sid = $closedSid } };wfp = @{ filters = $wfp; ports = @($PortLow, $PortHigh) } } |ConvertTo-Json -Depth 4 | Set-Content -Path (Join-Path $Root "setup.json") -Encoding ASCII@@ -280,6 +281,50 @@ def is_elevated() -> bool:return False+_ADMINISTRATORS_SID = "S-1-5-32-544"+++def can_elevate() -> bool:+ """This user can answer the administrator prompt: already elevated, or a member of+ Administrators (under UAC the group is on the filtered token, marked deny-only, and+ `whoami` still lists it). A standard user gets a prompt asking for someone else's+ password, which the app must not show as "one prompt"."""+ if sys.platform != "win32":+ return False+ if is_elevated():+ return True+ try:+ done = subprocess.run(["whoami", "/groups", "/fo", "csv"], capture_output=True, text=True, timeout=30)+ except (OSError, subprocess.SubprocessError):+ return False+ return _ADMINISTRATORS_SID in (done.stdout or "")+++NOT_SET_UP, OLDER, BROKEN, READY = "not_set_up", "older", "broken", "ready"+SETUP_COMMAND = "openworker machine sandbox setup"+++def info() -> dict[str, Any]:+ """What Settings ▸ Sandbox shows about the setup on this PC: its state, when it ran,+ whether this user can run it, and the command to hand to an administrator."""+ recorded = state()+ if not recorded:+ status = NOT_SET_UP+ elif not current():+ status = OLDER+ elif problem():+ status = BROKEN+ else:+ status = READY+ return {+ "state": status,+ "set_up_at": str(recorded.get("set_up_at") or "") if recorded else "",+ "problem": problem() or "",+ "can_elevate": can_elevate(),+ "command": SETUP_COMMAND,+ }++def _wfp_command() -> tuple[str, str]:"""How the elevated script runs windows_wfp.py: (executable, first argument)."""from ..launch import frozendiff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.pyindex 01dd524a..e914fdd3 100644--- a/coworker/sandbox/settings.py+++ b/coworker/sandbox/settings.py@@ -69,6 +69,7 @@ def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:"effective_provider": effective,"refused": refused,"providers": providers,+ "windows_setup": _windows_setup_info(),"network_profile": (cfg.sandbox_network_profile or network_profiles.default_profile()),"network_profiles": [{"name": name, "hosts": network_profiles.hosts(name)} for name in network_profiles.PROFILES@@ -79,9 +80,19 @@ def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:}+def _windows_setup_info() -> Optional[dict[str, Any]]:+ """The Windows setup's state for the page (UX-053): None off Windows."""+ if sys.platform != "win32":+ return None+ from .providers import windows_setup++ return windows_setup.info()++def _for_display(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:"""A shipped entry's title and wording are left out when the user has not changed- them, so the app can show them in the user's language; a user's own text is kept."""+ them, so the app can show them in the user's language; a user's own text is kept.+ `kind` says what the path is on this machine: file, folder, or "" when it is missing."""shipped = {e["name"]: e for e in credentials.DEFAULT_ENTRIES}out = []for row in rows:@@ -91,10 +102,67 @@ def _for_display(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:for key in ("title", "does"):if row.get(key) == base.get(key):row.pop(key, None)+ row["kind"] = credentials.kind_of(str(row.get("path") or ""))+ row["shipped"] = base is not Noneout.append(row)return out+def run_windows_setup() -> dict[str, Any]:+ """The setup dialog's "Set up now" (UX-053): run the elevated setup, prove the wall+ from inside a throwaway sandbox, and only then make the Windows sandbox this+ machine's choice. Returns the outcome with the new snapshot."""+ if sys.platform != "win32":+ return {"ok": False, "error": "the Windows sandbox exists only on Windows", **snapshot()}+ from .providers import windows_setup++ ok, said = windows_setup.run_setup()+ if not ok:+ return {"ok": False, "error": said or "setup did not finish", "said": said, **snapshot()}+ checked, detail = _throwaway_check()+ if not checked:+ return {"ok": False, "error": f"setup ran, but a throwaway sandbox failed its check: {detail}", "said": said, **snapshot()}+ app_config.set_global_value("sandbox_provider", WINDOWS)+ return {"ok": True, "said": said, "checked": detail, **snapshot()}+++def run_windows_remove() -> dict[str, Any]:+ """"Remove setup": undo what setup made and put the machine back on No sandbox."""+ if sys.platform != "win32":+ return {"ok": False, "error": "the Windows sandbox exists only on Windows", **snapshot()}+ from .providers import windows_setup++ ok, said = windows_setup.run_remove()+ if not ok:+ return {"ok": False, "error": said or "remove did not finish", "said": said, **snapshot()}+ app_config.set_global_value("sandbox_provider", DIRECT)+ return {"ok": True, "said": said, **snapshot()}+++def _throwaway_check() -> tuple[bool, str]:+ """Open one sandbox on an empty folder, let the provider prove the wall (the profile+ is not listable from inside; in the closed mode no local port but the proxy's), and+ close it. (ok, what was proved or what failed)."""+ import shutil+ import tempfile++ from .workspace import open_workspace++ folder = tempfile.mkdtemp(prefix="ow-check-")+ try:+ # The strict profile takes the closed account, so the loopback filters are proved+ # too. open_workspace runs the provider's verify(); it raises when the wall is down.+ ws = open_workspace(+ cwd=folder, provider=WINDOWS, session_id="setup-check", agent="setup", credentials=[], network_profile=network_profiles.DEFAULT_PROFILE, toolchains=[]+ )+ ws.close()+ return True, "your profile is not readable from inside; no local port but the proxy's is reachable"+ except Exception as exc: # noqa: BLE001 - the message is the outcome+ return False, str(exc)+ finally:+ shutil.rmtree(folder, ignore_errors=True)++def update(body: dict[str, Any]) -> dict[str, Any]:"""Apply a partial change and return the new snapshot. Validates before writing."""body = body or {}@@ -129,6 +197,10 @@ def update(body: dict[str, Any]) -> dict[str, Any]:for key in ("title", "path", "does"):if raw.get(key) is not None:row[key] = str(raw[key])+ if raw.get("label") is not None:+ if raw["label"] not in credentials.LABELS:+ return {"ok": False, "error": f"the label for '{raw['name']}' must be credential or configuration"}+ row["label"] = str(raw["label"])if raw.get("hosts") is not None:hosts = raw["hosts"]if not isinstance(hosts, list) or not all(isinstance(h, str) and ":" in h for h in hosts):diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 504f92ac..7677e7d6 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -2402,6 +2402,20 @@ def create_app(manager: SessionManager) -> FastAPI:return sandbox_settings.update(body or {})+ @app.post("/v1/settings/sandbox/setup")+ def settings_sandbox_setup() -> dict[str, Any]:+ # UX-053: the Windows setup dialog. Runs the elevated setup (Windows shows its own+ # prompt), proves the wall in a throwaway sandbox, then makes it the choice.+ from ..sandbox import settings as sandbox_settings++ return sandbox_settings.run_windows_setup()++ @app.post("/v1/settings/sandbox/remove")+ def settings_sandbox_remove() -> dict[str, Any]:+ from ..sandbox import settings as sandbox_settings++ return sandbox_settings.run_windows_remove()+@app.post("/v1/settings/compaction")def settings_set_compaction(body: dict) -> dict[str, Any]:# Auto-compaction overrides (OPE-27): threshold % of the context window, thediff --git a/docs/config.example.toml b/docs/config.example.tomlindex 4a4f1e73..15fcea64 100644--- a/docs/config.example.toml+++ b/docs/config.example.toml@@ -41,10 +41,17 @@ port = 8765# 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.+# 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".# [[sandbox_credentials]]# name = "ssh"# enabled = true+# [[sandbox_credentials]]+# name = "aws-keys"+# path = "~/.aws/credentials"+# label = "credential"+# hosts = ["*.amazonaws.com: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# adds one by name.diff --git a/docs/macos-sandbox.md b/docs/macos-sandbox.mdindex b02d6ff0..5bd95937 100644--- a/docs/macos-sandbox.md+++ b/docs/macos-sandbox.md@@ -78,8 +78,12 @@ nothing to push with. Settings ▸ Sandbox lists files you can share, all off by|---|---|---|---|| `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 |+| `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.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.diff --git a/docs/windows-sandbox.md b/docs/windows-sandbox.mdindex 4f118de5..ac07658b 100644--- a/docs/windows-sandbox.md+++ b/docs/windows-sandbox.md@@ -59,7 +59,11 @@ A few things are true by design:## Turn it on-Settings ▸ Sandbox ▸ "Windows sandbox", or in `config.toml`:+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`:```tomlsandbox_provider = "windows" # or "direct": commands run in the OpenWorker process@@ -68,12 +72,15 @@ sandbox_network_profile = "open" # the Windows default; or "strict", "standarThe setting is per machine; a project's own config cannot change it.-Choosing the Windows sandbox is choosing to set it up: OpenWorker shows what the one-time-setup changes and runs it on one administrator prompt (the command line form is-`openworker machine sandbox setup`). Until setup has run, the option cannot be used and the-machine stays on "No sandbox". There is no weaker mode. If setup is later found broken (an-account deleted, the rule or a filter gone), sessions on the machine are refused with the-way to set it up again, rather than run without the sandbox.+Choosing the Windows sandbox is choosing to set it up (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+found broken (an account deleted, the rule or a filter gone), sessions on the machine are+refused with the way to set it up again, rather than run without the sandbox. Switching the+sandbox off keeps the setup on the PC; "Remove setup" under the type undoes it.++Someone who is not an administrator sees the type with the command to hand to one.## What the setup does@@ -175,12 +182,15 @@ Not readable:By default the sandbox has none of your logins, which also means `git push` over SSH hasnothing 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` | use `aws` with your profiles | `*.amazonaws.com:443` |-| `kube` | `~/.kube` | use `kubectl` with your clusters | the servers named in the kubeconfig |+| 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).A copy is written into the sandbox account's own profile by the runner, so that WindowsOpenSSH accepts the key's permissions, and removed when the runner leaves. In the closeddiff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex 7b0f8e1f..600bda47 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -2092,10 +2092,21 @@ export async function getReviewerStats(sessionId: string): Promise<ReviewerStatsexport interface SandboxCredentialEntry {name: string;title?: string;- path?: string;+ path?: string; // a file or a folder under the home folderhosts?: string[];does?: string;+ label?: "credential" | "configuration"; // what is in itenabled: boolean;+ kind?: "file" | "folder" | ""; // display only: what the path is on this machine ("" = missing)+ shipped?: boolean; // display only: in the default list+}+// UX-053: the Windows one-time setup, as the page sees it (null off Windows).+export interface WindowsSetupInfo {+ state: "not_set_up" | "older" | "broken" | "ready";+ set_up_at: string; // ISO date, "" when unknown+ problem: string;+ can_elevate: boolean; // this user can answer the administrator prompt+ command: string; // to hand to an administrator}export interface SandboxToolchainEntry {name: string;@@ -2111,6 +2122,7 @@ export interface SandboxSettings {effective_provider: string;refused: string;providers: { name: string; usable: boolean; why: string }[];+ windows_setup: WindowsSetupInfo | null;network_profile: string;network_profiles: { name: string; hosts: string[] }[];credentials: SandboxCredentialEntry[];@@ -2135,6 +2147,21 @@ export async function setSandboxSettings(return res.json();}+// UX-053: "Set up now" in the Windows setup dialog. The server runs the elevated setup+// (Windows shows its own prompt), proves the wall in a throwaway sandbox, and makes the+// Windows sandbox the machine's choice. Blocks until Windows answers.+export async function runSandboxSetup(+ machineId?: string | null,+): Promise<{ ok: boolean; error?: string; said?: string; checked?: string } & Partial<SandboxSettings>> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/setup`, { method: "POST" });+ return res.json();+}++export async function runSandboxRemove(machineId?: string | null): Promise<{ ok: boolean; error?: string; said?: string } & Partial<SandboxSettings>> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox/remove`, { method: "POST" });+ return res.json();+}+export async function getSettings(machineId?: string | null): Promise<ModelSettings> {const res = await fetch(`${engineBase(machineId)}/v1/settings`);return res.json();diff --git a/surfaces/gui/src/components/SandboxSection.tsx b/surfaces/gui/src/components/SandboxSection.tsxnew file mode 100644index 00000000..6fa0fc09--- /dev/null+++ b/surfaces/gui/src/components/SandboxSection.tsx@@ -0,0 +1,737 @@+// Settings ▸ Sandbox (UX-051 A, UX-053 v3): one switch first; on reveals the sandbox type;+// a ready type reveals only its own options (network, the files an agent may be given,+// the tool folders the sandbox may read). Choosing the Windows sandbox opens its setup+// dialog, which runs the one-time elevated setup and proves the wall before the choice+// takes effect. Everything here is machine-level (the machine's config.toml through+// /v1/settings/sandbox); nothing is per project.+import { useEffect, useState } from "react";+import { useTranslation } from "react-i18next";+import {+ getSandboxSettings,+ runSandboxRemove,+ runSandboxSetup,+ setSandboxSettings,+ type Machine,+ type SandboxCredentialEntry,+ type SandboxSettings,+ type SandboxToolchainEntry,+} from "../api";+import { chooseFolder } from "../tauri";+import { Toggle } from "./Toggle";+import { PanelHead } from "./IntegrationsView";++const CARD = "rounded-xl2 border border-line bg-panel";+const FIELD_LABEL = "text-ui font-medium text-ink";+const FIELD_HELP = "text-meta text-muted mt-1.5 leading-relaxed";+const INPUT =+ "flex-1 min-w-0 px-3 py-2 rounded-lg border border-line bg-paper text-ui text-ink outline-none focus:border-accent";+const BTN_ACCENT = "text-ui px-3 py-2 rounded-lg bg-accent text-white shrink-0 disabled:opacity-40";+const BTN_BORDERED = "text-ui px-3 py-2 rounded-lg border border-line bg-paper hover:border-lineStrong shrink-0";+const TAG = "inline-flex items-center rounded px-1.5 text-label font-medium leading-5";++type SetupStage = "ask" | "working" | "done" | "failed";++function Chevron({ open }: { open: boolean }) {+ return (+ <svg+ viewBox="0 0 20 20"+ fill="none"+ stroke="currentColor"+ strokeWidth="1.6"+ className={"w-5 h-5 text-faint transition-transform shrink-0 " + (open ? "rotate-90" : "")}+ aria-hidden="true"+ >+ <path d="M8 5l5 5-5 5" />+ </svg>+ );+}++// A card that is one line until opened: chevron, title, one sentence, and a summary on+// the right. The body is the card's own list plus a foot with its action.+function DisclosureCard({+ id,+ open,+ onToggle,+ title,+ desc,+ summary,+ children,+}: {+ id: string;+ open: boolean;+ onToggle: () => void;+ title: string;+ desc: string;+ summary: React.ReactNode;+ children: React.ReactNode;+}) {+ return (+ <div className={CARD + " mb-2.5"} data-testid={`sandbox-card-${id}`}>+ <button+ type="button"+ className={"w-full text-left flex items-center gap-3 px-4 py-3 hover:bg-chrome rounded-xl2 " + (open ? "border-b border-line rounded-b-none" : "")}+ onClick={onToggle}+ aria-expanded={open}+ data-testid={`sandbox-card-${id}-toggle`}+ >+ <Chevron open={open} />+ <span className="flex-1 min-w-0">+ <span className="block text-ui font-medium text-ink">{title}</span>+ <span className="block text-meta text-muted">{desc}</span>+ </span>+ <span className="text-meta text-faint text-right shrink-0 max-w-[360px] flex flex-wrap justify-end gap-1.5">{summary}</span>+ </button>+ {open ? <div data-testid={`sandbox-card-${id}-body`}>{children}</div> : null}+ </div>+ );+}++function Chip({ on, children }: { on: boolean; children: React.ReactNode }) {+ return (+ <span className={"inline-flex items-center gap-1.5 rounded-full border px-2 py-px text-meta whitespace-nowrap " + (on ? "border-lineStrong text-muted" : "border-dashed border-lineStrong text-faint")}>+ {on ? <span className="w-1.5 h-1.5 rounded-full bg-ok" /> : null}+ {children}+ </span>+ );+}++function Modal({ children, testid }: { children: React.ReactNode; testid: string }) {+ return (+ <div className="fixed inset-0 z-50" role="dialog" aria-modal="true" data-testid={testid}>+ <div className="absolute inset-0 bg-black/30 backdrop-blur-[1px]" />+ <div className="absolute left-1/2 top-[12vh] -translate-x-1/2 w-[640px] max-w-[94vw] max-h-[80vh] rounded-xl2 border border-line bg-panel shadow-2xl overflow-auto p-6">+ {children}+ </div>+ </div>+ );+}++const SETUP_CHANGES = ["accounts", "rules", "folder", "record"] as const;++export function SandboxSection({ machine }: { machine?: Machine | null }) {+ const { t } = useTranslation();+ const mid = machine?.id ?? null;+ const [cfg, setCfg] = useState<SandboxSettings | null>(null);+ const [error, setError] = useState<string>("");+ const [wantOn, setWantOn] = useState(false); // the switch is on, no type is ready yet+ const [openCard, setOpenCard] = useState<"files" | "tools" | null>(null);+ const [editing, setEditing] = useState<string | null>(null); // credential name being edited, "" = new+ const [addingTool, setAddingTool] = useState(false); // the "Add a folder" editor of the toolchain list+ const [toolTitle, setToolTitle] = useState("");+ const [toolPath, setToolPath] = useState("~/");+ const [setupStage, setSetupStage] = useState<SetupStage | null>(null);+ const [setupOutcome, setSetupOutcome] = useState<{ checked?: string; error?: string }>({});+ const [removing, setRemoving] = useState(false);+ const [removeBusy, setRemoveBusy] = useState(false);++ useEffect(() => {+ getSandboxSettings(mid).then(setCfg).catch(() => setCfg(null));+ }, [mid]);++ const save = async (patch: Parameters<typeof setSandboxSettings>[0]) => {+ const res = await setSandboxSettings(patch, mid);+ if (!res.ok) {+ setError(res.error || "could not save");+ return;+ }+ setError("");+ setCfg(res as SandboxSettings);+ };++ if (!cfg) return null;+ const isWindows = cfg.platform === "win32";+ const isMac = cfg.platform === "darwin";+ const providerNames: Record<string, [string, string]> = {+ seatbelt: [t("settingsx.sandbox.provider_seatbelt"), t("settingsx.sandbox.provider_seatbelt_desc")],+ windows: [t("settingsx.sandbox.provider_windows"), t("settingsx.sandbox.provider_windows_desc")],+ openshell: [t("settingsx.sandbox.provider_openshell"), t("settingsx.sandbox.provider_openshell_desc")],+ };+ const chosen = cfg.provider || cfg.effective_provider || "direct";+ const active = chosen !== "direct"; // a type is the machine's choice+ const on = active || wantOn;+ const setup = cfg.windows_setup;+ const setupReady = setup?.state === "ready";+ const types = cfg.providers.filter((p) => p.name !== "direct" && (p.name !== "seatbelt" || isMac) && (p.name !== "windows" || isWindows));+ const anyType = types.some((p) => p.usable || (p.name === "windows" && setup?.can_elevate));+ const shipped = (name: string, key: "title" | "does", fallback?: string) => {+ const k = `settingsx.sandbox.${key}_${name}`;+ const v = t(k);+ return v === k ? fallback || "" : v;+ };+ const updateCredentials = (rows: SandboxCredentialEntry[]) =>+ save({ credentials: rows.map(({ kind: _k, shipped: _s, ...row }) => row) });+ const updateToolchains = (rows: SandboxToolchainEntry[]) =>+ save({ toolchains: rows.map(({ exists: _e, shipped: _s, ...row }) => row) });++ const switchStatus = !on+ ? t("settingsx.sandbox.switch_off")+ : active+ ? t("settingsx.sandbox.switch_on", { type: providerNames[chosen]?.[0] ?? chosen })+ : anyType+ ? t("settingsx.sandbox.switch_choose")+ : t("settingsx.sandbox.switch_none");++ const flip = (next: boolean) => {+ if (next) {+ setWantOn(true);+ return;+ }+ setWantOn(false);+ if (active) void save({ provider: "direct" });+ };++ const chooseType = (name: string) => {+ if (name === "windows" && !setupReady) {+ if (setup?.can_elevate) {+ setSetupOutcome({});+ setSetupStage("ask");+ }+ return;+ }+ void save({ provider: name });+ };++ const runSetup = async () => {+ setSetupStage("working");+ const res = await runSandboxSetup(mid);+ if (res.ok) {+ setCfg(res as SandboxSettings);+ setWantOn(false);+ setSetupOutcome({ checked: res.checked });+ setSetupStage("done");+ } else {+ if (res.platform) setCfg(res as SandboxSettings);+ setSetupOutcome({ error: res.error || "setup did not finish" });+ setSetupStage("failed");+ }+ };++ const runRemove = async () => {+ setRemoveBusy(true);+ const res = await runSandboxRemove(mid);+ setRemoveBusy(false);+ if (res.ok) {+ setCfg(res as SandboxSettings);+ setWantOn(false);+ setRemoving(false);+ } else {+ setError(res.error || "could not remove the setup");+ setRemoving(false);+ }+ };++ const setUpOn = setup?.set_up_at ? new Date(setup.set_up_at) : null;+ const setUpOnText = setUpOn && !Number.isNaN(setUpOn.getTime()) ? setUpOn.toLocaleDateString(undefined, { day: "numeric", month: "short", year: "numeric" }) : "";++ // The network list: Open first where it is the default (Windows).+ const profiles = isWindows ? [...cfg.network_profiles].sort((a, b) => (a.name === "open" ? -1 : b.name === "open" ? 1 : 0)) : cfg.network_profiles;+ const showTools = cfg.platform !== "linux" && chosen !== "openshell" && Boolean(cfg.toolchains);+ const toolsOn = (cfg.toolchains || []).filter((x) => x.enabled);++ return (+ <section data-testid="sandbox-section">+ <PanelHead+ title={t("settingsx.sandbox.title")}+ sub={machine ? t("settingsx.sandbox.sub_machine", { name: machine.name }) : isWindows ? t("settingsx.sandbox.sub_windows") : t("settingsx.sandbox.sub")}+ />+ {error ? <div className="mb-3 text-meta text-danger">{error}</div> : null}++ {/* 1. The switch */}+ <div className={CARD + " mb-1"}>+ <div className="flex items-start gap-3.5 px-4 py-3.5">+ <span className="mt-0.5">+ <Toggle checked={on} onChange={flip} title={t("settingsx.sandbox.switch_title")} />+ </span>+ <span className="flex-1 min-w-0">+ <span className="block text-ui font-medium text-ink">{t("settingsx.sandbox.switch_title")}</span>+ <span className="block text-meta text-muted max-w-[640px]">{t("settingsx.sandbox.switch_desc")}</span>+ </span>+ <span+ className={"text-meta shrink-0 whitespace-nowrap pt-0.5 " + (active ? "text-ok" : on && !anyType ? "text-warnInk" : "text-faint")}+ data-testid="sandbox-switch-status"+ >+ {switchStatus}+ </span>+ </div>+ </div>+ {!on ? <div className={FIELD_HELP + " mb-4"}>{t("settingsx.sandbox.switch_help_off")}</div> : <div className="mb-4" />}+ {cfg.refused ? <div className="mb-4 text-meta text-danger">{t("settingsx.sandbox.refused", { why: cfg.refused })}</div> : null}++ {/* 2. The type, once the switch is on */}+ {on ? (+ <>+ <div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.type")}</div>+ <div className={CARD + " mb-1 divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.type")}>+ {types.map((p) => {+ const [label, desc] = providerNames[p.name] ?? [p.name, ""];+ const isActive = chosen === p.name;+ const win = p.name === "windows";+ const canPick = p.usable || (win && Boolean(setup?.can_elevate));+ const why = !p.usable ? (win && setup && !setup.can_elevate ? t("settingsx.sandbox.needs_admin_why", { command: setup.command }) : win && setup?.can_elevate ? "" : p.why) : "";+ const status = win+ ? setupReady+ ? t("settingsx.sandbox.status_ready")+ : setup?.can_elevate+ ? t("settingsx.sandbox.status_setup")+ : t("settingsx.sandbox.status_needs_admin")+ : p.usable+ ? t("settingsx.sandbox.status_ready")+ : t("settingsx.sandbox.status_unavailable");+ 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}+ {win && setupReady ? (+ <span className="block text-meta text-muted mt-1.5" data-testid="sandbox-windows-setup-line">+ {setUpOnText ? t("settingsx.sandbox.set_up_on", { date: setUpOnText }) : t("settingsx.sandbox.set_up")}+ <span className="mx-1.5 text-faint">·</span>+ <button type="button" className="text-accent hover:underline" onClick={() => setRemoving(true)} data-testid="sandbox-remove-setup">+ {t("settingsx.sandbox.remove_setup")}+ </button>+ </span>+ ) : null}+ </span>+ <span className={"text-meta shrink-0 whitespace-nowrap pt-0.5 " + (win && !setupReady && setup && !setup.can_elevate ? "text-warnInk" : isActive || (win ? setupReady : p.usable) ? "text-ok" : "text-faint")}>+ {status}+ </span>+ </label>+ );+ })}+ </div>+ <div className={FIELD_HELP + " mb-4"}>+ {!active ? (anyType ? t("settingsx.sandbox.type_help") : t("settingsx.sandbox.type_help_admin")) : ""}+ </div>+ </>+ ) : null}++ {/* 3. The type's own options */}+ {active ? (+ <>+ <div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.network")}</div>+ <div className={CARD + " divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.network")}>+ {profiles.map((np) => (+ <label key={np.name} className="flex items-start gap-3 px-4 py-2.5 cursor-pointer">+ <input+ type="radio"+ name="sandbox-network"+ className="mt-1"+ checked={cfg.network_profile === np.name}+ onChange={() => save({ network_profile: np.name })}+ data-testid={`sandbox-network-${np.name}`}+ />+ <span className="flex-1 min-w-0 flex items-baseline gap-3">+ <span className="text-ui text-ink">{t(`settingsx.sandbox.profile_${np.name}`)}</span>+ <span className="text-meta text-muted ml-auto text-right">+ {t(`settingsx.sandbox.profile_${np.name}_desc`)}+ {np.name === "open" && isWindows ? " " + t("settingsx.sandbox.profile_open_default") : ""}+ </span>+ </span>+ </label>+ ))}+ </div>+ <div className={FIELD_HELP + " mb-5"}>+ {chosen === "windows" ? t("settingsx.sandbox.network_help_windows") : chosen === "openshell" ? t("settingsx.sandbox.network_help_openshell") : t("settingsx.sandbox.network_help")}+ </div>++ <div className={FIELD_LABEL}>{t("settingsx.sandbox.credentials")}</div>+ <div className={FIELD_HELP + " mb-2.5 mt-0.5"}>{t("settingsx.sandbox.credentials_intro")}</div>+ <DisclosureCard+ id="files"+ open={openCard === "files"}+ onToggle={() => setOpenCard(openCard === "files" ? null : "files")}+ title={isWindows ? t("settingsx.sandbox.files_title_windows") : isMac ? t("settingsx.sandbox.files_title_mac") : t("settingsx.sandbox.files_title")}+ desc={t("settingsx.sandbox.files_desc")}+ summary={+ cfg.credentials.length ? (+ cfg.credentials.map((c) => (+ <Chip key={c.name} on={c.enabled}>+ {c.title || shipped(c.name, "title", c.name)}+ </Chip>+ ))+ ) : (+ <span>{t("settingsx.sandbox.none_yet")}</span>+ )+ }+ >+ <div className="divide-y divide-line">+ {cfg.credentials.map((c) => (+ <div key={c.name} className="flex items-start gap-3 pl-6 pr-4 py-3" data-testid={`sandbox-credential-${c.name}`}>+ <input+ type="checkbox"+ className="mt-1"+ checked={c.enabled}+ onChange={(e) => updateCredentials(cfg.credentials.map((x) => (x.name === c.name ? { ...x, enabled: e.target.checked } : x)))}+ aria-label={c.title || shipped(c.name, "title", c.name)}+ />+ <span className="flex-1 min-w-0">+ <span className="flex items-center flex-wrap gap-2 text-ui text-ink">+ {c.title || shipped(c.name, "title", c.name)}+ <code className="text-meta text-muted font-mono">{c.path}</code>+ {c.kind ? (+ <span className={TAG + " bg-accentSoft text-accent"} data-testid={`sandbox-credential-${c.name}-kind`}>+ {t(c.kind === "folder" ? "settingsx.sandbox.kind_folder" : "settingsx.sandbox.kind_file")}+ </span>+ ) : (+ <span className="text-meta text-faint">{t("settingsx.sandbox.credential_missing")}</span>+ )}+ <span className={TAG + " " + (c.label === "configuration" ? "bg-paper text-muted" : "bg-warnSoft text-warnInk")}>+ {t(c.label === "configuration" ? "settingsx.sandbox.label_configuration" : "settingsx.sandbox.label_credential")}+ </span>+ </span>+ <span className="block text-meta text-muted">+ {c.does ? c.does : shipped(c.name, "does")}{" "}+ {c.hosts && c.hosts.length && cfg.network_profile !== "open" ? (+ <span className="text-faint">{t("settingsx.sandbox.also_allows", { hosts: c.hosts.join(", ") })}</span>+ ) : null}+ </span>+ </span>+ <span className="text-meta text-muted shrink-0 whitespace-nowrap">+ <button className="hover:text-ink" onClick={() => setEditing(c.name)}>+ {t("settingsx.sandbox.edit")}+ </button>+ <span className="mx-1.5 text-faint">·</span>+ <button className="hover:text-ink" onClick={() => updateCredentials(cfg.credentials.filter((x) => x.name !== c.name))}>+ {t("settingsx.sandbox.remove")}+ </button>+ </span>+ </div>+ ))}+ </div>+ <div className="flex items-center gap-3.5 pl-6 pr-4 py-3 bg-chrome border-t border-line rounded-b-xl2">+ <span className="text-meta text-faint flex-1">+ {t("settingsx.sandbox.files_foot")} {isWindows ? t("settingsx.sandbox.credman_note") : isMac ? t("settingsx.sandbox.keychain_note") : ""}+ </span>+ <button className={BTN_BORDERED + " text-meta px-2.5 py-1"} onClick={() => setEditing("")} data-testid="sandbox-credential-add">+ {t("settingsx.sandbox.add")}+ </button>+ </div>+ </DisclosureCard>+ {editing !== null ? (+ <CredentialEditor+ entry={editing ? cfg.credentials.find((c) => c.name === editing) ?? null : null}+ onCancel={() => setEditing(null)}+ onSave={(row) => {+ const rows = editing ? cfg.credentials.map((x) => (x.name === editing ? row : x)) : [...cfg.credentials, row];+ setEditing(null);+ updateCredentials(rows);+ }}+ />+ ) : null}++ {showTools ? (+ <>+ <div className={FIELD_LABEL + " mt-5 mb-2"}>{t("settingsx.sandbox.tools")}</div>+ <DisclosureCard+ id="tools"+ open={openCard === "tools"}+ onToggle={() => setOpenCard(openCard === "tools" ? null : "tools")}+ title={t("settingsx.sandbox.toolchains")}+ desc={t("settingsx.sandbox.tools_desc")}+ summary={+ <span data-testid="sandbox-tools-summary">+ {t("settingsx.sandbox.tools_count", { on: toolsOn.length, total: (cfg.toolchains || []).length })}+ {toolsOn.length ? " · " + toolsOn.slice(0, 6).map((x) => x.title || x.name).join(", ") + (toolsOn.length > 6 ? "…" : "") : ""}+ </span>+ }+ >+ <div className="divide-y divide-line">+ {cfg.toolchains.map((tc) => (+ <div key={tc.name} className="flex items-start gap-3 pl-6 pr-4 py-2.5" data-testid={`sandbox-toolchain-${tc.name}`}>+ <input+ type="checkbox"+ className="mt-1"+ checked={tc.enabled}+ onChange={(e) => updateToolchains(cfg.toolchains.map((x) => (x.name === tc.name ? { ...x, enabled: e.target.checked } : x)))}+ aria-label={tc.title || tc.name}+ />+ <span className="flex-1 min-w-0">+ <span className={"block text-ui " + (tc.exists === false ? "text-muted" : "text-ink")}>+ {tc.title || tc.name}+ {tc.exists === false ? <span className="text-meta text-faint"> · {t("settingsx.sandbox.toolchain_missing")}</span> : null}+ {!tc.shipped ? <span className="text-meta text-faint"> · {t("settingsx.sandbox.added_by_you")}</span> : null}+ </span>+ </span>+ <code className="text-meta text-muted font-mono shrink-0">{tc.path}</code>+ {!tc.shipped ? (+ <button className="text-meta text-muted hover:text-ink shrink-0" onClick={() => updateToolchains(cfg.toolchains.filter((x) => x.name !== tc.name))}>+ {t("settingsx.sandbox.remove")}+ </button>+ ) : null}+ </div>+ ))}+ </div>+ <div className="flex items-center gap-3.5 pl-6 pr-4 py-3 bg-chrome border-t border-line rounded-b-xl2">+ <span className="text-meta text-faint flex-1">{isWindows ? t("settingsx.sandbox.tools_foot_windows") : t("settingsx.sandbox.toolchains_help")}</span>+ <button className={BTN_BORDERED + " text-meta px-2.5 py-1"} onClick={() => setAddingTool(true)} data-testid="sandbox-toolchain-add">+ {t("settingsx.sandbox.add_toolchain")}+ </button>+ </div>+ </DisclosureCard>+ {addingTool ? (+ <div className={CARD + " p-4 mt-3"} data-testid="sandbox-toolchain-editor">+ <div className="grid grid-cols-[150px_1fr] gap-x-3 gap-y-2 items-center">+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_title")}</label>+ <input className={INPUT} value={toolTitle} onChange={(e) => setToolTitle(e.target.value)} />+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_toolchain_path")}</label>+ <div className="flex gap-2">+ <input className={INPUT + " font-mono"} value={toolPath} onChange={(e) => setToolPath(e.target.value)} />+ <button+ className={BTN_BORDERED}+ onClick={async () => {+ const picked = await chooseFolder();+ if (picked) setToolPath(picked);+ }}+ >+ {t("settingsx.sandbox.browse")}+ </button>+ </div>+ </div>+ <div className="flex justify-end gap-2 mt-3">+ <button className={BTN_BORDERED} onClick={() => setAddingTool(false)}>+ {t("settingsx.sandbox.cancel")}+ </button>+ <button+ className={BTN_ACCENT}+ disabled={!validPath(toolPath)}+ onClick={() => {+ const slug = (toolTitle || toolPath).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");+ setAddingTool(false);+ setToolTitle("");+ setToolPath("~/");+ updateToolchains([...cfg.toolchains, { name: slug, title: toolTitle || undefined, path: toolPath, enabled: true }]);+ }}+ >+ {t("settingsx.sandbox.done")}+ </button>+ </div>+ </div>+ ) : null}+ </>+ ) : null}+ <div className={FIELD_HELP + " mt-4"}>{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div>+ </>+ ) : null}++ {/* The Windows setup dialog */}+ {setupStage ? (+ <Modal testid="sandbox-setup-dialog">+ {setupStage === "ask" ? (+ <>+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_title")}</h3>+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_intro")}</p>+ <div className="text-label font-medium text-faint mb-1.5">{t("settingsx.sandbox.setup_changes")}</div>+ <div className="grid gap-2.5">+ {SETUP_CHANGES.map((k) => (+ <div key={k} className="text-ui leading-relaxed">+ {t(`settingsx.sandbox.setup_change_${k}`)}+ <div className="text-meta text-muted">{t(`settingsx.sandbox.setup_change_${k}_desc`)}</div>+ </div>+ ))}+ </div>+ <div className="flex items-center gap-2 mt-4">+ <span className="text-meta text-faint max-w-[320px] leading-relaxed">{t("settingsx.sandbox.setup_not_now_note")}</span>+ <span className="flex-1" />+ <button+ className={BTN_BORDERED}+ onClick={() => {+ setSetupStage(null);+ setWantOn(false);+ }}+ data-testid="sandbox-setup-not-now"+ >+ {t("settingsx.sandbox.not_now")}+ </button>+ <button className={BTN_ACCENT} onClick={runSetup} data-testid="sandbox-setup-now">+ {t("settingsx.sandbox.set_up_now")}+ </button>+ </div>+ </>+ ) : setupStage === "working" ? (+ <>+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_working_title")}</h3>+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_working_intro")}</p>+ <div className="rounded-lg border border-line bg-paper px-3 py-2.5 text-ui text-muted flex items-center gap-2.5">+ <span className="w-4 h-4 rounded-full border-2 border-lineStrong border-t-accent animate-spin shrink-0" />+ {t("settingsx.sandbox.setup_waiting")}+ </div>+ </>+ ) : setupStage === "done" ? (+ <>+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_done_title")}</h3>+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_done_intro")}</p>+ <div className="rounded-lg border border-okLine bg-okSoft px-3 py-2.5 text-ui text-ok leading-relaxed" data-testid="sandbox-setup-done-box">+ {t("settingsx.sandbox.setup_done_box", { checked: setupOutcome.checked || "" })}+ </div>+ <div className="flex justify-end mt-4">+ <button className={BTN_ACCENT} onClick={() => setSetupStage(null)} data-testid="sandbox-setup-done">+ {t("settingsx.sandbox.done")}+ </button>+ </div>+ </>+ ) : (+ <>+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.setup_failed_title")}</h3>+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.setup_failed_intro")}</p>+ <div className="rounded-lg border border-line bg-paper px-3 py-2.5 text-meta text-danger font-mono whitespace-pre-wrap break-words" data-testid="sandbox-setup-error">+ {setupOutcome.error}+ </div>+ <div className="flex justify-end gap-2 mt-4">+ <button+ className={BTN_BORDERED}+ onClick={() => {+ setSetupStage(null);+ setWantOn(false);+ }}+ >+ {t("settingsx.sandbox.close")}+ </button>+ <button className={BTN_ACCENT} onClick={() => setSetupStage("ask")}>+ {t("settingsx.sandbox.try_again")}+ </button>+ </div>+ </>+ )}+ </Modal>+ ) : null}++ {/* The Remove setup confirmation */}+ {removing ? (+ <Modal testid="sandbox-remove-dialog">+ <h3 className="text-heading font-semibold mb-1.5">{t("settingsx.sandbox.remove_title")}</h3>+ <p className="text-ui text-muted mb-3.5 leading-relaxed">{t("settingsx.sandbox.remove_intro")}</p>+ <div className="text-label font-medium text-faint mb-1.5">{t("settingsx.sandbox.remove_what")}</div>+ <div className="grid gap-2.5">+ {SETUP_CHANGES.map((k) => (+ <div key={k} className="text-ui leading-relaxed">+ {t(`settingsx.sandbox.setup_change_${k}`)}+ <div className="text-meta text-muted">{t(`settingsx.sandbox.remove_change_${k}_desc`)}</div>+ </div>+ ))}+ </div>+ <div className="flex items-center gap-2 mt-4">+ <span className="text-meta text-faint max-w-[320px] leading-relaxed">{t("settingsx.sandbox.remove_keep_note")}</span>+ <span className="flex-1" />+ <button className={BTN_BORDERED} onClick={() => setRemoving(false)} disabled={removeBusy}>+ {t("settingsx.sandbox.cancel")}+ </button>+ <button className={BTN_ACCENT} onClick={runRemove} disabled={removeBusy} data-testid="sandbox-remove-confirm">+ {removeBusy ? t("settingsx.sandbox.setup_waiting") : t("settingsx.sandbox.remove")}+ </button>+ </div>+ </Modal>+ ) : null}+ </section>+ );+}++function validPath(path: string): boolean {+ return (path.startsWith("~/") || path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path)) && path.length >= 3;+}++// Add or edit one entry: a file or a folder under the home folder, what is in it, the+// hosts its tool needs, and what it lets the agent do.+export function CredentialEditor({+ entry,+ onCancel,+ onSave,+}: {+ entry: SandboxCredentialEntry | null;+ onCancel: () => void;+ onSave: (row: SandboxCredentialEntry) => void;+}) {+ const { t } = useTranslation();+ const [title, setTitle] = useState(entry?.title ?? "");+ const [name, setName] = useState(entry?.name ?? "");+ const [path, setPath] = useState(entry?.path ?? "~/");+ const [hosts, setHosts] = useState((entry?.hosts ?? []).join("\n"));+ const [does, setDoes] = useState(entry?.does ?? "");+ const [label, setLabel] = useState<"credential" | "configuration">(entry?.label === "configuration" ? "configuration" : "credential");+ const slug = entry?.name || name || title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");+ const valid = Boolean(slug) && validPath(path);+ return (+ <div className={CARD + " p-4 mt-3"} data-testid="sandbox-credential-editor">+ <div className="grid grid-cols-[150px_1fr] gap-x-3 gap-y-2 items-center">+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_title")}</label>+ <input+ className={INPUT}+ value={title}+ onChange={(e) => {+ setTitle(e.target.value);+ if (!entry) setName("");+ }}+ />+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_path")}</label>+ <div className="flex gap-2">+ <input className={INPUT + " font-mono"} value={path} onChange={(e) => setPath(e.target.value)} />+ <button+ className={BTN_BORDERED}+ onClick={async () => {+ const picked = await chooseFolder();+ if (picked) setPath(picked);+ }}+ >+ {t("settingsx.sandbox.browse")}+ </button>+ </div>+ <label className="text-ui text-muted self-start pt-2">{t("settingsx.sandbox.field_label")}</label>+ <div className="grid grid-cols-2 gap-2" role="radiogroup" aria-label={t("settingsx.sandbox.field_label")}>+ {(["credential", "configuration"] as const).map((k) => (+ <label key={k} className={"flex items-start gap-2.5 rounded-lg border px-3 py-2 cursor-pointer " + (label === k ? "border-accent bg-accentSoft" : "border-line")}>+ <input type="radio" name="sandbox-credential-label" className="mt-1" checked={label === k} onChange={() => setLabel(k)} data-testid={`sandbox-credential-label-${k}`} />+ <span>+ <span className="block text-ui text-ink">{t(`settingsx.sandbox.label_${k}_title`)}</span>+ <span className="block text-meta text-muted">{t(`settingsx.sandbox.label_${k}_desc`)}</span>+ </span>+ </label>+ ))}+ </div>+ <label className="text-ui text-muted self-start pt-2">{t("settingsx.sandbox.field_hosts")}</label>+ <textarea className={INPUT + " font-mono"} rows={3} value={hosts} onChange={(e) => setHosts(e.target.value)} />+ <label className="text-ui text-muted">{t("settingsx.sandbox.field_does")}</label>+ <input className={INPUT} value={does} onChange={(e) => setDoes(e.target.value)} />+ </div>+ <div className="flex items-center gap-2 mt-3">+ <span className="text-meta text-faint">{t("settingsx.sandbox.editor_note")}</span>+ <span className="flex-1" />+ <button className={BTN_BORDERED} onClick={onCancel}>+ {t("settingsx.sandbox.cancel")}+ </button>+ <button+ className={BTN_ACCENT}+ disabled={!valid}+ onClick={() =>+ onSave({+ name: slug,+ title: title || undefined,+ path,+ hosts: hosts+ .split(/\s+/)+ .map((h) => h.trim())+ .filter(Boolean),+ does: does || undefined,+ label,+ enabled: entry?.enabled ?? true,+ })+ }+ >+ {t("settingsx.sandbox.done")}+ </button>+ </div>+ </div>+ );+}diff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsxindex 40bd3cb0..a4a64b50 100644--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx@@ -1,9 +1,11 @@-// Settings ▸ Sandbox (UX-051 A): the page shows what the machine reports and writes back-// the three kinds of change: provider, network profile, credential list.+// Settings ▸ Sandbox (UX-051 A, UX-053 v3): one switch first; on reveals the type; a ready+// type reveals its options. The page shows what the machine reports and writes back the+// changes: provider, network profile, credential list, toolchain list. On Windows, choosing+// the sandbox opens the setup dialog, which calls the setup route.import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";-import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import { cleanup, fireEvent, render, screen, waitFor, within } from "@testing-library/react";-const snapshot = {+const base = {platform: "darwin",provider: "",effective_provider: "direct",@@ -13,14 +15,17 @@ const snapshot = {{ name: "seatbelt", usable: true, why: "" },{ name: "openshell", usable: false, why: "OpenShell is not installed" },],+ windows_setup: null as any,network_profile: "strict",network_profiles: [{ name: "strict", hosts: ["github.com"] },{ name: "standard", hosts: ["github.com", "api.tavily.com"] },+ { name: "open", hosts: [] },],credentials: [- { name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], enabled: false },- { name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], enabled: true },+ { 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 },],toolchains: [{ name: "nvm", title: "nvm (Node versions)", path: "~/.nvm", enabled: true, exists: true, shipped: true },@@ -28,8 +33,11 @@ const snapshot = {],config_path: "/Users/sam/.config/coworker/config.toml",};+let snapshot: any = { ...base };const setSandboxSettings = vi.fn(async (patch: any) => ({ ok: true, ...snapshot, ...patch }));+const runSandboxSetup = vi.fn(async () => ({ ok: true, checked: "the wall held", ...snapshot, provider: "windows", windows_setup: { ...snapshot.windows_setup, state: "ready", set_up_at: "2026-09-28T10:00:00Z" } }));+const runSandboxRemove = vi.fn(async () => ({ ok: true, ...snapshot, provider: "direct", windows_setup: { ...snapshot.windows_setup, state: "not_set_up", set_up_at: "" } }));vi.mock("../api", async (importOriginal) => {const actual = await importOriginal<typeof import("../api")>();@@ -37,6 +45,8 @@ vi.mock("../api", async (importOriginal) => {...actual,getSandboxSettings: vi.fn(async () => snapshot),setSandboxSettings: (patch: any) => setSandboxSettings(patch),+ runSandboxSetup: () => runSandboxSetup(),+ runSandboxRemove: () => runSandboxRemove(),getMachines: vi.fn(async () => ({ machines: [] })),getCloudMachines: vi.fn(async () => ({ machines: [] })),getCloudConnections: vi.fn(async () => []),@@ -48,71 +58,100 @@ vi.mock("../api", async (importOriginal) => {import { SettingsView } from "./SettingsView";+const stripDisplay = (rows: any[]) => rows.map(({ kind: _k, shipped: _s, ...row }) => row);+describe("Settings ▸ Sandbox", () => {- beforeEach(() => setSandboxSettings.mockClear());+ beforeEach(() => {+ snapshot = { ...base };+ setSandboxSettings.mockClear();+ runSandboxSetup.mockClear();+ runSandboxRemove.mockClear();+ });afterEach(cleanup);- it("shows the providers, the allow list and the credential rows from the machine", async () => {+ it("off: one switch and nothing else; on reveals the type card only", async () => {render(<SettingsView initialTab="sandbox" />);await screen.findByTestId("sandbox-section");- expect((screen.getByTestId("sandbox-provider-direct") as HTMLInputElement).checked).toBe(true);+ const sw = screen.getByRole("switch");+ expect(sw.getAttribute("aria-checked")).toBe("false");+ expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("off");+ expect(screen.queryByTestId("sandbox-provider-seatbelt")).toBeNull();+ expect(screen.queryByTestId("sandbox-network-strict")).toBeNull();+ expect(screen.queryByTestId("sandbox-card-files")).toBeNull();+ fireEvent.click(sw);+ expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("choose a type");expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).disabled).toBe(true);expect(screen.getByTestId("sandbox-provider-openshell-why").textContent).toBe("OpenShell is not installed");- expect(screen.getByText("default")).toBeTruthy();- expect((screen.getByTestId("sandbox-network-strict") as HTMLInputElement).checked).toBe(true);- expect(screen.getByText("SSH keys")).toBeTruthy();- expect((screen.getByLabelText("GitHub CLI") as HTMLInputElement).checked).toBe(true);- expect(screen.getByText(/Also allows github.com:22/)).toBeTruthy();- expect(screen.getByText(/config\.toml/)).toBeTruthy();+ expect(screen.queryByTestId("sandbox-network-strict")).toBeNull(); // no type is ready yet+ expect(setSandboxSettings).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId("sandbox-provider-seatbelt"));+ await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ provider: "seatbelt" }));});- it("writes a provider change, a profile change and a credential switch", async () => {+ it("a ready type shows its options; switching off writes direct", async () => {+ snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };render(<SettingsView initialTab="sandbox" />);await screen.findByTestId("sandbox-section");- fireEvent.click(screen.getByTestId("sandbox-provider-seatbelt"));- await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ provider: "seatbelt" }));+ expect(screen.getByTestId("sandbox-switch-status").textContent).toBe("on · macOS sandbox");+ expect((screen.getByTestId("sandbox-network-strict") as HTMLInputElement).checked).toBe(true);fireEvent.click(screen.getByTestId("sandbox-network-standard"));await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ network_profile: "standard" }));+ // the files card is one line until opened; its chips name the entries+ expect(screen.getByTestId("sandbox-card-files")).toBeTruthy();+ expect(screen.queryByTestId("sandbox-card-files-body")).toBeNull();+ expect(within(screen.getByTestId("sandbox-card-files-toggle")).getByText("SSH keys")).toBeTruthy();+ expect(screen.getByTestId("sandbox-tools-summary").textContent).toContain("2 of 2 on");+ expect(screen.getByText(/config\.toml/)).toBeTruthy();+ fireEvent.click(screen.getByRole("switch"));+ await waitFor(() => expect(setSandboxSettings).toHaveBeenLastCalledWith({ provider: "direct" }));+ });++ it("the files card: switch, kind and label tags, add through the editor with a label, remove", async () => {+ snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };+ render(<SettingsView initialTab="sandbox" />);+ await screen.findByTestId("sandbox-section");+ fireEvent.click(screen.getByTestId("sandbox-card-files-toggle"));+ const body = screen.getByTestId("sandbox-card-files-body");+ expect(screen.getByTestId("sandbox-credential-ssh-kind").textContent).toBe("folder");+ expect(screen.getByTestId("sandbox-credential-aws-kind").textContent).toBe("file");+ expect(within(screen.getByTestId("sandbox-credential-gh")).getByText("not on this machine")).toBeTruthy();+ expect(within(screen.getByTestId("sandbox-credential-aws")).getByText("configuration")).toBeTruthy();+ expect(within(body).getByText(/Also allows github.com:22/)).toBeTruthy();fireEvent.click(screen.getByLabelText("SSH keys"));await waitFor(() =>expect(setSandboxSettings).toHaveBeenLastCalledWith({- credentials: [- { name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], enabled: true },- { name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], enabled: true },- ],+ credentials: stripDisplay([{ ...base.credentials[0], enabled: true }, base.credentials[1], base.credentials[2]]),}),);- });-- it("adds an entry through the editor and removes one", async () => {- render(<SettingsView initialTab="sandbox" />);- await screen.findByTestId("sandbox-section");fireEvent.click(screen.getByTestId("sandbox-credential-add"));const editor = screen.getByTestId("sandbox-credential-editor");- const inputs = editor.querySelectorAll("input, textarea");+ const inputs = editor.querySelectorAll("input[type=text], input:not([type]), textarea");fireEvent.change(inputs[0], { target: { value: "npm token" } });fireEvent.change(inputs[1], { target: { value: "~/.npmrc" } });+ fireEvent.click(screen.getByTestId("sandbox-credential-label-configuration"));fireEvent.change(inputs[2], { target: { value: "registry.npmjs.org:443" } });- fireEvent.click(screen.getByText("Done"));+ fireEvent.click(within(editor).getByText("Done"));await waitFor(() =>expect(setSandboxSettings).toHaveBeenLastCalledWith({credentials: [- ...snapshot.credentials,- { name: "npm-token", title: "npm token", path: "~/.npmrc", hosts: ["registry.npmjs.org:443"], does: undefined, enabled: true },+ ...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 },],}),);- fireEvent.click(screen.getAllByText("Remove")[0]);+ 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", "npm-token"]);+ expect(last.credentials.map((c: any) => c.name)).toEqual(["gh", "aws", "npm-token"]);});});- it("switches a toolchain folder off and adds one, without the display-only fields", async () => {+ it("the tools card: switch a folder off and add one, without the display-only fields", async () => {+ snapshot = { ...base, provider: "seatbelt", effective_provider: "seatbelt" };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)"));await waitFor(() =>@@ -126,14 +165,87 @@ describe("Settings ▸ Sandbox", () => {fireEvent.click(screen.getByTestId("sandbox-toolchain-add"));const editor = screen.getByTestId("sandbox-toolchain-editor");const inputs = editor.querySelectorAll("input");- fireEvent.change(inputs[0], { target: { value: "Zig" } });- fireEvent.change(inputs[1], { target: { value: "~/.zig" } });- fireEvent.click(screen.getAllByText("Done")[0]);+ 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.map((c: any) => c.name)).toEqual(["nvm", "mytools", "zig"]);- expect(last.toolchains[2]).toEqual({ name: "zig", title: "Zig", path: "~/.zig", enabled: true });+ expect(last.toolchains[last.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 () => {+ 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" },+ ],+ 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();+ expect(screen.queryByTestId("sandbox-provider-windows-why")).toBeNull(); // an administrator sees no warning+ fireEvent.click(screen.getByTestId("sandbox-provider-windows"));+ const dialog = screen.getByTestId("sandbox-setup-dialog");+ expect(within(dialog).getByText("Set up the Windows sandbox")).toBeTruthy();+ expect(setSandboxSettings).not.toHaveBeenCalled();+ fireEvent.click(screen.getByTestId("sandbox-setup-now"));+ await waitFor(() => expect(runSandboxSetup).toHaveBeenCalled());+ await screen.findByTestId("sandbox-setup-done-box");+ 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-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();+ // 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"));+ 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 () => {+ 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" },+ ],+ 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");+ 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();+ // 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(screen.getByTestId("sandbox-setup-not-now"));+ expect(screen.queryByTestId("sandbox-setup-dialog")).toBeNull();+ expect(screen.getByRole("switch").getAttribute("aria-checked")).toBe("false");+ expect(runSandboxSetup).not.toHaveBeenCalled();+ });});diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsxindex 339698f2..b9d99234 100644--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@ -19,10 +19,8 @@ import {type CloudStatus,type Machine,type MeInfo,- getSandboxSettings,getSettings,getTrustedWorkspaces,- setSandboxSettings,setAutoApprove,setAutoApproveShadow,setCompactionSettings,@@ -35,9 +33,6 @@ import {type CompactionSettings,type ModelSettings,type PdfSettings,- type SandboxCredentialEntry,- type SandboxToolchainEntry,- type SandboxSettings,type WorkspaceCommandTrust,} from "../api";import {@@ -75,6 +70,7 @@ import { MachineModelsPanel } from "./MachineModelsPanel";import { MachinesSection } from "./MachinesSection";import { RemoteConnectorsPanel } from "./RemoteConnectorsPanel";import { MemorySection } from "./MemorySection";+import { SandboxSection } from "./SandboxSection";import { PersonasTab } from "./PersonasTab";import { SkillsTab } from "./SkillsTab";import { showPersonas } from "../flags";@@ -721,287 +717,6 @@ function PersonasSection({// in, and the way out (moved here from the Machines page's inline bar). On// desktop and self-hosted browsers it is the optional OpenWorker Cloud// sign-in — the same one the sidebar's account menu offers, given a full page.-// Settings ▸ Sandbox (UX-051 A, design doc rulings 17, 29, 32): machine-level provider,-// network allow list, and the credential files an agent may be given. Reads and writes the-// machine's config.toml through /v1/settings/sandbox; nothing here is per project.-function SandboxSection({ machine }: { machine?: Machine | null }) {- const { t } = useTranslation();- const mid = machine?.id ?? null;- const [cfg, setCfg] = useState<SandboxSettings | null>(null);- const [error, setError] = useState<string>("");- const [editing, setEditing] = useState<string | null>(null); // credential name being edited, "" = new- const [addingTool, setAddingTool] = useState(false); // the "Add a folder" editor of the toolchain list- const [toolTitle, setToolTitle] = useState("");- const [toolPath, setToolPath] = useState("~/");-- useEffect(() => {- getSandboxSettings(mid).then(setCfg).catch(() => setCfg(null));- }, [mid]);-- const save = async (patch: Parameters<typeof setSandboxSettings>[0]) => {- const res = await setSandboxSettings(patch, mid);- if (!res.ok) {- setError(res.error || "could not save");- return;- }- setError("");- setCfg(res as SandboxSettings);- };-- if (!cfg) return null;- const providerNames: Record<string, [string, string]> = {- direct: [t("settingsx.sandbox.provider_direct"), t("settingsx.sandbox.provider_direct_desc")],- seatbelt: [t("settingsx.sandbox.provider_seatbelt"), t("settingsx.sandbox.provider_seatbelt_desc")],- windows: [t("settingsx.sandbox.provider_windows"), t("settingsx.sandbox.provider_windows_desc")],- openshell: [t("settingsx.sandbox.provider_openshell"), t("settingsx.sandbox.provider_openshell_desc")],- };- const chosen = cfg.provider || cfg.effective_provider || "direct";- const 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 });- const updateToolchains = (rows: SandboxToolchainEntry[]) => save({ toolchains: rows.map(({ exists: _e, shipped: _s, ...row }) => row) });-- return (- <section data-testid="sandbox-section">- <PanelHead- title={t("settingsx.sandbox.title")}- sub={machine ? t("settingsx.sandbox.sub_machine", { name: machine.name }) : cfg.platform === "win32" ? t("settingsx.sandbox.sub_windows") : t("settingsx.sandbox.sub")}- />- {error ? <div className="mb-3 text-meta text-danger">{error}</div> : null}-- <div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.run_in")}</div>- <div className={CARD + " mb-1 divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.run_in")}>- {cfg.providers- .filter((p) => (p.name !== "seatbelt" || cfg.platform === "darwin") && (p.name !== "windows" || cfg.platform === "win32"))- .map((p) => {- const [label, desc] = providerNames[p.name] ?? [p.name, ""];- const active = chosen === p.name;- return (- <label key={p.name} className="flex items-start gap-3 px-4 py-3 cursor-pointer">- <input- type="radio"- name="sandbox-provider"- className="mt-1"- checked={active}- disabled={!p.usable && !active}- onChange={() => save({ provider: p.name === "direct" && !cfg.provider ? "" : p.name })}- data-testid={`sandbox-provider-${p.name}`}- />- <span className="flex-1 min-w-0">- <span className="block text-ui text-ink">{label}</span>- <span className="block text-meta text-muted">{desc}</span>- {!p.usable && p.why ? (- <span className="block text-meta text-warnInk mt-1" data-testid={`sandbox-provider-${p.name}-why`}>{p.why}</span>- ) : null}- </span>- <span className={"text-meta shrink-0 " + (p.usable ? (active ? "text-success" : "text-muted") : "text-muted")}>- {p.name === "direct" && !cfg.provider- ? t("settingsx.sandbox.status_default")- : p.usable- ? t("settingsx.sandbox.status_ready")- : t("settingsx.sandbox.status_unavailable")}- </span>- </label>- );- })}- </div>- {cfg.refused ? <div className="mb-4 text-meta text-danger">{t("settingsx.sandbox.refused", { why: cfg.refused })}</div> : <div className="mb-4" />}-- <div className={FIELD_LABEL + " mb-2"}>{t("settingsx.sandbox.network")}</div>- <div className={CARD + " divide-y divide-line"} role="radiogroup" aria-label={t("settingsx.sandbox.network")}>- {cfg.network_profiles.map((np) => (- <label key={np.name} className="flex items-start gap-3 px-4 py-3 cursor-pointer">- <input- type="radio"- name="sandbox-network"- className="mt-1"- checked={cfg.network_profile === np.name}- onChange={() => save({ network_profile: np.name })}- data-testid={`sandbox-network-${np.name}`}- />- <span className="flex-1 min-w-0">- <span className="block text-ui text-ink">{t(`settingsx.sandbox.profile_${np.name}`)}</span>- <span className="block text-meta text-muted">{t(`settingsx.sandbox.profile_${np.name}_desc`)}</span>- </span>- </label>- ))}- </div>- <div className={FIELD_HELP + " mb-4"}>{t("settingsx.sandbox.network_help")}</div>-- <div className="flex items-center mb-2">- <div className={FIELD_LABEL}>{t("settingsx.sandbox.credentials")}</div>- <button className="ml-auto text-ui text-accent" onClick={() => setEditing("")} data-testid="sandbox-credential-add">- {t("settingsx.sandbox.add")}- </button>- </div>- <div className={CARD + " divide-y divide-line"}>- {cfg.credentials.map((c) => (- <div key={c.name} className="flex items-start gap-3 px-4 py-3" data-testid={`sandbox-credential-${c.name}`}>- <input- type="checkbox"- className="mt-1"- checked={c.enabled}- onChange={(e) => updateCredentials(cfg.credentials.map((x) => (x.name === c.name ? { ...x, enabled: e.target.checked } : x)))}- aria-label={c.title || shipped(c.name, "title", c.name)}- />- <span className="flex-1 min-w-0">- <span className="block text-ui text-ink">- {c.title || shipped(c.name, "title", c.name)}{" "}- <code className="text-meta text-muted font-mono">{c.path}</code>- </span>- <span className="block text-meta text-muted">- {c.does ? c.does : shipped(c.name, "does")}{" "}- {c.hosts && c.hosts.length && cfg.network_profile !== "open" ? (- <span className="text-faint">{t("settingsx.sandbox.also_allows", { hosts: c.hosts.join(", ") })}</span>- ) : null}- </span>- </span>- <span className="text-meta text-muted shrink-0 whitespace-nowrap">- <button className="hover:text-ink" onClick={() => setEditing(c.name)}>{t("settingsx.sandbox.edit")}</button>- <span className="mx-1.5 text-faint">·</span>- <button className="hover:text-ink" onClick={() => updateCredentials(cfg.credentials.filter((x) => x.name !== c.name))}>- {t("settingsx.sandbox.remove")}- </button>- </span>- </div>- ))}- </div>- <div className={FIELD_HELP}>{t("settingsx.sandbox.credentials_help")}</div>- {cfg.platform === "darwin" ? <div className={FIELD_HELP}>{t("settingsx.sandbox.keychain_note")}</div> : null}- <div className={FIELD_HELP + " mt-3"}>{t("settingsx.sandbox.saved_in", { path: cfg.config_path })}</div>-- {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}-- {cfg.platform !== "linux" && cfg.toolchains ? (- <>- <div className="flex items-center mb-2 mt-6">- <div className={FIELD_LABEL}>{t("settingsx.sandbox.toolchains")}</div>- <button className="ml-auto text-ui text-accent" onClick={() => setAddingTool(true)} data-testid="sandbox-toolchain-add">- {t("settingsx.sandbox.add_toolchain")}- </button>- </div>- <div className={CARD + " divide-y divide-line"}>- {cfg.toolchains.map((tc) => (- <div key={tc.name} className="flex items-start gap-3 px-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} <code className="text-meta text-muted font-mono">{tc.path}</code>- {tc.exists === false ? <span className="text-meta text-faint"> · {t("settingsx.sandbox.toolchain_missing")}</span> : null}- </span>- </span>- {!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={FIELD_HELP}>{t("settingsx.sandbox.toolchains_help")}</div>- {addingTool ? (- <div className={CARD + " p-4 mt-3"} data-testid="sandbox-toolchain-editor">- <div className="grid grid-cols-[150px_1fr] gap-x-3 gap-y-2 items-center">- <label className="text-ui text-muted">{t("settingsx.sandbox.field_title")}</label>- <input className={INPUT} value={toolTitle} onChange={(e) => setToolTitle(e.target.value)} />- <label className="text-ui text-muted">{t("settingsx.sandbox.field_toolchain_path")}</label>- <input className={INPUT + " font-mono"} value={toolPath} onChange={(e) => setToolPath(e.target.value)} />- </div>- <div className="flex justify-end gap-2 mt-3">- <button className={BTN_BORDERED} onClick={() => setAddingTool(false)}>{t("settingsx.sandbox.cancel")}</button>- <button- className={BTN_ACCENT}- disabled={!(toolPath.startsWith("~/") || toolPath.startsWith("/")) || toolPath.length < 3}- onClick={() => {- const slug = (toolTitle || toolPath).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");- setAddingTool(false);- setToolTitle("");- setToolPath("~/");- updateToolchains([...cfg.toolchains, { name: slug, title: toolTitle || undefined, path: toolPath, enabled: true }]);- }}- >- {t("settingsx.sandbox.done")}- </button>- </div>- </div>- ) : null}- </>- ) : null}- </section>- );-}--function CredentialEditor({- entry,- onCancel,- onSave,-}: {- entry: SandboxCredentialEntry | null;- onCancel: () => void;- onSave: (row: SandboxCredentialEntry) => void;-}) {- const { t } = useTranslation();- const [title, setTitle] = useState(entry?.title ?? "");- const [name, setName] = useState(entry?.name ?? "");- const [path, setPath] = useState(entry?.path ?? "~/");- const [hosts, setHosts] = useState((entry?.hosts ?? []).join("\n"));- const [does, setDoes] = useState(entry?.does ?? "");- const slug = entry?.name || name || title.toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "");- const valid = Boolean(slug) && (path.startsWith("~/") || path.startsWith("/"));- 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>- <input className={INPUT + " font-mono"} value={path} onChange={(e) => setPath(e.target.value)} />- <label className="text-ui text-muted self-start pt-2">{t("settingsx.sandbox.field_hosts")}</label>- <textarea className={INPUT + " font-mono"} rows={3} value={hosts} onChange={(e) => setHosts(e.target.value)} />- <label className="text-ui text-muted">{t("settingsx.sandbox.field_does")}</label>- <input className={INPUT} value={does} onChange={(e) => setDoes(e.target.value)} />- </div>- <div className="flex justify-end gap-2 mt-3">- <button className={BTN_BORDERED} onClick={onCancel}>{t("settingsx.sandbox.cancel")}</button>- <button- className={BTN_ACCENT}- disabled={!valid}- onClick={() =>- onSave({- name: slug,- title: title || undefined,- path,- hosts: hosts.split(/\s+/).map((h) => h.trim()).filter(Boolean),- does: does || undefined,- enabled: entry?.enabled ?? true,- })- }- >- {t("settingsx.sandbox.done")}- </button>- </div>- </div>- );-}-function AccountSection() {const { t } = useTranslation();return (diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex f3bcbc62..96c33c7a 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2271,54 +2271,124 @@"title": "Sandbox","sub": "Where agents run their commands and file tools on this Mac. Applies to every session on this machine; a project cannot change it.","sub_windows": "Where agents run their commands and file tools on this PC. Applies to every session on this machine; a project cannot change it.",- "sub_machine": "On ⌂ {{name}} — where its agents run their commands and file tools. Applies to every session on that machine; a project cannot change it.",- "run_in": "Run agents in",- "provider_direct": "No sandbox",- "provider_direct_desc": "Commands run as you, with no limits. Fastest. The default until you choose otherwise.",+ "sub_machine": "On ⌂ {{name}} — where its agents run commands and file tools. Applies to every session on that machine; a project cannot change it.",+ "switch_title": "Run agents in a sandbox",+ "switch_desc": "Commands run where they cannot see your files, your keys or OpenWorker's own state. Off, they run as you, with no limits.",+ "switch_off": "off",+ "switch_choose": "choose a type",+ "switch_on": "on · {{type}}",+ "switch_none": "no type can be used yet",+ "switch_help_off": "Turn it on to choose how agents are isolated on this machine.",+ "type": "Sandbox type",+ "type_help": "Nothing changes until a type is ready. Its options appear here once it is.",+ "type_help_admin": "Once an administrator has run the setup, come back here and choose the Windows sandbox.","provider_seatbelt": "macOS sandbox",- "provider_seatbelt_desc": "Commands can read and write only the session's folders and reach only the network hosts on the allow list. Your other files and logins are hidden.",+ "provider_seatbelt_desc": "The Seatbelt profile built into macOS. Nothing to install.","provider_windows": "Windows sandbox",- "provider_windows_desc": "Commands run as a hidden local account that cannot see your profile. The network is open, or limited to the allow list, as chosen below. One-time setup, with one administrator prompt.",+ "provider_windows_desc": "Commands run as a hidden Windows account that cannot see your profile. One-time setup, with one administrator prompt.","provider_openshell": "OpenShell (NVIDIA)",- "provider_openshell_desc": "One Linux container per agent, with the session's folders mounted. Needs OpenShell and Docker on this machine.",- "status_default": "default",+ "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",+ "status_unavailable": "not available on this machine",+ "status_setup": "one-time setup",+ "status_needs_admin": "needs an administrator",+ "needs_admin_why": "Needs an administrator to set up. Ask one to run this once on this PC: {{command}}",+ "set_up_on": "Set up on {{date}}",+ "set_up": "Set up",+ "remove_setup": "Remove setup…","refused": "Sessions on this machine are refused until this is fixed: {{why}}",- "network": "Network allow list",+ "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. The default on Windows.",- "network_help": "Shared credentials below add the hosts their tools need.",+ "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…",- "copied_from": "Copied from","also_allows": "Also allows {{hosts}}.","edit": "Edit","remove": "Remove","done": "Done","cancel": "Cancel",+ "close": "Close",+ "try_again": "Try again",+ "browse": "Browse…",+ "kind_file": "file",+ "kind_folder": "folder",+ "credential_missing": "not on this machine",+ "label_credential": "credential",+ "label_configuration": "configuration","field_title": "Name",- "field_path": "Path (under your home folder)",- "field_hosts": "Hosts it needs (host:port, one per line)",+ "field_path": "Path (a file or a folder under your home folder)",+ "field_label": "What is in it",+ "label_credential_title": "A credential",+ "label_credential_desc": "A key, a token, a password. The agent gets it only while this entry is on.",+ "label_configuration_title": "Configuration only",+ "label_configuration_desc": "Host names, profiles, options. No secret inside.",+ "field_hosts": "Hosts it needs (host:port, one per line; added to the allow list when this entry is on)","field_does": "Lets the agent",- "credentials_help": "Switched-on entries are copied into every sandbox on this machine for the session, and deleted with it. Your real files are never touched.",- "toolchains": "Developer tools the sandbox may read",- "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. Switch one off, or add a folder.",+ "editor_note": "A folder is copied whole, including anything added to it later. Prefer the one file a tool needs.",+ "tools": "Tools from your profile",+ "toolchains": "Tools from your profile the sandbox may read",+ "tools_desc": "Read only, never written. The rest of your profile stays invisible; the session inherits your PATH.",+ "tools_count": "{{on}} of {{total}} on",+ "toolchains_help": "Tools installed under your home folder are hidden with the rest of it. These folders are readable, never writable, so the agent can run them.",+ "tools_foot_windows": "Folders outside your profile, such as D:\\work, are readable as for any local account.","toolchain_missing": "not on this machine",+ "added_by_you": "added by you","add_toolchain": "Add a folder…","field_toolchain_path": "Folder (under your home folder)",- "keychain_note": "Logins kept in the macOS Keychain (git over HTTPS) are not files and cannot be shared. Use an SSH remote, or the GitHub connector.",+ "setup_title": "Set up the Windows sandbox",+ "setup_intro": "Agents' commands will run as a hidden Windows account that cannot see your profile: not your documents, not your keys, not OpenWorker's own state. Setting that up is one step, and Windows will ask for administrator permission once.",+ "setup_changes": "What setup changes on this PC",+ "setup_change_accounts": "Two hidden local accounts, OWSandboxOpenNet and OWSandboxClosedNet, with passwords nobody sees",+ "setup_change_accounts_desc": "Hidden from the sign-in screen. They cannot log on remotely or over the network.",+ "setup_change_rules": "One firewall rule and four loopback filters on the closed account",+ "setup_change_rules_desc": "It reaches the network only through OpenWorker's allow-list proxy. The open account has no rules.",+ "setup_change_folder": "A folder under C:\\ProgramData\\OpenWorker",+ "setup_change_folder_desc": "The accounts' passwords, readable by you and administrators only, and each session's private folder.",+ "setup_change_record": "A record of every change",+ "setup_change_record_desc": "Undo all of it any time with \"Remove setup\" on this page.",+ "setup_not_now_note": "\"Not now\" turns the sandbox off again. You can choose it any time.",+ "not_now": "Not now",+ "set_up_now": "Set up now",+ "setup_working_title": "Setting up the Windows sandbox",+ "setup_working_intro": "Windows is asking for administrator permission in its own prompt. Then the accounts, the rule and the filters are written, and the wall is tried from inside a throwaway sandbox. About ten seconds.",+ "setup_waiting": "Waiting for Windows…",+ "setup_done_title": "The Windows sandbox is ready",+ "setup_done_intro": "Every session on this PC now runs its commands as a hidden account. Your profile is out of reach. The network is open by default; the options for this type are now on this page.",+ "setup_done_box": "Accounts created · firewall rule written · loopback filters written · checked from inside a throwaway sandbox: {{checked}}",+ "setup_failed_title": "Setup did not finish",+ "setup_failed_intro": "Nothing is chosen until setup finishes and the wall is proved. Windows said:",+ "remove_title": "Remove the Windows sandbox setup",+ "remove_intro": "The sandbox turns off and this PC goes back to running commands as you. Windows will ask for administrator permission once. Nothing of yours is touched; only what setup made is removed:",+ "remove_what": "What is removed",+ "remove_change_accounts_desc": "Hidden from the sign-in screen. They cannot log on remotely or over the network.",+ "remove_change_rules_desc": "The closed account's rule and filters.",+ "remove_change_folder_desc": "The accounts' passwords and every session's private folder.",+ "remove_change_record_desc": "The record itself is the last thing to go.",+ "remove_keep_note": "Your network, credential and tool choices are kept for the next time.","does_ssh": "Push and pull over SSH, and log in to servers, as you.","does_gh": "Use gh as you: pull requests, issues, releases.",- "does_aws": "Use aws with your profiles.",+ "does_aws": "Use aws with your profiles: regions and profile names. ~/.aws/credentials stays out unless you add it.","does_kube": "Use kubectl with your clusters.","title_ssh": "SSH keys","title_gh": "GitHub CLI",- "title_aws": "AWS",+ "title_aws": "AWS profiles","title_kube": "Kubernetes","saved_in": "Saved in {{path}}"}@@ -2487,7 +2557,6 @@"related_conversations": "Related worker conversations","send": "Send","worker_offline": "Worker connection unavailable. Messages are disabled until reconnected.",- "open_view": "Open team view","open_worker_pane": "View {{name}} beside the lead","full_session": "Open full session","chat_off": "Team chat is off for this team"diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex ee6b690a..f846f025 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -2232,53 +2232,123 @@"sub": "同事在这台 Mac 上运行命令和文件工具的位置。适用于这台机器上的每个会话;项目无法更改。","sub_windows": "同事在这台 PC 上运行命令和文件工具的位置。适用于这台机器上的每个会话;项目无法更改。","sub_machine": "在 ⌂ {{name}} 上 —— 它的同事运行命令和文件工具的位置。适用于那台机器上的每个会话;项目无法更改。",- "run_in": "在哪里运行同事",- "provider_direct": "不使用沙箱",- "provider_direct_desc": "命令以你的身份运行,没有限制。最快。在你另作选择前为默认。",+ "switch_title": "在沙箱中运行同事",+ "switch_desc": "命令在看不到你的文件、密钥和 OpenWorker 自身状态的地方运行。关闭时,命令以你的身份运行,没有限制。",+ "switch_off": "关闭",+ "switch_choose": "选择一种类型",+ "switch_on": "开启 · {{type}}",+ "switch_none": "目前没有可用的类型",+ "switch_help_off": "开启后可选择这台机器上隔离同事的方式。",+ "type": "沙箱类型",+ "type_help": "在某种类型就绪之前不会有任何变化。就绪后它的选项会显示在这里。",+ "type_help_admin": "管理员完成设置后,回到这里选择 Windows 沙箱。","provider_seatbelt": "macOS 沙箱",- "provider_seatbelt_desc": "命令只能读写会话的文件夹,只能访问允许列表中的网络主机。你的其他文件和登录信息被隐藏。",+ "provider_seatbelt_desc": "macOS 内置的 Seatbelt 配置。无需安装。","provider_windows": "Windows 沙箱",- "provider_windows_desc": "命令以一个看不到你的用户配置文件的隐藏本地账户运行。网络按下方的选择:开放,或仅限允许列表。一次性设置,只需一次管理员确认。",+ "provider_windows_desc": "命令以一个看不到你的用户配置文件的隐藏 Windows 账户运行。一次性设置,只需一次管理员确认。","provider_openshell": "OpenShell(NVIDIA)",- "provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要这台机器上装有 OpenShell 和 Docker。",- "status_default": "默认",+ "provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要 OpenShell 和 Docker。","status_ready": "就绪",- "status_unavailable": "不可用",+ "status_unavailable": "这台机器上不可用",+ "status_setup": "一次性设置",+ "status_needs_admin": "需要管理员",+ "needs_admin_why": "需要管理员进行设置。请管理员在这台 PC 上运行一次:{{command}}",+ "set_up_on": "设置于 {{date}}",+ "set_up": "已设置",+ "remove_setup": "移除设置…","refused": "在修复此问题前,这台机器上的会话将被拒绝:{{why}}",- "network": "网络允许列表",+ "network": "网络","profile_strict": "严格","profile_strict_desc": "GitHub、GitLab 和软件包源(PyPI、npm、crates、Go)。","profile_standard": "标准","profile_standard_desc": "严格模式加上搜索 API。","profile_open": "开放",- "profile_open_desc": "任意主机。文件仍然隔离。Windows 上的默认值。",- "network_help": "下方共享的凭据会加入其工具所需的主机。",+ "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": "添加文件或文件夹…",- "copied_from": "复制自","also_allows": "同时允许 {{hosts}}。","edit": "编辑","remove": "移除","done": "完成","cancel": "取消",+ "close": "关闭",+ "try_again": "重试",+ "browse": "浏览…",+ "kind_file": "文件",+ "kind_folder": "文件夹",+ "credential_missing": "这台机器上没有",+ "label_credential": "凭据",+ "label_configuration": "配置","field_title": "名称",- "field_path": "路径(在你的主目录下)",- "field_hosts": "所需主机(host:port,每行一个)",+ "field_path": "路径(你主目录下的文件或文件夹)",+ "field_label": "内容类型",+ "label_credential_title": "凭据",+ "label_credential_desc": "密钥、令牌或密码。只有此条目开启时同事才能获得。",+ "label_configuration_title": "仅配置",+ "label_configuration_desc": "主机名、配置文件、选项。不含机密。",+ "field_hosts": "所需主机(host:port,每行一个;此条目开启时加入允许列表)","field_does": "让同事可以",- "credentials_help": "已开启的条目会在会话期间复制到这台机器上的每个沙箱中,并随沙箱一起删除。你的真实文件不会被改动。",- "toolchains": "沙箱可读取的开发工具",- "toolchains_help": "安装在你主目录下的工具会随主目录一起被隐藏。这些文件夹只读、不可写,以便同事运行它们。可关闭某一项,或添加文件夹。",+ "editor_note": "文件夹会整个复制,包括以后加入其中的内容。优先选择工具所需的单个文件。",+ "tools": "来自你用户配置文件的工具",+ "toolchains": "沙箱可读取的、来自你用户配置文件的工具",+ "tools_desc": "只读,从不写入。你配置文件的其余部分仍不可见;会话继承你的 PATH。",+ "tools_count": "{{total}} 项中 {{on}} 项已开启",+ "toolchains_help": "安装在你主目录下的工具会随主目录一起被隐藏。这些文件夹只读、不可写,以便同事运行它们。",+ "tools_foot_windows": "用户配置文件之外的文件夹(如 D:\\work)对任何本地账户都可读。","toolchain_missing": "这台机器上没有",+ "added_by_you": "由你添加","add_toolchain": "添加文件夹…","field_toolchain_path": "文件夹(在你的主目录下)",- "keychain_note": "保存在 macOS 钥匙串中的登录信息(HTTPS 方式的 git)不是文件,无法共享。请使用 SSH 远程地址,或 GitHub 连接器。",+ "setup_title": "设置 Windows 沙箱",+ "setup_intro": "同事的命令将以一个看不到你的用户配置文件的隐藏 Windows 账户运行:看不到你的文档、你的密钥,也看不到 OpenWorker 自身的状态。设置只需一步,Windows 会请求一次管理员权限。",+ "setup_changes": "设置会在这台 PC 上做出的更改",+ "setup_change_accounts": "两个隐藏的本地账户 OWSandboxOpenNet 和 OWSandboxClosedNet,密码无人可见",+ "setup_change_accounts_desc": "不在登录界面显示。不能远程登录,也不能通过网络登录。",+ "setup_change_rules": "封闭账户上的一条防火墙规则和四条回环过滤器",+ "setup_change_rules_desc": "它只能通过 OpenWorker 的允许列表代理访问网络。开放账户没有规则。",+ "setup_change_folder": "C:\\ProgramData\\OpenWorker 下的一个文件夹",+ "setup_change_folder_desc": "账户密码(只有你和管理员可读)以及每个会话的私有文件夹。",+ "setup_change_record": "每项更改的记录",+ "setup_change_record_desc": "随时可以通过本页的“移除设置”全部撤销。",+ "setup_not_now_note": "“暂不”会再次关闭沙箱。你可以随时再选择它。",+ "not_now": "暂不",+ "set_up_now": "立即设置",+ "setup_working_title": "正在设置 Windows 沙箱",+ "setup_working_intro": "Windows 正在通过它自己的提示请求管理员权限。随后会写入账户、规则和过滤器,并在一个临时沙箱内验证隔离墙。大约十秒。",+ "setup_waiting": "正在等待 Windows…",+ "setup_done_title": "Windows 沙箱已就绪",+ "setup_done_intro": "这台 PC 上的每个会话现在都以隐藏账户运行命令。你的用户配置文件不可访问。网络默认开放;此类型的选项现已显示在本页。",+ "setup_done_box": "已创建账户 · 已写入防火墙规则 · 已写入回环过滤器 · 已在临时沙箱内检查:{{checked}}",+ "setup_failed_title": "设置未完成",+ "setup_failed_intro": "在设置完成并验证隔离墙之前,不会选择任何类型。Windows 的输出:",+ "remove_title": "移除 Windows 沙箱设置",+ "remove_intro": "沙箱将关闭,这台 PC 恢复为以你的身份运行命令。Windows 会请求一次管理员权限。不会改动你的任何东西;只移除设置所创建的内容:",+ "remove_what": "将被移除的内容",+ "remove_change_accounts_desc": "不在登录界面显示。不能远程登录,也不能通过网络登录。",+ "remove_change_rules_desc": "封闭账户的规则和过滤器。",+ "remove_change_folder_desc": "账户密码和每个会话的私有文件夹。",+ "remove_change_record_desc": "记录本身最后移除。",+ "remove_keep_note": "你的网络、凭据和工具选择会保留到下次使用。","does_ssh": "以你的身份通过 SSH 推送和拉取,并登录服务器。","does_gh": "以你的身份使用 gh:拉取请求、议题、发布。",- "does_aws": "使用你的配置文件运行 aws。",+ "does_aws": "使用你的配置文件运行 aws:区域和配置文件名。除非你添加,~/.aws/credentials 不会包含在内。","does_kube": "使用你的集群运行 kubectl。","title_ssh": "SSH 密钥","title_gh": "GitHub CLI",- "title_aws": "AWS",+ "title_aws": "AWS 配置文件","title_kube": "Kubernetes","saved_in": "保存在 {{path}}"}@@ -2447,7 +2517,6 @@"related_conversations": "相关协作者会话","send": "发送","worker_offline": "成员连接不可用,重新连接之前无法发送消息。",- "open_view": "打开团队视图","open_worker_pane": "在主代理旁查看 {{name}}","full_session": "打开完整会话","chat_off": "此团队未启用团队聊天"diff --git a/tests/test_sandbox_credentials.py b/tests/test_sandbox_credentials.pyindex 1d6bf2a7..0e9d90b9 100644--- a/tests/test_sandbox_credentials.py+++ b/tests/test_sandbox_credentials.py@@ -28,6 +28,7 @@ def _home(tmp_path) -> Path:(home / ".config" / "gh").mkdir(parents=True)(home / ".config" / "gh" / "hosts.yml").write_text("github.com:\n oauth_token: gho_x\n")(home / ".aws").mkdir()+ (home / ".aws" / "config").write_text("[default]\nregion = us-east-1\n")(home / ".aws" / "credentials").write_text("[default]\naws_access_key_id = AKIA\n")(home / ".kube").mkdir()(home / ".kube" / "config").write_text("clusters:\n- cluster:\n server: https://k8s.example.com:6443\n")@@ -56,7 +57,30 @@ def test_a_user_entry_edits_or_adds_by_name(tmp_path):got = {g.name: g for g in creds.granted(configured, home=str(home))}assert set(got) == {"ssh", "npm"}assert got["ssh"].relative == ".ssh" and got["ssh"].hosts == ["github.com:22", "gitlab.com:22"]- assert got["npm"].hosts == ["registry.npmjs.org:443"]+ assert got["ssh"].kind == "folder" and got["ssh"].label == "credential"+ assert got["npm"].hosts == ["registry.npmjs.org:443"] and got["npm"].kind == "file"+++def test_an_entry_is_a_file_or_a_folder_with_a_label(tmp_path):+ """11d ruling 6: the path decides file or folder; the shipped AWS entry is the profiles+ file (configuration), so the keys stay out unless added; the kubeconfig is one file."""+ home = _home(tmp_path)+ got = {g.name: g for g in creds.granted([{"name": n, "enabled": True} for n in ("aws", "kube")], home=str(home))}+ assert got["aws"].kind == "file" and got["aws"].relative == os.path.join(".aws", "config") and got["aws"].label == "configuration"+ assert got["kube"].kind == "file" and got["kube"].hosts == ["k8s.example.com:6443"]+ assert creds.kind_of("~/.aws", home=str(home)) == "folder" and creds.kind_of("~/.aws/config", home=str(home)) == "file"+ assert creds.kind_of("~/.nothing", home=str(home)) == ""+ # a user's own entry for the keys file, and the folder form of AWS still work+ (home / ".npmrc").write_text("token\n")+ rows = [{"name": "aws-credentials", "enabled": True, "path": "~/.aws/credentials", "label": "credential"}, {"name": "aws", "enabled": True, "path": "~/.aws"}]+ got = {g.name: g for g in creds.granted(rows, home=str(home))}+ assert got["aws"].kind == "folder" and got["aws-credentials"].kind == "file" and got["aws-credentials"].label == "credential"+ run = tmp_path / "run2"+ run.mkdir()+ copied = creds.copy_in(list(got.values()), str(run), home=str(home))+ sb = Path(copied.home)+ assert copied.env["AWS_SHARED_CREDENTIALS_FILE"] == str(sb / ".aws" / "credentials") and copied.env["AWS_CONFIG_FILE"] == str(sb / ".aws" / "config")+ assert [e["label"] for e in creds.entries([{"name": "x", "label": "bogus"}]) if e["name"] == "x"] == ["credential"]def test_kube_hosts_come_from_the_kubeconfig(tmp_path):@@ -103,13 +127,14 @@ def test_copy_in_makes_a_private_home_and_the_tools_environment(tmp_path):assert copied.env["OPENWORKER_PATH_PREPEND"] == str(sb / "bin")assert copied.env["HOME"] == str(sb)assert copied.env["GH_CONFIG_DIR"] == str(sb / ".config" / "gh")- assert copied.env["AWS_SHARED_CREDENTIALS_FILE"] == str(sb / ".aws" / "credentials")+ assert copied.env["AWS_CONFIG_FILE"] == str(sb / ".aws" / "config") and "AWS_SHARED_CREDENTIALS_FILE" not in copied.env+ assert not (sb / ".aws" / "credentials").exists() # the profiles file only; the keys stay outassert copied.env["KUBECONFIG"] == str(sb / ".kube" / "config")assert copied.hosts == ["*.amazonaws.com:443", "api.github.com:443", "github.com:22", "github.com:443", "gitlab.com:22", "k8s.example.com:6443"]# the real files were not touchedassert (home / ".ssh" / "config").read_text() == "Host work\n HostName git.example.com\n"text = creds.context_lines(copied)- assert "SSH keys (.ssh): you can push and pull over SSH" in text and "deleted when the session ends" in text+ assert "SSH keys (.ssh, folder): you can push and pull over SSH" in text and "deleted when the session ends" in textdef test_no_grants_means_no_lines_for_the_agent(tmp_path):diff --git a/tests/test_sandbox_settings.py b/tests/test_sandbox_settings.pyindex 09af016a..f33ac07b 100644--- a/tests/test_sandbox_settings.py+++ b/tests/test_sandbox_settings.py@@ -30,7 +30,9 @@ def test_snapshot_reports_the_default_rule_and_the_shipped_entries(config_file):assert snap["network_profile"] == network_profiles.default_profile() # strict; `open` on Windowsassert [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["config_path"] == str(config_file)+ assert (snap["windows_setup"] is None) == (sys.platform != "win32")from coworker.sandbox import toolchainsassert [e["name"] for e in snap["toolchains"]] == [e["name"] for e in toolchains.defaults()]@@ -85,9 +87,64 @@ def test_update_refuses_bad_input_without_writing(config_file):assert settings.update({"credentials": [{"name": "x", "enabled": True, "path": "etc"}]})["ok"] is Falseassert settings.update({"credentials": [{"name": "x", "enabled": True, "hosts": ["nohost"]}]})["ok"] is Falseassert settings.update({"credentials": [{"enabled": True}]})["ok"] is False+ assert settings.update({"credentials": [{"name": "x", "enabled": True, "path": "~/x", "label": "secret"}]})["ok"] is Falseassert not config_file.exists()+def test_a_label_is_written_and_read_back(config_file):+ out = settings.update({"credentials": [{"name": "aws", "enabled": True, "path": "~/.aws", "label": "credential"}, {"name": "npmrc", "enabled": True, "path": "~/.npmrc", "label": "configuration"}]})+ assert out["ok"], out+ by = {e["name"]: e for e in settings.snapshot()["credentials"]}+ assert by["aws"]["label"] == "credential" and by["aws"]["path"] == "~/.aws" and by["npmrc"]["label"] == "configuration"+ assert by["gh"]["label"] == "credential" and by["gh"]["shipped"] and not by["npmrc"]["shipped"]+++def test_windows_setup_runs_checks_and_only_then_chooses_the_sandbox(config_file, monkeypatch):+ """UX-053: "Set up now" runs the elevated setup, proves the wall in a throwaway sandbox,+ and makes the Windows sandbox the choice; a failed check leaves the choice alone."""+ from types import SimpleNamespace++ from coworker.sandbox import selection+ from coworker.sandbox.providers import windows_setup++ monkeypatch.setattr(settings.sys, "platform", "win32")+ # Off Windows the provider module cannot even import; the snapshot's two probes are stubbed.+ monkeypatch.setattr(settings, "_availability", lambda name: (True, ""))+ monkeypatch.setattr(selection, "select", lambda name=None: SimpleNamespace(provider=name or "direct"))+ monkeypatch.setattr(windows_setup, "info", lambda: {"state": "ready", "set_up_at": "2026-09-28T10:00:00Z", "problem": "", "can_elevate": True, "command": "x"})+ monkeypatch.setattr(windows_setup, "run_setup", lambda: (True, "ok S-1 S-2"))+ monkeypatch.setattr(settings, "_throwaway_check", lambda: (False, "the home folder can be listed from inside"))+ out = settings.run_windows_setup()+ assert not out["ok"] and "throwaway sandbox failed" in out["error"] and "sandbox_provider" not in (config_file.read_text() if config_file.exists() else "")+ monkeypatch.setattr(settings, "_throwaway_check", lambda: (True, "proved"))+ out = settings.run_windows_setup()+ assert out["ok"] and out["checked"] == "proved" and out["provider"] == "windows" and out["windows_setup"]["state"] == "ready"+ monkeypatch.setattr(windows_setup, "run_setup", lambda: (False, "The operation was canceled by the user."))+ out = settings.run_windows_setup()+ assert not out["ok"] and "canceled" in out["error"] and out["provider"] == "windows" # the earlier choice stands+ monkeypatch.setattr(windows_setup, "run_remove", lambda: (True, "removed"))+ out = settings.run_windows_remove()+ assert out["ok"] and out["provider"] == "direct"+ monkeypatch.setattr(settings.sys, "platform", "darwin")+ assert not settings.run_windows_setup()["ok"] and not settings.run_windows_remove()["ok"]+++def test_windows_setup_info_states(monkeypatch):+ from coworker.sandbox.providers import windows_setup++ monkeypatch.setattr(windows_setup, "can_elevate", lambda: True)+ monkeypatch.setattr(windows_setup, "state", lambda: None)+ assert windows_setup.info()["state"] == "not_set_up"+ monkeypatch.setattr(windows_setup, "state", lambda: {"version": 1})+ assert windows_setup.info()["state"] == "older"+ monkeypatch.setattr(windows_setup, "state", lambda: {"version": windows_setup.SETUP_VERSION, "set_up_at": "2026-09-28T10:00:00Z"})+ monkeypatch.setattr(windows_setup, "problem", lambda: "the sandbox account for the open network mode is not usable by this user")+ info = windows_setup.info()+ assert info["state"] == "broken" and info["set_up_at"] == "2026-09-28T10:00:00Z" and info["can_elevate"] and info["command"]+ monkeypatch.setattr(windows_setup, "problem", lambda: None)+ assert windows_setup.info()["state"] == "ready"++def test_removing_a_shipped_entry_and_going_back_to_the_default_rule(config_file):settings.update({"provider": "direct", "credentials": [{"name": "ssh", "enabled": True}]})assert 'sandbox_provider = "direct"' in config_file.read_text()