Python
Sandbox starts at the first turn; Mac gateway restart; plain preparing line
Rohit C Prasad56a7fe37b68f
diff --git a/coworker/agent.py b/coworker/agent.pyindex 2c3d0190..92516cf1 100644--- a/coworker/agent.py+++ b/coworker/agent.py@@ -349,6 +349,7 @@ def build_engine(credentials=config.sandbox_credentials,network_profile=config.sandbox_network_profile,extra_hosts=config.sandbox_network_hosts,+ start=False, # made when the first turn needs it, not when the session openstoolchains=config.sandbox_toolchains,)if ws is not Nonediff --git a/coworker/engine.py b/coworker/engine.pyindex 676538c1..081b60a0 100644--- a/coworker/engine.py+++ b/coworker/engine.py@@ -418,6 +418,10 @@ class TurnEngine:self.permissions.clear_run_allowances()yield Event(EventType.TURN_START, data)try:+ async for event in self._start_sandbox():+ yield event+ if event.type is EventType.ERROR:+ returnasync for event in self._loop():yield eventfinally:@@ -500,9 +504,34 @@ class TurnEngine:returnself._cancel.clear()yield Event(EventType.TURN_START, {"input": ""})+ async for event in self._start_sandbox():+ yield event+ if event.type is EventType.ERROR:+ returnasync for event in self._loop():yield event+ async def _start_sandbox(self) -> AsyncIterator[Event]:+ """The session's sandbox is made by its first turn, not when the session opens+ (RunnerWorkspace(start=False)). Off the event loop: an OpenShell container takes+ seconds. A sandbox that cannot be made ends the turn with the reason, and Retry+ tries again."""+ workspace = getattr(self, "sandbox_workspace", None)+ start = getattr(workspace, "ensure_started", None)+ if start is None or getattr(workspace, "started", True):+ return+ provider = str(getattr(getattr(workspace, "provider", None), "name", "") or "sandbox")+ yield Event(EventType.SANDBOX_PREPARING, {"provider": provider})+ try:+ await asyncio.to_thread(start)+ except Exception as exc:+ text = f"The {provider} sandbox could not start: {exc}"+ self._append_notice("error", text)+ yield Event(EventType.ERROR, {"error": text, "error_type": type(exc).__name__})+ return+ info = workspace.describe()+ yield Event(EventType.SANDBOX_READY, {k: info.get(k) for k in ("provider", "enforcement", "reason", "sandbox") if info.get(k) is not None})+async def resume(self) -> AsyncIterator[Event]:"""Continue a turn that was suspended at a prompt and persisted — durable resume after arestart (or engine eviction). Re-process the trailing assistant message's UNANSWEREDdiff --git a/coworker/events.py b/coworker/events.pyindex 37e9ca09..eff4f5d7 100644--- a/coworker/events.py+++ b/coworker/events.py@@ -45,6 +45,10 @@ class EventType(str, Enum):# OPE-171: the reply was cut off at the output-token limit with no tool call; the# engine nudged the model to act and is going round the loop again.CONTINUATION = "continuation"+ # The session's sandbox is being made (its first turn), and is up: the surfaces show+ # "Preparing the … sandbox" in between.+ SANDBOX_PREPARING = "sandbox_preparing"+ SANDBOX_READY = "sandbox_ready"@dataclassdiff --git a/coworker/sandbox/client.py b/coworker/sandbox/client.pyindex ebebc6b1..09ef366e 100644--- a/coworker/sandbox/client.py+++ b/coworker/sandbox/client.py@@ -42,6 +42,9 @@ class _Pending:class RunnerClient:def __init__(self, open_transport: Callable[[], Transport], *, ping_seconds: float = P.PING_SECONDS) -> None:self._open = open_transport+ # Called by the first call() when nothing is connected yet: a workspace whose+ # sandbox starts on first use sets it, and clears it once started.+ self.starter: Optional[Callable[[], Any]] = Noneself._ping_seconds = ping_secondsself._transport: Optional[Transport] = Noneself._send_lock = threading.Lock()@@ -129,6 +132,12 @@ class RunnerClient:) -> dict[str, Any]:with self._state_lock:transport = self._transport+ if transport is None and self.starter is not None and not self._closed:+ # A sandbox that starts on first use (RunnerWorkspace(start=False)): whatever+ # reaches the runner first, a command or a file tool, starts it.+ self.starter()+ with self._state_lock:+ transport = self._transportif transport is None:raise P.RunnerError(P.INTERNAL_ERROR, "not connected to a tool runner")return self._call_on(transport, method, params or {}, timeout=timeout, on_notify=on_notify)diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.pyindex 0e4d27c4..6c8e9938 100644--- a/coworker/sandbox/providers/openshell.py+++ b/coworker/sandbox/providers/openshell.py@@ -254,6 +254,7 @@ class OpenShellProvider:# -- lifecycle --------------------------------------------------------------------def create(self) -> None:+ self._create_tried = Truetry:self._create()except Exception:@@ -352,7 +353,8 @@ class OpenShellProvider:passdef destroy(self) -> None:- self._delete()+ if getattr(self, "_create_tried", False): # never asked the gateway: nothing to delete there+ self._delete()shutil.rmtree(self._tmp, ignore_errors=True)diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.pyindex e9849cd8..a756bee2 100644--- a/coworker/sandbox/setup_cmd.py+++ b/coworker/sandbox/setup_cmd.py@@ -177,8 +177,7 @@ def steps() -> list[Step]:docs="" if openshell_ok else GUIDE_URL,))- gateway_toml = _openshell_home() / "gateway.toml"- binds = gateway_toml.is_file() and "enable_bind_mounts = true" in gateway_toml.read_text(encoding="utf-8")+ binds = _allows_bind_mounts(gateway_config_in_use())out.append(Step("bind_mounts", ROWS["bind_mounts"], binds, fixable=True))if sys.platform.startswith("linux"):linger = _run(["loginctl", "show-user", getpass.getuser(), "-p", "Linger"], 15).stdout.strip() == "Linger=yes"@@ -238,17 +237,64 @@ def apply_bind_mounts() -> Optional[str]:gateway_toml, gateway_env = home / "gateway.toml", home / "gateway.env"home.mkdir(parents=True, exist_ok=True)existing = gateway_toml.read_text(encoding="utf-8") if gateway_toml.is_file() else ""- if "[openshell.drivers.docker]" in existing:+ if "[openshell.drivers.docker]" in existing and not _allows_bind_mounts(gateway_toml):return f"{gateway_toml} already has a [openshell.drivers.docker] table; add `enable_bind_mounts = true` to it by hand."- gateway_toml.write_text((existing.rstrip() + "\n\n" if existing.strip() else "") + _BIND_MOUNTS, encoding="utf-8")+ if not _allows_bind_mounts(gateway_toml):+ gateway_toml.write_text((existing.rstrip() + "\n\n" if existing.strip() else "") + _BIND_MOUNTS, encoding="utf-8")env_line = f"OPENSHELL_GATEWAY_CONFIG={gateway_toml}\n"env_text = gateway_env.read_text(encoding="utf-8") if gateway_env.is_file() else ""if "OPENSHELL_GATEWAY_CONFIG=" not in env_text:gateway_env.write_text(env_text + env_line, encoding="utf-8")- _run(["systemctl", "--user", "restart", "openshell-gateway"], 120)+ return restart_gateway()+++def restart_gateway() -> Optional[str]:+ """Restart the local gateway so it reads its config again: a Homebrew service on a Mac+ (the formula's start script reads `gateway.env`), a user systemd unit on Linux. Returns+ an error text, or None. Before 2026-09-28 the Mac was never restarted: the setting was+ written, the running gateway kept Homebrew's own config, and sessions were refused."""+ if sys.platform == "darwin":+ if not shutil.which("brew"):+ return "Homebrew is not on PATH, so the OpenShell gateway could not be restarted; run: brew services restart nvidia/openshell/openshell"+ done = _run(["brew", "services", "restart", "nvidia/openshell/openshell"], 120)+ else:+ done = _run(["systemctl", "--user", "restart", "openshell-gateway"], 120)+ if done.returncode != 0:+ return f"the OpenShell gateway did not restart: {(done.stderr or done.stdout or '').strip()[:300]}"return None+def _allows_bind_mounts(config: Optional[Path]) -> bool:+ try:+ return config is not None and config.is_file() and "enable_bind_mounts = true" in config.read_text(encoding="utf-8")+ except OSError:+ return False+++def gateway_config_in_use() -> Optional[Path]:+ """The config file the RUNNING gateway was started with: its `--config` argument, else+ the one `gateway.env` names, else `gateway.toml` under the OpenShell config folder. A+ file written after the gateway started is not in use until it restarts, so the check+ reads what the process was given rather than what is on disk."""+ home = _openshell_home()+ listing = _run(["ps", "-Ao", "args="], 15).stdout if sys.platform != "win32" else ""+ for line in listing.splitlines():+ parts = line.split()+ if not parts or not parts[0].endswith("openshell-gateway"):+ continue+ if "--config" in parts[:-1]:+ return Path(parts[parts.index("--config") + 1])+ break+ env_file = home / "gateway.env"+ try:+ for line in env_file.read_text(encoding="utf-8").splitlines() if env_file.is_file() else []:+ if line.startswith("OPENSHELL_GATEWAY_CONFIG="):+ return Path(line.split("=", 1)[1].strip())+ except OSError:+ pass+ return home / "gateway.toml"++def enable_linger() -> Optional[str]:"""Try as the user, then as an administrator without a password (`admin_prefix`);return the command to run when both are refused."""diff --git a/coworker/sandbox/workspace.py b/coworker/sandbox/workspace.pyindex 6d5b0087..b2e41796 100644--- a/coworker/sandbox/workspace.py+++ b/coworker/sandbox/workspace.py@@ -13,6 +13,7 @@ step 2 (design doc, section 11).from __future__ import annotationsimport os+import threadingfrom abc import ABC, abstractmethodfrom pathlib import Pathfrom typing import Any, Optional@@ -61,6 +62,14 @@ class DirectWorkspace(Workspace):class RunnerWorkspace(Workspace):+ """A workspace whose commands and file tools run in a sandbox, through the tool runner.++ `start=False` (a session's workspace): the sandbox is not made until something needs+ it, the first turn (TurnEngine starts it, so the session can say so) or, failing that,+ the first call to the runner. Opening a session, or picking its folder, builds nothing+ (seen 2026-09-28: every folder pick made a sandbox). The client and executor exist from+ the start, so the file tools are always routed to the runner, never run here."""+def __init__(self,provider: Any,@@ -71,6 +80,7 @@ class RunnerWorkspace(Workspace):session_id: str = "",agent: str = "",live_roots: Optional[list] = None,+ start: bool = True,) -> None:from .client import RunnerClientfrom .executor import RunnerExecutor@@ -82,31 +92,53 @@ class RunnerWorkspace(Workspace):# The session's own RootDir list. It changes while the session runs (a folder is# granted or taken away); a sandbox's walls are fixed when it starts.self._live_roots = live_roots- if registry is not None:- registry.reap() # sandboxes left behind by a server that is gone- registry.check_room()- # Reserve the name before the sandbox exists: engine builds run concurrently- # (OPE-206), and another build's reap() would otherwise delete this one while- # it is still provisioning, because it is not yet in the registry.- self._record(state="creating")- try:- provider.create()- except Exception:- provider.destroy() # a half-made sandbox may already hold copied credentials- if registry is not None and self._registered:- registry.close(self._registered)- raise- try:- self.client = RunnerClient(provider.open_runner)- self.hello = self.client.connect()- self._after_connect()- except Exception:- provider.destroy()- raise+ self._start_lock = threading.Lock()+ self.started = False+ self.hello: dict[str, Any] = {}+ self.client = RunnerClient(lambda: provider.open_runner()) # looked up when it connectsself._executor = RunnerExecutor(self.client, cwd=str(Path(cwd).expanduser().resolve()), shell=shell, before_call=self.sync_roots)- self._record()+ if start:+ self.ensure_started()+ else:+ self.client.starter = self.ensure_started++ def ensure_started(self) -> None:+ """Make the sandbox, connect to its runner and prove the wall. Once; a failure+ leaves nothing behind and the next call tries again."""+ with self._start_lock:+ if self.started:+ return+ registry = self.registry+ if registry is not None:+ registry.reap() # sandboxes left behind by a server that is gone+ registry.check_room()+ # Reserve the name before the sandbox exists: engine builds run concurrently+ # (OPE-206), and another build's reap() would otherwise delete this one while+ # it is still provisioning, because it is not yet in the registry.+ self._record(state="creating")+ try:+ self.provider.create()+ except Exception:+ self.provider.destroy() # a half-made sandbox may already hold copied credentials+ if registry is not None and self._registered:+ registry.close(self._registered)+ self._registered = None+ raise+ try:+ self.hello = self.client.connect()+ self._after_connect()+ except Exception:+ self.client.detach()+ self.provider.destroy()+ if registry is not None and self._registered:+ registry.close(self._registered)+ self._registered = None+ raise+ self._record()+ self.started = True+ self.client.starter = Nonedef _record(self, state: str = "ready") -> None:"""Enter this sandbox in the registry; after a restart that replaced it, under its@@ -131,7 +163,9 @@ class RunnerWorkspace(Workspace):def sync_roots(self) -> Optional[str]:"""Restart the sandbox when the session's folders are no longer the ones it was- started with (design ruling 15). Returns what to tell the agent, or None."""+ started with (design ruling 15). Returns what to tell the agent, or None. Runs+ before every command, so it is also where a sandbox not yet started starts."""+ self.ensure_started()regrant = getattr(self.provider, "regrant", None)if regrant is None or self._live_roots is None:return None@@ -181,6 +215,13 @@ class RunnerWorkspace(Workspace):return {**self.provider.describe(), "runner": {k: self.hello.get(k) for k in ("runner_version", "os", "machine", "instance_id")}}def close(self) -> None:+ if not self.started:+ self.client.close()+ try:+ self.provider.destroy() # no sandbox was made; its private folder may have been+ except Exception:+ pass+ returntry:self._executor.close()finally:@@ -219,11 +260,13 @@ def open_workspace(network_profile: Optional[str] = None,toolchains: Optional[list] = None,extra_hosts: Optional[list] = None,+ start: bool = True,) -> Workspace:"""The session's workspace for the configured provider. `credentials`: the machine's`sandbox_credentials` setting; the enabled entries are copied into the sandbox(design doc, section 11b). Ignored in `direct` mode, where nothing is hidden anyway. `direct` unless told otherwise.`extra_hosts`: the machine's `sandbox_network_hosts`, the sites an allow list lets through.+ `start=False`: make the sandbox on first use instead of now (a session's workspace).`toolchains`: the machine's `sandbox_toolchains` setting; the switched-on folders thatexist are readable inside (Seatbelt, Windows full mode).`roots`: the session's RootDir list (primary first); without it the workspace folder is@@ -259,6 +302,7 @@ def open_workspace(session_id=session_id,agent=agent,live_roots=roots,+ start=start,)if name == OPENSHELL:from .providers.openshell import OpenShellProvider@@ -272,6 +316,7 @@ def open_workspace(session_id=session_id,agent=agent,live_roots=roots,+ start=start,)if name == WINDOWS:from .providers.windows import WindowsProvider@@ -284,5 +329,6 @@ def open_workspace(session_id=session_id,agent=agent,live_roots=roots,+ start=start,)raise ValueError(f"unknown sandbox provider: {name!r} (known: {DIRECT}, {SEATBELT}, {WINDOWS}, {OPENSHELL}, {RUNNER_LOCAL})")diff --git a/coworker/server/app.py b/coworker/server/app.pyindex f83d73e1..872073ad 100644--- a/coworker/server/app.py+++ b/coworker/server/app.py@@ -2862,15 +2862,11 @@ def create_app(manager: SessionManager) -> FastAPI:mcp_tools = await manager.prepare_mcp_tools(session_id, workspace=workspace, agent=agent)- # Building the engine can mean building a sandbox: with OpenShell, a container is- # created, its runner started and its mounts verified, which takes seconds (and on- # first use, minutes). Done on the event loop that wait froze the whole server, so- # the GUI saw its health checks fail and showed the app-wide "Starting OpenWorker…"- # screen instead of this session (OPE-206). So: say what is happening on THIS- # socket, build on a worker thread, and report the outcome here too.- sandbox_provider = manager.pending_sandbox_build(session_id)- if sandbox_provider:- await ws.send_json({"type": "sandbox_preparing", "data": {"provider": sandbox_provider}})+ # The engine is built off the event loop (OPE-206: a build once froze the server).+ # Its sandbox is not made here: the first turn makes it and says so+ # (TurnEngine._start_sandbox), so opening a session or picking its folder builds+ # nothing. A sandbox that cannot be used at all is still refused here, by the+ # provider choice (select), with the reason.try:engine = await asyncio.to_thread(manager.get_engine,@@ -2896,14 +2892,6 @@ def create_app(manager: SessionManager) -> FastAPI:await ws.send_json({"type": "error", "data": {"error": str(exc)}})await ws.close(code=WS_CLOSE_SESSION_REFUSED, reason="session refused")return- if sandbox_provider and engine is not None:- info = getattr(getattr(engine, "sandbox_workspace", None), "describe", dict)()- await ws.send_json(- {- "type": "sandbox_ready",- "data": {key: info.get(key) for key in ("provider", "enforcement", "reason", "sandbox") if info.get(key) is not None},- }- )if engine is None:await ws.send_json({diff --git a/coworker/server/manager.py b/coworker/server/manager.pyindex 5d0e6ec5..6270aa31 100644--- a/coworker/server/manager.py+++ b/coworker/server/manager.py@@ -709,13 +709,6 @@ class SessionManager:return "" if chosen == DIRECT else chosenreturn OPENSHELL if is_headless() else ""- def pending_sandbox_build(self, session_id: str) -> str:- """The sandbox provider a NEW engine for this session would be built with, or ""- when the engine exists already or commands would run directly (OPE-206)."""- if session_id in self._engines:- return ""- return self._wanted_sandbox_provider()-def apply_sandbox_setting(self) -> list[str]:"""Settings ▸ Sandbox changed the provider: every live engine built under anotherprovider is dropped, so its next connection rebuilds it under the new rule (anddiff --git a/surfaces/gui/src/App.tsx b/surfaces/gui/src/App.tsxindex 3dcbd729..a162477c 100644--- a/surfaces/gui/src/App.tsx+++ b/surfaces/gui/src/App.tsx@@ -2285,7 +2285,9 @@ export function App() {{/* Not gated on `connected`: switching sessions keeps the previous socket'sconnected=true until this one's `ready`, which also clears the flag. */}{preparingSandbox && (- <WaitingForAgent label={t("app.preparing_sandbox", { provider: preparingSandbox })} />+ <WaitingForAgent+ label={t(["seatbelt", "windows", "openshell"].includes(preparingSandbox) ? `app.preparing_sandbox_${preparingSandbox}` : "app.preparing_sandbox")}+ />)}{/* Compaction runs between provider turns (nothing streams during it), sothe transient takes over the waiting slot with a specific label. */}diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.jsonindex faa2e9ec..cee5e13d 100644--- a/surfaces/gui/src/locales/en.json+++ b/surfaces/gui/src/locales/en.json@@ -464,7 +464,10 @@"jump_to_latest": "Jump to latest","waiting_for_agent": "Waiting for agent...","compacting_context": "Compacting context…",- "preparing_sandbox": "Preparing the {{provider}} sandbox for this session… (a Linux container with only this session's folders)",+ "preparing_sandbox": "Preparing the sandbox for this session…",+ "preparing_sandbox_seatbelt": "Preparing the macOS sandbox for this session…",+ "preparing_sandbox_windows": "Preparing the Windows sandbox for this session…",+ "preparing_sandbox_openshell": "Preparing the OpenShell sandbox for this session… (a Linux container with only this session's folders)","allow_anyway_message": "I reviewed the blocked {{name}} action — go ahead with it exactly as proposed.","temp_folder_failed": "Could not create a temporary folder.","temp_folder_created": "Temporary folder created",diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.jsonindex 1a8d5c1b..d86df862 100644--- a/surfaces/gui/src/locales/zh.json+++ b/surfaces/gui/src/locales/zh.json@@ -456,7 +456,10 @@"jump_to_latest": "跳到最新","waiting_for_agent": "正在等待 agent…","compacting_context": "正在压缩上下文…",- "preparing_sandbox": "正在为此会话准备 {{provider}} 沙箱…(一个仅包含此会话文件夹的 Linux 容器)",+ "preparing_sandbox": "正在为此会话准备沙箱…",+ "preparing_sandbox_seatbelt": "正在为此会话准备 macOS 沙箱…",+ "preparing_sandbox_windows": "正在为此会话准备 Windows 沙箱…",+ "preparing_sandbox_openshell": "正在为此会话准备 OpenShell 沙箱…(一个只包含此会话文件夹的 Linux 容器)","allow_anyway_message": "我已审阅被拦截的 {{name}} 操作 —— 请按原样执行。","temp_folder_failed": "无法创建临时文件夹。","temp_folder_created": "已创建临时文件夹",diff --git a/tests/test_sandbox_setup_job.py b/tests/test_sandbox_setup_job.pyindex c5eaceff..261cbf90 100644--- a/tests/test_sandbox_setup_job.py+++ b/tests/test_sandbox_setup_job.py@@ -234,3 +234,38 @@ def test_the_readiness_endpoint_and_the_job_endpoints(tmp_path, monkeypatch):assert client.post("/v1/settings/sandbox/setup/cancel").json()["status"] == "needs_you" # nothing running: unchangedmonkeypatch.setattr(settings.sys, "platform", "win32")assert client.get("/v1/settings/sandbox/readiness").json() == {"platform": "win32", "supported": False, "steps": [], "all_ok": False}+++def test_the_folder_step_restarts_the_gateway_and_the_check_reads_the_config_in_use(tmp_path, monkeypatch):+ """Seen on a Mac, 2026-09-28: the setting was written but the Homebrew gateway kept the+ config it had started with, the check said yes, and sessions were refused."""+ from types import SimpleNamespace++ monkeypatch.setenv("XDG_CONFIG_HOME", str(tmp_path))+ ran: list[list[str]] = []+ listing = {"out": "/bin/zsh\n/opt/homebrew/opt/openshell/bin/openshell-gateway --config /opt/homebrew/var/openshell/gateway.toml\n"}++ def fake_run(argv, timeout=600):+ ran.append(argv)+ return SimpleNamespace(returncode=0, stdout=listing["out"] if argv[0] == "ps" else "", stderr="")++ monkeypatch.setattr(setup_cmd, "_run", fake_run)+ monkeypatch.setattr(setup_cmd.sys, "platform", "darwin")+ monkeypatch.setattr(setup_cmd.shutil, "which", lambda name: f"/opt/homebrew/bin/{name}")+ # Started with Homebrew's own config: not in use yet, whatever is on disk.+ assert setup_cmd.gateway_config_in_use() == setup_cmd.Path("/opt/homebrew/var/openshell/gateway.toml")+ assert setup_cmd.apply_bind_mounts() is None+ assert ["brew", "services", "restart", "nvidia/openshell/openshell"] in ran+ ours = tmp_path / "openshell" / "gateway.toml"+ assert "enable_bind_mounts = true" in ours.read_text()+ # Restarted: no --config, so `gateway.env` names the file, and the check is satisfied.+ listing["out"] = "/opt/homebrew/opt/openshell/bin/openshell-gateway\n"+ assert setup_cmd.gateway_config_in_use() == ours and setup_cmd._allows_bind_mounts(ours)+ # Running it again is fine: the setting is there, only the restart happens.+ ran.clear()+ assert setup_cmd.apply_bind_mounts() is None and ours.read_text().count("enable_bind_mounts") == 1+ assert ["brew", "services", "restart", "nvidia/openshell/openshell"] in ran+ # Linux restarts the user unit.+ monkeypatch.setattr(setup_cmd.sys, "platform", "linux")+ ran.clear()+ assert setup_cmd.restart_gateway() is None and ran == [["systemctl", "--user", "restart", "openshell-gateway"]]diff --git a/tests/test_sandbox_tools.py b/tests/test_sandbox_tools.pyindex 452a7ab5..e4f9c56f 100644--- a/tests/test_sandbox_tools.py+++ b/tests/test_sandbox_tools.py@@ -194,3 +194,29 @@ def test_the_packed_runner_carries_the_toolkits_and_needs_no_site_packages(tmp_pdone = subprocess.run([sys.executable, "-S", "-c", probe, str(zipapp), str(tmp_path / "ws")], capture_output=True, text=True)assert done.returncode == 0, done.stderrassert done.stdout.strip() == "['a.txt']"+++def test_a_session_workspace_makes_its_sandbox_on_first_use(tmp_path):+ """RunnerWorkspace(start=False): nothing is made until the runner is needed, and the+ file tools are still routed to the runner (never run here) before that."""+ folder = tmp_path / "ws"+ folder.mkdir()+ (folder / "a.txt").write_text("hello\n")+ provider = RunnerLocalProvider(cwd=folder, runner_path=build_runner_zipapp(tmp_path / "dist"))+ made: list[str] = []+ real_create = provider.create+ provider.create = lambda: (made.append("create"), real_create())[1]+ sandbox = RunnerWorkspace(provider, cwd=folder, start=False)+ try:+ assert not sandbox.started and made == []+ ctx = AgentContext(workspace=folder, executor=sandbox.executor, sandbox=sandbox)+ tools = {t.__name__: t for t in catalog.expand(["code_files"], ctx)}+ assert getattr(tools["read_file"], "__wrapped_in_runner__", True) # proxied, not local+ assert "hello" in str(tools["read_file"]("a.txt")) # the first call makes the sandbox+ assert sandbox.started and made == ["create"]+ assert sandbox.executor.run("echo again")["exit_code"] == 0 and made == ["create"]+ finally:+ sandbox.close()+ unused = RunnerWorkspace(RunnerLocalProvider(cwd=folder, runner_path=build_runner_zipapp(tmp_path / "dist2")), cwd=folder, start=False)+ unused.close() # never started: nothing to take down+ assert not unused.starteddiff --git a/tests/test_session_socket_sandbox_build.py b/tests/test_session_socket_sandbox_build.pyindex 15334be8..96b16868 100644--- a/tests/test_session_socket_sandbox_build.py+++ b/tests/test_session_socket_sandbox_build.py@@ -1,9 +1,9 @@-"""A socket connect that has to build a sandbox (OPE-206).+"""A socket connect and a session's sandbox (OPE-206, 2026-09-28).-The engine build used to run on the event loop; with OpenShell that is a container being-created, so the whole server stopped answering and the GUI fell back to its startup-screen. Now the socket says `sandbox_preparing`, the build runs on a worker thread, and-the socket reports `sandbox_ready` (or an `error` with the reason) before `ready`.+The engine is built on a worker thread, so a slow build never stops the server. The+sandbox itself is not made at connect: the first turn makes it and says so+(`sandbox_preparing`, then `sandbox_ready`, or an error that ends the turn). Opening a+session, or picking its folder (a new session id each time), builds no sandbox."""from __future__ import annotations@@ -19,36 +19,23 @@ from coworker.server import create_appfrom tests.test_persona_connections import _mgr-class _FakeSandbox:- def describe(self):- return {"provider": "openshell", "enforcement": "full", "reason": "OpenShell 0.0.116: Landlock and seccomp", "sandbox": "ow-abc", "runner": {"os": "Linux"}}---def test_a_connect_that_builds_a_sandbox_says_so_and_builds_off_the_loop(tmp_path, monkeypatch):+def test_a_connect_builds_the_engine_off_the_loop_and_no_sandbox(tmp_path, monkeypatch):mgr = _mgr(tmp_path, monkeypatch)- monkeypatch.setattr(mgr, "pending_sandbox_build", lambda session_id: "openshell")seen: dict = {}real = mgr.get_enginedef build(session_id, **kwargs):- seen["thread"] = threading.current_thread().nametry:asyncio.get_running_loop()seen["on_loop"] = Trueexcept RuntimeError:seen["on_loop"] = False- engine = real(session_id, **kwargs)- engine.sandbox_workspace = _FakeSandbox()- return engine+ return real(session_id, **kwargs)monkeypatch.setattr(mgr, "get_engine", build)client = TestClient(create_app(mgr))with client.websocket_connect("/ws/session/s-box?agent=cowork") as ws:- first, second, third = ws.receive_json(), ws.receive_json(), ws.receive_json()- assert first == {"type": "sandbox_preparing", "data": {"provider": "openshell"}}- assert second["type"] == "sandbox_ready"- assert second["data"] == {"provider": "openshell", "enforcement": "full", "reason": "OpenShell 0.0.116: Landlock and seccomp", "sandbox": "ow-abc"}- assert third["type"] == "ready"+ assert ws.receive_json()["type"] == "ready" # no sandbox_preparing at connectassert seen["on_loop"] is False # the build ran on a worker thread, the loop stayed free@@ -61,7 +48,6 @@ def test_a_connect_that_needs_no_sandbox_is_unchanged(tmp_path, monkeypatch):def test_a_refused_sandbox_is_reported_on_the_socket_not_as_a_server_error(tmp_path, monkeypatch):mgr = _mgr(tmp_path, monkeypatch)- monkeypatch.setattr(mgr, "pending_sandbox_build", lambda session_id: "openshell")refusal = "The sandbox base image is not downloaded yet (about 5 GB, one time). Run `openworker machine sandbox setup`."def refuse(session_id, **kwargs):@@ -74,31 +60,50 @@ def test_a_refused_sandbox_is_reported_on_the_socket_not_as_a_server_error(tmp_pfrom coworker.server.app import WS_CLOSE_SESSION_REFUSEDwith client.websocket_connect("/ws/session/s-refused?agent=cowork") as ws:- assert ws.receive_json()["type"] == "sandbox_preparing"assert ws.receive_json() == {"type": "error", "data": {"error": refusal}}with pytest.raises(WebSocketDisconnect) as closed: # closed cleanly, with the "final" codews.receive_json()assert closed.value.code == WS_CLOSE_SESSION_REFUSED # so the client does not retry the refusal-def test_pending_sandbox_build_reads_the_config_and_knows_an_existing_engine(tmp_path, monkeypatch):- from coworker import config+class _LazySandbox:+ """A workspace whose sandbox is made on first use, like RunnerWorkspace(start=False)."""- mgr = _mgr(tmp_path, monkeypatch)- monkeypatch.delenv("OPENWORKER_SANDBOX_PROVIDER", raising=False)- monkeypatch.delenv("OPENWORKER_HEADLESS", raising=False)- monkeypatch.setattr(config, "global_config_path", lambda: tmp_path / "config.toml")- assert mgr.pending_sandbox_build("s-new") == "" # default rule on a desktop: direct- monkeypatch.setenv("OPENWORKER_HEADLESS", "1")- assert mgr.pending_sandbox_build("s-new") == "openshell" # a headless machine's default- monkeypatch.delenv("OPENWORKER_HEADLESS")- mgr.get_engine("s-built", agent="cowork") # direct mode here: no OpenShell on a test box- config.set_global_value("sandbox_provider", "openshell")- assert mgr.pending_sandbox_build("s-new") == "openshell"- assert mgr.pending_sandbox_build("s-built") == "" # built already: nothing pending- monkeypatch.setenv("OPENWORKER_SANDBOX_PROVIDER", "direct")- assert mgr.pending_sandbox_build("s-new") == "" # the environment wins+ def __init__(self, fail: str = "") -> None:+ self.started, self.fail, self.starts = False, fail, 0+ self.provider = type("P", (), {"name": "seatbelt"})()++ def ensure_started(self):+ self.starts += 1+ if self.fail:+ raise RuntimeError(self.fail)+ self.started = True+ def describe(self):+ return {"provider": "seatbelt", "enforcement": "full", "reason": "the macOS sandbox", "runner": {}}+++def _events(engine, text="hi"):+ async def collect():+ return [e async for e in engine._start_sandbox()]++ return asyncio.run(collect())+++def test_the_first_turn_makes_the_sandbox_and_says_so(tmp_path, monkeypatch):+ mgr = _mgr(tmp_path, monkeypatch)+ engine = mgr.get_engine("s-lazy", agent="cowork")+ engine.sandbox_workspace = _LazySandbox()+ events = _events(engine)+ assert [e.type.value for e in events] == ["sandbox_preparing", "sandbox_ready"]+ assert events[0].data == {"provider": "seatbelt"} and events[1].data["enforcement"] == "full"+ assert _events(engine) == [] # made once+ # A sandbox that cannot start ends the turn with the reason, kept in the transcript.+ engine.sandbox_workspace = _LazySandbox(fail="bind mounts are off")+ events = _events(engine)+ assert [e.type.value for e in events] == ["sandbox_preparing", "error"]+ assert "bind mounts are off" in events[1].data["error"]+ assert engine.messages[-1]["kind"] == "error"def test_two_connects_to_one_session_build_one_engine(tmp_path, monkeypatch):mgr = _mgr(tmp_path, monkeypatch)