authoravatarclover caruso<git@paperclover.net>2026-11-21 19:59:51-08:00
committeravatarclover caruso<git@paperclover.net>2026-11-22 00:44:03-08:00
log3dc3f61c5d3bbda749756a50026ab3694f886b5d
tree66bb28d89c34f0f64be3032f071125db4e145060
parentc584c4d8a4cca56a74abd108b2f6595ac50fd5ec
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Mac VMs: manage m3-phoenix-box beside m3-devbox

The dashboard knew one Mac VM, so Computer MCP connections could not be granted the network-locked Phoenix guest. SNOWGLOBE_MAC_VM now lists the VMs, requests to the Mac bridge name the VM, and the bridge maps each name to a Tart VM (power through the locked start script, status without probing the guest agent). install-mac-computer.py takes the guest to install into. Assisted-by: claude-sonnet-5.5

12 files changed, 223 insertions(+), 54 deletions(-)

nixos/mac-vm.nix+5-2
...@@ -1,16 +1,19 @@...@@ -1,16 +1,19 @@
1{ ... }:1{ ... }:
2let2let
3 workspace = builtins.fromJSON (builtins.readFile ../config/mac-studio-sandbox.json);3 workspace = builtins.fromJSON (builtins.readFile ../config/mac-studio-sandbox.json);
4 owner = "8c909fab-98b0-4472-9171-9606ccebe9d5";
4in {5in {
5 systemd.services.snowglobe-host = {6 systemd.services.snowglobe-host = {
6 environment.SNOWGLOBE_MAC_VM = builtins.toJSON {7 environment.SNOWGLOBE_MAC_VM = builtins.toJSON {
7 name = "m3-devbox";
8 owner = "8c909fab-98b0-4472-9171-9606ccebe9d5";
9 address = workspace.clientAddress;8 address = workspace.clientAddress;
10 port = 22;9 port = 22;
11 user = "clo";10 user = "clo";
12 identity = "/var/lib/snowglobe/mac-vm/ssh_key";11 identity = "/var/lib/snowglobe/mac-vm/ssh_key";
13 knownHosts = "/var/lib/snowglobe/mac-vm/known_hosts";12 knownHosts = "/var/lib/snowglobe/mac-vm/known_hosts";
13 vms = [
14 { name = "m3-devbox"; inherit owner; console = true; suspend = true; }
15 { name = "m3-phoenix-box"; inherit owner; console = false; suspend = false; }
16 ];
14 };17 };
15 serviceConfig.IPAddressAllow = [ "${workspace.clientAddress}/32" ];18 serviceConfig.IPAddressAllow = [ "${workspace.clientAddress}/32" ];
16 };19 };
tools/dashboard-host-test.py+1-1
...@@ -213,7 +213,7 @@ class Host:...@@ -213,7 +213,7 @@ class Host:
213 while not (root / 'release').exists(): time.sleep(.01)213 while not (root / 'release').exists(): time.sleep(.01)
214 return {'operation': request['operation'], 'active_snapshot': active_snapshot}214 return {'operation': request['operation'], 'active_snapshot': active_snapshot}
215m.Host = Host215m.Host = Host
216m.vms.mac_vms.CONFIG = {'name': 'managed-mac'}216m.vms.mac_vms.CONFIG = {'vms': [{'name': 'managed-mac'}]}
217with m.vms.computer_lock('fixture', 'exec') as active, m.vms.computer_lock('managed-mac', 'exec'):217with m.vms.computer_lock('fixture', 'exec') as active, m.vms.computer_lock('managed-mac', 'exec'):
218 (root / 'active.json').write_text(json.dumps(active))218 (root / 'active.json').write_text(json.dumps(active))
219 m.main()219 m.main()
tools/dashboard-host.py+3-3
...@@ -217,7 +217,7 @@ class Host:...@@ -217,7 +217,7 @@ class Host:
217 except ValueError as error:217 except ValueError as error:
218 raise Rejected(str(error)) from error218 raise Rejected(str(error)) from error
219 if action == "clipboard":219 if action == "clipboard":
220 if not vms.mac_vms.CONFIG or payload["name"] != vms.mac_vms.CONFIG["name"]:220 if not vms.mac_vms.owns(payload["name"]):
221 raise Rejected("This VM does not support this guest operation.")221 raise Rejected("This VM does not support this guest operation.")
222 try:222 try:
223 return vms.mac_vms.handle(action, payload)223 return vms.mac_vms.handle(action, payload)
...@@ -385,7 +385,7 @@ def stream_console(connection, host, request):...@@ -385,7 +385,7 @@ def stream_console(connection, host, request):
385 screen.connect(details["path"])385 screen.connect(details["path"])
386 screen.setblocking(False)386 screen.setblocking(False)
387 elif details.get("remote"):387 elif details.get("remote"):
388 _, screen = resources.enter_context(vms.mac_vms.connect({"action": "console"}, timeout=20))388 _, screen = resources.enter_context(vms.mac_vms.connect(details["name"], {"action": "console"}, timeout=20))
389 screen.setblocking(False)389 screen.setblocking(False)
390 else:390 else:
391 identity = details["uuid"]391 identity = details["uuid"]
...@@ -533,7 +533,7 @@ def serve_connection(connection, host, allowed_uid, allowed_operations=None):...@@ -533,7 +533,7 @@ def serve_connection(connection, host, allowed_uid, allowed_operations=None):
533 operation_handle = action.get("action") == "process" and isinstance(identity, str) and identity.startswith("operation:")533 operation_handle = action.get("action") == "process" and isinstance(identity, str) and identity.startswith("operation:")
534 control = operation_handle and action.get("operation") == "status"534 control = operation_handle and action.get("operation") == "status"
535 if (action.get("action") == "status" or operation_handle and action.get("operation") == "stop") and (535 if (action.get("action") == "status" or operation_handle and action.get("operation") == "stop") and (
536 not vms.mac_vms.CONFIG or payload["name"] != vms.mac_vms.CONFIG["name"]536 not vms.mac_vms.owns(payload["name"])
537 ):537 ):
538 active_snapshot = vms.computer_activity(payload["name"])538 active_snapshot = vms.computer_activity(payload["name"])
539 control = active_snapshot is not None539 control = active_snapshot is not None
tools/dashboard-stage.py+6-3
...@@ -148,9 +148,11 @@ def stage(computer=None):...@@ -148,9 +148,11 @@ def stage(computer=None):
148 selected = saved["computer"].split(",")148 selected = saved["computer"].split(",")
149 for name in selected:149 for name in selected:
150 boundary.vms.ensure_name(name)150 boundary.vms.ensure_name(name)
151 if not mac or name != mac["name"]:151 if not mac or all(entry["name"] != name for entry in mac["vms"]):
152 snowglobe.command("virsh", "domuuid", name, capture=True)152 snowglobe.command("virsh", "domuuid", name, capture=True)
153 if mac and mac["name"] not in selected:153 if mac:
154 mac["vms"] = [entry for entry in mac["vms"] if entry["name"] in selected]
155 if mac and not mac["vms"]:
154 mac = None156 mac = None
155 nix = ["nix", "--extra-experimental-features", "nix-command flakes"]157 nix = ["nix", "--extra-experimental-features", "nix-command flakes"]
156 package = "path:" + str(snowglobe.REPO) + "#dashboard-image"158 package = "path:" + str(snowglobe.REPO) + "#dashboard-image"
...@@ -229,7 +231,8 @@ def stage(computer=None):...@@ -229,7 +231,8 @@ def stage(computer=None):
229 owner = accounts.execute("SELECT id FROM users WHERE username='preview'").fetchone()231 owner = accounts.execute("SELECT id FROM users WHERE username='preview'").fetchone()
230 if not owner:232 if not owner:
231 raise ValueError("The preview account is unavailable.")233 raise ValueError("The preview account is unavailable.")
232 mac["owner"] = owner[0]234 for entry in mac["vms"]:
235 entry["owner"] = owner[0]
233 computer_environment.append("--setenv=SNOWGLOBE_MAC_VM=" + json.dumps(mac))236 computer_environment.append("--setenv=SNOWGLOBE_MAC_VM=" + json.dumps(mac))
234 host_python = snowglobe.command(*nix, "build", "--out-link", str(root / "host-python"), "--print-out-paths", "path:" + str(snowglobe.REPO) + "#host-python", capture=True).stdout.strip()237 host_python = snowglobe.command(*nix, "build", "--out-link", str(root / "host-python"), "--print-out-paths", "path:" + str(snowglobe.REPO) + "#host-python", capture=True).stdout.strip()
235 subprocess.run(["systemctl", "stop", "snowglobe-preview-screen-" + identity], capture_output=True)238 subprocess.run(["systemctl", "stop", "snowglobe-preview-screen-" + identity], capture_output=True)
tools/install-mac-computer.py+7-5
...@@ -1,17 +1,19 @@...@@ -1,17 +1,19 @@
1#!/usr/bin/env python31#!/usr/bin/env python3
2"""Install computer-use support in the existing managed Mac guest and bridge."""2"""Install computer-use support in a managed Mac guest (default: the devbox) and refresh the shared bridge."""
3from importlib import import_module3from importlib import import_module
4import json4import json
5import os5import os
6from pathlib import Path6from pathlib import Path
7import sys
7import tempfile8import tempfile
89
9vm = import_module("mac-agent-vm")10vm = import_module("mac-agent-vm")
10root = Path(__file__).resolve().parent11root = Path(__file__).resolve().parent
11identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip()12guest = sys.argv[1] if len(sys.argv) > 1 else vm.NAME
13identity = vm.tart("exec", guest, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip()
12print("Installing guest tools in " + identity, flush=True)14print("Installing guest tools in " + identity, flush=True)
13source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]}15source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]}
14vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", '''16vm.tart("exec", "-i", guest, "/Library/Developer/CommandLineTools/usr/bin/python3", "-c", '''
15import json, pathlib, subprocess, sys, tempfile17import json, pathlib, subprocess, sys, tempfile
16files = json.load(sys.stdin)18files = json.load(sys.stdin)
17with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary:19with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary:
...@@ -23,7 +25,7 @@ with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as tempor...@@ -23,7 +25,7 @@ with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as tempor
23 for source, destination in [("mac-computer.py", "/usr/local/libexec/snowglobe-computer.py"), ("agent-gui", "/usr/local/bin/agent-gui")]:25 for source, destination in [("mac-computer.py", "/usr/local/libexec/snowglobe-computer.py"), ("agent-gui", "/usr/local/bin/agent-gui")]:
24 subprocess.run(["sudo", "-n", "install", "-m", "755", str(root / source), destination], check=True)26 subprocess.run(["sudo", "-n", "install", "-m", "755", str(root / source), destination], check=True)
25''', input=json.dumps(source).encode(), timeout=180)27''', input=json.dumps(source).encode(), timeout=180)
26for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]:28for name in ["mac-agent-vm.py", "mac-vm-bridge.py"] if guest == vm.NAME else []:
27 target = vm.ROOT / "runtime/control" / name29 target = vm.ROOT / "runtime/control" / name
28 with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as outgoing:30 with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as outgoing:
29 pending = Path(outgoing.name)31 pending = Path(outgoing.name)
...@@ -33,7 +35,7 @@ for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]:...@@ -33,7 +35,7 @@ for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]:
33 os.replace(pending, target)35 os.replace(pending, target)
34 finally:36 finally:
35 pending.unlink(missing_ok=True)37 pending.unlink(missing_ok=True)
36result = vm.tart("exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py",38result = vm.tart("exec", "-i", guest, "/Library/Developer/CommandLineTools/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py",
37 input=b'{"action":"status"}', capture_output=True, timeout=15)39 input=b'{"action":"status"}', capture_output=True, timeout=15)
38value = json.loads(result.stdout)40value = json.loads(result.stdout)
39if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]):41if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]):
tools/mac-computer-test.py+1-1
...@@ -71,7 +71,7 @@ class ComputerTests(unittest.TestCase):...@@ -71,7 +71,7 @@ class ComputerTests(unittest.TestCase):
71 tart.write_text("#!/usr/bin/python3\n" + output + "\n")71 tart.write_text("#!/usr/bin/python3\n" + output + "\n")
72 tart.chmod(0o700)72 tart.chmod(0o700)
73 with patch.object(bridge.vm, "TART", tart), self.assertRaisesRegex(ValueError, message):73 with patch.object(bridge.vm, "TART", tart), self.assertRaisesRegex(ValueError, message):
74 bridge.computer({"action": "status"})74 bridge.computer("gui-agent", {"action": "status"})
7575
7676
77if __name__ == "__main__":77if __name__ == "__main__":
tools/mac-vm-bridge.py+44-8
...@@ -1,5 +1,5 @@...@@ -1,5 +1,5 @@
1#!/usr/bin/env python31#!/usr/bin/env python3
2"""Restricted SSH entry point for the existing Mac development VM."""2"""Restricted SSH entry point for the managed Mac VMs."""
3import fcntl3import fcntl
4from importlib import import_module4from importlib import import_module
5import json5import json
...@@ -13,6 +13,10 @@ import tempfile...@@ -13,6 +13,10 @@ import tempfile
13import time13import time
1414
15vm = import_module("mac-agent-vm")15vm = import_module("mac-agent-vm")
16# Dashboard names mapped to Tart VMs. The first is managed end to end by mac-agent-vm.py; the others are
17# network-locked guests with their own start script, reached only through Tart's guest agent.
18VMS = {"m3-devbox": vm.NAME, "m3-phoenix-box": "m3-phoenix-box"}
19LOCKED_START = vm.ROOT / "runtime/control/start-m3-phoenix-box"
1620
1721
18def status():22def status():
...@@ -38,18 +42,27 @@ def status():...@@ -38,18 +42,27 @@ def status():
38 "agent": agent, "pendingAction": pending, "mac": current["MACAddress"]}42 "agent": agent, "pendingAction": pending, "mac": current["MACAddress"]}
3943
4044
45def locked_status(name):
46 current = json.loads(vm.tart("get", name, "--format", "json", capture_output=True, text=True, timeout=5).stdout)
47 disk = vm.ROOT / "state/vms" / name / "disk.img"
48 return {"state": {"running": "running", "stopped": "shutoff", "suspended": "pmsuspended"}[current["State"]],
49 "vcpus": current["CPU"], "memory": current["Memory"] * 2**20,
50 "disk": {"capacity": disk.stat().st_size, "allocation": disk.stat().st_blocks * 512},
51 "agent": None, "pendingAction": None, "mac": current["MACAddress"]}
52
53
41def respond(value):54def respond(value):
42 data = json.dumps(value).encode()55 data = json.dumps(value).encode()
43 sys.stdout.buffer.write(struct.pack("!I", len(data)) + data)56 sys.stdout.buffer.write(struct.pack("!I", len(data)) + data)
44 sys.stdout.buffer.flush()57 sys.stdout.buffer.flush()
4558
4659
47def computer(request):60def computer(name, request):
48 with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector:61 with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector:
49 source.write(json.dumps(request).encode())62 source.write(json.dumps(request).encode())
50 source.seek(0)63 source.seek(0)
51 # Recovery must work when the selected Xcode is unavailable.64 # Recovery must work when the selected Xcode is unavailable.
52 process = subprocess.Popen([str(vm.TART), "exec", "-i", vm.NAME, "/Library/Developer/CommandLineTools/usr/bin/python3",65 process = subprocess.Popen([str(vm.TART), "exec", "-i", name, "/Library/Developer/CommandLineTools/usr/bin/python3",
53 "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE,66 "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE,
54 stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")})67 stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")})
55 output = bytearray()68 output = bytearray()
...@@ -108,6 +121,18 @@ def lifecycle(action):...@@ -108,6 +121,18 @@ def lifecycle(action):
108 process.wait()121 process.wait()
109122
110123
124def locked_power(name, action):
125 if action in {"stop", "reboot"}:
126 vm.tart("stop", name, timeout=120)
127 if action in {"start", "reboot"}:
128 subprocess.run([str(LOCKED_START)], check=True, stdout=subprocess.DEVNULL, timeout=30)
129 for _ in range(60):
130 if json.loads(vm.tart("get", name, "--format", "json", capture_output=True, text=True, timeout=5).stdout)["Running"]:
131 return
132 time.sleep(1)
133 raise ValueError("The VM did not start.")
134
135
111def main():136def main():
112 line = sys.stdin.buffer.readline(1048577)137 line = sys.stdin.buffer.readline(1048577)
113 if len(line) > 1048576 or not line.endswith(b"\n"):138 if len(line) > 1048576 or not line.endswith(b"\n"):
...@@ -115,25 +140,36 @@ def main():...@@ -115,25 +140,36 @@ def main():
115 request = json.loads(line)140 request = json.loads(line)
116 if not isinstance(request, dict):141 if not isinstance(request, dict):
117 raise ValueError("Choose a supported VM operation.")142 raise ValueError("Choose a supported VM operation.")
143 # Hosts that predate multiple VMs omit the name.
144 requested = request.pop("vm", "m3-devbox")
145 name = VMS.get(requested) if isinstance(requested, str) else None
146 if name is None:
147 raise ValueError("Choose a managed VM.")
148 primary = name == vm.NAME
118 action = request.get("action")149 action = request.get("action")
119 if action == "status" and set(request) == {"action"}:150 if action == "status" and set(request) == {"action"}:
120 respond({"value": status()})151 respond({"value": {**(status() if primary else locked_status(name)), "name": name}})
121 elif action in {"start", "shutdown", "reboot", "suspend", "resume"} and set(request) == {"action"}:152 elif action in {"start", "shutdown", "reboot", "suspend", "resume"} and set(request) == {"action"}:
153 if not primary and action in {"suspend", "resume"}:
154 raise ValueError("This operation is unavailable for this Mac VM.")
122 action = {"shutdown": "stop", "resume": "start"}.get(action, action)155 action = {"shutdown": "stop", "resume": "start"}.get(action, action)
123 lifecycle(action)156 if primary:
157 lifecycle(action)
158 else:
159 locked_power(name, action)
124 respond({"value": None})160 respond({"value": None})
125 elif action == "clipboard" and set(request) == {"action", "text"}:161 elif action == "clipboard" and set(request) == {"action", "text"}:
126 value = request["text"]162 value = request["text"]
127 if not isinstance(value, str) or len(value.encode()) > 262144:163 if not isinstance(value, str) or len(value.encode()) > 262144:
128 raise ValueError("Shorten the clipboard text, then send it again.")164 raise ValueError("Shorten the clipboard text, then send it again.")
129 vm.tart("exec", "-i", vm.NAME, "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy",165 vm.tart("exec", "-i", name, "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy",
130 input=value.encode(), capture_output=True, timeout=15)166 input=value.encode(), capture_output=True, timeout=15)
131 respond({"value": None})167 respond({"value": None})
132 elif action == "computer" and set(request) == {"action", "request"}:168 elif action == "computer" and set(request) == {"action", "request"}:
133 if not isinstance(request["request"], dict):169 if not isinstance(request["request"], dict):
134 raise ValueError("Send a computer operation.")170 raise ValueError("Send a computer operation.")
135 respond({"value": computer(request["request"])})171 respond({"value": computer(name, request["request"])})
136 elif action == "console" and set(request) == {"action"}:172 elif action == "console" and set(request) == {"action"} and primary:
137 with vm.guest_screen() as upstream:173 with vm.guest_screen() as upstream:
138 respond({"value": None})174 respond({"value": None})
139 try:175 try:
tools/mac-vm-test.py+76-5
...@@ -19,11 +19,16 @@ bridge = import_module("mac-vm-bridge")...@@ -19,11 +19,16 @@ bridge = import_module("mac-vm-bridge")
19backend = import_module("mac-vms")19backend = import_module("mac-vms")
2020
2121
22FIXTURE = {"vms": [{"name": "mac-fixture", "owner": "fixture-owner", "console": True, "suspend": True},
23 {"name": "locked-fixture", "owner": "fixture-owner", "console": False, "suspend": False}]}
24
25
22class MacVMTests(unittest.TestCase):26class MacVMTests(unittest.TestCase):
23 def test_protocol_rejects_arbitrary_commands_and_unbounded_clipboards(self):27 def test_protocol_rejects_arbitrary_commands_and_unbounded_clipboards(self):
24 for request in [{"action": "exec", "command": "id"}, {"action": "status", "name": "other"},28 for request in [{"action": "exec", "command": "id"}, {"action": "status", "name": "other"},
25 {"action": "clipboard", "text": "a" * 262145}, ["status"],29 {"action": "clipboard", "text": "a" * 262145}, ["status"],
26 {"action": "clipboard", "text": 42}]:30 {"action": "clipboard", "text": 42}, {"action": "status", "vm": "other"},
31 {"action": "status", "vm": ["m3-devbox"]}]:
27 with self.subTest(request=str(request)[:80]), \32 with self.subTest(request=str(request)[:80]), \
28 patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(request).encode() + b"\n"))), \33 patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(request).encode() + b"\n"))), \
29 patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "lifecycle") as lifecycle:34 patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "lifecycle") as lifecycle:
...@@ -49,7 +54,7 @@ class MacVMTests(unittest.TestCase):...@@ -49,7 +54,7 @@ class MacVMTests(unittest.TestCase):
49 "pendingAction": None, "disk": {"capacity": 128 * 2**30, "allocation": 42 * 2**30},54 "pendingAction": None, "disk": {"capacity": 128 * 2**30, "allocation": 42 * 2**30},
50 "mac": "00:11:22:33:44:55"}, None55 "mac": "00:11:22:33:44:55"}, None
51 with tempfile.TemporaryDirectory() as directory, \56 with tempfile.TemporaryDirectory() as directory, \
52 patch.object(backend, "CONFIG", {"name": "mac-fixture", "owner": "fixture-owner"}), \57 patch.object(backend, "CONFIG", FIXTURE), \
53 patch.object(backend, "CACHE", Path(directory) / "cache.json"):58 patch.object(backend, "CACHE", Path(directory) / "cache.json"):
54 with patch.object(backend, "connect", side_effect=ValueError("offline")):59 with patch.object(backend, "connect", side_effect=ValueError("offline")):
55 first = backend.domain()[0]60 first = backend.domain()[0]
...@@ -66,21 +71,87 @@ class MacVMTests(unittest.TestCase):...@@ -66,21 +71,87 @@ class MacVMTests(unittest.TestCase):
66 self.assertEqual(offline["name"], "mac-fixture")71 self.assertEqual(offline["name"], "mac-fixture")
67 self.assertEqual(offline["owner"], "fixture-owner")72 self.assertEqual(offline["owner"], "fixture-owner")
68 self.assertTrue(offline["ownerOnly"])73 self.assertTrue(offline["ownerOnly"])
69 self.assertEqual(backend.handle("owner", {}), {"owner": "fixture-owner", "ownerOnly": True})74 self.assertEqual(backend.handle("owner", {"name": "mac-fixture"}), {"owner": "fixture-owner", "ownerOnly": True})
70 self.assertEqual(offline["memory"], live["memory"])75 self.assertEqual(offline["memory"], live["memory"])
71 self.assertEqual(offline["state"], "unreachable")76 self.assertEqual(offline["state"], "unreachable")
72 self.assertIsNone(offline["agent"])77 self.assertIsNone(offline["agent"])
73 self.assertIsNone(offline["pendingAction"])78 self.assertIsNone(offline["pendingAction"])
7479
75 def test_unsupported_operations_never_contact_mac(self):80 def test_unsupported_operations_never_contact_mac(self):
76 with patch.object(backend, "connect") as connect:81 with patch.object(backend, "CONFIG", FIXTURE), patch.object(backend, "connect") as connect:
77 for action in ["delete", "update", "preset", "media"]:82 for action in ["delete", "update", "preset", "media"]:
78 with self.subTest(action=action), self.assertRaises(ValueError):83 with self.subTest(action=action), self.assertRaises(ValueError):
79 backend.handle(action, {"name": "mac-fixture"})84 backend.handle(action, {"name": "mac-fixture"})
80 with self.assertRaises(ValueError):85 with self.assertRaises(ValueError):
81 backend.handle("act", {"action": "destroy"})86 backend.handle("act", {"name": "mac-fixture", "action": "destroy"})
82 connect.assert_not_called()87 connect.assert_not_called()
8388
89 def test_each_vm_keeps_its_own_features_and_requests_name_it(self):
90 @contextlib.contextmanager
91 def connected(name, request, timeout=10):
92 yield {"state": "running", "vcpus": 8, "memory": 2**34, "agent": None, "pendingAction": None,
93 "disk": {"capacity": 2**36, "allocation": 2**35}, "mac": "00:11:22:33:44:55", "name": name}, None
94 with tempfile.TemporaryDirectory() as directory, patch.object(backend, "CONFIG", FIXTURE), \
95 patch.object(backend, "CACHE", Path(directory) / "cache.json"):
96 with patch.object(backend, "connect", connected):
97 full, locked = backend.domain()
98 self.assertEqual((full["name"], full["console"], "suspend" in full["capabilities"]), ("mac-fixture", True, True))
99 self.assertEqual((locked["name"], locked["console"], "suspend" in locked["capabilities"]), ("locked-fixture", False, False))
100 self.assertIn("computer", locked["capabilities"])
101 self.assertTrue(backend.owns("locked-fixture") and not backend.owns("other"))
102 with patch.object(backend, "connect") as connect:
103 for action, payload in [("console", {}), ("act", {"action": "suspend"}), ("act", {"action": "resume"})]:
104 with self.subTest(operation=action, payload=payload), self.assertRaises(ValueError):
105 backend.handle(action, {"name": "locked-fixture", **payload})
106 connect.assert_not_called()
107 self.assertEqual(backend.handle("console", {"name": "mac-fixture"}), {"remote": True, "name": "mac-fixture"})
108 with patch.object(backend, "connect", connected), patch.object(backend, "CACHE", Path(directory) / "cache.json"):
109 self.assertEqual(backend.handle("computer", {"name": "locked-fixture", "request": {"action": "status"}})["name"], "locked-fixture")
110 with patch.object(backend, "connect", side_effect=ValueError("offline")) as offline:
111 self.assertEqual([value["state"] for value in backend.domain()], ["unreachable", "unreachable"])
112 self.assertEqual([value["memory"] for value in backend.domain()], [2**34, 2**34])
113 self.assertEqual({call.args[0] for call in offline.call_args_list}, {"mac-fixture", "locked-fixture"})
114
115 def test_bridge_serves_only_named_vms_and_hosts_without_a_name_get_the_devbox(self):
116 def run(request):
117 with patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(request).encode() + b"\n"))), \
118 patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "respond") as respond, \
119 patch.object(bridge, "status", return_value={"state": "devbox"}) as status, \
120 patch.object(bridge, "locked_status", return_value={"state": "locked"}) as locked_status, \
121 patch.object(bridge, "lifecycle") as lifecycle, patch.object(bridge, "locked_power") as locked_power:
122 bridge.main()
123 return tart, respond, status, locked_status, lifecycle, locked_power
124 _, respond, status, locked_status, *_ = run({"action": "status"})
125 respond.assert_called_once_with({"value": {"state": "devbox", "name": "gui-agent"}})
126 _, respond, status, locked_status, *_ = run({"action": "status", "vm": "m3-phoenix-box"})
127 respond.assert_called_once_with({"value": {"state": "locked", "name": "m3-phoenix-box"}})
128 locked_status.assert_called_once_with("m3-phoenix-box")
129 status.assert_not_called()
130 tart, *_ = run({"action": "clipboard", "text": "x", "vm": "m3-phoenix-box"})
131 self.assertEqual(tart.call_args.args[:3], ("exec", "-i", "m3-phoenix-box"))
132 *_, lifecycle, locked_power = run({"action": "reboot", "vm": "m3-phoenix-box"})
133 locked_power.assert_called_once_with("m3-phoenix-box", "reboot")
134 lifecycle.assert_not_called()
135 *_, lifecycle, locked_power = run({"action": "shutdown", "vm": "m3-devbox"})
136 lifecycle.assert_called_once_with("stop")
137 locked_power.assert_not_called()
138 for request in [{"action": "suspend", "vm": "m3-phoenix-box"}, {"action": "resume", "vm": "m3-phoenix-box"},
139 {"action": "console", "vm": "m3-phoenix-box"}]:
140 with self.subTest(request=request), self.assertRaises(ValueError):
141 run(request)
142
143 def test_locked_vm_start_waits_until_tart_reports_it_running(self):
144 states = iter([False, False, True])
145 def tart(*args, **kwargs):
146 if args[0] == "get":
147 return subprocess.CompletedProcess(args, 0, stdout=json.dumps({"Running": next(states)}))
148 with patch.object(bridge.vm, "tart", side_effect=tart) as run, patch.object(bridge.subprocess, "run") as launch, \
149 patch.object(bridge.time, "sleep"):
150 bridge.locked_power("m3-phoenix-box", "reboot")
151 self.assertEqual(run.call_args_list[0].args, ("stop", "m3-phoenix-box"))
152 launch.assert_called_once()
153 self.assertEqual(sum(call.args[0] == "get" for call in run.call_args_list), 3)
154
84 def test_lifecycle_timeout_reaps_commands_but_preserves_detached_runner(self):155 def test_lifecycle_timeout_reaps_commands_but_preserves_detached_runner(self):
85 with tempfile.TemporaryDirectory() as directory:156 with tempfile.TemporaryDirectory() as directory:
86 root = Path(directory)157 root = Path(directory)
tools/mac-vms.py+46-22
...@@ -1,3 +1,4 @@...@@ -1,3 +1,4 @@
1import concurrent.futures
1import contextlib2import contextlib
2import json3import json
3import os4import os
...@@ -9,12 +10,19 @@ import tempfile...@@ -9,12 +10,19 @@ import tempfile
910
1011
11CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null"))12CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null"))
12CAPABILITIES = ["start", "shutdown", "reboot", "suspend", "resume", "clipboard", "computer"]
13CACHE = Path(os.environ.get("SNOWGLOBE_MAC_VM_CACHE", "/var/lib/snowglobe/host/mac-vm.json"))13CACHE = Path(os.environ.get("SNOWGLOBE_MAC_VM_CACHE", "/var/lib/snowglobe/host/mac-vm.json"))
1414
1515
16def vm(name):
17 return next((entry for entry in CONFIG["vms"] if entry["name"] == name), None) if CONFIG else None
18
19
20def owns(name):
21 return vm(name) is not None
22
23
16@contextlib.contextmanager24@contextlib.contextmanager
17def connect(request, timeout=10):25def connect(name, request, timeout=10):
18 if not CONFIG:26 if not CONFIG:
19 raise ValueError("The Mac VM is not configured on this host.")27 raise ValueError("The Mac VM is not configured on this host.")
20 parent, child = socket.socketpair()28 parent, child = socket.socketpair()
...@@ -30,7 +38,7 @@ def connect(request, timeout=10):...@@ -30,7 +38,7 @@ def connect(request, timeout=10):
30 ], stdin=child, stdout=child, stderr=subprocess.DEVNULL)38 ], stdin=child, stdout=child, stderr=subprocess.DEVNULL)
31 child.close()39 child.close()
32 parent.settimeout(timeout)40 parent.settimeout(timeout)
33 parent.sendall(json.dumps(request).encode() + b"\n")41 parent.sendall(json.dumps({**request, "vm": name}).encode() + b"\n")
3442
35 def read(size):43 def read(size):
36 data = bytearray()44 data = bytearray()
...@@ -68,56 +76,72 @@ def connect(request, timeout=10):...@@ -68,56 +76,72 @@ def connect(request, timeout=10):
68 process.wait()76 process.wait()
6977
7078
71def ownership():79def ownership(entry):
72 return {"owner": CONFIG["owner"], "ownerOnly": True}80 return {"owner": entry["owner"], "ownerOnly": True}
7381
7482
75def domain():83def power(entry):
76 if not CONFIG:84 return ["start", "shutdown", "reboot"] + (["suspend", "resume"] if entry["suspend"] else [])
77 return []85
78 value = {"name": CONFIG["name"], **ownership(), "host": "Mac Studio", "arch": "aarch64",86
87def observe(entry):
88 value = {"name": entry["name"], **ownership(entry), "host": "Mac Studio", "arch": "aarch64",
79 "state": "unreachable", "reason": None,89 "state": "unreachable", "reason": None,
80 "os": "macOS", "vcpus": None, "memory": None, "balloon": None, "pinned": None,90 "os": "macOS", "vcpus": None, "memory": None, "balloon": None, "pinned": None,
81 "autostart": False, "startedAt": None, "agent": None, "setup": None, "pendingAction": None,91 "autostart": False, "startedAt": None, "agent": None, "setup": None, "pendingAction": None,
82 "disks": [], "media": [], "firmware": "uefi", "platform": "macos", "console": True,92 "disks": [], "media": [], "firmware": "uefi", "platform": "macos", "console": entry["console"],
83 "serial": False, "interfaces": [], "hostdevs": [], "capabilities": CAPABILITIES}93 "serial": False, "interfaces": [], "hostdevs": [], "capabilities": power(entry) + ["clipboard", "computer"]}
84 try:94 try:
85 with connect({"action": "status"}, timeout=8) as (status, _):95 with connect(entry["name"], {"action": "status"}, timeout=8) as (status, _):
86 value.update({key: status[key] for key in ("state", "vcpus", "memory", "agent", "pendingAction")})96 value.update({key: status[key] for key in ("state", "vcpus", "memory", "agent", "pendingAction")})
87 value["balloon"] = value["memory"]97 value["balloon"] = value["memory"]
88 value["disks"] = [{"target": "disk", "pool": "Mac Studio", "source": "gui-agent", **status["disk"]}]98 value["disks"] = [{"target": "disk", "pool": "Mac Studio", "source": status.get("name", entry["name"]), **status["disk"]}]
89 value["interfaces"] = [{"source": "Mac Studio NAT", "mac": status["mac"], "addresses": []}]99 value["interfaces"] = [{"source": "Mac Studio NAT", "mac": status["mac"], "addresses": []}]
90 except (ValueError, OSError, KeyError, TypeError):100 except (ValueError, OSError, KeyError, TypeError):
91 try:101 try:
92 previous = json.loads(CACHE.read_text())102 previous = json.loads(CACHE.read_text())[entry["name"]]
93 for key in ("vcpus", "memory", "balloon", "disks", "interfaces"):103 for key in ("vcpus", "memory", "balloon", "disks", "interfaces"):
94 value[key] = previous[key]104 value[key] = previous[key]
95 except (ValueError, OSError, KeyError, TypeError):105 except (ValueError, OSError, KeyError, TypeError):
96 pass106 pass
97 value.update(state="unreachable", agent=None, pendingAction=None)107 value.update(state="unreachable", agent=None, pendingAction=None)
98 else:108 return value, value["state"] != "unreachable"
109
110
111def domain():
112 if not CONFIG:
113 return []
114 with concurrent.futures.ThreadPoolExecutor(len(CONFIG["vms"])) as pool:
115 observed = list(pool.map(observe, CONFIG["vms"]))
116 live = {value["name"]: value for value, reachable in observed if reachable}
117 if live:
99 try:118 try:
100 CACHE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)119 CACHE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
120 try:
121 live = {**json.loads(CACHE.read_text()), **live}
122 except (ValueError, OSError):
123 pass
101 descriptor, temporary = tempfile.mkstemp(dir=CACHE.parent, prefix=".mac-vm-")124 descriptor, temporary = tempfile.mkstemp(dir=CACHE.parent, prefix=".mac-vm-")
102 try:125 try:
103 with os.fdopen(descriptor, "w") as outgoing:126 with os.fdopen(descriptor, "w") as outgoing:
104 json.dump(value, outgoing)127 json.dump(live, outgoing)
105 os.replace(temporary, CACHE)128 os.replace(temporary, CACHE)
106 finally:129 finally:
107 Path(temporary).unlink(missing_ok=True)130 Path(temporary).unlink(missing_ok=True)
108 except OSError:131 except OSError:
109 pass132 pass
110 return [value]133 return [value for value, _ in observed]
111134
112135
113def handle(action, payload):136def handle(action, payload):
137 entry = vm(payload["name"])
114 if action == "owner":138 if action == "owner":
115 return ownership()139 return ownership(entry)
116 if action == "access":140 if action == "access":
117 return None141 return None
118 if action == "console":142 if action == "console" and entry["console"]:
119 return {"remote": True}143 return {"remote": True, "name": entry["name"]}
120 if action == "act" and payload["action"] in {"start", "shutdown", "reboot", "suspend", "resume"}:144 if action == "act" and payload["action"] in power(entry):
121 request = {"action": payload["action"]}145 request = {"action": payload["action"]}
122 elif action == "clipboard":146 elif action == "clipboard":
123 request = {"action": "clipboard", "text": payload["text"]}147 request = {"action": "clipboard", "text": payload["text"]}
...@@ -125,5 +149,5 @@ def handle(action, payload):...@@ -125,5 +149,5 @@ def handle(action, payload):
125 request = {"action": "computer", "request": payload["request"]}149 request = {"action": "computer", "request": payload["request"]}
126 else:150 else:
127 raise ValueError("This operation is unavailable for this Mac VM.")151 raise ValueError("This operation is unavailable for this Mac VM.")
128 with connect(request, timeout=220) as (value, _):152 with connect(entry["name"], request, timeout=220) as (value, _):
129 return value153 return value
tools/phoenix-box.md created+30
...@@ -0,0 +1,30 @@
1# Phoenix box
2
3`m3-phoenix-box` is a macOS 15 Tart VM beside `gui-agent`, in the same VM home under
4`/Volumes/Documents/VM/macOS Code Sandbox`. It holds Discord Phoenix and runs it against
5Spacebar, so its network is locked from outside the guest.
6
7Start it with `runtime/control/start-m3-phoenix-box` in that VM home. The script owns the
8flags: headless, `--vnc-experimental`, and Softnet with every destination blocked except
9`100.64.0.1/32`, Snow Globe's tailnet address. This Mac's NAT only leaves through Tailscale
10(its own routes do not reach the internet), and Snow Globe's Caddy answers on that address.
11Softnet filters by address, not port, so the VM can reach every port Snow Globe accepts
12on the tailnet.
13
14- **Names:** the guest has no DNS (its gateway is blocked), so `/etc/hosts` maps
15 `spacebar.paperclover.net` to `100.64.0.1`. Go ignores `/etc/hosts` on macOS unless
16 `GODEBUG=netdns=go`, which `run-phoenix-spacebar` sets for the Caddy relay.
17- **Access:** Softnet also blocks host to guest, so there is no SSH or Screen Sharing.
18 Tart's own VNC server (random password per run, printed to `run.log` in
19 `private/m3-phoenix-box`, listening on every interface of this Mac) and `tart exec` are
20 the ways in. Console login is `admin` / `admin`; SSH accepts only the key in that
21 private directory.
22- **Softnet:** 0.23.0 at `/usr/local/bin/softnet`, owned by root with the setuid bit.
23 Releases from 0.24 need macOS 26.
24- **Dashboard:** `nixos/mac-vm.nix` lists both Mac VMs. The Mac-side bridge
25 (`runtime/control/mac-vm-bridge.py`) maps each dashboard name to a Tart VM, so Computer
26 MCP connections can be granted `m3-phoenix-box` like any VM. It has no dashboard
27 console or suspend; power operations run `start-m3-phoenix-box` and `tart stop`.
28
29To manage another Mac VM, add it to `VMS` in the bridge and to `nixos/mac-vm.nix`, then run
30`python3 tools/install-mac-computer.py <tart name>` to install the guest worker.
tools/vm-computer.py+2-2
...@@ -536,7 +536,7 @@ def handle(name, request, *, active_snapshot=None):...@@ -536,7 +536,7 @@ def handle(name, request, *, active_snapshot=None):
536 validate(request)536 validate(request)
537 vms.ensure_name(name)537 vms.ensure_name(name)
538 if request['action'] == 'process' and request['id'].startswith('operation:'):538 if request['action'] == 'process' and request['id'].startswith('operation:'):
539 if vms.mac_vms.CONFIG and name == vms.mac_vms.CONFIG['name']:539 if vms.mac_vms.owns(name):
540 raise ValueError('This VM does not provide active operation handles.')540 raise ValueError('This VM does not provide active operation handles.')
541 identity = request['id']541 identity = request['id']
542 with vms.computer_control(name) as control:542 with vms.computer_control(name) as control:
...@@ -568,7 +568,7 @@ def handle(name, request, *, active_snapshot=None):...@@ -568,7 +568,7 @@ def handle(name, request, *, active_snapshot=None):
568 return {'running': False}568 return {'running': False}
569 finish_operation(name, unfinished)569 finish_operation(name, unfinished)
570 return {'running': False, 'cancelled': True, 'id': identity}570 return {'running': False, 'cancelled': True, 'id': identity}
571 if vms.mac_vms.CONFIG and name == vms.mac_vms.CONFIG['name']:571 if vms.mac_vms.owns(name):
572 return vms.mac_vms.handle('computer', {'name':name,'request':request})572 return vms.mac_vms.handle('computer', {'name':name,'request':request})
573 token = DEADLINE.set(time.monotonic() + 210)573 token = DEADLINE.set(time.monotonic() + 210)
574 operation_token = None574 operation_token = None
tools/vms.py+2-2
...@@ -203,7 +203,7 @@ def validate(action, payload):...@@ -203,7 +203,7 @@ def validate(action, payload):
203 for field, minimum, maximum in [("vcpus", 1, host["cpus"]), ("memory", 2**29, host["memory"]), ("disk", 2**30, 2**63 - 1)]:203 for field, minimum, maximum in [("vcpus", 1, host["cpus"]), ("memory", 2**29, host["memory"]), ("disk", 2**30, 2**63 - 1)]:
204 if type(payload[field]) is not int or not minimum <= payload[field] <= maximum:204 if type(payload[field]) is not int or not minimum <= payload[field] <= maximum:
205 raise ValueError(f"Choose {field} within the host's supported range.")205 raise ValueError(f"Choose {field} within the host's supported range.")
206 if action == "create" and mac_vms.CONFIG and payload["name"] == mac_vms.CONFIG["name"]:206 if action == "create" and mac_vms.owns(payload["name"]):
207 raise ValueError("A VM already has this name. Choose another name.")207 raise ValueError("A VM already has this name. Choose another name.")
208 if DISKS.is_symlink() or (DISKS / payload["name"]).is_symlink():208 if DISKS.is_symlink() or (DISKS / payload["name"]).is_symlink():
209 raise ValueError("The VM disk directory is a symbolic link. Remove the link before continuing.")209 raise ValueError("The VM disk directory is a symbolic link. Remove the link before continuing.")
...@@ -1106,7 +1106,7 @@ def main():...@@ -1106,7 +1106,7 @@ def main():
1106 return result1106 return result
1107 if action == "library":1107 if action == "library":
1108 return library()1108 return library()
1109 if mac_vms.CONFIG and isinstance(payload, dict) and payload.get("name") == mac_vms.CONFIG["name"]:1109 if isinstance(payload, dict) and mac_vms.owns(payload.get("name")):
1110 return mac_vms.handle(action, payload)1110 return mac_vms.handle(action, payload)
1111 if action == "console":1111 if action == "console":
1112 return console_target(payload["name"])1112 return console_target(payload["name"])