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 @@
11{ ... }:
22let
33 workspace = builtins.fromJSON (builtins.readFile ../config/mac-studio-sandbox.json);
4 owner = "8c909fab-98b0-4472-9171-9606ccebe9d5";
45in {
56 systemd.services.snowglobe-host = {
67 environment.SNOWGLOBE_MAC_VM = builtins.toJSON {
7 name = "m3-devbox";
8 owner = "8c909fab-98b0-4472-9171-9606ccebe9d5";
98 address = workspace.clientAddress;
109 port = 22;
1110 user = "clo";
1211 identity = "/var/lib/snowglobe/mac-vm/ssh_key";
1312 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 ];
1417 };
1518 serviceConfig.IPAddressAllow = [ "${workspace.clientAddress}/32" ];
1619 };
tools/dashboard-host-test.py+1-1
......@@ -213,7 +213,7 @@ class Host:
213213 while not (root / 'release').exists(): time.sleep(.01)
214214 return {'operation': request['operation'], 'active_snapshot': active_snapshot}
215215m.Host = Host
216m.vms.mac_vms.CONFIG = {'name': 'managed-mac'}
216m.vms.mac_vms.CONFIG = {'vms': [{'name': 'managed-mac'}]}
217217with m.vms.computer_lock('fixture', 'exec') as active, m.vms.computer_lock('managed-mac', 'exec'):
218218 (root / 'active.json').write_text(json.dumps(active))
219219 m.main()
tools/dashboard-host.py+3-3
......@@ -217,7 +217,7 @@ class Host:
217217 except ValueError as error:
218218 raise Rejected(str(error)) from error
219219 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"]):
221221 raise Rejected("This VM does not support this guest operation.")
222222 try:
223223 return vms.mac_vms.handle(action, payload)
......@@ -385,7 +385,7 @@ def stream_console(connection, host, request):
385385 screen.connect(details["path"])
386386 screen.setblocking(False)
387387 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))
389389 screen.setblocking(False)
390390 else:
391391 identity = details["uuid"]
......@@ -533,7 +533,7 @@ def serve_connection(connection, host, allowed_uid, allowed_operations=None):
533533 operation_handle = action.get("action") == "process" and isinstance(identity, str) and identity.startswith("operation:")
534534 control = operation_handle and action.get("operation") == "status"
535535 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"])
537537 ):
538538 active_snapshot = vms.computer_activity(payload["name"])
539539 control = active_snapshot is not None
tools/dashboard-stage.py+6-3
......@@ -148,9 +148,11 @@ def stage(computer=None):
148148 selected = saved["computer"].split(",")
149149 for name in selected:
150150 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"]):
152152 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"]:
154156 mac = None
155157 nix = ["nix", "--extra-experimental-features", "nix-command flakes"]
156158 package = "path:" + str(snowglobe.REPO) + "#dashboard-image"
......@@ -229,7 +231,8 @@ def stage(computer=None):
229231 owner = accounts.execute("SELECT id FROM users WHERE username='preview'").fetchone()
230232 if not owner:
231233 raise ValueError("The preview account is unavailable.")
232 mac["owner"] = owner[0]
234 for entry in mac["vms"]:
235 entry["owner"] = owner[0]
233236 computer_environment.append("--setenv=SNOWGLOBE_MAC_VM=" + json.dumps(mac))
234237 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()
235238 subprocess.run(["systemctl", "stop", "snowglobe-preview-screen-" + identity], capture_output=True)
tools/install-mac-computer.py+7-5
......@@ -1,17 +1,19 @@
11#!/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."""
33from importlib import import_module
44import json
55import os
66from pathlib import Path
7import sys
78import tempfile
89
910vm = import_module("mac-agent-vm")
1011root = 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()
1214print("Installing guest tools in " + identity, flush=True)
1315source = {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", '''
1517import json, pathlib, subprocess, sys, tempfile
1618files = json.load(sys.stdin)
1719with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary:
......@@ -23,7 +25,7 @@ with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as tempor
2325 for source, destination in [("mac-computer.py", "/usr/local/libexec/snowglobe-computer.py"), ("agent-gui", "/usr/local/bin/agent-gui")]:
2426 subprocess.run(["sudo", "-n", "install", "-m", "755", str(root / source), destination], check=True)
2527''', 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 []:
2729 target = vm.ROOT / "runtime/control" / name
2830 with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as outgoing:
2931 pending = Path(outgoing.name)
......@@ -33,7 +35,7 @@ for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]:
3335 os.replace(pending, target)
3436 finally:
3537 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",
3739 input=b'{"action":"status"}', capture_output=True, timeout=15)
3840value = json.loads(result.stdout)
3941if 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):
7171 tart.write_text("#!/usr/bin/python3\n" + output + "\n")
7272 tart.chmod(0o700)
7373 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
7777if __name__ == "__main__":
tools/mac-vm-bridge.py+44-8
......@@ -1,5 +1,5 @@
11#!/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."""
33import fcntl
44from importlib import import_module
55import json
......@@ -13,6 +13,10 @@ import tempfile
1313import time
1414
1515vm = 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
1822def status():
......@@ -38,18 +42,27 @@ def status():
3842 "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
4154def respond(value):
4255 data = json.dumps(value).encode()
4356 sys.stdout.buffer.write(struct.pack("!I", len(data)) + data)
4457 sys.stdout.buffer.flush()
4558
4659
47def computer(request):
60def computer(name, request):
4861 with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector:
4962 source.write(json.dumps(request).encode())
5063 source.seek(0)
5164 # 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",
5366 "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE,
5467 stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")})
5568 output = bytearray()
......@@ -108,6 +121,18 @@ def lifecycle(action):
108121 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
111136def main():
112137 line = sys.stdin.buffer.readline(1048577)
113138 if len(line) > 1048576 or not line.endswith(b"\n"):
......@@ -115,25 +140,36 @@ def main():
115140 request = json.loads(line)
116141 if not isinstance(request, dict):
117142 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
118149 action = request.get("action")
119150 if action == "status" and set(request) == {"action"}:
120 respond({"value": status()})
151 respond({"value": {**(status() if primary else locked_status(name)), "name": name}})
121152 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.")
122155 action = {"shutdown": "stop", "resume": "start"}.get(action, action)
123 lifecycle(action)
156 if primary:
157 lifecycle(action)
158 else:
159 locked_power(name, action)
124160 respond({"value": None})
125161 elif action == "clipboard" and set(request) == {"action", "text"}:
126162 value = request["text"]
127163 if not isinstance(value, str) or len(value.encode()) > 262144:
128164 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",
130166 input=value.encode(), capture_output=True, timeout=15)
131167 respond({"value": None})
132168 elif action == "computer" and set(request) == {"action", "request"}:
133169 if not isinstance(request["request"], dict):
134170 raise ValueError("Send a computer operation.")
135 respond({"value": computer(request["request"])})
136 elif action == "console" and set(request) == {"action"}:
171 respond({"value": computer(name, request["request"])})
172 elif action == "console" and set(request) == {"action"} and primary:
137173 with vm.guest_screen() as upstream:
138174 respond({"value": None})
139175 try:
tools/mac-vm-test.py+76-5
......@@ -19,11 +19,16 @@ bridge = import_module("mac-vm-bridge")
1919backend = 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
2226class MacVMTests(unittest.TestCase):
2327 def test_protocol_rejects_arbitrary_commands_and_unbounded_clipboards(self):
2428 for request in [{"action": "exec", "command": "id"}, {"action": "status", "name": "other"},
2529 {"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"]}]:
2732 with self.subTest(request=str(request)[:80]), \
2833 patch.object(sys, "stdin", io.TextIOWrapper(io.BytesIO(json.dumps(request).encode() + b"\n"))), \
2934 patch.object(bridge.vm, "tart") as tart, patch.object(bridge, "lifecycle") as lifecycle:
......@@ -49,7 +54,7 @@ class MacVMTests(unittest.TestCase):
4954 "pendingAction": None, "disk": {"capacity": 128 * 2**30, "allocation": 42 * 2**30},
5055 "mac": "00:11:22:33:44:55"}, None
5156 with tempfile.TemporaryDirectory() as directory, \
52 patch.object(backend, "CONFIG", {"name": "mac-fixture", "owner": "fixture-owner"}), \
57 patch.object(backend, "CONFIG", FIXTURE), \
5358 patch.object(backend, "CACHE", Path(directory) / "cache.json"):
5459 with patch.object(backend, "connect", side_effect=ValueError("offline")):
5560 first = backend.domain()[0]
......@@ -66,21 +71,87 @@ class MacVMTests(unittest.TestCase):
6671 self.assertEqual(offline["name"], "mac-fixture")
6772 self.assertEqual(offline["owner"], "fixture-owner")
6873 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})
7075 self.assertEqual(offline["memory"], live["memory"])
7176 self.assertEqual(offline["state"], "unreachable")
7277 self.assertIsNone(offline["agent"])
7378 self.assertIsNone(offline["pendingAction"])
7479
7580 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:
7782 for action in ["delete", "update", "preset", "media"]:
7883 with self.subTest(action=action), self.assertRaises(ValueError):
7984 backend.handle(action, {"name": "mac-fixture"})
8085 with self.assertRaises(ValueError):
81 backend.handle("act", {"action": "destroy"})
86 backend.handle("act", {"name": "mac-fixture", "action": "destroy"})
8287 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
84155 def test_lifecycle_timeout_reaps_commands_but_preserves_detached_runner(self):
85156 with tempfile.TemporaryDirectory() as directory:
86157 root = Path(directory)
tools/mac-vms.py+46-22
......@@ -1,3 +1,4 @@
1import concurrent.futures
12import contextlib
23import json
34import os
......@@ -9,12 +10,19 @@ import tempfile
910
1011
1112CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null"))
12CAPABILITIES = ["start", "shutdown", "reboot", "suspend", "resume", "clipboard", "computer"]
1313CACHE = 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
1624@contextlib.contextmanager
17def connect(request, timeout=10):
25def connect(name, request, timeout=10):
1826 if not CONFIG:
1927 raise ValueError("The Mac VM is not configured on this host.")
2028 parent, child = socket.socketpair()
......@@ -30,7 +38,7 @@ def connect(request, timeout=10):
3038 ], stdin=child, stdout=child, stderr=subprocess.DEVNULL)
3139 child.close()
3240 parent.settimeout(timeout)
33 parent.sendall(json.dumps(request).encode() + b"\n")
41 parent.sendall(json.dumps({**request, "vm": name}).encode() + b"\n")
3442
3543 def read(size):
3644 data = bytearray()
......@@ -68,56 +76,72 @@ def connect(request, timeout=10):
6876 process.wait()
6977
7078
71def ownership():
72 return {"owner": CONFIG["owner"], "ownerOnly": True}
79def ownership(entry):
80 return {"owner": entry["owner"], "ownerOnly": True}
7381
7482
75def domain():
76 if not CONFIG:
77 return []
78 value = {"name": CONFIG["name"], **ownership(), "host": "Mac Studio", "arch": "aarch64",
83def power(entry):
84 return ["start", "shutdown", "reboot"] + (["suspend", "resume"] if entry["suspend"] else [])
85
86
87def observe(entry):
88 value = {"name": entry["name"], **ownership(entry), "host": "Mac Studio", "arch": "aarch64",
7989 "state": "unreachable", "reason": None,
8090 "os": "macOS", "vcpus": None, "memory": None, "balloon": None, "pinned": None,
8191 "autostart": False, "startedAt": None, "agent": None, "setup": None, "pendingAction": None,
82 "disks": [], "media": [], "firmware": "uefi", "platform": "macos", "console": True,
83 "serial": False, "interfaces": [], "hostdevs": [], "capabilities": CAPABILITIES}
92 "disks": [], "media": [], "firmware": "uefi", "platform": "macos", "console": entry["console"],
93 "serial": False, "interfaces": [], "hostdevs": [], "capabilities": power(entry) + ["clipboard", "computer"]}
8494 try:
85 with connect({"action": "status"}, timeout=8) as (status, _):
95 with connect(entry["name"], {"action": "status"}, timeout=8) as (status, _):
8696 value.update({key: status[key] for key in ("state", "vcpus", "memory", "agent", "pendingAction")})
8797 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"]}]
8999 value["interfaces"] = [{"source": "Mac Studio NAT", "mac": status["mac"], "addresses": []}]
90100 except (ValueError, OSError, KeyError, TypeError):
91101 try:
92 previous = json.loads(CACHE.read_text())
102 previous = json.loads(CACHE.read_text())[entry["name"]]
93103 for key in ("vcpus", "memory", "balloon", "disks", "interfaces"):
94104 value[key] = previous[key]
95105 except (ValueError, OSError, KeyError, TypeError):
96106 pass
97107 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:
99118 try:
100119 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
101124 descriptor, temporary = tempfile.mkstemp(dir=CACHE.parent, prefix=".mac-vm-")
102125 try:
103126 with os.fdopen(descriptor, "w") as outgoing:
104 json.dump(value, outgoing)
127 json.dump(live, outgoing)
105128 os.replace(temporary, CACHE)
106129 finally:
107130 Path(temporary).unlink(missing_ok=True)
108131 except OSError:
109132 pass
110 return [value]
133 return [value for value, _ in observed]
111134
112135
113136def handle(action, payload):
137 entry = vm(payload["name"])
114138 if action == "owner":
115 return ownership()
139 return ownership(entry)
116140 if action == "access":
117141 return None
118 if action == "console":
119 return {"remote": True}
120 if action == "act" and payload["action"] in {"start", "shutdown", "reboot", "suspend", "resume"}:
142 if action == "console" and entry["console"]:
143 return {"remote": True, "name": entry["name"]}
144 if action == "act" and payload["action"] in power(entry):
121145 request = {"action": payload["action"]}
122146 elif action == "clipboard":
123147 request = {"action": "clipboard", "text": payload["text"]}
......@@ -125,5 +149,5 @@ def handle(action, payload):
125149 request = {"action": "computer", "request": payload["request"]}
126150 else:
127151 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, _):
129153 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):
536536 validate(request)
537537 vms.ensure_name(name)
538538 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):
540540 raise ValueError('This VM does not provide active operation handles.')
541541 identity = request['id']
542542 with vms.computer_control(name) as control:
......@@ -568,7 +568,7 @@ def handle(name, request, *, active_snapshot=None):
568568 return {'running': False}
569569 finish_operation(name, unfinished)
570570 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):
572572 return vms.mac_vms.handle('computer', {'name':name,'request':request})
573573 token = DEADLINE.set(time.monotonic() + 210)
574574 operation_token = None
tools/vms.py+2-2
......@@ -203,7 +203,7 @@ def validate(action, payload):
203203 for field, minimum, maximum in [("vcpus", 1, host["cpus"]), ("memory", 2**29, host["memory"]), ("disk", 2**30, 2**63 - 1)]:
204204 if type(payload[field]) is not int or not minimum <= payload[field] <= maximum:
205205 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"]):
207207 raise ValueError("A VM already has this name. Choose another name.")
208208 if DISKS.is_symlink() or (DISKS / payload["name"]).is_symlink():
209209 raise ValueError("The VM disk directory is a symbolic link. Remove the link before continuing.")
......@@ -1106,7 +1106,7 @@ def main():
11061106 return result
11071107 if action == "library":
11081108 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")):
11101110 return mac_vms.handle(action, payload)
11111111 if action == "console":
11121112 return console_target(payload["name"])