Skip to content
Python

OpenShell setup on a Mac: show Docker Desktop's host networking in the app

Rohit C Prasad34c39d5adcae
diff --git a/coworker/sandbox/providers/openshell.py b/coworker/sandbox/providers/openshell.py
index 38b7e29c..5a87bc61 100644
--- a/coworker/sandbox/providers/openshell.py
+++ b/coworker/sandbox/providers/openshell.py
@@ -105,9 +105,27 @@ def preflight() -> dict[str, Any]:
f"{IMAGE_MISSING_PREFIX} (about 5 GB, one time). Run `openworker machine sandbox setup`, "
f"or `{image_tool() or 'docker'} pull {sandbox_image()}`, then start the session again."
)
+ problem = host_network_problem()
+ if problem:
+ raise OpenShellUnavailable(problem)
return {"version": version}
+def _host_network_problem() -> Optional[str]:
+ """On a Mac: what to do when Docker Desktop's host networking is off, else None.
+ OpenShell 0.1 cannot start a sandbox without it, and says only "failed to connect"."""
+ if sys.platform != "darwin":
+ return None
+ from ..setup_cmd import DOCKER_HOST_NETWORK_FIX, docker_host_network
+
+ return f"{DOCKER_HOST_NETWORK_FIX}." if docker_host_network() is False else None
+
+
+# What `preflight` calls. A name of its own so tests can stand in for it: the real one
+# starts a container.
+host_network_problem = _host_network_problem
+
+
def active_driver() -> str:
"""The gateway's compute driver ("docker", "podman", "kubernetes", "vm"), or "" when it
cannot be told. Read from `openshell gateway info -o json`."""
diff --git a/coworker/sandbox/setup_cmd.py b/coworker/sandbox/setup_cmd.py
index 77cb33e6..e3f74a6e 100644
--- a/coworker/sandbox/setup_cmd.py
+++ b/coworker/sandbox/setup_cmd.py
@@ -27,6 +27,7 @@ import getpass
import os
import shutil
import socket
+import time
import subprocess
import sys
import threading
@@ -194,6 +195,9 @@ def docker_landlock() -> Optional[bool]:
return None
+_host_network_ok_at = 0.0
+
+
def docker_host_network() -> Optional[bool]:
"""On a Mac: whether a container on Docker's host network reaches the gateway on this
Mac's loopback address, tried from a throwaway container of the base image. None when
@@ -210,8 +214,15 @@ def docker_host_network() -> Optional[bool]:
image = openshell.sandbox_image()
if _run(["docker", "image", "inspect", image], 30).returncode != 0:
return None
+ # A yes is kept for a while: this is asked before every session, the answer needs a
+ # container, and the setting does not turn itself off. A no is asked again each time,
+ # so ticking the box is seen at once.
+ global _host_network_ok_at
+ if _host_network_ok_at and time.monotonic() - _host_network_ok_at < 600:
+ return True
probe = f"import socket; socket.create_connection(('127.0.0.1', {port}), 4).close()"
done = _run(["docker", "run", "--rm", "--network", "host", "--entrypoint", openshell_policy.PYTHON, image, "-c", probe], 90)
+ _host_network_ok_at = time.monotonic() if done.returncode == 0 else 0.0
return done.returncode == 0
diff --git a/surfaces/gui/src/components/SandboxSection.tsx b/surfaces/gui/src/components/SandboxSection.tsx
index 5ea1eac3..bcccd5d5 100644
--- a/surfaces/gui/src/components/SandboxSection.tsx
+++ b/surfaces/gui/src/components/SandboxSection.tsx
@@ -1048,10 +1048,11 @@ function OpenShellDialog({
const good = (r?: Row) => Boolean(r) && (r!.state ? r!.state === "ok" || r!.state === "fixed" : r!.ok);
const docker = byKey("docker");
const kernel = byKey("docker_landlock"); // a Mac: does Docker Desktop's Linux kernel have Landlock
+ const hostNet = byKey("docker_host_network"); // a Mac: is Docker Desktop's host networking on
const openshell = byKey("openshell");
- const rest = rows.filter((r) => r.key !== "docker" && r.key !== "docker_landlock" && r.key !== "openshell");
+ const rest = rows.filter((r) => r.key !== "docker" && r.key !== "docker_landlock" && r.key !== "docker_host_network" && r.key !== "openshell");
const blocked = rest.find((r) => r.state === "needs_you" || r.state === "failed");
- const dockerOk = good(docker) && (!kernel || good(kernel));
+ const dockerOk = good(docker) && (!kernel || good(kernel)) && (!hostNet || good(hostNet));
const checksOk = dockerOk && good(openshell);
const allOk = rows.length > 0 && rows.every((r) => good(r));
const done = job?.status === "done" || (!job && ready && allOk);
@@ -1121,6 +1122,15 @@ function OpenShellDialog({
</span>
<span className="block">{t("settingsx.sandbox.os_docker_update_why")}</span>
</span>
+ ) : docker && good(docker) && hostNet && !good(hostNet) ? (
+ <span className="block text-meta text-muted mt-0.5" data-testid="sandbox-setup-hostnet">
+ <span className="block">
+ {t("settingsx.sandbox.os_docker_hostnet")}{" "}
+ {link(hostNet.docs || "https://docs.docker.com/engine/network/drivers/host/#docker-desktop", t("settingsx.sandbox.docker_hostnet_link"), "sandbox-setup-docs-hostnet")}
+ </span>
+ <span className="block">{t("settingsx.sandbox.os_docker_hostnet_where")}</span>
+ <span className="block">{t("settingsx.sandbox.os_docker_hostnet_why")}</span>
+ </span>
) : docker && !good(docker) ? (
<span className="block text-meta text-muted mt-0.5">
{t(mac ? "settingsx.sandbox.os_docker_fix_mac" : "settingsx.sandbox.os_docker_fix")}{" "}
diff --git a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
index 39346ff6..68120165 100644
--- a/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
+++ b/surfaces/gui/src/components/SettingsView.sandbox.test.tsx
@@ -190,6 +190,35 @@ describe("Settings ▸ Sandbox", () => {
expect(screen.getByTestId("sandbox-setup-check")).toBeTruthy();
});
+ it("OpenShell on a Mac with Docker Desktop's host networking off: where to turn it on, then check again", async () => {
+ snapshot = { ...base, platform: "darwin", providers: [{ name: "direct", usable: true, why: "" }, { name: "seatbelt", usable: true, why: "" }, { name: "openshell", usable: false, why: "", state: "unavailable" }] };
+ readinessNow = {
+ ...readiness,
+ steps: [
+ { ...readiness.steps[0], ok: true },
+ { key: "docker_host_network", what: "Docker Desktop's host networking is on", ok: false, hint: "Turn on host networking in Docker Desktop", fixable: false, command: "", docs: "https://docs.docker.com/engine/network/drivers/host/#docker-desktop" },
+ { ...readiness.steps[1], ok: true },
+ { ...readiness.steps[2], ok: true },
+ readiness.steps[3],
+ ],
+ };
+ render(<SettingsView initialTab="sandbox" />);
+ await screen.findByTestId("sandbox-section");
+ fireEvent.click(masterSwitch());
+ fireEvent.click(screen.getByTestId("sandbox-setup-openshell"));
+ await screen.findByTestId("sandbox-setup-hostnet");
+ const dialog = screen.getByTestId("sandbox-openshell-dialog");
+ expect(dialog.querySelectorAll("li").length).toBe(3); // still three rows: it folds into Docker's
+ expect(screen.getByTestId("sandbox-setup-row-docker").getAttribute("data-state")).toBe("bad");
+ const lines = screen.getByTestId("sandbox-setup-hostnet").children;
+ expect(lines[0].textContent).toBe("Turn on host networking in Docker Desktop, then check again. Docker's guide");
+ expect(lines[1].textContent).toBe("Settings ▸ Resources ▸ Network ▸ Enable host networking, then Apply & restart.");
+ expect(lines[2].textContent).toBe("OpenShell's sandboxes reach its gateway that way.");
+ expect((screen.getByTestId("sandbox-setup-docs-hostnet") as HTMLAnchorElement).href).toBe("https://docs.docker.com/engine/network/drivers/host/#docker-desktop");
+ expect(screen.queryByTestId("sandbox-setup-start")).toBeNull(); // Check again, not Set up
+ expect(screen.getByTestId("sandbox-setup-check")).toBeTruthy();
+ });
+
it("OpenShell: both checks pass, Set up runs; the rows stay and the third shows the download", async () => {
snapshot = { ...base, platform: "darwin", providers: [{ name: "direct", usable: true, why: "" }, { name: "seatbelt", usable: true, why: "" }, { name: "openshell", usable: false, why: "", state: "needs_download" }] };
readinessNow = { ...readiness, steps: [{ ...readiness.steps[0], ok: true }, { ...readiness.steps[1], ok: true }, { ...readiness.steps[2], ok: true }, readiness.steps[3]] };
diff --git a/surfaces/gui/src/locales/en.json b/surfaces/gui/src/locales/en.json
index 31d2de20..964b7f83 100644
--- a/surfaces/gui/src/locales/en.json
+++ b/surfaces/gui/src/locales/en.json
@@ -2500,6 +2500,10 @@
"sites_total": "{{count}} allowed",
"os_docker_update": "Update Docker Desktop, then check again.",
"os_docker_update_why": "This version's Linux kernel has no Landlock, which OpenShell needs.",
+ "os_docker_hostnet": "Turn on host networking in Docker Desktop, then check again.",
+ "os_docker_hostnet_where": "Settings ▸ Resources ▸ Network ▸ Enable host networking, then Apply & restart.",
+ "os_docker_hostnet_why": "OpenShell's sandboxes reach its gateway that way.",
+ "docker_hostnet_link": "Docker's guide",
"applies_note": "Applies to sessions you start from now on. Open sessions keep running as they are."
}
},
diff --git a/surfaces/gui/src/locales/zh.json b/surfaces/gui/src/locales/zh.json
index 3b5ff0ee..5330f9d2 100644
--- a/surfaces/gui/src/locales/zh.json
+++ b/surfaces/gui/src/locales/zh.json
@@ -2460,6 +2460,10 @@
"sites_total": "已允许 {{count}} 个",
"os_docker_update": "请更新 Docker Desktop,然后重新检查。",
"os_docker_update_why": "此版本的 Linux 内核没有 Landlock,而 OpenShell 需要它。",
+ "os_docker_hostnet": "请在 Docker Desktop 中开启主机网络,然后重新检查。",
+ "os_docker_hostnet_where": "设置 ▸ 资源 ▸ 网络 ▸ 启用主机网络,然后点击“应用并重启”。",
+ "os_docker_hostnet_why": "OpenShell 的沙盒通过它连接网关。",
+ "docker_hostnet_link": "Docker 指南",
"applies_note": "对此后新开始的会话生效。已打开的会话保持原样继续运行。"
}
},
diff --git a/tests/conftest.py b/tests/conftest.py
index fa9b4cbf..392a40df 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -27,6 +27,17 @@ def _isolated_state_dir(tmp_path, monkeypatch):
monkeypatch.delenv("COWORKER_API_TOKEN", raising=False)
[email protected](autouse=True)
+def _no_docker_host_network_probe(monkeypatch):
+ """OpenShell's preflight asks, on a Mac, whether Docker Desktop's host networking is on,
+ by starting a container. No unit test may do that; the check has its own tests."""
+ from coworker.sandbox import setup_cmd
+ from coworker.sandbox.providers import openshell
+
+ monkeypatch.setattr(openshell, "host_network_problem", lambda: None)
+ monkeypatch.setattr(setup_cmd, "_host_network_ok_at", 0.0)
+
+
@pytest_asyncio.fixture
async def fake_slack(monkeypatch):
"""A running FakeSlack control object; `SLACK_API_URL` is set to it for the test's duration."""
diff --git a/tests/test_sandbox_openshell.py b/tests/test_sandbox_openshell.py
index 1a54661f..32865ad9 100644
--- a/tests/test_sandbox_openshell.py
+++ b/tests/test_sandbox_openshell.py
@@ -592,3 +592,27 @@ def test_only_the_runner_is_mounted_into_a_sandbox(tmp_path, monkeypatch):
assert not str(registry.path).startswith(str(runner.parent) + os.sep)
sources = [m["source"] for m in policy.mounts(ROOTS, str(runner.parent))["docker"]["mounts"]]
assert str(runner.parent) in sources and str(tmp_path / "sandbox") not in sources
+
+
+def test_on_a_mac_a_session_is_refused_early_when_docker_desktops_host_networking_is_off(monkeypatch):
+ from coworker.sandbox import setup_cmd
+
+ monkeypatch.setattr(openshell.sys, "platform", "darwin")
+ monkeypatch.setattr(setup_cmd, "docker_host_network", lambda: False)
+ assert "Enable host networking" in openshell._host_network_problem()
+ monkeypatch.setattr(setup_cmd, "docker_host_network", lambda: True)
+ assert openshell._host_network_problem() is None
+ monkeypatch.setattr(setup_cmd, "docker_host_network", lambda: None) # cannot tell: not a refusal
+ assert openshell._host_network_problem() is None
+ monkeypatch.setattr(openshell.sys, "platform", "linux")
+ monkeypatch.setattr(setup_cmd, "docker_host_network", lambda: False)
+ assert openshell._host_network_problem() is None # Docker Engine on Linux always has it
+
+ # preflight refuses with it, after the version, gateway and image checks pass.
+ monkeypatch.setattr(openshell.shutil, "which", lambda name: "/usr/bin/openshell")
+ present = {"--version": _OK_VERSION, "status": _CONNECTED, "gateway": _DOCKER_GATEWAY, "image": ("[{...}]", 0)}
+ monkeypatch.setattr(openshell.subprocess, "run", _fake_cli(present))
+ monkeypatch.setattr(openshell, "host_network_problem", lambda: "Turn on host networking in Docker Desktop.")
+ with pytest.raises(openshell.OpenShellUnavailable, match="host networking"):
+ openshell.preflight()
+