authoravatarclover caruso<git@paperclover.net>2026-10-21 19:30:36-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-24 19:01:23-07:00
logbc97ccbb76c079f855e64b943306227f3cf9e5ce
tree561d16f5552668400a13321e5e2adb402f9a9cb9
parent3adad9767eb19ab651b35e1f76b7f4a358df0225
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Add owner-scoped computer MCP for the Mac devbox

Expose screenshots, accessibility inspection, and bounded guest scripts through per-VM OAuth grants. Install the Mac guest worker and provide explicit preview access to the configured devbox. Verify ownership, scopes, revocation, desktop input, and process timeout cleanup. Assisted-by: gpt-6-astra

21 files changed, 573 insertions(+), 27 deletions(-)

dashboard/src/computer.rs created+141
......@@ -0,0 +1,141 @@
1use crate::*;
2use rmcp::{
3 ErrorData, RoleServer, ServerHandler,
4 model::{
5 CacheScope, CallToolRequestParams, CallToolResponse, CallToolResult, ContentBlock,
6 ListToolsResult, PaginatedRequestParams, ServerCapabilities, ServerConfig, Tool,
7 ToolAnnotations,
8 },
9 service::RequestContext,
10};
11
12pub async fn resources(owner: &Value) -> Result<Vec<Value>> {
13 let domains = host::call(json!({"operation":"vm.domains"})).await?;
14 Ok(array(&domains)
15 .iter()
16 .filter(|vm| {
17 vm["owner"] == owner["id"] && array(&vm["capabilities"]).iter().any(|c| c == "computer")
18 })
19 .map(|vm| json!({"id":vm["name"],"name":vm["name"],"description":vm["description"]}))
20 .collect())
21}
22
23fn permitted(grant: &Value, vm: &str, scope: &str, owner: &Value) -> Result<()> {
24 if !array(&grant["scopes"]).iter().any(|s| s == scope)
25 || !array(&grant["resources"]).iter().any(|id| id == vm)
26 || owner["owner"].as_str().is_none()
27 || owner["owner"] != grant["user"]
28 {
29 return Err(Error::new(
30 403,
31 "This VM is outside the connection's access. Update access in MCP settings.",
32 ));
33 }
34 Ok(())
35}
36
37#[derive(Clone)]
38struct Computer;
39impl ServerHandler for Computer {
40 fn get_info(&self) -> ServerConfig {
41 ServerConfig::new(ServerCapabilities::builder().enable_tools().build())
42 }
43 async fn list_tools(
44 &self,
45 _: Option<PaginatedRequestParams>,
46 _: RequestContext<RoleServer>,
47 ) -> std::result::Result<ListToolsResult, ErrorData> {
48 let tools = [
49 ("computer_list", "List granted VMs with computer-use support.", json!({}), json!([])),
50 ("computer_status", "Check a VM's desktop permissions and scripting capabilities.", json!({"vm":{"type":"string"}}), json!(["vm"])),
51 ("computer_shot", "Capture the selected VM's current desktop as an image.", json!({"vm":{"type":"string"}}), json!(["vm"])),
52 ("computer_ui", "Read a bounded macOS accessibility tree, including roles, values, bounds and available actions. Use an application PID to inspect that app, or omit it for the frontmost app. Read a fresh tree before using its child paths.", json!({"vm":{"type":"string"},"pid":{"type":"integer","minimum":1}}), json!(["vm"])),
53 ("computer_exec", "Run a zsh script inside the selected Mac VM's logged-in desktop. Returns exit status, stdout/stderr (64 KiB each), and optionally a screenshot. Batch actions into one script. Use /usr/local/bin/agent-gui tree [PID], press PID 0.1.2, click X Y, key CODE [command|shift|option|control], and type - (UTF-8 stdin). Coordinates use macOS screen points; compare screenshot dimensions with display bounds before pixel input. sudo -n is available for guest setup. Timeout kills the script process group. For long-lived apps, redirect stdin/stdout/stderr before backgrounding. Never assume a timed-out command did not run.", json!({"vm":{"type":"string"},"script":{"type":"string","maxLength":65536},"timeout_ms":{"type":"integer","minimum":1,"maximum":180000,"default":60000},"screenshot":{"type":"boolean","default":true}}), json!(["vm","script"])),
54 ].into_iter().map(|(name, description, properties, required)| {
55 Tool::new(name, description, json!({"type":"object","properties":properties,"required":required,"additionalProperties":false}).as_object().unwrap().clone())
56 .with_annotations(ToolAnnotations::new().read_only(name != "computer_exec"))
57 }).collect();
58 Ok(ListToolsResult {
59 tools,
60 ttl_ms: Some(0),
61 cache_scope: Some(CacheScope::Private),
62 ..Default::default()
63 })
64 }
65 async fn call_tool(
66 &self,
67 request: CallToolRequestParams,
68 context: RequestContext<RoleServer>,
69 ) -> std::result::Result<CallToolResponse, ErrorData> {
70 let result: Result<Value> = async {
71 let grant = &context.extensions.get::<axum::http::request::Parts>()
72 .and_then(|p| p.extensions.get::<mcp::Grant>())
73 .ok_or_else(|| Error::new(401, "This connection expired. Connect again."))?.0;
74 let mut arguments = request.arguments.unwrap_or_default();
75 if request.name == "computer_list" {
76 if !arguments.is_empty() { return Err(Error::new(400, "This tool takes no arguments.")); }
77 return Ok(json!({"computers":resources(&json!({"id":grant["user"]})).await?.into_iter()
78 .filter(|vm| array(&grant["resources"]).iter().any(|id| id == &vm["id"])).collect::<Vec<_>>()}));
79 }
80 let vm = arguments.remove("vm").and_then(|v| v.as_str().map(str::to_owned))
81 .filter(|s| !s.is_empty() && s.len() <= 63)
82 .ok_or_else(|| Error::new(400, "Choose a granted VM."))?;
83 if !array(&grant["resources"]).iter().any(|id| id == &vm) {
84 return Err(Error::new(403, "Choose a VM granted to this connection."));
85 }
86 let scope = if request.name == "computer_exec" { "computer:control" } else { "computer:read" };
87 let owner = host::call(json!({"operation":"vm.owner","payload":{"name":vm}})).await?;
88 permitted(grant, &vm, scope, &owner)?;
89 let operation = match request.name.as_ref() {
90 "computer_status" => json!({"action":"status"}),
91 "computer_shot" => json!({"action":"shot"}),
92 "computer_ui" => json!({"action":"ui","pid":arguments.remove("pid")}),
93 "computer_exec" => json!({"action":"exec", "script":arguments.remove("script"),
94 "timeout_ms":arguments.remove("timeout_ms").unwrap_or(json!(60000)),
95 "screenshot":arguments.remove("screenshot").unwrap_or(json!(true))}),
96 _ => return Err(Error::new(404, "No tool with that name.")),
97 };
98 if !arguments.is_empty() { return Err(Error::new(400, "Use the fields listed for this tool.")); }
99 host::call(json!({"operation":"vm.computer","payload":{"name":vm,"request":operation}})).await
100 }.await;
101 Ok(match result {
102 Ok(mut value) => {
103 let png = value.as_object_mut().and_then(|v| v.remove("png"));
104 let mut content = vec![ContentBlock::text(value.to_string())];
105 if let Some(png) = png.and_then(|v| v.as_str().map(str::to_owned)) {
106 content.push(ContentBlock::image(png, "image/png"));
107 }
108 CallToolResult::success(content)
109 }
110 Err(error) => CallToolResult::error(vec![ContentBlock::text(error.message)]),
111 }
112 .into())
113 }
114}
115
116pub fn router(app: Arc<App>) -> Router {
117 mcp::router(app, "computer", || Ok(Computer))
118}
119
120#[cfg(test)]
121mod tests {
122 use super::*;
123 #[test]
124 fn control_requires_the_current_owner_selected_vm_and_scope() {
125 let grant = json!({"user":"clover","scopes":["computer:read"],"resources":["m3-devbox"]});
126 let owner = json!({"owner":"clover","ownerOnly":true});
127 assert!(permitted(&grant, "m3-devbox", "computer:read", &owner).is_ok());
128 assert!(permitted(&grant, "m3-devbox", "computer:control", &owner).is_err());
129 assert!(permitted(&grant, "other", "computer:read", &owner).is_err());
130 assert!(
131 permitted(
132 &grant,
133 "m3-devbox",
134 "computer:read",
135 &json!({"owner":"another-user"})
136 )
137 .is_err()
138 );
139 assert!(permitted(&grant, "m3-devbox", "computer:read", &Value::Null).is_err());
140 }
141}
dashboard/src/host.rs+1-1
......@@ -34,7 +34,7 @@ pub async fn open(request: Value) -> Result<(Value, tokio::net::UnixStream)> {
3434 Some("vm.create" | "vm.media" | "vm.preset")
3535 ) {
3636 910
37 } else if request["operation"] == "vm.act" {
37 } else if matches!(request["operation"].as_str(), Some("vm.act" | "vm.computer")) {
3838 240
3939 } else if request["operation"] == "copyparty.manage" {
4040 310
dashboard/src/main.rs+2
......@@ -4,6 +4,7 @@ mod auth;
44mod atproto;
55mod identity;
66mod cache;
7mod computer;
78mod core;
89mod deploys;
910mod files;
......@@ -593,6 +594,7 @@ async fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
593594 .nest_service("/assets", ServeDir::new(format!("{dist}/assets")))
594595 .with_state(app.clone())
595596 .merge(observability::router(app.clone()))
597 .merge(computer::router(app.clone()))
596598 .merge(shale::router(app.clone()))
597599 .merge(relay::router(app.clone()))
598600 .fallback_service(
dashboard/src/mcp.rs+8-1
......@@ -8,6 +8,7 @@ use sha2::{Digest, Sha256};
88use std::os::unix::fs::{DirBuilderExt, PermissionsExt};
99
1010const CATALOGS: &[(&str, &str, &[&str])] = &[
11 ("computer", "Computers", &["computer:read", "computer:control", "offline_access"]),
1112 (
1213 "observability",
1314 "Logs and traces",
......@@ -499,6 +500,8 @@ pub(crate) fn active_owner(app: &App, grant: &Value) -> Result<bool> {
499500 };
500501 Ok(profile["enabled"] == true
501502 && !guest::is_guest(&profile)
503 && (grant["resource"] != app.mcp.resource("computer")
504 || array(&profile["groups"]).iter().any(|role| matches!(role["name"].as_str(), Some("vm" | "infra-admin"))))
502505 && (grant["resource"] != app.mcp.resource("observability")
503506 || array(&profile["groups"])
504507 .iter()
......@@ -794,6 +797,10 @@ pub async fn manage(
794797 }
795798 Err(error) => return Err(error),
796799 }
800 } else if consent_resource == app.mcp.resource("computer")
801 && array(&me["sections"]).iter().any(|s| s == "vms")
802 {
803 computer::resources(&owner).await?
797804 } else if consent_resource == app.mcp.resource("observability")
798805 && array(&me["sections"]).iter().any(|s| s == "admin")
799806 && array(&owner["groups"])
......@@ -1062,7 +1069,7 @@ mod tests {
10621069 json!({"client_name":"Codex","redirect_uris":[uri]})).unwrap()).await;
10631070 let mut request = fields(json!({"response_type":"code","client_id":client["client_id"],"state":"fixture-state",
10641071 "code_challenge":"AdJpfUsRa6XMg54f2khmgo2onMwePN3vmU9DOOoaTzo","code_challenge_method":"S256",
1065 "redirect_uri":uri,"scope":"observability:read offline_access sessions:read sessions:write shale:read shale:write"}));
1072 "redirect_uri":uri,"scope":"observability:read offline_access sessions:read sessions:write shale:read shale:write computer:read computer:control"}));
10661073 for (catalog, _, allowed) in CATALOGS {
10671074 request.insert("resource".into(), fixture.store.resource(catalog));
10681075 let response = fixture.store.oauth("authorize", &Method::GET, &request, &HeaderMap::new(), Value::Null).unwrap();
dashboard/web/pages/MCP.tsx+13-5
......@@ -16,6 +16,7 @@ import type { Access, Catalog } from "../types/mcp.ts";
1616import "./MCP.css";
1717
1818const descriptions: Record<Catalog, string> = {
19 computer: "Inspect and control selected virtual machines, run commands, and install guest software.",
1920 shale: "Read and edit issues across your Shale repositories.",
2021 agents: "Connect to Codex and Claude Code on your machines.",
2122 observability: "Read logs and traces from your services.",
......@@ -148,9 +149,16 @@ export function MCP(props: { me: Me }) {
148149 </Show>
149150 <section class="mcp-panel"><h2>Connected clients</h2>
150151 <Show when={connections().length} fallback={<p class="muted">No clients connected. Add the connector URL to your AI client to get started.</p>}>
151 <div class="mcp-client-list"><For each={connections()}>{(client) => <article class="mcp-client">
152 <div><h3>{client.name}</h3><p>{client.resources === "all" ? "All Repositories" : client.resources.join(", ")}</p><p class="muted">{client.scopes.includes("sessions:write") ? "Session control" : client.scopes.includes("shale:write") ? "Issue editing" : "Read only"} · Connected <Ago t={client.createdAt} /></p></div>
153 <div class="mcp-actions"><button class="button small" disabled={busy()} onClick={() => setEditing(editing() === client.id ? "" : client.id)}>Edit access</button>
152 <div class="mcp-client-list"><For each={connections()}>{(client) => {
153 let editButton!: HTMLButtonElement;
154 const cancel = () => { setEditing(""); editButton.focus(); };
155 return <article class="mcp-client" onKeyDown={(event) => {
156 if (event.key === "Escape" && editing() === client.id && !busy()) {
157 event.preventDefault(); event.stopPropagation(); cancel();
158 }
159 }}>
160 <div><h3>{client.name}</h3><p>{client.resources === "all" ? "All Repositories" : client.resources.join(", ")}</p><p class="muted">{client.scopes.includes("computer:control") ? "VM control and commands" : client.scopes.includes("sessions:write") ? "Session control" : client.scopes.includes("shale:write") ? "Issue editing" : "Read only"} · Connected <Ago t={client.createdAt} /></p></div>
161 <div class="mcp-actions"><button ref={editButton} class="button small" aria-expanded={editing() === client.id} disabled={busy()} onClick={() => setEditing(editing() === client.id ? "" : client.id)}>Edit access</button>
154162 <button class="button small" disabled={busy()} onClick={() => showConfirmDialog({ title: "Revoke this connection?", description: `${client.name} will lose access immediately.`, confirmLabel: "Revoke", destructive: true, onConfirm: async () => {
155163 await parseResponse(api.mcp.connections[":id"].$delete({ param: { id: client.id } })); if (editing() === client.id) setEditing(""); await refetch(); toast("Connection revoked");
156164 } })}>Revoke</button></div>
......@@ -164,11 +172,11 @@ export function MCP(props: { me: Me }) {
164172 try { await parseResponse(api.mcp.connections[":id"].$post({ param: { id: client.id }, json: { resources: selection() } })); setEditing(""); await refetch(); }
165173 catch (error) { toast(reason(error)); }
166174 finally { setBusy(false); }
167 }}>Save access</button><button class="button" disabled={busy()} onClick={() => setEditing("")}>Cancel</button></div>
175 }}>Save access</button><button class="button" disabled={busy()} onClick={cancel}>Cancel</button></div>
168176 </Show>}
169177 </Loaded>
170178 </div></Show>
171 </article>}</For></div>
179 </article>; }}</For></div>
172180 </Show>
173181 </section>
174182 </>}</Show>
dashboard/web/pages/MCPAccess.tsx+2-2
......@@ -10,7 +10,7 @@ export function MCPAccess(props: {
1010 disabled: boolean;
1111}) {
1212 return <fieldset class="mcp-access" disabled={props.disabled}>
13 <legend>{props.catalog === "shale" ? "Repositories" : props.catalog === "agents" ? "Machines" : "Services"}</legend>
13 <legend>{props.catalog === "computer" ? "Virtual machines" : props.catalog === "shale" ? "Repositories" : props.catalog === "agents" ? "Machines" : "Services"}</legend>
1414 <Show when={props.catalog === "shale"}>
1515 <div class="mcp-access-modes">
1616 <label><input type="radio" name="repository-access" checked={props.value === "all"} onChange={() => props.onChange("all")} />
......@@ -28,7 +28,7 @@ export function MCPAccess(props: {
2828 props.onChange(checked ? [...selected, resource.id] : selected.filter((id) => id !== resource.id));
2929 }}><span>{resource.name}<Show when={resource.description}><small class="muted">{resource.description}</small></Show></span></Checkbox>
3030 }</For></div>
31 <Show when={!props.resources.length}><p class="muted">{props.catalog === "agents" ? "No machines linked. Link a machine in MCP settings before connecting a client." : props.catalog === "shale" ? "No repositories available to select." : "No services available to your account."}</p></Show>
31 <Show when={!props.resources.length}><p class="muted">{props.catalog === "computer" ? "No supported VMs belong to your account." : props.catalog === "agents" ? "No machines linked. Link a machine in MCP settings before connecting a client." : props.catalog === "shale" ? "No repositories available to select." : "No services available to your account."}</p></Show>
3232 </Show>
3333 </fieldset>;
3434}
dashboard/web/pages/MCPConsent.tsx+3-2
......@@ -58,10 +58,11 @@ export function MCPConsent() {
5858 </>}>
5959 {(data) => <>
6060 <h1 id="connection-title">Connect {data().client}</h1>
61 <p class="mcp-approval-intro">{data().catalog === "shale" ? "Grant access to Shale issues." : data().catalog === "agents" ? "Grant access to your local agents." : "Grant access to logs and traces."}</p>
61 <p class="mcp-approval-intro">{data().catalog === "computer" ? "Grant access to selected virtual machines." : data().catalog === "shale" ? "Grant access to Shale issues." : data().catalog === "agents" ? "Grant access to your local agents." : "Grant access to logs and traces."}</p>
6262 <dl class="mcp-request-identity"><div><dt>Signed in as</dt><dd>{data().account}</dd></div><div><dt>Return to</dt><dd>{data().redirectHost}</dd></div></dl>
6363 <div class="mcp-permissions"><h2>Requested access</h2>
64 <p>{data().catalog === "shale" ? "Read issues and comments" : data().catalog === "agents" ? "Read saved chats" : "Read logs and traces"}</p>
64 <p>{data().catalog === "computer" ? "Read VM status, screenshots, and application controls" : data().catalog === "shale" ? "Read issues and comments" : data().catalog === "agents" ? "Read saved chats" : "Read logs and traces"}</p>
65 <Show when={data().scopes.includes("computer:control")}><p>Control the desktop, run commands, and install software inside the selected VMs</p></Show>
6566 <Show when={data().scopes.includes("shale:write")}><p>Create issues, comment, and edit issue titles and status</p></Show>
6667 <Show when={data().scopes.includes("sessions:write")}><p>Send messages, start chats, and interrupt turns</p></Show>
6768 <Show when={data().scopes.includes("offline_access")}><p>Stay connected without signing in again</p></Show>
dashboard/web/types/mcp.ts+1-1
......@@ -1,4 +1,4 @@
1export type Catalog = "shale" | "agents" | "observability";
1export type Catalog = "shale" | "agents" | "observability" | "computer";
22export type Access = "all" | string[];
33export type Resources = { id: string; name: string; description?: string }[];
44
tools/dashboard-host.py+2-2
......@@ -186,9 +186,9 @@ class Host:
186186 vms.validate(action, payload)
187187 except ValueError as error:
188188 raise Rejected(str(error)) from error
189 if action == "clipboard":
189 if action in {"clipboard", "computer"}:
190190 if not vms.mac_vms.CONFIG or payload["name"] != vms.mac_vms.CONFIG["name"]:
191 raise Rejected("Use this VM's screen clipboard.")
191 raise Rejected("This VM does not support this guest operation.")
192192 try:
193193 return vms.mac_vms.handle(action, payload)
194194 except ValueError as error:
tools/dashboard-stage-test.py+11-1
......@@ -34,7 +34,7 @@ class PreviewBoundary(unittest.TestCase):
3434 return json.loads(sent[4:]), host
3535
3636 def test_denies_host_mutations_and_vm_streams_before_dispatch(self):
37 for operation in ["vm.create", "vm.start", "vm.console", "vm.serial", "vm.guest", "vm.upload", "storage.destroy", "deploy.start", "deploy.secret.get", "shale.write", "copyparty.manage", []]:
37 for operation in ["vm.create", "vm.start", "vm.console", "vm.serial", "vm.guest", "vm.upload", "vm.computer", "vm.owner", "storage.destroy", "deploy.start", "deploy.secret.get", "shale.write", "copyparty.manage", []]:
3838 with self.subTest(operation=operation):
3939 response, host = self.call({"operation": operation})
4040 self.assertEqual(response["status"], 403)
......@@ -53,6 +53,16 @@ class PreviewBoundary(unittest.TestCase):
5353 with self.assertRaisesRegex(ValueError, "invalid dashboard stage"):
5454 stage.metadata(identity)
5555
56 def test_attached_computer_cannot_target_another_vm(self):
57 host = stage.PreviewHost({"clone": "globe/staging/fixture", "computer": "mac-fixture"})
58 with patch.object(boundary.Host, "handle", return_value={"ok": True}) as call:
59 for operation in ["vm.computer", "vm.owner"]:
60 with self.assertRaises(boundary.dashboard_runs.Error):
61 host.handle({"operation": operation, "payload": {"name": "personal"}})
62 call.assert_not_called()
63 self.assertEqual(host.handle({"operation": operation, "payload": {"name": "mac-fixture"}}), {"ok": True})
64 call.reset_mock()
65
5666 def test_file_operations_cannot_name_production_or_account_dataset(self):
5767 dataset = "globe/staging/dashboard-preview-12345678"
5868 host = stage.PreviewHost({"clone": dataset})
tools/dashboard-stage.py+27-4
......@@ -9,6 +9,7 @@ import secrets
99import shlex
1010import shutil
1111import socket
12import sqlite3
1213import subprocess
1314import sys
1415import threading
......@@ -35,6 +36,10 @@ class PreviewHost(boundary.Host):
3536
3637 def handle(self, request):
3738 operation = request.get("operation") if isinstance(request, dict) else None
39 if operation in {"vm.computer", "vm.owner"}:
40 payload = request.get("payload")
41 if not self.stage.get("computer") or not isinstance(payload, dict) or payload.get("name") != self.stage["computer"]:
42 raise boundary.dashboard_runs.Error(403, "Choose the VM explicitly attached to this preview.")
3843 if operation == "shale.access":
3944 service = request.get("service", "")
4045 if not re.fullmatch(r"shale-preview-[0-9a-f]{8}", service):
......@@ -86,11 +91,12 @@ def serve(stage):
8691 if not slots.acquire(blocking=False):
8792 connection.close()
8893 continue
89 work = workers.submit(boundary.serve_connection, connection, host, saved["uid"], OPERATIONS)
94 operations = OPERATIONS | {"vm.computer", "vm.owner"} if saved.get("computer") else OPERATIONS
95 work = workers.submit(boundary.serve_connection, connection, host, saved["uid"], operations)
9096 work.add_done_callback(lambda _: slots.release())
9197
9298
93def stage():
99def stage(computer=None):
94100 snowglobe.token()
95101 site = json.loads(snowglobe.command("pkl", "eval", "-f", "json", str(snowglobe.REPO / "config/site.pkl"), capture=True).stdout)
96102 site["hostRoot"] = str(Path(site["root"]) / "prod/dashboard")
......@@ -107,6 +113,16 @@ def stage():
107113 saved = {"sourceId": "dashboard", "tasks": ["app"], "inputs": {}, "mount": str(root),
108114 "clone": site["pool"] + "/staging/" + identity, "uid": snowglobe.identity("dashboard"),
109115 "stageIsolation": "fresh"} if created else metadata(identity)
116 if computer:
117 saved["computer"] = computer
118 host_environment = shlex.split(snowglobe.command("systemctl", "show", "snowglobe-host", "--property=Environment", "--value", capture=True).stdout)
119 host_path = next(value for value in host_environment if value.startswith("PATH="))
120 mac = None
121 if saved.get("computer"):
122 configured = next((value.partition("=")[2] for value in host_environment if value.startswith("SNOWGLOBE_MAC_VM=")), "null")
123 mac = json.loads(configured)
124 if not mac or mac["name"] != saved["computer"]:
125 raise ValueError("Choose the configured managed Mac VM for this preview.")
110126 nix = ["nix", "--extra-experimental-features", "nix-command flakes"]
111127 package = "path:" + str(snowglobe.REPO) + "#dashboard-image"
112128 image = subprocess.run([*nix, "eval", "--raw", package, "--apply", 'image: "${image.imageName}:${image.imageTag}"'],
......@@ -166,13 +182,20 @@ def stage():
166182 *["--env=" + key + "=" + value for key, value in env.items()], image, "--preview-account", capture=True)
167183 snowglobe.write_private(root / "access.json", imported.stdout)
168184 runtime = "/run/snowglobe-preview/" + identity
169 host_environment = snowglobe.command("systemctl", "show", "snowglobe-host", "--property=Environment", "--value", capture=True).stdout
170 host_path = next(value for value in shlex.split(host_environment) if value.startswith("PATH="))
185 computer_environment = []
186 if mac:
187 with sqlite3.connect(f"file:{root / 'data/accounts.sqlite'}?mode=ro", uri=True) as accounts:
188 owner = accounts.execute("SELECT id FROM users WHERE username='preview'").fetchone()
189 if not owner:
190 raise ValueError("The preview account is unavailable.")
191 mac["owner"] = owner[0]
192 computer_environment.append("--setenv=SNOWGLOBE_MAC_VM=" + json.dumps(mac))
171193 host_python = snowglobe.command(*nix, "build", "--no-link", "--print-out-paths", "path:" + str(snowglobe.REPO) + "#host-python", capture=True).stdout.strip()
172194 subprocess.run(["systemctl", "stop", "snowglobe-preview-" + identity], capture_output=True)
173195 snowglobe.command("systemd-run", "--collect", "--quiet", "--unit=snowglobe-preview-" + identity,
174196 "--property=Restart=on-failure", "--property=MemoryMax=256M", "--property=TasksMax=32",
175197 "--setenv=" + host_path, "--setenv=SNOWGLOBE_DOMAIN=" + site["domain"],
198 *computer_environment,
176199 host_python + "/bin/python3", str(Path(__file__).resolve()), "--serve", identity)
177200 for _ in range(100):
178201 if Path(runtime, "host.sock").exists():
tools/deploy.py+5
......@@ -163,6 +163,7 @@ def upload(main=False):
163163def main():
164164 parser = argparse.ArgumentParser(description="Preview working changes and deploy main")
165165 parser.add_argument("mode", choices=["stage", "publish", "prod", "rollback", "history", "backups", "data-restore", "bootstrap", "allocate", "destroy", "secrets"])
166 parser.add_argument("--computer", help="Give a dashboard preview access to this managed Mac VM")
166167 parser.add_argument("target", nargs="?")
167168 parser.add_argument("--env", action="append", default=[])
168169 parser.add_argument("--file", type=Path)
......@@ -170,6 +171,8 @@ def main():
170171 parser.add_argument("--backup")
171172 parser.add_argument("--discard-writes", action="store_true")
172173 args = parser.parse_args()
174 if args.computer and (args.mode != "stage" or args.target != "dashboard" or not NAME.fullmatch(args.computer)):
175 parser.error("--computer requires stage dashboard and a VM name")
173176 if args.mode in {"stage", "allocate", "destroy", "secrets", "data-restore"} and (not args.target or not NAME.fullmatch(args.target)):
174177 parser.error(f"{args.mode} requires a service or stage ID")
175178 if args.mode == "rollback" and args.target and not RELEASE_ID.fullmatch(args.target):
......@@ -202,6 +205,8 @@ def main():
202205 if args.mode == "stage":
203206 release = upload()
204207 overrides = "".join(f" --env {shlex.quote(value)}" for value in args.env)
208 if args.computer:
209 overrides += " --computer " + shlex.quote(args.computer)
205210 run_logged("stage", args.target, f"python3 {REMOTE}/releases/{release}/tools/snowglobe.py stage {args.target}{overrides}")
206211 elif args.mode == "secrets":
207212 release = upload()
tools/install-mac-computer.py created+41
......@@ -0,0 +1,41 @@
1#!/usr/bin/env python3
2"""Install computer-use support in the existing managed Mac guest and bridge."""
3from importlib import import_module
4import json
5import os
6from pathlib import Path
7import tempfile
8
9vm = import_module("mac-agent-vm")
10root = Path(__file__).resolve().parent
11identity = vm.tart("exec", vm.NAME, "/bin/hostname", capture_output=True, text=True, timeout=10).stdout.strip()
12print("Installing guest tools in " + identity, flush=True)
13source = {name: (root / name).read_text() for name in ["mac-computer.py", "mac-agent-gui.swift"]}
14vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "-c", '''
15import json, pathlib, subprocess, sys, tempfile
16files = json.load(sys.stdin)
17with tempfile.TemporaryDirectory(prefix="snowglobe-computer-install-") as temporary:
18 root = pathlib.Path(temporary)
19 for name, content in files.items():
20 (root / name).write_text(content)
21 subprocess.run(["/usr/bin/swiftc", "-O", str(root / "mac-agent-gui.swift"), "-o", str(root / "agent-gui")], check=True)
22 subprocess.run(["sudo", "-n", "mkdir", "-p", "/usr/local/libexec"], check=True)
23 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)
25''', input=json.dumps(source).encode(), timeout=180)
26for name in ["mac-agent-vm.py", "mac-vm-bridge.py"]:
27 target = vm.ROOT / "runtime/control" / name
28 with tempfile.NamedTemporaryFile(dir=target.parent, delete=False) as outgoing:
29 pending = Path(outgoing.name)
30 outgoing.write((root / name).read_bytes())
31 try:
32 pending.chmod(target.stat().st_mode & 0o777)
33 os.replace(pending, target)
34 finally:
35 pending.unlink(missing_ok=True)
36result = vm.tart("exec", "-i", vm.NAME, "/usr/bin/python3", "/usr/local/libexec/snowglobe-computer.py",
37 input=b'{"action":"status"}', capture_output=True, timeout=15)
38value = json.loads(result.stdout)
39if not all(value.get("permissions", {}).get(name) for name in ["accessibility", "screenCapture", "postEvent"]):
40 raise SystemExit("The guest needs computer-use permissions; check its System Settings.")
41print(json.dumps(value))
tools/mac-agent-gui.swift+4-1
......@@ -81,7 +81,10 @@ case "screenshot":
8181 else { fail("Could not create the output PNG.") }
8282 CGImageDestinationAddImage(destination, image, nil)
8383 guard CGImageDestinationFinalize(destination) else { fail("Could not write the output PNG.") }
84 output(["width": image.width, "height": image.height, "path": arguments[1]])
84 let bounds = CGDisplayBounds(CGMainDisplayID())
85 output(["width": image.width, "height": image.height, "path": arguments[1],
86 "bounds": [bounds.origin.x, bounds.origin.y, bounds.width, bounds.height],
87 "scale": [Double(image.width) / bounds.width, Double(image.height) / bounds.height]])
8588case "tree", "press":
8689 guard AXIsProcessTrusted() else { fail("Accessibility permission is required.") }
8790 let app: AXUIElement
tools/mac-agent-vm.md+34-3
......@@ -78,9 +78,10 @@ Snow Globe connects to the Mac's existing SSH service with a dedicated key at
7878`/var/lib/snowglobe/mac-vm/ssh_key` and a pinned host key in the adjacent
7979`known_hosts`. Both are root-only. The corresponding Mac `authorized_keys`
8080entry uses `restrict,command=` to invoke `mac-vm-bridge.py`; it grants no shell,
81forwarding, PTY, arbitrary VM selection, or arbitrary guest command. Deploy the
82bridge and `mac-agent-vm.py` together under the VM home's `runtime/control` and
83keep that forced command pointed there, independent of an agent session.
81forwarding, PTY, or arbitrary VM selection. Its computer operation runs commands
82inside the fixed guest. Deploy the bridge and `mac-agent-vm.py` together under
83the VM home's `runtime/control` and keep that forced command pointed there,
84independent of an agent session.
8485
8586The existing host sshd provides supervision. Each console connection creates
8687a fresh, pinned guest SSH tunnel, authenticates Screen Sharing on the Mac,
......@@ -102,6 +103,36 @@ video stream without reconnecting. A deliberately closed viewer connection
102103also recovered without restarting the guest. The idle legacy tailnet relay
103104was retired; the actively used loopback recovery console was preserved.
104105
106## Computer MCP
107
108The `computer` MCP catalog uses the dashboard's OAuth flow. Grants select VMs
109owned by the account; every call rechecks the current owner, selected VM, and
110`computer:read` or `computer:control` scope. Infrastructure administrators do
111not bypass ownership. Read access provides status, screenshots, and AX trees;
112control also runs bounded zsh scripts with `agent-gui` input primitives and
113optional screenshots. The guest's passwordless sudo permits software setup.
114This managed devbox remains persistent.
115
116Install from this Mac while the guest is running:
117
118```sh
119python3 tools/install-mac-computer.py
120python3 tools/deploy.py stage dashboard --computer m3-devbox
121```
122
123The installer compiles the GUI helper in the guest, installs the stdin/stdout
124worker, refreshes the restricted host bridge, and checks permissions. The
125worker serializes operations, caps command output, and kills the command's
126process group on timeout. Commands deliberately detached into another session
127can outlive a call; this is a development shell, not a process sandbox.
128Screenshot pixels include display bounds and scale for point-based input.
129
130Dashboard previews have no computer access by default. `--computer` explicitly
131attaches the real managed guest to the preview account; subsequent staging
132updates retain that attachment. Only the preview host's configuration remaps
133ownership. Its credentials grant access to the live guest, so keep them private.
134Destroying the preview removes its access. Production ownership is unchanged.
135
105136## Guest access
106137
107138`~/.local/bin/code-vm` links to the installed `runtime/control/code-vm` under
tools/mac-computer-test.py created+78
......@@ -0,0 +1,78 @@
1#!/usr/bin/env python3
2"""Disposable command, timeout, output-bound and protocol tests."""
3from importlib import import_module
4import os
5import signal
6import subprocess
7import tempfile
8import unittest
9from pathlib import Path
10from unittest.mock import patch
11
12worker = import_module("mac-computer")
13bridge = import_module("mac-vm-bridge")
14
15
16class ComputerTests(unittest.TestCase):
17 def run_script(self, script, timeout=3000):
18 return worker.execute({"action": "exec", "script": script, "timeout_ms": timeout, "screenshot": False})
19
20 def test_commands_preserve_unicode_exit_status_and_limit_output(self):
21 result = self.run_script("printf 'Clover 🦊 日本語'; printf 'diagnostic' >&2; exit 7")
22 self.assertEqual(result, {"exit": 7, "stdout": "Clover 🦊 日本語", "stderr": "diagnostic"})
23 result = self.run_script("/usr/bin/python3 -c 'print(\"x\" * 200000)'")
24 self.assertEqual(len(result["stdout"]), 65536)
25 self.assertEqual(result["truncated"], ["stdout"])
26 self.assertEqual(result["exit"], 0)
27
28 def test_timeout_kills_the_script_group(self):
29 killpg = os.killpg
30 def cleanup(args, **kwargs):
31 self.assertEqual(args[:5], ["/usr/bin/sudo", "-n", "/bin/kill", "-KILL", "--"])
32 killpg(-int(args[-1]), signal.SIGKILL)
33 return subprocess.CompletedProcess(args, 0)
34 with patch.object(worker.subprocess, "run", side_effect=cleanup), \
35 patch.object(worker.os, "killpg", side_effect=PermissionError):
36 result = self.run_script("sleep 30 &\nprintf '%s' $!\nwait", 250)
37 self.assertTrue(result["timed_out"])
38 self.assertEqual(result["exit"], -signal.SIGKILL)
39 pid = int(result["stdout"])
40 state = subprocess.run(["ps", "-p", str(pid), "-o", "stat="], capture_output=True, text=True).stdout.strip()
41 self.assertTrue(not state or state.startswith("Z"), state)
42
43 def test_delayed_child_output_is_collected(self):
44 result = self.run_script("(sleep .3; printf 'late child') &")
45 self.assertEqual(result, {"exit": 0, "stdout": "late child", "stderr": ""})
46
47 def test_capture_failure_preserves_command_result(self):
48 for failure in [subprocess.TimeoutExpired("capture", 15), OSError("capture failed")]:
49 with patch.object(worker.subprocess, "run", side_effect=failure):
50 result = worker.execute({"action": "exec", "script": "printf completed; exit 7", "timeout_ms": 3000, "screenshot": True})
51 self.assertEqual(result["exit"], 7)
52 self.assertEqual(result["stdout"], "completed")
53 self.assertIn("capture_error", result)
54
55 def test_invalid_requests_never_run_commands(self):
56 requests = [[], {"action": []}, {"action": "status", "command": "id"},
57 {"action": "ui", "pid": True}, {"action": "ui", "pid": -1}]
58 for field, value in [("script", ""), ("script", "a" * 65537), ("timeout_ms", True),
59 ("timeout_ms", 180001), ("screenshot", "yes")]:
60 requests.append({"action": "exec", "script": "id", "timeout_ms": 1000, "screenshot": False, field: value})
61 with patch.object(worker.subprocess, "Popen") as start:
62 for request in requests:
63 with self.subTest(request=str(request)[:100]), self.assertRaises(ValueError):
64 worker.execute(request)
65 start.assert_not_called()
66
67 def test_bridge_bounds_guest_output_and_rejects_nonobjects(self):
68 with tempfile.TemporaryDirectory() as directory:
69 tart = Path(directory) / "tart"
70 for output, message in [("print('x' * (17 * 1024 * 1024))", "too large"), ("print('[]')", "incomplete")]:
71 tart.write_text("#!/usr/bin/python3\n" + output + "\n")
72 tart.chmod(0o700)
73 with patch.object(bridge.vm, "TART", tart), self.assertRaisesRegex(ValueError, message):
74 bridge.computer({"action": "status"})
75
76
77if __name__ == "__main__":
78 unittest.main()
tools/mac-computer.py created+135
......@@ -0,0 +1,135 @@
1#!/usr/bin/env python3
2"""Computer operations in the logged-in Mac guest, over stdin/stdout."""
3import base64
4import fcntl
5import json
6import os
7from pathlib import Path
8import selectors
9import signal
10import subprocess
11import sys
12import tempfile
13import time
14
15GUI = "/usr/local/bin/agent-gui"
16
17
18def execute(request):
19 if not isinstance(request, dict):
20 raise ValueError("Send a computer operation.")
21 action = request.get("action")
22 fields = {"status": {"action"}, "shot": {"action"}, "ui": {"action", "pid"},
23 "exec": {"action", "script", "timeout_ms", "screenshot"}}
24 if not isinstance(action, str) or action not in fields or set(request) != fields[action]:
25 raise ValueError("Use the fields listed for this computer operation.")
26 if action == "ui" and (request["pid"] is not None and (type(request["pid"]) is not int or request["pid"] <= 0)):
27 raise ValueError("Choose a positive application PID, or omit it for the active app.")
28 if action == "exec":
29 if not isinstance(request["script"], str) or not 1 <= len(request["script"].encode()) <= 65536:
30 raise ValueError("Provide a script of at most 64 KiB.")
31 if type(request["timeout_ms"]) is not int or not 1 <= request["timeout_ms"] <= 180000:
32 raise ValueError("Choose a timeout between 1 and 180000 milliseconds.")
33 if type(request["screenshot"]) is not bool:
34 raise ValueError("Choose whether to return a screenshot.")
35 if action == "status":
36 result = subprocess.run([GUI, "status"], capture_output=True, timeout=10, check=True)
37 return {"permissions": json.loads(result.stdout), "hostname": os.uname().nodename,
38 "platform": "macos", "script": "zsh", "max_timeout_ms": 180000}
39 if action == "ui":
40 args = [GUI, "tree"] + ([] if request["pid"] is None else [str(request["pid"])])
41 result = subprocess.run(args, capture_output=True, timeout=15, check=True)
42 if len(result.stdout) > 2 * 1024 * 1024:
43 raise ValueError("The UI tree is too large. Select an application PID.")
44 return {"tree": json.loads(result.stdout)}
45 with tempfile.TemporaryDirectory(prefix="snowglobe-computer-") as directory:
46 reply = {}
47 if action == "exec":
48 script = Path(directory) / "script"
49 script.write_text(request["script"])
50 with script.open("rb") as source, selectors.DefaultSelector() as selector:
51 process = subprocess.Popen(["/bin/zsh", "-s"], stdin=source,
52 stdout=subprocess.PIPE, stderr=subprocess.PIPE, start_new_session=True)
53 streams = {"stdout": bytearray(), "stderr": bytearray()}
54 truncated = []
55 for name in streams:
56 stream = getattr(process, name)
57 os.set_blocking(stream.fileno(), False)
58 selector.register(stream, selectors.EVENT_READ, name)
59 deadline = time.monotonic() + request["timeout_ms"] / 1000
60 try:
61 while True:
62 if time.monotonic() >= deadline:
63 reply["timed_out"] = True
64 break
65 events = selector.select(min(.1, max(0, deadline - time.monotonic())))
66 for key, _ in events:
67 data = os.read(key.fd, 65536)
68 if not data:
69 selector.unregister(key.fileobj)
70 continue
71 output = streams[key.data]
72 remaining = 65536 - len(output)
73 output.extend(data[:remaining])
74 if len(data) > remaining and key.data not in truncated:
75 truncated.append(key.data)
76 if process.poll() is not None and not selector.get_map():
77 break
78 finally:
79 if process.poll() is None or reply.get("timed_out"):
80 try:
81 cleanup = subprocess.run(["/usr/bin/sudo", "-n", "/bin/kill", "-KILL", "--", "-" + str(process.pid)],
82 stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, timeout=5)
83 if cleanup.returncode:
84 reply["cleanup_error"] = "Privileged cleanup failed. Check for remaining child processes."
85 except (OSError, subprocess.SubprocessError):
86 reply["cleanup_error"] = "Privileged cleanup failed. Check for remaining child processes."
87 try:
88 os.killpg(process.pid, signal.SIGKILL)
89 except (ProcessLookupError, PermissionError):
90 pass
91 process.wait()
92 process.stdout.close()
93 process.stderr.close()
94 reply.update(exit=process.returncode, **{k: bytes(v).decode("utf-8", "replace") for k, v in streams.items()})
95 if truncated:
96 reply["truncated"] = truncated
97 if action == "shot" or request.get("screenshot"):
98 shot = Path(directory) / "screen.png"
99 try:
100 result = subprocess.run([GUI, "screenshot", str(shot)], capture_output=True, timeout=15, check=True)
101 if shot.stat().st_size > 8 * 1024 * 1024:
102 reply["capture_error"] = "The screenshot exceeds 8 MiB. Reduce the guest display resolution."
103 else:
104 reply.update(json.loads(result.stdout))
105 reply.pop("path", None)
106 reply["png"] = base64.b64encode(shot.read_bytes()).decode("ascii")
107 except subprocess.TimeoutExpired:
108 reply["capture_error"] = "Screen capture timed out. Check the guest's screen recording permission."
109 except (OSError, ValueError, subprocess.SubprocessError):
110 reply["capture_error"] = "Screen capture failed. Check the guest's screen recording permission."
111 return reply
112
113
114def main():
115 raw = sys.stdin.buffer.read(524289)
116 if len(raw) > 524288:
117 raise ValueError("The computer request is too large.")
118 request = json.loads(raw)
119 lock_path = Path.home() / "Library/Caches/net.paperclover.computer.lock"
120 descriptor = os.open(lock_path, os.O_CREAT | os.O_RDWR | os.O_NOFOLLOW, 0o600)
121 with os.fdopen(descriptor, "w") as lock:
122 try:
123 fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
124 except BlockingIOError:
125 raise ValueError("Another computer operation is running. Wait for it to finish.")
126 return execute(request)
127
128
129if __name__ == "__main__":
130 try:
131 print(json.dumps(main(), ensure_ascii=True))
132 except ValueError as error:
133 print(json.dumps({"error": str(error)}))
134 except (OSError, subprocess.SubprocessError):
135 print(json.dumps({"error": "The guest operation failed. Check its arguments, permissions, and connection."}))
tools/mac-vm-bridge.py+53
......@@ -4,10 +4,13 @@ import fcntl
44from importlib import import_module
55import json
66import os
7import selectors
78import signal
89import struct
910import subprocess
1011import sys
12import tempfile
13import time
1114
1215vm = import_module("mac-agent-vm")
1316
......@@ -41,6 +44,52 @@ def respond(value):
4144 sys.stdout.buffer.flush()
4245
4346
47def computer(request):
48 with tempfile.TemporaryFile() as source, selectors.DefaultSelector() as selector:
49 source.write(json.dumps(request).encode())
50 source.seek(0)
51 process = subprocess.Popen([str(vm.TART), "exec", "-i", vm.NAME, "/usr/bin/python3",
52 "/usr/local/libexec/snowglobe-computer.py"], stdin=source, stdout=subprocess.PIPE,
53 stderr=subprocess.PIPE, start_new_session=True, env={**os.environ, "TART_HOME": str(vm.ROOT / "state")})
54 output = bytearray()
55 errors = 0
56 selector.register(process.stdout, selectors.EVENT_READ, True)
57 selector.register(process.stderr, selectors.EVENT_READ, False)
58 deadline = time.monotonic() + 205
59 try:
60 while selector.get_map():
61 remaining = deadline - time.monotonic()
62 if remaining <= 0:
63 raise ValueError("The guest command timed out. Check its status before retrying.")
64 for key, _ in selector.select(remaining):
65 data = os.read(key.fd, 65536)
66 if not data:
67 selector.unregister(key.fileobj)
68 elif key.data:
69 output.extend(data)
70 else:
71 errors += len(data)
72 if len(output) > 16 * 1024 * 1024 or errors > 65536:
73 raise ValueError("The computer response is too large.")
74 if process.wait(timeout=max(.001, deadline - time.monotonic())):
75 raise ValueError("The Mac guest did not answer. Check its agent and retry.")
76 value = json.loads(output)
77 if not isinstance(value, dict):
78 raise ValueError("The Mac guest returned an incomplete response.")
79 if "error" in value:
80 raise ValueError(str(value["error"]))
81 return value
82 finally:
83 if process.poll() is None:
84 try:
85 os.killpg(process.pid, signal.SIGKILL)
86 except ProcessLookupError:
87 pass
88 process.wait()
89 process.stdout.close()
90 process.stderr.close()
91
92
4493def lifecycle(action):
4594 process = subprocess.Popen([sys.executable, vm.__file__, action], stdout=subprocess.DEVNULL,
4695 start_new_session=True)
......@@ -77,6 +126,10 @@ def main():
77126 vm.tart("exec", "-i", vm.NAME, "/usr/bin/env", "LC_CTYPE=en_US.UTF-8", "/usr/bin/pbcopy",
78127 input=value.encode(), capture_output=True, timeout=15)
79128 respond({"value": None})
129 elif action == "computer" and set(request) == {"action", "request"}:
130 if not isinstance(request["request"], dict):
131 raise ValueError("Send a computer operation.")
132 respond({"value": computer(request["request"])})
80133 elif action == "console" and set(request) == {"action"}:
81134 with vm.guest_screen() as upstream:
82135 respond({"value": None})
tools/mac-vms.py+5-3
......@@ -9,7 +9,7 @@ import tempfile
99
1010
1111CONFIG = json.loads(os.environ.get("SNOWGLOBE_MAC_VM", "null"))
12CAPABILITIES = ["start", "shutdown", "reboot", "suspend", "resume", "clipboard"]
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
......@@ -42,7 +42,7 @@ def connect(request, timeout=10):
4242 return data
4343
4444 size, = struct.unpack("!I", read(4))
45 if size > 65536:
45 if size > (16 * 1024 * 1024 if request["action"] == "computer" else 65536):
4646 raise ValueError("The Mac response is too large.")
4747 reply = json.loads(read(size))
4848 if "error" in reply:
......@@ -113,10 +113,12 @@ def handle(action, payload):
113113 return None
114114 if action == "console":
115115 return {"remote": True}
116 if action == "act" and payload["action"] in CAPABILITIES:
116 if action == "act" and payload["action"] in {"start", "shutdown", "reboot", "suspend", "resume"}:
117117 request = {"action": payload["action"]}
118118 elif action == "clipboard":
119119 request = {"action": "clipboard", "text": payload["text"]}
120 elif action == "computer":
121 request = {"action": "computer", "request": payload["request"]}
120122 else:
121123 raise ValueError("This operation is unavailable for this Mac VM.")
122124 with connect(request, timeout=220) as (value, _):
tools/snowglobe.py+4-1
......@@ -950,6 +950,7 @@ def main():
950950 ],
951951 )
952952 parser.add_argument("name", nargs="?")
953 parser.add_argument("--computer")
953954 parser.add_argument("--base-domain")
954955 parser.add_argument("--root")
955956 parser.add_argument("--pool")
......@@ -957,10 +958,12 @@ def main():
957958 parser.add_argument("--env", action="append", default=[])
958959 parser.add_argument("--key", action="append", default=[])
959960 args = parser.parse_args()
961 if args.computer and (args.mode != "stage" or args.name != "dashboard"):
962 parser.error("--computer requires stage dashboard")
960963 if args.mode == "stage" and args.name == "dashboard":
961964 if args.env or args.base_domain or args.root or args.pool or args.media_root:
962965 parser.error("dashboard staging uses the host configuration")
963 __import__("dashboard-stage").stage()
966 __import__("dashboard-stage").stage(args.computer)
964967 return
965968 if args.mode == "destroy" and args.name and NAME.fullmatch(args.name):
966969 saved = STATE / "stages" / f"{args.name}.json"
tools/vms.py+3
......@@ -77,6 +77,7 @@ ACTION_FIELDS = {
7777 "library": None, "media": {"name", "image"},
7878 "preset": {"name", "id", "os", "description"},
7979 "clipboard": {"name", "text"},
80 "computer": {"name", "request"},
8081 "console": {"name"}, "serial": {"name"}, "guest": {"name"}, "owner": {"name"}, "access": {"name"}, "upload": {"volume", "size"},
8182}
8283
......@@ -164,6 +165,8 @@ def validate(action, payload):
164165 if "name" not in payload:
165166 raise ValueError("Enter a VM name.")
166167 ensure_name(payload["name"])
168 if action == "computer" and not isinstance(payload["request"], dict):
169 raise ValueError("Send a computer operation.")
167170 if "description" in payload and (not isinstance(payload["description"], str) or len(payload["description"]) > 200):
168171 raise ValueError("Keep the description under 200 characters.")
169172 for field in ("autostart", "start", "disks"):