Python
Session header: a chip says whether the session is sandboxed
Rohit C Prasadba76e0df983b
diff --git a/coworker/sandbox/settings.py b/coworker/sandbox/settings.pyindex a4516f32..62e9aa83 100644--- a/coworker/sandbox/settings.py+++ b/coworker/sandbox/settings.py@@ -319,3 +319,44 @@ def add_site(host: str) -> list[str]:current.append(entry)app_config.set_global_list("sandbox_network_hosts", current)return current+++def session_sandbox(engine: Any) -> dict[str, Any]:+ """What a session's header says about its sandbox (OPE-218): the walls THIS session+ runs behind, which were fixed when it started, not the machine's current setting.++ - `sandboxed`: its commands and file tools run in a sandbox. Carries the provider, the+ network setting, the allowed sites (for "Only the sites you allow"), the folders and+ the shared logins.+ - `not_sandboxed`: the machine is set to use a sandbox, and this session has none (it+ was opened before the switch). The one state worth a warning.+ - `off`: no sandbox on this machine and none here. Nothing was promised.+ """+ from .workspace import DIRECT, provider_name++ workspace = getattr(engine, "sandbox_workspace", None)+ provider = getattr(workspace, "provider", None)+ if provider is not None:+ profile = str(getattr(provider, "profile", "") or "")+ sites = getattr(getattr(engine, "permissions", None), "sandbox_sites", None)+ if sites is None:+ sites = list(getattr(provider, "extra_hosts", None) or [])+ return {+ "state": "sandboxed",+ "provider": str(getattr(provider, "name", "") or ""),+ "network": profile,+ "sites": [str(x) for x in sites] if profile == "allowlist" else [],+ "folders": [+ {"path": str(r.get("path", "")), "writable": bool(r.get("writable"))}+ for r in (getattr(provider, "roots", None) or [])+ ],+ "logins": [str(getattr(g, "title", "") or getattr(g, "name", "")) for g in (getattr(provider, "grants", None) or [])],+ "started": bool(getattr(workspace, "started", False)),+ }+ try:+ configured = provider_name(app_config.load_config().sandbox_provider)+ except Exception: # noqa: BLE001 - a broken config must not break the header+ configured = DIRECT+ if configured != DIRECT:+ return {"state": "not_sandboxed", "provider": configured}+ return {"state": "off"}diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 872073ad..42ca57ef 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -167,6 +167,17 @@ from ..inbox import VIS_INBOX, VIS_INLINE, args_previewfrom ..permissions import Modefrom ..providers import AssistantTurnfrom .. import toolchain+++def _session_sandbox(engine: Any) -> dict[str, Any]:+ """The session's sandbox, for its header chip. Never raises: a header must not break+ a session."""+ try:+ from ..sandbox.settings import session_sandbox++ return session_sandbox(engine)+ except Exception: # noqa: BLE001+ return {"state": "off"}from ..teams.model import AuthorityError as TeamsAuthorityErrorfrom ..teams.model import BoardError as TeamsBoardErrorfrom ..teams.model import BoardNotFoundError as TeamsBoardNotFoundError@@ -2934,6 +2945,8 @@ def create_app(manager: SessionManager) -> FastAPI:"agent": getattr(engine, "agent_name", "code"),"model": engine.model,"mode": engine.permissions.mode.value,+ # OPE-218: the header chip says which walls this session runs behind.+ "sandbox": _session_sandbox(engine),"workspace": (str(getattr(engine, "executor").cwd)if getattr(engine, "executor", None)diff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsxindex 997dd5ce..865eee37 100644--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@ -81,6 +81,7 @@ import { SearchModal } from "./components/SearchModal";import { SessionIntro } from "./components/SessionIntro";import { FolderGate } from "./components/FolderGate";import { SessionSetupRow } from "./components/SessionSetupRow";+import { SandboxChip, type SessionSandbox } from "./components/SandboxChip";import { SendFolderDialog } from "./components/SendFolderDialog";import { Onboarding } from "./components/Onboarding";import { UpdateBanner } from "./components/UpdateBanner";@@ -251,6 +252,8 @@ export function App() {// OPE-206: the provider name while this session's sandbox is being built (the socket// is open, `ready` has not come yet); null otherwise. Drives the waiting row.const [preparingSandbox, setPreparingSandbox] = useState<string | null>(null);+ // OPE-218: which walls this session runs behind, for the header chip. From `ready`.+ const [sandboxInfo, setSandboxInfo] = useState<SessionSandbox | null>(null);// The server refused to build this session (its sandbox cannot be used) and closed the// socket for good: no reconnect strip, the error notice in the transcript says why.const [sessionRefused, setSessionRefused] = useState(false);@@ -880,6 +883,7 @@ export function App() {break;case "ready":setPreparingSandbox(null);+ setSandboxInfo(d.sandbox || null);setSessionRefused(false);setConnected(true);if (d.model) setModel(d.model);@@ -2183,6 +2187,11 @@ export function App() {<span className="topbar-artifacts-count">{artifactCount}</span></button>)}+ {/* OPE-218: which walls this session runs behind. No chip when the machine has+ no sandbox; amber only for a session opened before the sandbox was switched on. */}+ {surface === "session" && (+ <SandboxChip info={sandboxInfo} onOpenSettings={() => openSettings("sandbox")} />+ )}{/* §32: the panel toggle is the ONE session-panel entry, for every non-chat persona(the rail now carries Access, so code-family gets it too). */}{agent !== "chat" && (diff --git a/surfaces/gui/src/components/SandboxChip.test.tsx b/surfaces/gui/src/components/SandboxChip.test.tsxnew file mode 100644index 00000000..11ed0e04--- /dev/null+++ b/surfaces/gui/src/components/SandboxChip.test.tsx@@ -0,0 +1,55 @@+// The session header's sandbox chip (OPE-218).+import { afterEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen } from "@testing-library/react";+import { SandboxChip, type SessionSandbox } from "./SandboxChip";++afterEach(cleanup);++const sandboxed: SessionSandbox = {+ state: "sandboxed", provider: "openshell", network: "allowlist",+ sites: ["github.com:443", "api.github.com:443", "pypi.org:443"],+ folders: [{ path: "/home/sam/code/billing", writable: true }], logins: ["GitHub CLI"], started: true,+};++describe("SandboxChip", () => {+ it("says the sandbox and how many sites, and lists the walls on click", () => {+ const openSettings = vi.fn();+ render(<SandboxChip info={sandboxed} onOpenSettings={openSettings} />);+ const chip = screen.getByTestId("sandbox-chip");+ expect(chip.textContent).toBe("OpenShell · 3 sites");+ expect(chip.getAttribute("data-state")).toBe("sandboxed");+ expect(screen.queryByTestId("sandbox-chip-panel")).toBeNull();+ fireEvent.click(chip);+ const panel = screen.getByTestId("sandbox-chip-panel").textContent || "";+ expect(panel).toContain("This session is sandboxed");+ expect(panel).toContain("OpenShell. Commands and file tools run inside it.");+ expect(panel).toContain("/home/sam/code/billing");+ expect(panel).toContain("github.com, api.github.com, pypi.org"); // the web port is not shown+ expect(panel).toContain("GitHub CLI");+ fireEvent.click(screen.getByTestId("sandbox-chip-settings"));+ expect(openSettings).toHaveBeenCalled();+ });++ it("any site, and one site", () => {+ const { rerender } = render(<SandboxChip info={{ ...sandboxed, provider: "seatbelt", network: "open", sites: [] }} />);+ expect(screen.getByTestId("sandbox-chip").textContent).toBe("macOS sandbox · any site");+ rerender(<SandboxChip info={{ ...sandboxed, sites: ["github.com:443"] }} />);+ expect(screen.getByTestId("sandbox-chip").textContent).toBe("OpenShell · 1 site");+ });++ it("warns only for a session opened before the sandbox was switched on", () => {+ render(<SandboxChip info={{ state: "not_sandboxed", provider: "openshell" }} />);+ const chip = screen.getByTestId("sandbox-chip");+ expect(chip.textContent).toBe("Not sandboxed");+ expect(chip.getAttribute("data-state")).toBe("not_sandboxed");+ fireEvent.click(chip);+ expect(screen.getByTestId("sandbox-chip-panel").textContent).toContain("opened before the sandbox was switched on");+ });++ it("shows nothing when the machine has no sandbox, or the server says nothing", () => {+ const { container, rerender } = render(<SandboxChip info={{ state: "off" }} />);+ expect(container.textContent).toBe("");+ rerender(<SandboxChip info={null} />);+ expect(container.textContent).toBe("");+ });+});diff --git a/surfaces/gui/src/components/SandboxChip.tsx b/surfaces/gui/src/components/SandboxChip.tsxnew file mode 100644index 00000000..0764198f--- /dev/null+++ b/surfaces/gui/src/components/SandboxChip.tsx@@ -0,0 +1,125 @@+// The session header's sandbox chip (OPE-218; mock ux-improvements/mocks/+// sandbox-indicator-and-site-card.html, approved 2026-10-02). It says which walls THIS+// session runs behind, which were fixed when the session started:+// - sandboxed: green, "OpenShell · 3 sites" / "macOS sandbox · any site";+// - not sandboxed although the machine is set to use a sandbox (the session was opened+// before the switch): amber, "Not sandboxed", the one state worth a warning;+// - no sandbox on this machine: no chip at all, since nothing was promised.+// Clicking it lists the session's folders, sites and shared logins.+import { useEffect, useRef, useState } from "react";+import { useTranslation } from "react-i18next";+import { Icon } from "./Icon";++export interface SessionSandbox {+ state: "sandboxed" | "not_sandboxed" | "off";+ provider?: string;+ network?: string; // "allowlist" | "open"+ sites?: string[];+ folders?: { path: string; writable: boolean }[];+ logins?: string[];+ started?: boolean;+}++// "github.com:443" reads as "github.com": the port only matters when it is not the web's.+const siteName = (entry: string): string => entry.replace(/:443$/, "");++export function SandboxChip({ info, onOpenSettings }: { info: SessionSandbox | null; onOpenSettings?: () => void }) {+ const { t } = useTranslation();+ const [open, setOpen] = useState(false);+ const box = useRef<HTMLDivElement | null>(null);++ useEffect(() => {+ if (!open) return;+ const close = (e: MouseEvent) => {+ if (box.current && !box.current.contains(e.target as Node)) setOpen(false);+ };+ const key = (e: KeyboardEvent) => {+ if (e.key === "Escape") setOpen(false);+ };+ window.addEventListener("mousedown", close);+ window.addEventListener("keydown", key);+ return () => {+ window.removeEventListener("mousedown", close);+ window.removeEventListener("keydown", key);+ };+ }, [open]);++ if (!info || info.state === "off") return null;++ const sandboxed = info.state === "sandboxed";+ const providerLabel = t(`sandboxchip.provider_${info.provider}`, { defaultValue: info.provider || "" });+ const sites = info.sites || [];+ const network = !sandboxed+ ? ""+ : info.network === "allowlist"+ ? t("sandboxchip.sites", { count: sites.length })+ : t("sandboxchip.any_site");+ const label = sandboxed ? `${providerLabel} · ${network}` : t("sandboxchip.not_sandboxed");+ const tone = sandboxed ? "border-okLine bg-okSoft text-ok" : "border-lineStrong bg-warnSoft text-warnInk";++ return (+ <div className="relative" ref={box} onMouseDown={(e) => e.stopPropagation()}>+ <button+ className={"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full border text-meta whitespace-nowrap " + tone}+ onClick={() => setOpen((v) => !v)}+ data-testid="sandbox-chip"+ data-state={info.state}+ aria-expanded={open}+ >+ {sandboxed && <Icon name="shield" size={12} />}+ {label}+ </button>+ {open && (+ <div+ className="absolute right-0 top-full mt-2 z-40 w-[330px] bg-panel border border-line rounded-xl2 shadow-xl p-4 text-left"+ data-testid="sandbox-chip-panel"+ >+ {sandboxed ? (+ <>+ <div className="text-ui font-semibold text-ink">{t("sandboxchip.title")}</div>+ <div className="text-meta text-muted mt-0.5">{t("sandboxchip.sub", { provider: providerLabel })}</div>+ <div className="text-label text-faint mt-3 mb-0.5">{t("sandboxchip.folders")}</div>+ {(info.folders || []).map((f) => (+ <div key={f.path} className="text-meta text-ink font-mono truncate" title={f.path}>+ {f.path}{" "}+ <span className="text-faint font-sans">{f.writable ? t("sandboxchip.read_write") : t("sandboxchip.read_only")}</span>+ </div>+ ))}+ <div className="text-label text-faint mt-3 mb-0.5">{t("sandboxchip.sites_label")}</div>+ <div className="text-meta text-ink">+ {info.network === "allowlist"+ ? sites.length+ ? sites.map(siteName).join(", ")+ : t("sandboxchip.no_sites")+ : t("sandboxchip.any_site_long")}+ </div>+ {(info.logins || []).length > 0 && (+ <>+ <div className="text-label text-faint mt-3 mb-0.5">{t("sandboxchip.logins")}</div>+ <div className="text-meta text-ink">{(info.logins || []).join(", ")}</div>+ </>+ )}+ </>+ ) : (+ <>+ <div className="text-ui font-semibold text-ink">{t("sandboxchip.not_title")}</div>+ <div className="text-meta text-muted mt-0.5">{t("sandboxchip.not_sub")}</div>+ </>+ )}+ {onOpenSettings && (+ <button+ className="mt-3 text-meta text-accent hover:underline"+ onClick={() => {+ setOpen(false);+ onOpenSettings();+ }}+ data-testid="sandbox-chip-settings"+ >+ {t("sandboxchip.open_settings")}+ </button>+ )}+ </div>+ )}+ </div>+ );+}diff --git a/surfaces/gui/src/gallery/states.contract.json b/surfaces/gui/src/gallery/states.contract.jsonindex 07ece95d..59e8ac56 100644--- a/surfaces/gui/src/gallery/states.contract.json+++ b/surfaces/gui/src/gallery/states.contract.json@@ -8935,6 +8935,31 @@"reason": "Check the invoice object's PDF field","category": "network"},+ "site-off-the-allowed-sites": {+ "name": "web_fetch",+ "arguments": {+ "url": "https://weather.com/weather/today/l/San+Francisco+CA"+ },+ "reason": "weather.com is not on your allowed sites",+ "escalation": {+ "kind": "human_required",+ "reason": "weather.com is not on your allowed sites"+ },+ "site_wall": "weather.com"+ },+ "search-provider-off-the-allowed-sites": {+ "name": "web_search",+ "arguments": {+ "query": "weather in San Francisco today"+ },+ "reason": "api.search.brave.com is not on your allowed sites",+ "escalation": {+ "kind": "human_required",+ "reason": "api.search.brave.com is not on your allowed sites"+ },+ "search_provider": "brave",+ "site_wall": "api.search.brave.com"+ },"connector-action": {"name": "github_create_pull_request","arguments": {@@ -9179,6 +9204,60 @@"provenance": ""}},+ "site-off-the-allowed-sites": {+ "id": "gallery-item",+ "session_id": "gallery-session",+ "kind": "approval",+ "title": "Run `web_fetch`?",+ "body": "weather.com is not on your allowed sites",+ "state": "pending",+ "resolution": null,+ "inbox": "default",+ "created_at": "2026-09-17T09:30:00Z",+ "resolved_at": null,+ "visibility": "inbox",+ "session_title": "Mention #3 · Invoice PDF download",+ "session_agent": "swe-lead",+ "session_exists": true,+ "data": {+ "tool": "web_fetch",+ "arguments": {+ "url": "https://weather.com/weather/today/l/San+Francisco+CA"+ },+ "escalation": {+ "kind": "human_required",+ "reason": "weather.com is not on your allowed sites"+ },+ "provenance": ""+ }+ },+ "search-provider-off-the-allowed-sites": {+ "id": "gallery-item",+ "session_id": "gallery-session",+ "kind": "approval",+ "title": "Run `web_search`?",+ "body": "api.search.brave.com is not on your allowed sites",+ "state": "pending",+ "resolution": null,+ "inbox": "default",+ "created_at": "2026-09-17T09:30:00Z",+ "resolved_at": null,+ "visibility": "inbox",+ "session_title": "Mention #3 · Invoice PDF download",+ "session_agent": "swe-lead",+ "session_exists": true,+ "data": {+ "tool": "web_search",+ "arguments": {+ "query": "weather in San Francisco today"+ },+ "escalation": {+ "kind": "human_required",+ "reason": "api.search.brave.com is not on your allowed sites"+ },+ "provenance": ""+ }+ },"connector-action": {"id": "gallery-item","session_id": "gallery-session",diff --git a/surfaces/gui/src/gallery/states/approval.ts b/surfaces/gui/src/gallery/states/approval.tsindex 853383d6..8a4ac9b9 100644--- a/surfaces/gui/src/gallery/states/approval.ts+++ b/surfaces/gui/src/gallery/states/approval.ts@@ -78,6 +78,31 @@ export const approvalStates: CardState[] = [category: "network",},},+ {+ id: "site-off-the-allowed-sites",+ title: "A site that is not on the allowed sites",+ note: "The session is sandboxed with \"Only the sites you allow\" and the page is on a site outside the list. The card says so and offers to add the site to the machine's list (OPE-219). In Bypass the call is refused with no card.",+ payload: {+ name: "web_fetch",+ arguments: { url: "https://weather.com/weather/today/l/San+Francisco+CA" },+ reason: "weather.com is not on your allowed sites",+ escalation: { kind: "human_required", reason: "weather.com is not on your allowed sites" },+ site_wall: "weather.com",+ },+ },+ {+ id: "search-provider-off-the-allowed-sites",+ title: "Web search when the search provider is not on the allowed sites",+ note: "A search goes to one site, the configured provider. Same card, for that host.",+ payload: {+ name: "web_search",+ arguments: { query: "weather in San Francisco today" },+ reason: "api.search.brave.com is not on your allowed sites",+ escalation: { kind: "human_required", reason: "api.search.brave.com is not on your allowed sites" },+ search_provider: "brave",+ site_wall: "api.search.brave.com",+ },+ },{id: "connector-action",title: "Connector action",diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex a2b5e674..fb3337f3 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -2642,5 +2642,26 @@"open_worker_pane": "View {{name}} beside the lead","full_session": "Open full session","chat_off": "Team chat is off for this team"+ },+ "sandboxchip": {+ "provider_openshell": "OpenShell",+ "provider_seatbelt": "macOS sandbox",+ "provider_windows": "Windows sandbox",+ "sites_one": "{{count}} site",+ "sites_other": "{{count}} sites",+ "any_site": "any site",+ "not_sandboxed": "Not sandboxed",+ "title": "This session is sandboxed",+ "sub": "{{provider}}. Commands and file tools run inside it. It was set when the session started.",+ "folders": "Folders",+ "read_write": "read and write",+ "read_only": "read only",+ "sites_label": "Sites",+ "no_sites": "None. Add sites in Settings ▸ Sandbox.",+ "any_site_long": "Any site",+ "logins": "Shared logins",+ "not_title": "This session is not sandboxed",+ "not_sub": "It was opened before the sandbox was switched on. Its commands run on this computer without the sandbox. Start a new session to use the sandbox.",+ "open_settings": "Open Settings ▸ Sandbox"}}diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 450a1788..18e7a234 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -2602,5 +2602,26 @@"open_worker_pane": "在主代理旁查看 {{name}}","full_session": "打开完整会话","chat_off": "此团队未启用团队聊天"+ },+ "sandboxchip": {+ "provider_openshell": "OpenShell",+ "provider_seatbelt": "macOS 沙盒",+ "provider_windows": "Windows 沙盒",+ "sites_one": "{{count}} 个网站",+ "sites_other": "{{count}} 个网站",+ "any_site": "任意网站",+ "not_sandboxed": "未在沙盒中",+ "title": "此会话在沙盒中运行",+ "sub": "{{provider}}。命令和文件工具在其中运行。沙盒在会话开始时确定。",+ "folders": "文件夹",+ "read_write": "可读写",+ "read_only": "只读",+ "sites_label": "网站",+ "no_sites": "无。可在 设置 ▸ 沙盒 中添加网站。",+ "any_site_long": "任意网站",+ "logins": "共享的登录",+ "not_title": "此会话未在沙盒中运行",+ "not_sub": "它在开启沙盒之前打开,其命令在本机上不经沙盒运行。新建会话即可使用沙盒。",+ "open_settings": "打开 设置 ▸ 沙盒"}}diff --git a/tests/test_site_wall.py b/tests/test_site_wall.pyindex 64a81bd0..3021b0bd 100644--- a/tests/test_site_wall.py+++ b/tests/test_site_wall.py@@ -116,3 +116,39 @@ def test_add_site_joins_the_machines_list_once(tmp_path, monkeypatch):assert hosts == ["weather.com:443"]settings.add_site("weather.com")assert app_config.load_config().sandbox_network_hosts == hosts # no duplicate+++# -- what the session header is told (OPE-218) ----------------------------------------------+++def test_session_sandbox_summary(tmp_path, monkeypatch):+ from types import SimpleNamespace++ from coworker.sandbox import settings++ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))+ grant = SimpleNamespace(name="gh", title="GitHub CLI")+ provider = SimpleNamespace(+ name="openshell", profile="allowlist", extra_hosts=["github.com:443"],+ roots=[{"path": "/home/sam/code/app", "writable": True}], grants=[grant],+ )+ engine = SimpleNamespace(+ sandbox_workspace=SimpleNamespace(provider=provider, started=False),+ permissions=SimpleNamespace(sandbox_sites=["github.com:443", "weather.com"]),+ )+ info = settings.session_sandbox(engine)+ assert info["state"] == "sandboxed" and info["provider"] == "openshell" and info["network"] == "allowlist"+ assert info["sites"] == ["github.com:443", "weather.com"] # the live list, with what the user added+ assert info["folders"] == [{"path": "/home/sam/code/app", "writable": True}] and info["logins"] == ["GitHub CLI"]+ assert info["started"] is False++ provider.profile = "open"+ engine.permissions.sandbox_sites = None+ assert settings.session_sandbox(engine)["sites"] == [] # any site: no list to show++ # A session with no sandbox: "off" when the machine has none either...+ plain = SimpleNamespace(sandbox_workspace=SimpleNamespace(), permissions=SimpleNamespace(sandbox_sites=None))+ assert settings.session_sandbox(plain) == {"state": "off"}+ # ...and "not sandboxed" when the machine is now set to use one (opened before the switch).+ (tmp_path / "config.toml").write_text('sandbox_provider = "openshell"\n')+ assert settings.session_sandbox(plain) == {"state": "not_sandboxed", "provider": "openshell"}