Python
Access section: the session's allowed sites, with a list of its own
Rohit C Prasada5bc274fb838
diff --git a/coworker/agent.py b/coworker/agent.pyindex 9325bee5..a68a8b10 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -756,6 +756,7 @@ def build_engine(engine.permissions.grant_site = _grant_siteengine.permissions.open_site = _open_site+ engine.permissions.close_site = lambda entry: sandbox_workspace.remove_hosts([entry])# The agent can ask for a site, except where nobody can answer (full access).from .permissions import Mode as _Modefrom .tools.network import request_network_access_tooldiff --git a/coworker/permissions.py b/coworker/permissions.pyindex decc8977..820e8941 100644--- a/coworker/permissions.py+++ b/coworker/permissions.py@@ -348,6 +348,8 @@ class PermissionEngine:grant_site: Optional[Callable[[str], Optional[list[str]]]] = None# Opens a site on the session's running sandbox, so commands reach it too (OPE-219).open_site: Optional[Callable[[str], None]] = None+ # Takes a site back from the session's running sandbox.+ close_site: Optional[Callable[[str], None]] = None# "host:port" entries a person allowed for this session only (either card, or the# session's own list in the app). The machine's list is `sandbox_sites`.session_sites: list[str] = field(default_factory=list)@@ -700,6 +702,22 @@ class PermissionEngine:self._note_session_site(str(entry))self._open(str(entry))+ def remove_session_site(self, entry: str) -> bool:+ """The person took back a site they had allowed for this session. Sites on the+ machine's list are not touched here; those are changed in Settings. Raises when the+ running sandbox could not drop it, and then nothing is changed."""+ if entry not in self.session_sites:+ return False+ if self.close_site is not None:+ self.close_site(entry)+ self.session_sites.remove(entry)+ self.site_open_errors.pop(entry, None)+ host = entry.rsplit(":", 1)[0]+ if not any(other.rsplit(":", 1)[0] == host for other in self.session_sites):+ self.session_allow_domains.discard(host)+ self.session_allow_domains.discard(host[4:] if host.startswith("www.") else host)+ return True+def _note_session_site(self, host_or_entry: str) -> None:from .sandbox.network_profiles import clean_hostdiff --git a/coworker/sandbox/netproxy.py b/coworker/sandbox/netproxy.pyindex 3d749b8a..271b7467 100644--- a/coworker/sandbox/netproxy.py+++ b/coworker/sandbox/netproxy.py@@ -57,6 +57,14 @@ class AllowListProxy:if host and port.isdigit():self._extra.add((host.lower().rstrip("."), int(port)))+ def remove_hosts(self, hosts: Sequence[str]) -> None:+ """Stop letting these "host:port" entries out (the person took a site back from the+ session). Connections already open are not cut."""+ for item in hosts:+ host, _, port = str(item).rpartition(":")+ if host and port.isdigit():+ self._extra.discard((host.lower().rstrip("."), int(port)))+def blocked_since(self, since: float) -> list[tuple[float, str]]:"""The connections refused at or after `since`, oldest first."""return [item for item in list(self.blocked) if item[0] >= since]diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.pyindex 93742824..79184122 100644--- a/coworker/sandbox/providers/openshell.py+++ b/coworker/sandbox/providers/openshell.py@@ -366,6 +366,17 @@ class OpenShellProvider:return # not made yet: the next create renders the list as it stands_cli("policy", "set", self.sandbox_name, "--policy", str(self._write_policy()), "--wait", timeout=120)+ def remove_hosts(self, hosts: Sequence[str]) -> None:+ """Take "host:port" entries back from the running sandbox: the policy is rendered+ without them and set again. OpenShell closes connections opened under the old rules."""+ gone = [str(h) for h in hosts if str(h) in self.extra_hosts]+ if not gone:+ return+ self.extra_hosts = [h for h in self.extra_hosts if h not in gone]+ if not getattr(self, "_create_tried", False):+ return+ _cli("policy", "set", self.sandbox_name, "--policy", str(self._write_policy()), "--wait", timeout=120)+reports_blocked = False # see blocked_sincedef blocked_since(self, since: float) -> list[tuple[float, str]]:diff --git a/coworker/sandbox/providers/seatbelt.py b/coworker/sandbox/providers/seatbelt.pyindex 86992e3a..b9b63bfb 100644--- a/coworker/sandbox/providers/seatbelt.py+++ b/coworker/sandbox/providers/seatbelt.py@@ -231,6 +231,15 @@ class SeatbeltProvider:if new and self._proxy is not None:self._proxy.add_hosts(new)+ def remove_hosts(self, hosts: Sequence[str]) -> None:+ """Take "host:port" entries back from the running sandbox. Hosts a shared login+ needs stay: they came with the credential, not from the list."""+ keep = {h for g in self.grants for h in g.hosts}+ gone = [str(h) for h in hosts if str(h) in self.extra_hosts]+ self.extra_hosts = [h for h in self.extra_hosts if h not in gone]+ if self._proxy is not None:+ self._proxy.remove_hosts([h for h in gone if h not in keep])+reports_blocked = True # its proxy records what it refusesdef blocked_since(self, since: float) -> list[tuple[float, str]]:diff --git a/coworker/sandbox/providers/windows.py b/coworker/sandbox/providers/windows.pyindex f0e9720d..5a57c741 100644--- a/coworker/sandbox/providers/windows.py+++ b/coworker/sandbox/providers/windows.py@@ -329,6 +329,15 @@ class WindowsProvider:if new and self._proxy is not None:self._proxy.add_hosts(new)+ def remove_hosts(self, hosts: Sequence[str]) -> None:+ """Take "host:port" entries back from the running sandbox. Hosts a shared login+ needs stay: they came with the credential, not from the list."""+ keep = {h for g in self.grants for h in g.hosts}+ gone = [str(h) for h in hosts if str(h) in self.extra_hosts]+ self.extra_hosts = [h for h in self.extra_hosts if h not in gone]+ if self._proxy is not None:+ self._proxy.remove_hosts([h for h in gone if h not in keep])+reports_blocked = True # its proxy records what it refusesdef blocked_since(self, since: float) -> list[tuple[float, str]]:diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.pyindex 20434ab0..3b38aa04 100644--- a/coworker/sandbox/workspace.py+++ b/coworker/sandbox/workspace.py@@ -214,6 +214,11 @@ class RunnerWorkspace(Workspace):notes = getattr(self.provider, "notes", None) or []return "\n".join(part for part in [text, *notes, self._network_context()] if part)+ def remove_hosts(self, hosts: Sequence[str]) -> None:+ """The person took a site back from this session: the sandbox stops letting it out."""+ with self._start_lock:+ self.provider.remove_hosts(hosts)+def _asking(self) -> bool:try:return bool(self.can_ask_network())diff --git a/coworker/server/app.py b/coworker/server/app.pyindex 42ca57ef..53cd1b64 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -800,6 +800,19 @@ def create_app(manager: SessionManager) -> FastAPI:def session_remove_root(session_id: str, path: str) -> dict[str, Any]:return manager.remove_root(session_id, path)+ # OPE-219: the session's allowed sites, for its header chip and Access section.+ @app.get("/v1/sessions/{session_id}/sites")+ def session_sites(session_id: str) -> dict[str, Any]:+ return {"sandbox": manager.session_sites(session_id)}++ @app.post("/v1/sessions/{session_id}/sites")+ def session_allow_site(session_id: str, body: dict) -> dict[str, Any]:+ return manager.allow_session_site(session_id, str((body or {}).get("host", "")))++ @app.delete("/v1/sessions/{session_id}/sites")+ def session_remove_site(session_id: str, host: str) -> dict[str, Any]:+ return manager.remove_session_site(session_id, host)+@app.get("/v1/sessions/{session_id}/artifacts")def session_artifacts(session_id: str) -> dict[str, Any]:return {"artifacts": manager.list_artifacts(session_id)}diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 50b0384a..f1e1e86b 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -7467,6 +7467,76 @@ class SessionManager:self._promotion_rebuild.add(session_id)return {"ok": True, "path": str(resolved), "roots": self.get_roots(session_id)}+ # -- the session's allowed sites (OPE-219): the person's own list for one session ------+ def session_sites(self, session_id: str) -> dict[str, Any]:+ """The session's sandbox as its header chip and Access section show it: the sites+ from Settings, and those allowed for this session only."""+ from ..sandbox.settings import session_sandbox++ engine = self._engines.get(session_id)+ if engine is None:+ return {"state": "off"}+ try:+ return session_sandbox(engine)+ except Exception: # noqa: BLE001 - a list must not break the pane+ return {"state": "off"}++ def _session_site_engine(self, session_id: str, host: str):+ """(engine, "host:port") for a change to the session's own sites, or an error text.+ Exact host names only, as on the agent's card: wildcards stay in Settings."""+ from ..permissions import network_request_hosts++ engine = self._engines.get(session_id)+ if engine is None or getattr(engine.permissions, "sandbox_sites", None) is None:+ return None, "", "This session has no allowed-sites list."+ good, bad = network_request_hosts({"hosts": [host]})+ if bad or len(good) != 1:+ return None, "", "Give an exact host name, such as registry.npmjs.org (add a port only when it is not 443)."+ return engine, good[0], ""++ def allow_session_site(self, session_id: str, host: str) -> dict[str, Any]:+ """The person allows a site for this session, from the Access section. Commands and+ web tools reach it at once; nothing is stored, and it ends with the session."""+ engine, entry, error = self._session_site_engine(session_id, host)+ if engine is None:+ return {"ok": False, "error": error}+ permissions = engine.permissions+ if permissions._entry_allowed(entry):+ return {"ok": True, "sandbox": self.session_sites(session_id)}+ permissions.allow_network_hosts([entry], always=False)+ failed = permissions.site_open_errors.get(entry)+ if failed:+ # The sandbox did not take it: do not leave a site listed that commands lack.+ permissions.site_open_errors.pop(entry, None)+ if entry in permissions.session_sites:+ permissions.session_sites.remove(entry)+ permissions.session_allow_domains.discard(entry.rsplit(":", 1)[0])+ return {"ok": False, "error": f"The sandbox could not take {entry}: {failed}", "sandbox": self.session_sites(session_id)}+ self._audit_session_site(session_id, "allowed", entry)+ return {"ok": True, "sandbox": self.session_sites(session_id)}++ def remove_session_site(self, session_id: str, host: str) -> dict[str, Any]:+ """The person takes back a site allowed for this session. Sites from Settings are+ not removed here."""+ engine, entry, error = self._session_site_engine(session_id, host)+ if engine is None:+ return {"ok": False, "error": error}+ try:+ removed = engine.permissions.remove_session_site(entry)+ except Exception as exc: # noqa: BLE001+ return {"ok": False, "error": f"The sandbox could not drop {entry}: {exc}", "sandbox": self.session_sites(session_id)}+ if not removed:+ return {"ok": False, "error": f"{entry} is not a site allowed for this session. Sites from Settings are changed in Settings > Sandbox.", "sandbox": self.session_sites(session_id)}+ self._audit_session_site(session_id, "removed", entry)+ return {"ok": True, "sandbox": self.session_sites(session_id)}++ def _audit_session_site(self, session_id: str, what: str, entry: str) -> None:+ try:+ # Allowing a site widens what the session reaches ("raised"); taking it back narrows it.+ self.audit_autonomy_change(session_id, "session_site", *(("", entry) if what == "allowed" else (entry, "")))+ except Exception: # noqa: BLE001 - the audit line must not fail the change+ pass+def add_root(self, session_id: str, path: str, writable: bool = False) -> dict[str, Any]:diff --git a/docs/macos-sandbox.md b/docs/macos-sandbox.mdindex 211106e7..0c39c8ce 100644--- a/docs/macos-sandbox.md+++ b/docs/macos-sandbox.md@@ -85,8 +85,11 @@ says whether the sandbox has in fact blocked it. You choose **Allow for this ses**Always allow**, or **Deny**; the site opens for the running session without a restart.The coworker is told which sites the sandbox blocked while a command ran, so it asks for theright one. With full access (no approvals) the coworker cannot ask;-add the site in Settings ▸ Sandbox yourself. The header chip lists the session's sites, those-from Settings and those allowed for this session only.+add the site in Settings ▸ Sandbox yourself.++The session's **Access** section lists its sites. Those you allowed for this session only+are marked **Session only**; you can take one back there, or allow another for the session.+Sites from Settings are changed in Settings ▸ Sandbox. A session site ends with the session.## Sharing a credential on purposediff --git a/docs/openshell.md b/docs/openshell.mdindex 6bf29046..95578292 100644--- a/docs/openshell.md+++ b/docs/openshell.md@@ -143,8 +143,11 @@ says whether the sandbox has in fact blocked it. You choose **Allow for this ses**Always allow**, or **Deny**; the site opens for the running session without a restart.On OpenShell the coworker is not yet told which sites were blocked; it asks from thecommand's own error. With full access (no approvals) the coworker cannot ask;-add the site in Settings ▸ Sandbox yourself. The header chip lists the session's sites, those-from Settings and those allowed for this session only.+add the site in Settings ▸ Sandbox yourself.++The session's **Access** section lists its sites. Those you allowed for this session only+are marked **Session only**; you can take one back there, or allow another for the session.+Sites from Settings are changed in Settings ▸ Sandbox. A session site ends with the session.OpenShell enforces the list in the container.diff --git a/docs/windows-sandbox.md b/docs/windows-sandbox.mdindex 539d96f2..fc5d4f20 100644--- a/docs/windows-sandbox.md+++ b/docs/windows-sandbox.md@@ -154,8 +154,11 @@ says whether the sandbox has in fact blocked it. You choose **Allow for this ses**Always allow**, or **Deny**; the site opens for the running session without a restart.The coworker is told which sites the sandbox blocked while a command ran, so it asks for theright one. With full access (no approvals) the coworker cannot ask;-add the site in Settings ▸ Sandbox yourself. The header chip lists the session's sites, those-from Settings and those allowed for this session only.+add the site in Settings ▸ Sandbox yourself.++The session's **Access** section lists its sites. Those you allowed for this session only+are marked **Session only**; you can take one back there, or allow another for the session.+Sites from Settings are changed in Settings ▸ Sandbox. A session site ends with the session.Choosing a mode never touches the firewall. The rules are written once at setup; OpenWorkerpicks the account. In the closed mode a sandbox can still **listen** on a local port (a devdiff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsxindex aff36f8d..388ee4eb 100644--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@ -2560,6 +2560,9 @@ export function App() {scratchPrimary={tempWorkspace || !isProjectScoped(personaOf(agent))}openAccessKey={accessKey}onOpenIntegrations={() => openSettings("connectors")}+ sandbox={sandboxInfo}+ onSandbox={setSandboxInfo}+ onOpenSandboxSettings={() => openSettings("sandbox")}board={board}onExpandBoard={() => openTeamView()}onOpenBoardItem={openTeamView}diff --git a/surfaces/gui/src/api.ts b/surfaces/gui/src/api.tsindex cc276b7f..adaeb30f 100644--- a/surfaces/gui/src/api.ts+++ b/surfaces/gui/src/api.ts@@ -648,6 +648,28 @@ export async function removeRoot(return res.json();}+// -- the session's allowed sites (OPE-219) -------------------------------------+// The answer carries the session's sandbox as the header chip shows it.+type SitesAnswer = { ok: boolean; error?: string; sandbox?: any };++export async function allowSessionSite(sessionId: string, host: string): Promise<SitesAnswer> {+ const res = await fetch(`${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/sites`, {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ host }),+ });+ return res.json();+}++export async function removeSessionSite(sessionId: string, host: string): Promise<SitesAnswer> {+ const q = new URLSearchParams({ host });+ const res = await fetch(+ `${sessionApiBase(sessionId)}/v1/sessions/${encodeURIComponent(sessionId)}/sites?${q.toString()}`,+ { method: "DELETE" },+ );+ return res.json();+}+// -- MCP servers --------------------------------------------------------------export interface McpServer {name: string;diff --git a/surfaces/gui/src/components/AccessSection.tsx b/surfaces/gui/src/components/AccessSection.tsxindex f16151c6..b499147a 100644--- a/surfaces/gui/src/components/AccessSection.tsx+++ b/surfaces/gui/src/components/AccessSection.tsx@@ -10,6 +10,8 @@// to expand it and scroll it into view.import { useCallback, useEffect, useRef, useState } from "react";+import { SessionSites } from "./SessionSites";+import type { SessionSandbox } from "./SandboxChip";import { Trans, useTranslation } from "react-i18next";import {CLOUD_CHANGED,@@ -61,6 +63,9 @@ export function AccessSection({scratchPrimary,openKey = 0,onOpenIntegrations,+ sandbox = null,+ onSandbox,+ onOpenSandboxSettings,}: {sessionId: string;personaId?: string;@@ -72,6 +77,10 @@ export function AccessSection({// Bumped by deep links ("Configure ›", onboarding's Start-working) → expand + scroll here.openKey?: number;onOpenIntegrations?: () => void;+ // OPE-219: the session's sandbox, for the Sites group (the header chip shows the same data).+ sandbox?: SessionSandbox | null;+ onSandbox?: (next: SessionSandbox) => void;+ onOpenSandboxSettings?: () => void;}) {const [open, setOpen] = useState(false);const [conns, setConns] = useState<SessionConnections | null>(null);@@ -489,6 +498,8 @@ export function AccessSection({)}{rootsError && <div className="roots-err">{rootsError}</div>}</div>+ {/* The sites this session's commands and web tools reach (sandboxed sessions only). */}+ <SessionSites sessionId={sessionId} sandbox={sandbox} onSandbox={onSandbox} onOpenSettings={onOpenSandboxSettings} /></div>)}</div>diff --git a/surfaces/gui/src/components/RightRail.tsx b/surfaces/gui/src/components/RightRail.tsxindex dd2f5975..c5abd3ee 100644--- a/surfaces/gui/src/components/RightRail.tsx+++ b/surfaces/gui/src/components/RightRail.tsx@@ -1,4 +1,5 @@import { useEffect, useRef, useState, type ReactNode } from "react";+import type { SessionSandbox } from "./SandboxChip";import { useTranslation } from "react-i18next";// Emits the asset URL only; the worker itself loads lazily with the pdfjs chunk.import pdfWorkerUrl from "pdfjs-dist/build/pdf.worker.min.mjs?url";@@ -69,6 +70,10 @@ interface Props {scratchPrimary?: boolean;openAccessKey?: number;onOpenIntegrations?: () => void;+ // OPE-219: the session's sandbox, for the Access section's Sites group.+ sandbox?: SessionSandbox | null;+ onSandbox?: (next: SessionSandbox) => void;+ onOpenSandboxSettings?: () => void;// Agent teams (OPE-96): App owns board data (the plan gate needs it too);// the rail renders the summary section and the expand affordance.board?: Board | null;@@ -110,6 +115,9 @@ export function RightRail({scratchPrimary,openAccessKey = 0,onOpenIntegrations,+ sandbox = null,+ onSandbox,+ onOpenSandboxSettings,board,onExpandBoard,onOpenBoardItem,@@ -426,6 +434,9 @@ export function RightRail({scratchPrimary={scratchPrimary}openKey={openAccessKey}onOpenIntegrations={onOpenIntegrations}+ sandbox={sandbox}+ onSandbox={onSandbox}+ onOpenSandboxSettings={onOpenSandboxSettings}/></div></>diff --git a/surfaces/gui/src/components/SessionSites.test.tsx b/surfaces/gui/src/components/SessionSites.test.tsxnew file mode 100644index 00000000..ca3d1252--- /dev/null+++ b/surfaces/gui/src/components/SessionSites.test.tsx@@ -0,0 +1,83 @@+// The Access section's Sites group (OPE-219).+import { afterEach, beforeEach, describe, expect, it, vi } from "vitest";+import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";+import type { SessionSandbox } from "./SandboxChip";++const api = vi.hoisted(() => ({ allowSessionSite: vi.fn(), removeSessionSite: vi.fn() }));+vi.mock("../api", () => api);++import { SessionSites } from "./SessionSites";++afterEach(cleanup);+beforeEach(() => {+ api.allowSessionSite.mockReset();+ api.removeSessionSite.mockReset();+});++const sandboxed: SessionSandbox = {+ state: "sandboxed", provider: "openshell", network: "allowlist",+ sites: ["github.com:443", "pypi.org:443"], session_sites: ["registry.npmjs.org:443"],+ folders: [], logins: [], started: true,+};++describe("SessionSites", () => {+ it("lists the machine's sites plain and the session's with a tag", () => {+ render(<SessionSites sessionId="s1" sandbox={sandboxed} onOpenSettings={vi.fn()} />);+ const rows = screen.getAllByTestId("session-site");+ expect(rows.map((r) => [r.getAttribute("data-source"), r.textContent])).toEqual([+ ["settings", "github.com"],+ ["settings", "pypi.org"],+ ["session", "registry.npmjs.orgSession only×"],+ ]);+ // A site from Settings says where it can be removed; it has no remove control here.+ expect(rows[0].getAttribute("title")).toBe("This can be removed from Settings ▸ Sandbox");+ expect(screen.getAllByTestId("session-site-remove")).toHaveLength(1);+ expect(screen.getByTestId("session-sites-settings").textContent).toBe("Open Settings ▸ Sandbox");+ });++ it("allows one more site for the session and hands the new list up", async () => {+ const next = { ...sandboxed, session_sites: ["registry.npmjs.org:443", "db.acme.dev:5432"] };+ api.allowSessionSite.mockResolvedValue({ ok: true, sandbox: next });+ const onSandbox = vi.fn();+ render(<SessionSites sessionId="s1" sandbox={sandboxed} onSandbox={onSandbox} />);+ fireEvent.click(screen.getByTestId("session-site-add"));+ fireEvent.change(screen.getByTestId("session-site-input"), { target: { value: " db.acme.dev:5432 " } });+ fireEvent.click(screen.getByTestId("session-site-allow"));+ await waitFor(() => expect(onSandbox).toHaveBeenCalledWith(next));+ expect(api.allowSessionSite).toHaveBeenCalledWith("s1", "db.acme.dev:5432");+ await waitFor(() => expect(screen.queryByTestId("session-site-input")).toBeNull());+ });++ it("says why a site was not taken and keeps the box open", async () => {+ api.allowSessionSite.mockResolvedValue({ ok: false, error: "Give an exact host name, such as registry.npmjs.org (add a port only when it is not 443)." });+ render(<SessionSites sessionId="s1" sandbox={sandboxed} />);+ fireEvent.click(screen.getByTestId("session-site-add"));+ fireEvent.change(screen.getByTestId("session-site-input"), { target: { value: "*.npmjs.org" } });+ fireEvent.click(screen.getByTestId("session-site-allow"));+ await waitFor(() => expect(screen.getByTestId("session-sites-error").textContent).toContain("exact host name"));+ expect(screen.getByTestId("session-site-input")).toBeTruthy();+ });++ it("takes a session site back", async () => {+ const next = { ...sandboxed, session_sites: [] };+ api.removeSessionSite.mockResolvedValue({ ok: true, sandbox: next });+ const onSandbox = vi.fn();+ render(<SessionSites sessionId="s1" sandbox={sandboxed} onSandbox={onSandbox} />);+ fireEvent.click(screen.getByTestId("session-site-remove"));+ await waitFor(() => expect(onSandbox).toHaveBeenCalledWith(next));+ expect(api.removeSessionSite).toHaveBeenCalledWith("s1", "registry.npmjs.org:443");+ });++ it("any site, no sites yet, and no group without a sandbox", () => {+ const { rerender, container } = render(<SessionSites sessionId="s1" sandbox={{ ...sandboxed, network: "open", sites: [], session_sites: [] }} />);+ expect(screen.getByTestId("session-sites").textContent).toContain("Any site");+ expect(screen.queryByTestId("session-site-add")).toBeNull();+ rerender(<SessionSites sessionId="s1" sandbox={{ ...sandboxed, sites: [], session_sites: [] }} />);+ expect(screen.getByTestId("session-sites").textContent).toContain("Commands and web tools reach no sites yet.");+ expect(screen.getByTestId("session-site-add")).toBeTruthy();+ for (const info of [null, { state: "off" } as SessionSandbox, { state: "not_sandboxed", provider: "openshell" } as SessionSandbox]) {+ rerender(<SessionSites sessionId="s1" sandbox={info} />);+ expect(container.textContent).toBe("");+ }+ });+});diff --git a/surfaces/gui/src/components/SessionSites.tsx b/surfaces/gui/src/components/SessionSites.tsxnew file mode 100644index 00000000..2b94541e--- /dev/null+++ b/surfaces/gui/src/components/SessionSites.tsx@@ -0,0 +1,168 @@+// The Access section's Sites group (OPE-219; mock ux-improvements/mocks/+// session-allowed-sites.html, approved 2026-10-03): which sites THIS session's commands and+// web tools reach. Sites from Settings are listed plain, with a hover saying where to+// remove them; sites the person allowed for this session carry a "Session only" tag and can+// be taken back here. The person can allow one more for the session. Shown only for a+// sandboxed session; with "Allow everything" there is nothing to list.+import { useState } from "react";+import { useTranslation } from "react-i18next";+import { allowSessionSite, removeSessionSite } from "../api";+import type { SessionSandbox } from "./SandboxChip";++const SEC_H = "text-label text-faint font-medium";+const siteName = (entry: string): string => entry.replace(/:443$/, "");++export function SessionSites({+ sessionId,+ sandbox,+ onSandbox,+ onOpenSettings,+}: {+ sessionId: string;+ sandbox: SessionSandbox | null;+ // The server's answer after a change: the header chip follows the same data.+ onSandbox?: (next: SessionSandbox) => void;+ onOpenSettings?: () => void;+}) {+ const { t } = useTranslation();+ const [adding, setAdding] = useState(false);+ const [typed, setTyped] = useState("");+ const [busy, setBusy] = useState(false);+ const [error, setError] = useState("");++ if (!sandbox || sandbox.state !== "sandboxed") return null;+ const allowlist = sandbox.network === "allowlist";+ const sites = sandbox.sites || [];+ const sessionSites = sandbox.session_sites || [];++ const change = async (call: () => Promise<{ ok: boolean; error?: string; sandbox?: SessionSandbox }>) => {+ setBusy(true);+ setError("");+ try {+ const res = await call();+ if (res.sandbox) onSandbox?.(res.sandbox);+ if (!res.ok) setError(res.error || t("access.sites.failed"));+ return res.ok;+ } catch {+ setError(t("access.sites.failed"));+ return false;+ } finally {+ setBusy(false);+ }+ };++ const settingsLink = onOpenSettings && (+ <button className="mt-1 block text-meta text-accent hover:underline text-left" onClick={onOpenSettings} data-testid="session-sites-settings">+ {t("access.sites.open_settings")}+ </button>+ );++ return (+ <div data-testid="session-sites">+ <div className={`${SEC_H} mb-1.5`}>{t("access.sites.title")}</div>+ {!allowlist ? (+ <>+ <div className="text-ui text-ink">{t("access.sites.any_site")}</div>+ <div className="text-meta text-faint mt-0.5">{t("access.sites.any_site_note")}</div>+ {settingsLink}+ </>+ ) : (+ <>+ {sites.length + sessionSites.length === 0 && <div className="text-meta text-faint">{t("access.sites.none")}</div>}+ <div className="-mx-1.5">+ {sites.map((entry) => (+ <div+ key={entry}+ className="px-1.5 py-1 rounded-md font-mono text-meta text-ink truncate"+ title={t("access.sites.settings_hint")}+ data-testid="session-site"+ data-source="settings"+ >+ {siteName(entry)}+ </div>+ ))}+ {sessionSites.map((entry) => (+ <div+ key={entry}+ className="group flex items-center gap-2 px-1.5 py-1 rounded-md hover:bg-paper"+ data-testid="session-site"+ data-source="session"+ >+ <span className="flex-1 min-w-0 truncate font-mono text-meta text-ink">{siteName(entry)}</span>+ <span className="text-label px-1.5 py-0.5 rounded-full border border-accent/25 bg-accentSoft text-accent whitespace-nowrap">+ {t("access.sites.session_only")}+ </span>+ <button+ className="text-faint hover:text-ink opacity-0 group-hover:opacity-100 focus:opacity-100 disabled:opacity-40"+ title={t("access.sites.remove")}+ aria-label={t("access.sites.remove_named", { host: siteName(entry) })}+ disabled={busy}+ onClick={() => void change(() => removeSessionSite(sessionId, entry))}+ data-testid="session-site-remove"+ >+ ×+ </button>+ </div>+ ))}+ </div>+ {adding ? (+ <form+ className="mt-1.5"+ onSubmit={(e) => {+ e.preventDefault();+ const host = typed.trim();+ if (!host) return;+ void change(() => allowSessionSite(sessionId, host)).then((ok) => {+ if (ok) {+ setTyped("");+ setAdding(false);+ }+ });+ }}+ >+ <div className="flex gap-1.5">+ <input+ className="flex-1 min-w-0 px-2 py-1.5 rounded-lg border border-line focus:border-accent bg-paper font-mono text-meta text-ink outline-none"+ placeholder={t("access.sites.placeholder")}+ value={typed}+ onChange={(e) => {+ setTyped(e.target.value);+ if (error) setError("");+ }}+ onKeyDown={(e) => {+ if (e.key === "Escape") {+ setAdding(false);+ setTyped("");+ setError("");+ }+ }}+ autoFocus+ data-testid="session-site-input"+ />+ <button+ type="submit"+ className="text-meta px-2.5 py-1.5 rounded-lg bg-accent text-white hover:opacity-90 disabled:opacity-40 shrink-0"+ disabled={busy || !typed.trim()}+ data-testid="session-site-allow"+ >+ {t("access.sites.allow")}+ </button>+ </div>+ <div className="text-label text-faint mt-1">{t("access.sites.add_note")}</div>+ </form>+ ) : (+ <button className="mt-1 block text-meta text-accent hover:underline text-left" onClick={() => setAdding(true)} data-testid="session-site-add">+ + {t("access.sites.add")}+ </button>+ )}+ {error && (+ <div className="roots-err" data-testid="session-sites-error">+ {error}+ </div>+ )}+ {settingsLink}+ </>+ )}+ </div>+ );+}diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex d304fb78..a87c0233 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -764,7 +764,23 @@"choose_location": "Choose location","channel_add_error": "Couldn't add that channel.","summary_folder_count_one": "{{count}} folder",- "summary_folder_count_other": "{{count}} folders"+ "summary_folder_count_other": "{{count}} folders",+ "sites": {+ "title": "Sites",+ "session_only": "Session only",+ "settings_hint": "This can be removed from Settings ▸ Sandbox",+ "add": "Allow a site for this session…",+ "allow": "Allow",+ "placeholder": "registry.npmjs.org",+ "add_note": "For this session only. Commands and web tools reach it at once.",+ "remove": "Remove from this session",+ "remove_named": "Remove {{host}} from this session",+ "none": "Commands and web tools reach no sites yet.",+ "any_site": "Any site",+ "any_site_note": "This machine's sandbox allows every site.",+ "open_settings": "Open Settings ▸ Sandbox",+ "failed": "That did not work. Try again."+ }},"root": {"temporary_space": "Temporary folder",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex fc0a038b..28dc967a 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -752,7 +752,23 @@"cancel": "取消","choose_location": "选择位置","channel_add_error": "无法添加该频道。",- "summary_folder_count_other": "{{count}} 个文件夹"+ "summary_folder_count_other": "{{count}} 个文件夹",+ "sites": {+ "title": "网站",+ "session_only": "仅本次会话",+ "settings_hint": "可在 设置 ▸ 沙盒 中移除",+ "add": "为本次会话允许一个网站…",+ "allow": "允许",+ "placeholder": "registry.npmjs.org",+ "add_note": "仅对本次会话生效。命令和网页工具立即可以访问。",+ "remove": "从本次会话移除",+ "remove_named": "从本次会话移除 {{host}}",+ "none": "命令和网页工具目前不能访问任何网站。",+ "any_site": "任何网站",+ "any_site_note": "本机的沙盒允许访问所有网站。",+ "open_settings": "打开 设置 ▸ 沙盒",+ "failed": "操作没有成功,请重试。"+ }},"root": {"temporary_space": "临时文件夹",diff --git a/tests/test_network_access.py b/tests/test_network_access.pyindex 373b24dc..3640ec1c 100644--- a/tests/test_network_access.py+++ b/tests/test_network_access.py@@ -228,3 +228,74 @@ def test_a_sandbox_that_cannot_report_blocks_gives_the_card_no_evidence(tmp_pathseen.blocked = [(__import__("time").time() - 30, "registry.npmjs.org:443")]shown = payload(seen)assert shown["evidence"] is True and 29 <= shown["hosts"][0]["blocked_seconds_ago"] <= 35+++# -- the person's own list for one session (the Access section) ----------------------------+def test_the_person_adds_and_takes_back_a_session_site(tmp_path, monkeypatch):+ from coworker.server.manager import SessionManager++ opened: list[str] = []+ closed: list[str] = []+ eng = engine(tmp_path, open_site=opened.append, close_site=closed.append)+ holder = SimpleNamespace(permissions=eng, sandbox_workspace=None)+ manager = SimpleNamespace(_engines={"s1": holder}, audit_autonomy_change=lambda *a: None)+ for name in ("session_sites", "_session_site_engine", "allow_session_site", "remove_session_site", "_audit_session_site"):+ setattr(manager, name, getattr(SessionManager, name).__get__(manager))++ assert manager.allow_session_site("s1", "Registry.NPMjs.org")["ok"]+ assert eng.session_sites == ["registry.npmjs.org:443"] and opened == ["registry.npmjs.org:443"]+ assert manager.allow_session_site("s1", "github.com")["ok"] and eng.session_sites == ["registry.npmjs.org:443"] # already on the machine's list+ for bad in ("*.npmjs.org", "10.0.0.8", "two hosts.dev other.dev", ""):+ assert not manager.allow_session_site("s1", bad)["ok"], bad+ # Only a session site can be taken back here; the machine's list is changed in Settings.+ refused = manager.remove_session_site("s1", "github.com")+ assert not refused["ok"] and "Settings > Sandbox" in refused["error"]+ assert manager.remove_session_site("s1", "registry.npmjs.org")["ok"]+ assert eng.session_sites == [] and closed == ["registry.npmjs.org:443"]+ assert ask(eng, ["registry.npmjs.org"]).needs_user+ assert not eng.evaluate("web_fetch", {"url": "https://registry.npmjs.org/x"}, None).allowed+ assert not manager.allow_session_site("nope", "a.dev")["ok"] # no such session+++def test_a_site_the_sandbox_cannot_take_is_not_left_on_the_list(tmp_path):+ from coworker.server.manager import SessionManager++ def refuse(entry: str) -> None:+ raise RuntimeError("the gateway did not answer")++ eng = engine(tmp_path, open_site=refuse)+ manager = SimpleNamespace(_engines={"s1": SimpleNamespace(permissions=eng, sandbox_workspace=None)}, audit_autonomy_change=lambda *a: None)+ for name in ("session_sites", "_session_site_engine", "allow_session_site", "_audit_session_site"):+ setattr(manager, name, getattr(SessionManager, name).__get__(manager))+ result = manager.allow_session_site("s1", "registry.npmjs.org")+ assert not result["ok"] and "the gateway did not answer" in result["error"]+ assert eng.session_sites == [] and ask(eng, ["registry.npmjs.org"]).needs_user+++def test_a_running_sandbox_drops_a_site_taken_back(tmp_path, monkeypatch):+ proxy = netproxy.AllowListProxy("allowlist", extra_hosts=["github.com:443"])+ try:+ proxy.add_hosts(["registry.npmjs.org:443"])+ proxy.remove_hosts(["registry.npmjs.org:443"])+ assert not proxy.allows("registry.npmjs.org", 443) and proxy.allows("github.com", 443)+ finally:+ proxy.close()+ from coworker.sandbox.providers import openshell++ monkeypatch.setenv("COWORKER_STATE_DIR", str(tmp_path))+ monkeypatch.setattr(openshell, "build_runner_zipapp", lambda: tmp_path / "sandbox" / "runner" / "runner-x.pyz")+ project = tmp_path / "project"+ project.mkdir()+ seen: list = []+ monkeypatch.setattr(openshell, "_cli", lambda *args, **kw: seen.append(args))+ provider = openshell.OpenShellProvider(roots=[{"path": str(project), "writable": True}], extra_hosts=["github.com:443", "registry.npmjs.org:443"], registry="abc")+ provider._create_tried = True+ provider.remove_hosts(["registry.npmjs.org:443", "never.there:443"])+ (call,) = seen+ assert call[:2] == ("policy", "set") and provider.extra_hosts == ["github.com:443"]+ import yaml+ from pathlib import Path++ written = yaml.safe_load(Path(call[call.index("--policy") + 1]).read_text())+ hosts = {e["host"] for rule in written["network_policies"].values() for e in rule["endpoints"]}+ assert "github.com" in hosts and "registry.npmjs.org" not in hosts