Python
Settings: a Sandbox page for the provider, the network allow list and shared credentials
Devika Verma48fecdf4caac
diff --git a/coworker/agent.py b/coworker/agent.pyindex 3685ea4c..40fd651f 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -347,6 +347,7 @@ def build_engine(session_id=session_id or "",agent=agent.name,credentials=config.sandbox_credentials,+ network_profile=config.sandbox_network_profile,)if ws is not Noneelse Nonediff --git a/coworker/config.py b/coworker/config.pyindex 9f8d7f45..26c05ff8 100644--- a/coworker/config.py+++ b/coworker/config.py@@ -124,6 +124,9 @@ class Config:# for the same reason as the provider. The shipped entries and their defaults are in# coworker/sandbox/credentials.py; an entry here edits or adds by name.sandbox_credentials: list[dict[str, Any]] = field(default_factory=list)+ # Which hosts a sandbox may reach: a profile name from coworker/sandbox/network_profiles.py+ # ("strict" when unset). Machine-level, like the provider.+ sandbox_network_profile: Optional[str] = None_FIELDS = {@@ -135,6 +138,7 @@ _FIELDS = {"tool_result_max_bytes","sandbox_provider","sandbox_credentials",+ "sandbox_network_profile","compaction_cap_tokens","compaction_summary_max_tokens","allowed_commands",@@ -160,6 +164,7 @@ _FIELDS = {_GLOBAL_ONLY_FIELDS = {"sandbox_provider","sandbox_credentials",+ "sandbox_network_profile","allowed_commands","auto_allow","allowed_domains",@@ -188,6 +193,43 @@ def set_global_value(key: str, value: str, *, path: Optional[Path] = None) -> Pareturn target+def set_global_tables(key: str, rows: list[dict[str, Any]], *, path: Optional[Path] = None) -> Path:+ """Replace every `[[key]]` table in the machine's config.toml with `rows`, keeping the+ rest of the file. Values may be strings, booleans, integers and lists of strings."""+ if key not in _FIELDS:+ raise ValueError(f"not a config key: {key}")+ target = Path(path) if path is not None else global_config_path()+ target.parent.mkdir(parents=True, exist_ok=True)+ lines = target.read_text(encoding="utf-8").splitlines() if target.is_file() else []+ kept: list[str] = []+ skipping = False+ header = re.compile(r"^\s*\[\[?\s*([^\]]+?)\s*\]\]?\s*$")+ for line in lines:+ m = header.match(line)+ if m:+ skipping = m.group(1).strip() == key and line.strip().startswith("[[")+ if not skipping:+ kept.append(line)+ while kept and not kept[-1].strip():+ kept.pop()++ def value(v: Any) -> str:+ if isinstance(v, bool):+ return "true" if v else "false"+ if isinstance(v, int):+ return str(v)+ if isinstance(v, (list, tuple)):+ return "[" + ", ".join(value(str(x)) for x in v) + "]"+ text = str(v).replace("\\", "\\\\").replace('"', '\\"')+ return f'"{text}"'++ out = list(kept)+ for row in rows:+ out += ["", f"[[{key}]]"] + [f"{k} = {value(v)}" for k, v in row.items() if v is not None]+ target.write_text("\n".join(out).lstrip("\n") + "\n", encoding="utf-8")+ return target++def _read(path: Path) -> dict[str, Any]:try:with open(path, "rb") as f:diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.pynew file mode 100644index 00000000..46c30e65--- /dev/null+++ b/coworker/sandbox/settings.py@@ -0,0 +1,147 @@+"""The Settings ▸ Sandbox page's data (UX-051 A): which provider this machine uses, which+network profile, and which credential files an agent may be given. Everything here is+machine-level and lives in the machine's config.toml, never in a repository's.+"""++from __future__ import annotations++import sys+from typing import Any, Optional++from .. import config as app_config+from . import credentials, network_profiles+from .workspace import DIRECT, OPENSHELL, SEATBELT+++def _availability(name: str) -> tuple[bool, str]:+ """(usable, why not) for a provider on this machine."""+ if name == DIRECT:+ return True, ""+ if name == SEATBELT:+ if sys.platform != "darwin":+ return False, "macOS only"+ from .providers import seatbelt++ try:+ seatbelt.preflight()+ return True, ""+ except seatbelt.SeatbeltUnavailable as exc:+ return False, str(exc)+ if name == OPENSHELL:+ from .selection import openshell_problem++ problem = openshell_problem()+ return (problem is None), (problem or "")+ return False, "unknown"+++def snapshot(cfg: Optional[app_config.Config] = None) -> dict[str, Any]:+ cfg = cfg or app_config.load_config()+ from .selection import select++ try:+ chosen = select(cfg.sandbox_provider)+ effective, refused = chosen.provider, ""+ except Exception as exc: # an explicit choice that cannot be used: sessions are refused+ effective, refused = "", str(exc)+ providers = []+ for name in (DIRECT, SEATBELT, OPENSHELL):+ usable, why = _availability(name)+ providers.append({"name": name, "usable": usable, "why": why})+ return {+ "platform": sys.platform,+ "provider": cfg.sandbox_provider or "", # "" = the default rule+ "effective_provider": effective,+ "refused": refused,+ "providers": providers,+ "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+ ],+ "credentials": _for_display(credentials.entries(cfg.sandbox_credentials)),+ "config_path": str(app_config.global_config_path()),+ }+++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."""+ shipped = {e["name"]: e for e in credentials.DEFAULT_ENTRIES}+ out = []+ for row in rows:+ base = shipped.get(row["name"])+ row = dict(row)+ if base is not None:+ for key in ("title", "does"):+ if row.get(key) == base.get(key):+ row.pop(key, None)+ out.append(row)+ return out+++def update(body: dict[str, Any]) -> dict[str, Any]:+ """Apply a partial change and return the new snapshot. Validates before writing."""+ body = body or {}+ if "provider" in body:+ provider = str(body.get("provider") or "").strip().lower()+ if provider and provider not in (DIRECT, SEATBELT, OPENSHELL):+ return {"ok": False, "error": f"unknown sandbox provider: {provider}"}+ app_config.set_global_value("sandbox_provider", provider) if provider else _unset("sandbox_provider")+ from .selection import openshell_problem++ if provider == OPENSHELL:+ openshell_problem(fresh=True)+ if "network_profile" in body:+ profile = str(body.get("network_profile") or "").strip().lower()+ try:+ network_profiles.check(profile)+ except ValueError as exc:+ return {"ok": False, "error": str(exc)}+ app_config.set_global_value("sandbox_network_profile", profile)+ if "credentials" in body:+ rows = body.get("credentials")+ if not isinstance(rows, list):+ return {"ok": False, "error": "credentials must be a list"}+ cleaned: list[dict[str, Any]] = []+ for raw in rows:+ if not isinstance(raw, dict) or not str(raw.get("name") or "").strip():+ return {"ok": False, "error": "every credential entry needs a name"}+ path = str(raw.get("path") or "").strip()+ if path and not (path == "~" or path.startswith("~/") or path.startswith("/") or path[1:3] == ":\\"):+ return {"ok": False, "error": f"the path for '{raw['name']}' must start with ~/ or be absolute"}+ row: dict[str, Any] = {"name": str(raw["name"]).strip(), "enabled": bool(raw.get("enabled"))}+ for key in ("title", "path", "does"):+ if raw.get(key) is not None:+ row[key] = str(raw[key])+ 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):+ return {"ok": False, "error": f"hosts for '{raw['name']}' must be host:port entries"}+ row["hosts"] = [h.strip() for h in hosts]+ cleaned.append(row)+ # Keep only what differs from the shipped entry, so the file stays small and the+ # shipped defaults can still improve underneath.+ shipped = {e["name"]: e for e in credentials.DEFAULT_ENTRIES}+ slim: list[dict[str, Any]] = []+ for row in cleaned:+ base = shipped.get(row["name"])+ if base is None:+ slim.append(row)+ continue+ diff = {k: v for k, v in row.items() if k == "name" or base.get(k) != v}+ if len(diff) > 1:+ slim.append(diff)+ app_config.set_global_tables("sandbox_credentials", slim)+ return {"ok": True, **snapshot()}+++def _unset(key: str) -> None:+ """Remove a top-level key from the machine's config.toml (back to the default rule)."""+ import re++ target = app_config.global_config_path()+ if not target.is_file():+ return+ lines = target.read_text(encoding="utf-8").splitlines()+ kept = [line for line in lines if not re.match(rf"\s*{re.escape(key)}\s*=", line)]+ target.write_text("\n".join(kept) + "\n", encoding="utf-8")diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.pyindex 11308b79..7b2a80f1 100644--- a/coworker/sandbox/workspace.py+++ b/coworker/sandbox/workspace.py@@ -182,6 +182,7 @@ def open_workspace(session_id: str = "",agent: str = "",credentials: Optional[list] = None,+ network_profile: Optional[str] = None,) -> Workspace:"""The session's workspace for the configured provider. `credentials`: the machine's`sandbox_credentials` setting; the enabled entries are copied into the sandbox@@ -201,12 +202,15 @@ def open_workspace(from .credentials import grantedgrants = granted(credentials)+ from .network_profiles import DEFAULT_PROFILE, check++ profile = check((network_profile or "").strip().lower() or DEFAULT_PROFILE)if name == SEATBELT:from .providers.seatbelt import SeatbeltProviderfrom .registry import SandboxRegistryreturn RunnerWorkspace(- SeatbeltProvider(roots=listed, cwd=str(cwd), credentials=grants),+ SeatbeltProvider(roots=listed, cwd=str(cwd), credentials=grants, profile=profile),cwd=cwd,registry=SandboxRegistry(),session_id=session_id,@@ -219,7 +223,7 @@ def open_workspace(label = "-".join(part for part in (session_id[:24], agent[:24]) if part)return RunnerWorkspace(- OpenShellProvider(roots=listed, cwd=str(cwd), label=label, credentials=grants),+ OpenShellProvider(roots=listed, cwd=str(cwd), label=label, credentials=grants, profile=profile),cwd=cwd,registry=SandboxRegistry(),session_id=session_id,diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 1b7e10c1..504f92ac 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -2388,6 +2388,20 @@ def create_app(manager: SessionManager) -> FastAPI:max_mb=b.get("pdf_max_mb"),)+ @app.get("/v1/settings/sandbox")+ def settings_get_sandbox() -> dict[str, Any]:+ # Settings ▸ Sandbox (UX-051 A): provider, network profile, credential grants.+ # Machine-level, read from the machine's config.toml.+ from ..sandbox import settings as sandbox_settings++ return sandbox_settings.snapshot()++ @app.post("/v1/settings/sandbox")+ def settings_set_sandbox(body: dict) -> dict[str, Any]:+ from ..sandbox import settings as sandbox_settings++ return sandbox_settings.update(body or {})+@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/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex 2a88bdb8..5209a656 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -2088,6 +2088,44 @@ export async function getReviewerStats(sessionId: string): Promise<ReviewerStatsreturn res.json();}+// -- Settings ▸ Sandbox (UX-051 A): machine-level provider, network profile, credential grants --+export interface SandboxCredentialEntry {+ name: string;+ title?: string;+ path?: string;+ hosts?: string[];+ does?: string;+ enabled: boolean;+}+export interface SandboxSettings {+ platform: string;+ provider: string; // "" = the default rule+ effective_provider: string;+ refused: string;+ providers: { name: string; usable: boolean; why: string }[];+ network_profile: string;+ network_profiles: { name: string; hosts: string[] }[];+ credentials: SandboxCredentialEntry[];+ config_path: string;+}++export async function getSandboxSettings(machineId?: string | null): Promise<SandboxSettings> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox`);+ return res.json();+}++export async function setSandboxSettings(+ patch: Partial<Pick<SandboxSettings, "provider" | "network_profile" | "credentials">>,+ machineId?: string | null,+): Promise<{ ok: boolean; error?: string } & Partial<SandboxSettings>> {+ const res = await fetch(`${engineBase(machineId)}/v1/settings/sandbox`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(patch),+ });+ 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/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsxnew file mode 100644index 00000000..a6630ed9--- /dev/null+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx@@ -0,0 +1,107 @@+// 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.+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";++const snapshot = {+ platform: "darwin",+ provider: "",+ effective_provider: "direct",+ refused: "",+ providers: [+ { name: "direct", usable: true, why: "" },+ { name: "seatbelt", usable: true, why: "" },+ { name: "openshell", usable: false, why: "OpenShell is not installed" },+ ],+ network_profile: "strict",+ network_profiles: [+ { name: "strict", hosts: ["github.com"] },+ { name: "standard", hosts: ["github.com", "api.tavily.com"] },+ ],+ credentials: [+ { name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], enabled: false },+ { name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], enabled: true },+ ],+ config_path: "/Users/sam/.config/coworker/config.toml",+};++const setSandboxSettings = vi.fn(async (patch: any) => ({ ok: true, ...snapshot, ...patch }));++vi.mock("../api", async (importOriginal) => {+ const actual = await importOriginal<typeof import("../api")>();+ return {+ ...actual,+ getSandboxSettings: vi.fn(async () => snapshot),+ setSandboxSettings: (patch: any) => setSandboxSettings(patch),+ getMachines: vi.fn(async () => ({ machines: [] })),+ getCloudMachines: vi.fn(async () => ({ machines: [] })),+ getCloudConnections: vi.fn(async () => []),+ getConnectors: vi.fn(async () => []),+ getCloudStatus: vi.fn(async () => ({ signed_in: false })),+ isCloudMode: () => false,+ };+});++import { SettingsView } from "./SettingsView";++describe("Settings ▸ Sandbox", () => {+ beforeEach(() => setSandboxSettings.mockClear());+ afterEach(cleanup);++ it("shows the providers, the allow list and the credential rows from the machine", async () => {+ render(<SettingsView initialTab="sandbox" />);+ await screen.findByTestId("sandbox-section");+ expect((screen.getByTestId("sandbox-provider-direct") as HTMLInputElement).checked).toBe(true);+ expect((screen.getByTestId("sandbox-provider-openshell") as HTMLInputElement).disabled).toBe(true);+ 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();+ });++ it("writes a provider change, a profile change and a credential switch", async () => {+ render(<SettingsView initialTab="sandbox" />);+ await screen.findByTestId("sandbox-section");+ fireEvent.click(screen.getByTestId("sandbox-provider-seatbelt"));+ await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ provider: "seatbelt" }));+ fireEvent.click(screen.getByTestId("sandbox-network-standard"));+ await waitFor(() => expect(setSandboxSettings).toHaveBeenCalledWith({ network_profile: "standard" }));+ fireEvent.click(screen.getByLabelText("SSH keys"));+ await waitFor(() =>+ expect(setSandboxSettings).toHaveBeenLastCalledWith({+ credentials: [+ { name: "ssh", path: "~/.ssh", hosts: ["github.com:22"], enabled: true },+ { name: "gh", path: "~/.config/gh", hosts: ["api.github.com:443"], enabled: true },+ ],+ }),+ );+ });++ 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");+ fireEvent.change(inputs[0], { target: { value: "npm token" } });+ fireEvent.change(inputs[1], { target: { value: "~/.npmrc" } });+ fireEvent.change(inputs[2], { target: { value: "registry.npmjs.org:443" } });+ fireEvent.click(screen.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 },+ ],+ }),+ );+ fireEvent.click(screen.getAllByText("Remove")[0]);+ 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"]);+ });+ });+});diff --git a/surfaces/gui/src/components/SettingsView.tsx b/surfaces/gui/src/components/SettingsView.tsxindex f4670d56..01cf5790 100644--- a/surfaces/gui/src/components/SettingsView.tsx+++ b/surfaces/gui/src/components/SettingsView.tsx@@ -19,8 +19,10 @@ import {type CloudStatus,type Machine,type MeInfo,+ getSandboxSettings,getSettings,getTrustedWorkspaces,+ setSandboxSettings,setAutoApprove,setAutoApproveShadow,setCompactionSettings,@@ -33,6 +35,8 @@ import {type CompactionSettings,type ModelSettings,type PdfSettings,+ type SandboxCredentialEntry,+ type SandboxSettings,type WorkspaceCommandTrust,} from "../api";import {@@ -89,6 +93,7 @@ export type SetTab =| "skills"| "voice"| "memory"+ | "sandbox"| "machines"| "connectors"| "personas"@@ -119,6 +124,7 @@ type SetIcon =| "book"| "refresh"| "plug"+ | "shield"| "user";// `labelKey` = the i18n key for the label; tabs without one yet show `label` as is.type TabDef = { key: SetTab; label: string; labelKey?: string; icon: SetIcon };@@ -146,6 +152,7 @@ const SET_GROUPS: { name: string; nameKey?: string; scope: "app" | "machine" | "{ key: "context", label: "Context optimization", labelKey: "settings.tab.context", icon: "refresh" },{ key: "skills", label: "Skills", labelKey: "settings.tab.skills", icon: "book" },{ key: "memory", label: "Memory", labelKey: "settings.tab.memory", icon: "archive" },+ { key: "sandbox", label: "Sandbox", labelKey: "settingsx.tab.sandbox", icon: "shield" },{ key: "personas", label: "Coworkers", labelKey: "settings.tab.personas", icon: "sparkle" },],},@@ -386,6 +393,8 @@ export function SettingsView({machine={scoped}onAskWorker={(machineId) => onAskWorker?.(machineId)}/>+ ) : tab === "sandbox" ? (+ <SandboxSection key={scopeId || "local"} machine={scoped} />) : tab === "machines" ? (<MachinesSection />) : tab === "slack" || tab === "github" ? (@@ -711,6 +720,215 @@ 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++ 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")],+ 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 });++ return (+ <section data-testid="sandbox-section">+ <PanelHead+ title={t("settingsx.sandbox.title")}+ sub={machine ? t("settingsx.sandbox.sub_machine", { name: machine.name }) : t("settingsx.sandbox.sub")}+ />+ {error ? <div className="mb-3 text-meta text-danger">{error}</div> : null}++ <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")+ .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>+ </span>+ <span className={"text-meta shrink-0 " + (p.usable ? (active ? "text-success" : "text-muted") : "text-muted")} title={p.why || undefined}>+ {p.name === "direct" && !cfg.provider+ ? t("settingsx.sandbox.status_default")+ : p.usable+ ? t("settingsx.sandbox.status_ready")+ : t("settingsx.sandbox.status_unavailable")}+ </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 ? <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}+ </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 ad3c39ec..5bda529e 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2198,7 +2198,8 @@"account": "Account","slack": "Slack","github": "GitHub",- "machines": "Machines"+ "machines": "Machines",+ "sandbox": "Sandbox"},"back_to_app": "Back to app","machine_scope_aria": "Machine scope",@@ -2265,6 +2266,51 @@"enable_desc": "Adds an <em>Auto-approve</em> option to the mode picker. In that mode, your session model reviews each action that would normally need approval and clears the routine ones; anything doubtful still asks you. It can never allow something the rules block. One extra model call per check, billed to your usage.","shadow_title": "Shadow evaluation <faint>(for measuring)</faint>","shadow_desc": "On any mode, the reviewer records what it <em>would</em> have decided next to your own choice — without changing anything. Lets you see how it would behave before trusting it. Also costs one model call per approval."+ },+ "sandbox": {+ "title": "Sandbox",+ "sub": "Where agents run their commands and file tools on this Mac. Applies to every session on this machine; a project cannot change it.",+ "sub_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.",+ "provider_seatbelt": "macOS sandbox",+ "provider_seatbelt_desc": "Commands can read and write only the session's folders and reach only the network hosts on the allow list. Your other files and logins are hidden.",+ "provider_openshell": "OpenShell (NVIDIA)",+ "provider_openshell_desc": "One Linux container per agent, with the session's folders mounted. Needs OpenShell and Docker on this machine.",+ "status_default": "default",+ "status_ready": "ready",+ "status_unavailable": "not available",+ "refused": "Sessions on this machine are refused until this is fixed: {{why}}",+ "network": "Network allow list",+ "profile_strict": "Strict",+ "profile_strict_desc": "GitHub, GitLab and the package registries (PyPI, npm, crates, Go).",+ "profile_standard": "Standard",+ "profile_standard_desc": "Strict plus the search APIs.",+ "network_help": "Shared credentials below add the hosts their tools need.",+ "credentials": "Credentials an agent may be given",+ "add": "Add a file or folder…",+ "copied_from": "Copied from",+ "also_allows": "Also allows {{hosts}}.",+ "edit": "Edit",+ "remove": "Remove",+ "done": "Done",+ "cancel": "Cancel",+ "field_title": "Name",+ "field_path": "Path (under your home folder)",+ "field_hosts": "Hosts it needs (host:port, one per line)",+ "field_does": "Lets the agent",+ "credentials_help": "Switched-on entries are copied into every sandbox on this machine for the session, and deleted with it. Your real files are never touched.",+ "keychain_note": "Logins kept in the macOS Keychain (git over HTTPS) are not files and cannot be shared. Use an SSH remote, or the GitHub connector.",+ "does_ssh": "Push and pull over SSH, and log in to servers, as you.",+ "does_gh": "Use gh as you: pull requests, issues, releases.",+ "does_aws": "Use aws with your profiles.",+ "does_kube": "Use kubectl with your clusters.",+ "title_ssh": "SSH keys",+ "title_gh": "GitHub CLI",+ "title_aws": "AWS",+ "title_kube": "Kubernetes",+ "saved_in": "Saved in {{path}}"}},"misc": {diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 43605202..8eb9980b 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -2158,7 +2158,8 @@"account": "账户","slack": "Slack","github": "GitHub",- "machines": "机器"+ "machines": "机器",+ "sandbox": "沙箱"},"back_to_app": "返回应用","machine_scope_aria": "机器范围",@@ -2225,6 +2226,51 @@"enable_desc": "在模式选择器中添加<em>自动审批</em>选项。在该模式下,会话模型会审查每个通常需要审批的操作,并放行常规操作;拿不准的仍会询问你。它永远无法允许规则禁止的操作。每次检查多一次模型调用,计入你的用量。","shadow_title": "影子评估 <faint>(用于衡量)</faint>","shadow_desc": "在任何模式下,审查器都会在你自己的选择旁记录它<em>本会</em>做出的决定 —— 不改变任何事情。让你在信任它之前先看看它的表现。每次审批同样多一次模型调用。"+ },+ "sandbox": {+ "title": "沙箱",+ "sub": "同事在这台 Mac 上运行命令和文件工具的位置。适用于这台机器上的每个会话;项目无法更改。",+ "sub_machine": "在 ⌂ {{name}} 上 —— 它的同事运行命令和文件工具的位置。适用于那台机器上的每个会话;项目无法更改。",+ "run_in": "在哪里运行同事",+ "provider_direct": "不使用沙箱",+ "provider_direct_desc": "命令以你的身份运行,没有限制。最快。在你另作选择前为默认。",+ "provider_seatbelt": "macOS 沙箱",+ "provider_seatbelt_desc": "命令只能读写会话的文件夹,只能访问允许列表中的网络主机。你的其他文件和登录信息被隐藏。",+ "provider_openshell": "OpenShell(NVIDIA)",+ "provider_openshell_desc": "每个同事一个 Linux 容器,挂载会话的文件夹。需要这台机器上装有 OpenShell 和 Docker。",+ "status_default": "默认",+ "status_ready": "就绪",+ "status_unavailable": "不可用",+ "refused": "在修复此问题前,这台机器上的会话将被拒绝:{{why}}",+ "network": "网络允许列表",+ "profile_strict": "严格",+ "profile_strict_desc": "GitHub、GitLab 和软件包源(PyPI、npm、crates、Go)。",+ "profile_standard": "标准",+ "profile_standard_desc": "严格模式加上搜索 API。",+ "network_help": "下方共享的凭据会加入其工具所需的主机。",+ "credentials": "可提供给同事的凭据",+ "add": "添加文件或文件夹…",+ "copied_from": "复制自",+ "also_allows": "同时允许 {{hosts}}。",+ "edit": "编辑",+ "remove": "移除",+ "done": "完成",+ "cancel": "取消",+ "field_title": "名称",+ "field_path": "路径(在你的主目录下)",+ "field_hosts": "所需主机(host:port,每行一个)",+ "field_does": "让同事可以",+ "credentials_help": "已开启的条目会在会话期间复制到这台机器上的每个沙箱中,并随沙箱一起删除。你的真实文件不会被改动。",+ "keychain_note": "保存在 macOS 钥匙串中的登录信息(HTTPS 方式的 git)不是文件,无法共享。请使用 SSH 远程地址,或 GitHub 连接器。",+ "does_ssh": "以你的身份通过 SSH 推送和拉取,并登录服务器。",+ "does_gh": "以你的身份使用 gh:拉取请求、议题、发布。",+ "does_aws": "使用你的配置文件运行 aws。",+ "does_kube": "使用你的集群运行 kubectl。",+ "title_ssh": "SSH 密钥",+ "title_gh": "GitHub CLI",+ "title_aws": "AWS",+ "title_kube": "Kubernetes",+ "saved_in": "保存在 {{path}}"}},"misc": {diff --git a/tests/test_sandbox_settings.py b/tests/test_sandbox_settings.pynew file mode 100644index 00000000..9ec4d77b--- /dev/null+++ b/tests/test_sandbox_settings.py@@ -0,0 +1,83 @@+"""Settings ▸ Sandbox: the machine-level snapshot and updates behind /v1/settings/sandbox."""++from __future__ import annotations++from pathlib import Path++import pytest++from coworker import config as app_config+from coworker.sandbox import settings+++def config_file(tmp_path, monkeypatch):+ target = tmp_path / "config.toml"+ monkeypatch.setattr(app_config, "global_config_path", lambda: target)+ monkeypatch.delenv("OPENWORKER_SANDBOX_PROVIDER", raising=False)+ return target+++def test_snapshot_reports_the_default_rule_and_the_shipped_entries(config_file):+ snap = settings.snapshot()+ assert snap["provider"] == "" and snap["effective_provider"] == "direct" and snap["refused"] == ""+ assert [p["name"] for p in snap["providers"]] == ["direct", "seatbelt", "openshell"]+ assert next(p for p in snap["providers"] if p["name"] == "direct")["usable"]+ assert snap["network_profile"] == "strict" and [n["name"] for n in snap["network_profiles"]] == ["strict", "standard"]+ assert [(e["name"], e["enabled"]) for e in snap["credentials"]] == [("ssh", False), ("gh", False), ("aws", False), ("kube", False)]+ assert snap["config_path"] == str(config_file)+++def test_update_writes_only_what_differs_from_the_shipped_entries(config_file):+ out = settings.update(+ {+ "network_profile": "standard",+ "credentials": [+ {"name": "ssh", "enabled": True},+ {"name": "gh", "enabled": False},+ {"name": "aws", "enabled": True, "path": "~/.aws-work", "hosts": ["*.amazonaws.com:443"]},+ {"name": "npm", "enabled": True, "path": "~/.npmrc", "hosts": ["registry.npmjs.org:443"], "title": "npm"},+ ],+ }+ )+ assert out["ok"], out+ text = config_file.read_text()+ assert 'sandbox_network_profile = "standard"' in text+ assert text.count("[[sandbox_credentials]]") == 3 # gh is untouched, so not written+ assert 'path = "~/.aws-work"' in text and 'hosts = ["registry.npmjs.org:443"]' in text+ snap = settings.snapshot()+ by = {e["name"]: e for e in snap["credentials"]}+ assert by["ssh"]["enabled"] and not by["gh"]["enabled"] and by["aws"]["path"] == "~/.aws-work" and by["npm"]["title"] == "npm"+ assert app_config.load_config().sandbox_credentials[0] == {"name": "ssh", "enabled": True}+++def test_update_refuses_bad_input_without_writing(config_file):+ assert settings.update({"provider": "bwrap"})["ok"] is False+ assert settings.update({"network_profile": "wide-open"})["ok"] is False+ assert settings.update({"credentials": [{"name": "x", "enabled": True, "path": "etc"}]})["ok"] is False+ assert settings.update({"credentials": [{"name": "x", "enabled": True, "hosts": ["nohost"]}]})["ok"] is False+ assert settings.update({"credentials": [{"enabled": True}]})["ok"] is False+ assert not config_file.exists()+++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()+ out = settings.update({"provider": "", "credentials": []})+ assert out["ok"] and out["provider"] == "" and out["effective_provider"] == "direct"+ text = config_file.read_text()+ assert "sandbox_provider" not in text and "[[sandbox_credentials]]" not in text+++def test_an_explicit_provider_that_cannot_be_used_shows_as_refused(config_file, monkeypatch):+ from coworker.sandbox import selection+ from coworker.sandbox.providers.openshell import OpenShellUnavailable++ monkeypatch.setattr(selection, "openshell_problem", lambda fresh=False: "OpenShell is not installed")+ assert settings.update({"provider": "openshell"})["ok"]+ snap = settings.snapshot()+ assert snap["provider"] == "openshell" and snap["effective_provider"] == ""+ assert "no session will start" in snap["refused"] and "not installed" in snap["refused"]+ assert not next(p for p in snap["providers"] if p["name"] == "openshell")["usable"]+ with pytest.raises(OpenShellUnavailable):+ selection.select("openshell")