Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.
Rust agentai-agentapplecomputer-usecomputer-use-agentcontainerizationcuadesktop-automationhacktoberfestlumemacosmanusoperatorswiftvirtualizationvirtualization-frameworkwindowswindows-sandbox
Spaces macOS: ask Local Network from the daemon before a create, and on the permissions page (CUA-2350) (#6009)
cua-agents[bot]c64eb385fe5f
diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swiftindex 3167bd680f..d04edee951 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/AppModel.swift@@ -1230,6 +1230,37 @@ public final class AppModel {/// set one).public var localNetworkGate: LocalNetworkGate?+ /// What the daemon found when it last tried this Mac's local network:+ /// true allowed, false blocked, nil not known yet. The daemon is the+ /// process that reaches the macOS VMs, and macOS decides Local Network+ /// per process, so the app's own connect (`localNetworkGate`) can pass+ /// while the daemon is still blocked. The daemon's connect is also what+ /// makes macOS ask, so this runs where the person expects it: the+ /// permissions page.+ public private(set) var daemonLocalNetworkAllowed: Bool?+ private var daemonLocalNetworkAt = Date.distantPast+ private var daemonLocalNetworkBusy = false++ /// Asks the daemon (its machine check, `machine.local_network`) and+ /// remembers the answer; at most once per `minimum` seconds.+ public func checkLocalNetworkFromDaemon(every minimum: TimeInterval = 4) async {+ guard !daemonLocalNetworkBusy, Date().timeIntervalSince(daemonLocalNetworkAt) >= minimum else { return }+ daemonLocalNetworkBusy = true+ defer {+ daemonLocalNetworkBusy = false+ daemonLocalNetworkAt = Date()+ }+ let backend = self.backend+ let answer = await withTimeout(seconds: 20) { try await backend.machineHealth(machine: nil) }+ guard case .success(let health) = answer,+ let check = health.checks.first(where: { $0.id == "machine.local_network" }) else { return }+ switch check.status {+ case "pass": daemonLocalNetworkAllowed = true+ case "fail": daemonLocalNetworkAllowed = false+ default: break+ }+ }+/// How long the daemon may take to take a create (its first progress/// report, "Preparing", comes as it starts): past it the create fails/// at once, with Try again, instead of after the 4 min stall.diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LocalNetworkPermission.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LocalNetworkPermission.swiftindex e2849491a0..ff28b241f8 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LocalNetworkPermission.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/Models/LocalNetworkPermission.swift@@ -159,7 +159,12 @@ public struct LiveLocalNetworkProbe: LocalNetworkProbing {}public func access() async -> AppLocalNetworkAccess {- guard let host = LiveLocalNetworkPermission.firstSubnetHost() else { return .unknown }+ // The router (the default gateway) answers a connect, even to refuse+ // it; the first host of the subnet may be an address nobody has, and+ // a connect to it stalls and says nothing.+ let table = await routes()+ guard let host = LiveLocalNetworkPermission.defaultGateway(inRoutes: table)+ ?? LiveLocalNetworkPermission.firstSubnetHost() else { return .unknown }let queue = DispatchQueue(label: "com.trycua.cua-spaces.local-network.check")return await withCheckedContinuation { (done: CheckedContinuation<AppLocalNetworkAccess, Never>) in// Port 9 (discard): nothing has to listen; a refusal comes back@@ -243,6 +248,20 @@ public enum LiveLocalNetworkPermission {return nil}+ /// The default route's gateway in `netstat -rn -f inet` output, when it+ /// is an IPv4 address on a real network (not a VPN's tunnel, not a+ /// `link#` route).+ static func defaultGateway(inRoutes netstat: String) -> String? {+ for line in netstat.split(separator: "\n") {+ let cols = line.split(whereSeparator: { $0 == " " || $0 == "\t" })+ guard cols.count >= 4, cols[0] == "default",+ !isTunnelOrBridge(String(cols[3])) else { continue }+ let parts = cols[1].split(separator: ".", omittingEmptySubsequences: false)+ if parts.count == 4, parts.allSatisfy({ UInt8($0) != nil }) { return String(cols[1]) }+ }+ return nil+ }+static func isTunnelOrBridge(_ name: String) -> Bool {["bridge", "utun", "ipsec", "ppp", "tun", "tap", "wg"].contains { name.hasPrefix($0) }}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swiftindex 0748a4301d..2cba465ea6 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Pages.swift@@ -295,6 +295,16 @@ extension WebUIBridge {guard url.hasPrefix("x-apple.systempreferences:"), let u = URL(string: url) else {throw Failure.badArgs("Only System Settings panes open here")}+ // Local Network: the daemon connects (which makes macOS ask, in a+ // dialog of its own); the pane opens only when it stays blocked+ // and no macOS prompt is waiting for an answer.+ if url.contains("Privacy_LocalNetwork") {+ await model.checkLocalNetworkFromDaemon(every: 0)+ if model.daemonLocalNetworkAllowed != true, LiveLocalNetworkProbe().promptsShowing() == 0 {+ NSWorkspace.shared.open(u)+ }+ return NSNull()+ }// Screen Recording and Accessibility: the app's guide to the// pane (PermissionFlow), never macOS's bare prompt.if !PermissionGuide.guide(url) { NSWorkspace.shared.open(u) }diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex 198ed42588..1b37c48890 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -309,7 +309,14 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {return machines()case "host.status":if model.host.state == nil, model.servicesIn { await model.host.refresh() }- return hostStatus()+ // The permissions page also asks for Local Network: the daemon+ // checks it in the background (its connect makes macOS ask), and+ // the page reads the answer on its next poll.+ let localNetwork = (args["localNetwork"] as? Bool) == true+ if localNetwork, model.servicesIn {+ Task { @MainActor [model] in await model.checkLocalNetworkFromDaemon() }+ }+ return hostStatus(localNetwork: localNetwork)case "agents.list", "agents.runs", "agents.events", "agents.pause", "agents.resume","agents.setup", "agents.configure", "agents.signIn", "agents.start", "agents.message":@@ -856,8 +863,20 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {/// `HostStatus`, with the signed-in `account` it was checked against),/// plus its relay machine id and what a running setup or Sign In waits/// for (`progress`); null until it answered.- func hostStatus() -> Any {+ func hostStatus(localNetwork: Bool = false) -> Any {guard let state = model.host.state, var out = BridgeValue.encode(state) as? [String: Any] else { return NSNull() }+ // A Mac that runs macOS Spaces needs Local Network access for the+ // daemon: listed (granted or not) for the permissions page, which+ // asks the daemon to check it. Not for Spaces-less Macs or Intel.+ if localNetwork, state.provideSpaces, AppModel.hostArch == "arm64" {+ var list = out["permissions"] as? [[String: Any]] ?? []+ list.append([+ "id": "local-network", "title": "Local Network",+ "settingsUrl": "x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork",+ "instructions": NSNull(), "granted": model.daemonLocalNetworkAllowed == true,+ ])+ out["permissions"] = list+ }out["machineId"] = model.host.machineId ?? NSNull()out["progress"] = model.host.progress ?? NSNull()// The name System Settings lists this app under ("Cua Spaces Local"),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/LocalNetworkPermissionTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/LocalNetworkPermissionTests.swiftindex a5c215a02c..b12ea083ca 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/LocalNetworkPermissionTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/LocalNetworkPermissionTests.swift@@ -18,6 +18,23 @@ struct LocalNetworkPermissionTests {#expect(LiveLocalNetworkPermission.subnetHost(ip: ip, mask: 0xFFFF_FFFF) == nil)}+ @Test func theProbeAimsAtTheDefaultGateway() {+ let table = """+ Routing tables++ Internet:+ Destination Gateway Flags Netif Expire+ default 192.168.1.254 UGScg en1+ default link#24 UCSIg utun4+ 10.200.1.190/32 link#24 UCS utun4+ """+ #expect(LiveLocalNetworkPermission.defaultGateway(inRoutes: table) == "192.168.1.254")+ // A VPN's tunnel or a link route is no local network.+ #expect(LiveLocalNetworkPermission.defaultGateway(inRoutes: "default 10.0.0.1 UGScg utun3") == nil)+ #expect(LiveLocalNetworkPermission.defaultGateway(inRoutes: "default link#6 UCSg en0") == nil)+ #expect(LiveLocalNetworkPermission.defaultGateway(inRoutes: "") == nil)+ }+/// A probe that answers from a script.final class FakeProbe: LocalNetworkProbing, @unchecked Sendable {var answers: [AppLocalNetworkAccess]diff --git a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx b/apps/cua-spaces-web/src/__tests__/first-run.test.tsxindex 27dd5cc134..5420dda5ea 100644--- a/apps/cua-spaces-web/src/__tests__/first-run.test.tsx+++ b/apps/cua-spaces-web/src/__tests__/first-run.test.tsx@@ -409,6 +409,28 @@ describe.skipIf(!wasmBuilt)("the first run (real route, wasm core)", () => {await waitFor(() => expect(heading()).toBe("Share this Mac's screen."));});+ it("a Mac that runs macOS Spaces also asks for Local Network on the permissions screen, and checks it there", async () => {+ const LN = "x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork";+ let granted = false;+ writeFirstRun({ step: "permissions", picked: ["codex"] });+ const calls = await mount({+ signedIn: true,+ host: (h) => ({ ...h, configured: true, shareDesktop: true, permissions: [{ id: "local-network", label: "Local Network", settingsUrl: LN, granted }] }),+ });+ await waitFor(() => expect(heading()).toBe("Share this Mac's screen."));+ expect(document.body.textContent).toMatch(/Allow three permissions so your team and agents can see and use this Mac, and so macOS Spaces can run on it\./);+ const rows = () => [...document.querySelectorAll<HTMLElement>("[data-first-run-permissions] [data-first-run-status]")].map((e) => `${e.dataset.firstRunStatus}:${e.dataset.state}`);+ await waitFor(() => expect(rows()).toEqual(["screen-recording:ok", "accessibility:ok", "local-network:fix"]));+ // The page asks the host to check it (the daemon's own connect is what makes macOS ask).+ expect(calls.some((c) => c.op === "host.status" && (c.args as { localNetwork?: boolean } | undefined)?.localNetwork === true)).toBe(true);+ click('[data-first-run-status="local-network"] [data-first-run-action="allow"]');+ await waitFor(() => expect(calls.find((c) => c.op === "host.openSettings")?.args).toEqual({ url: LN }));+ // Allowed on this Mac: a check, live.+ granted = true;+ fireEvent.focus(window);+ await waitFor(() => expect(rows()).toEqual(["screen-recording:ok", "accessibility:ok", "local-network:ok"]));+ });+it("Not now on the permissions screen goes on; a Mac kept for Spaces only never sees it", async () => {writeFirstRun({ step: "permissions", picked: ["codex"] });let share = true;diff --git a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts b/apps/cua-spaces-web/src/bridge/contracts/first-run.tsindex ccadc2903a..9ae039da91 100644--- a/apps/cua-spaces-web/src/bridge/contracts/first-run.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/first-run.ts@@ -234,7 +234,7 @@ export interface FirstRunDevicesView {export interface FirstRunPermissionsView {title: string;lede: string;- /** `screen-recording`, `accessibility`: `ok`, `fix` (Allow), `checking`. */+ /** `screen-recording`, `accessibility`, `local-network`: `ok`, `fix` (Allow), `checking`. */rows: FirstRunRow[];note: string;/** "Continue" once both are granted. */@@ -246,7 +246,7 @@ export interface FirstRunPermissionsView {export type FirstRunRowState = "checking" | "ok" | "fix";export interface FirstRunRow {- id: "agent" | "computer" | "account" | "screen-recording" | "accessibility";+ id: "agent" | "computer" | "account" | "screen-recording" | "accessibility" | "local-network";state: FirstRunRowState;title: string;note: string;diff --git a/apps/cua-spaces-web/src/bridge/first-run.ts b/apps/cua-spaces-web/src/bridge/first-run.tsindex 8823b0c634..944c468d03 100644--- a/apps/cua-spaces-web/src/bridge/first-run.ts+++ b/apps/cua-spaces-web/src/bridge/first-run.ts@@ -47,6 +47,7 @@ import type {FirstRunOffer,FirstRunPermissionsView,FirstRunPlan,+ FirstRunRow,FirstRunStep,FirstRunTodos,FirstRunView,@@ -239,12 +240,15 @@ function fallbackView(input: FirstRunInput): FirstRunView {case "permissions": {const host = input.host;const known = host?.configured && !input.hostSettingUp ? host : null;- const rows = (- [- ["screen-recording", `See ${place}'s screen`, "So your team and agents can see what's on it.", "Privacy_ScreenCapture"],- ["accessibility", "Use the mouse and keyboard", `So they can click and type on ${place}.`, "Privacy_Accessibility"],- ] as const- ).map(([id, title, note, pane]) => {+ const localNetwork = Boolean(host?.permissions.some((p) => p.id === "local-network"));+ const wanted: ReadonlyArray<readonly [FirstRunRow["id"], string, string, string]> = [+ ["screen-recording", `See ${place}'s screen`, "So your team and agents can see what's on it.", "Privacy_ScreenCapture"],+ ["accessibility", "Use the mouse and keyboard", `So they can click and type on ${place}.`, "Privacy_Accessibility"],+ ...(localNetwork+ ? [["local-network", "Run Spaces on this Mac", "So the macOS Spaces you create here can start and connect.", "Privacy_LocalNetwork"] as const]+ : []),+ ];+ const rows = wanted.map(([id, title, note, pane]) => {const missing = known?.permissions.find((p) => p.id === id && !p.granted);if (!known) return { id, state: "checking" as const, title, note: `Adding ${place} to your account first…`, action: null, settingsUrl: null };if (!missing) return { id, state: "ok" as const, title, note: "Allowed", action: null, settingsUrl: null };@@ -255,7 +259,9 @@ function fallbackView(input: FirstRunInput): FirstRunView {...base,permissions: {title: `Share ${place}'s screen.`,- lede: `Allow two permissions so your team and agents can see and use ${place}.`,+ lede: localNetwork+ ? `Allow three permissions so your team and agents can see and use ${place}, and so macOS Spaces can run on it.`+ : `Allow two permissions so your team and agents can see and use ${place}.`,rows,note: `Allow opens System Settings, where you turn on ${host?.appName || "Cua Spaces"}.`,primary: all ? { id: "continue", label: "Continue" } : null,@@ -523,7 +529,7 @@ export function useScreenPermissions(active = true, pollMs = FIRST_RUN_POLL_MS):let live = true;const read = () =>void adapter- .call("host.status", {})+ .call("host.status", { localNetwork: true }).then((h) => live && setHost(h)).catch(() => {});read();@@ -608,8 +614,9 @@ export function useFirstRun(active = true, pollMs = FIRST_RUN_POLL_MS): FirstRun.catch(() => live && setAgents((a) => a ?? []));}if (step === "devices" || step === "permissions" || step === "setup" || s.finishedLater) {+ // On the permissions page the host also checks Local Network access (which makes macOS ask).void adapter- .call("host.status", {})+ .call("host.status", step === "permissions" ? { localNetwork: true } : {}).then((h) => live && setHost(h)).catch(() => {});}diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex b929a7de83..520708cad7 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -238,7 +238,9 @@ export interface HostOperations"spaces.open": { args: { spaceId: string; name?: string; os?: SpaceOs }; result: null };"machines.list": { args: Record<string, never>; result: MachineRow[] };- "host.status": { args: Record<string, never>; result: HostStatus };+ /** `localNetwork`: the permissions page is asking, so a Mac that runs macOS Spaces also lists its+ * Local Network access ("local-network", granted or not) and checks it from the daemon. */+ "host.status": { args: { localNetwork?: boolean }; result: HostStatus };"settings.get": { args: Record<string, never>; result: SettingsSnapshot };"settings.set": { args: { key: SettingKey; value: SettingsValues[SettingKey] }; result: SettingsSnapshot };diff --git a/libs/cua/crates/cua-daemon/src/local.rs b/libs/cua/crates/cua-daemon/src/local.rsindex f2802af51b..77f270a535 100644--- a/libs/cua/crates/cua-daemon/src/local.rs+++ b/libs/cua/crates/cua-daemon/src/local.rs@@ -2414,17 +2414,32 @@ async fn preflight_refusal(os: cua_vmm::GuestOs, backend: BackendKind) -> RuntimRuns::Vm};let req = cua_vmm::preflight::request(cua_vmm::preflight::guest_of(os), runs, None);- let mut facts = cua_vmm::preflight::gather(&req).await;+ let mut facts =+ cua_vmm::preflight::gather_waiting(&req, cua_vmm::local_network::PROMPT_PATIENCE).await;facts.free_bytes = None;match cua_vmm::preflight::evaluate(&req, &facts).into_iter().next(){- Some(issue) => Err(RuntimeError::Other(issue.message)),+ Some(issue) => Err(RuntimeError::Other(refusal_text(issue))),None => Ok(()),}}+/// The refusal's words: a Local Network refusal names the app macOS holds+/// responsible for this daemon (what System Settings lists: "Cua Spaces+/// Local" for the Local build), not the generic name.+fn refusal_text(issue: cua_create_failure::preflight::Issue) -> String {+ use cua_create_failure::preflight::{IssueKind, local_network_denied};+ if issue.kind == IssueKind::LocalNetwork+ && let Some(app) = cua_vmm::local_network::ResponsibleApp::of_this_process()+ && app.bundle+ {+ return local_network_denied(&app.name);+ }+ issue.message+}+// ------------------------------------------------------------------ doctor/// `cua runtime doctor`: the `cua-vmm` report (read-only).diff --git a/libs/cua/crates/cua-daemon/src/machine_doctor.rs b/libs/cua/crates/cua-daemon/src/machine_doctor.rsindex d0441218a7..fea0b870f1 100644--- a/libs/cua/crates/cua-daemon/src/machine_doctor.rs+++ b/libs/cua/crates/cua-daemon/src/machine_doctor.rs@@ -51,6 +51,9 @@ pub struct Facts {pub runtimes_missing: Vec<String>,/// The daemon's own Local Network probe (macOS).pub local_network: Option<local_network::Report>,+ /// A connect from the daemon to this Mac's router, for when no macOS VM+ /// runs to test with (`local_network`'s probe says nothing then).+ pub local_network_lan: Option<cua_create_failure::local_network::Access>,/// Where Spaces are written: (`name`, available bytes).pub disk: Option<(String, u64)>,/// Physical memory, and what running macOS VMs were given (bytes).@@ -127,6 +130,37 @@ pub fn checks(f: &Facts) -> Vec<Check> {).skip_reason("inconclusive"),};+ // No VM to test with: the daemon's connect to the router says the+ // same (a first connect also makes macOS ask, in this app's name).+ if c.status == Status::Skip {+ use cua_create_failure::local_network::Access;+ match f.local_network_lan {+ Some(Access::Blocked) => {+ c = Check::new(+ "machine.local_network",+ Status::Fail,+ format!(+ "Cua can't reach this Mac's local network, so it can't reach its \+ macOS VMs: Local Network access is off for {name}"+ ),+ )+ .fix(format!(+ "open System Settings > Privacy & Security > Local Network and turn on {name}"+ ))+ .fact("settings_url", LOCAL_NETWORK_URL);+ }+ Some(Access::Allowed) => {+ c = Check::new(+ "machine.local_network",+ Status::Pass,+ format!(+ "reached this Mac's local network: Local Network access is on for {name}"+ ),+ );+ }+ _ => {}+ }+ }c = c.fact("app", &name);if let Some(a) = app {c = c.fact("app_path", a.path.display());@@ -307,7 +341,11 @@ pub async fn gather() -> Facts {.map(|v| (v.name, v.available));if os == "macos" && (f.provide_spaces || f.lume_serving) {let base = local_network::lume_base();- f.local_network = Some(local_network::report(&base).await);+ let report = local_network::report(&base).await;+ if !matches!(report.probe, local_network::Probe::Reached { .. }) {+ f.local_network_lan = Some(local_network::lan_access_now().await);+ }+ f.local_network = Some(report);let client = cua_vmm::lume::LumeClient::new(&base);if let Ok(Ok(vms)) = tokio::time::timeout(Duration::from_secs(2), client.list()).await {for vm in vms.iter().filter(|v| v.status == "running") {@@ -445,6 +483,43 @@ mod tests {assert!(c.facts["settings_url"].contains("Privacy_LocalNetwork"));}+ /// With no macOS VM running, the daemon's own connect to the router+ /// decides the check: blocked fails it, allowed passes it.+ #[test]+ fn without_a_vm_the_daemons_lan_connect_decides_local_network() {+ use cua_create_failure::local_network::Access;+ let mut f = mac();+ f.local_network = Some(local_network::Report {+ probe: local_network::Probe::NoRunningVm,+ app: Some(local_network::ResponsibleApp {+ name: "Cua Spaces Local".into(),+ path: PathBuf::from("/Applications/Cua Spaces Local.app"),+ bundle: true,+ }),+ pid: 1,+ });+ f.local_network_lan = Some(Access::Blocked);+ let cs = checks(&f);+ let c = by_id(&cs, "machine.local_network");+ assert_eq!(c.status, Status::Fail);+ assert!(+ c.message.contains("off for Cua Spaces Local"),+ "{}",+ c.message+ );+ assert!(c.facts["settings_url"].contains("Privacy_LocalNetwork"));+ f.local_network_lan = Some(Access::Allowed);+ assert_eq!(+ by_id(&checks(&f), "machine.local_network").status,+ Status::Pass+ );+ f.local_network_lan = Some(Access::Unknown);+ assert_eq!(+ by_id(&checks(&f), "machine.local_network").status,+ Status::Skip+ );+ }+#[test]fn low_disk_warns_then_fails() {let mut f = mac();diff --git a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs b/libs/cua/crates/cua-spaces-app-core/src/first_run.rsindex b54612fec9..8207ebf224 100644--- a/libs/cua/crates/cua-spaces-app-core/src/first_run.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/first_run.rs@@ -1203,7 +1203,11 @@ pub fn asks_permissions(input: &FirstRunInput) -> bool {.is_none_or(|h| h.share_desktop != Some(false))}-/// The two permissions a shared screen needs, as rows: also what Settings+/// The host's permission id for macOS Local Network access.+pub const LOCAL_NETWORK: &str = "local-network";++/// The permissions a shared screen needs (two, and Local Network where macOS+/// Spaces run), as rows: also what Settings/// shows later (the same words and buttons).pub fn permissions_view(input: &FirstRunInput) -> PermissionsView {let place = this_computer(&input.host_os);@@ -1218,7 +1222,13 @@ pub fn permissions_view(input: &FirstRunInput) -> PermissionsView {.host.as_ref().filter(|h| h.configured && !input.host_setting_up);- let rows: Vec<CheckRow> = [+ // The host lists a "local-network" entry (granted or not) when macOS Spaces+ // can run on this Mac, and the page then asks for it with the other two.+ let local_network = input+ .host+ .as_ref()+ .is_some_and(|h| h.permissions.iter().any(|p| p.id == LOCAL_NETWORK));+ let mut wanted = vec![// Plain words, not the panes' names: macOS renames them (Accessibility// is "Device Control and Data Access" from macOS 27), and Allow opens// the right one anyway.@@ -1234,40 +1244,57 @@ pub fn permissions_view(input: &FirstRunInput) -> PermissionsView {format!("So they can click and type on {place}."),"x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility",),- ]- .into_iter()- .map(|(id, title, note, pane)| {- let (state, note, action, settings_url) = match known {- None => (- RowState::Checking,- format!("Adding {place} to your account first…"),- None,- None,- ),- Some(host) => match missing_permission(host, id) {- Some(p) => (- RowState::Fix,- note,- Some(button("allow", "Allow")),- Some(p.settings_url.unwrap_or_else(|| pane.into())),+ ];+ if local_network {+ wanted.push((+ LOCAL_NETWORK,+ "Run Spaces on this Mac".to_string(),+ "So the macOS Spaces you create here can start and connect.".to_string(),+ "x-apple.systempreferences:com.apple.preference.security?Privacy_LocalNetwork",+ ));+ }+ let count = wanted.len();+ let rows: Vec<CheckRow> = wanted+ .into_iter()+ .map(|(id, title, note, pane)| {+ let (state, note, action, settings_url) = match known {+ None => (+ RowState::Checking,+ format!("Adding {place} to your account first…"),+ None,+ None,),- None => (RowState::Ok, "Allowed".into(), None, None),- },- };- CheckRow {- id: id.into(),- state,- title,- note,- action,- settings_url,- }- })- .collect();+ Some(host) => match missing_permission(host, id) {+ Some(p) => (+ RowState::Fix,+ note,+ Some(button("allow", "Allow")),+ Some(p.settings_url.unwrap_or_else(|| pane.into())),+ ),+ None => (RowState::Ok, "Allowed".into(), None, None),+ },+ };+ CheckRow {+ id: id.into(),+ state,+ title,+ note,+ action,+ settings_url,+ }+ })+ .collect();let all = rows.iter().all(|r| r.state == RowState::Ok);PermissionsView {title: format!("Share {place}'s screen."),- lede: format!("Allow two permissions so your team and agents can see and use {place}."),+ lede: if count == 2 {+ format!("Allow two permissions so your team and agents can see and use {place}.")+ } else {+ format!(+ "Allow three permissions so your team and agents can see and use {place}, and \+ so macOS Spaces can run on it."+ )+ },rows,note: format!("Allow opens System Settings, where you turn on {app}."),primary: all.then(|| button("continue", "Continue")),@@ -2332,6 +2359,47 @@ mod tests {assert!(p.primary.is_none());}+ #[test]+ fn a_mac_that_runs_macos_spaces_also_asks_for_local_network() {+ let mut i = FirstRunInput {+ step: FirstRunStep::Permissions,+ host_os: "macos".into(),+ signed_in: true,+ host: Some(FirstRunHost {+ configured: true,+ running: true,+ permissions: vec![FirstRunPermission {+ id: LOCAL_NETWORK.into(),+ granted: false,+ settings_url: None,+ }],+ ..Default::default()+ }),+ ..Default::default()+ };+ let p = view(&i).permissions.unwrap();+ assert_eq!(+ p.rows.iter().map(|r| r.id.as_str()).collect::<Vec<_>>(),+ ["screen-recording", "accessibility", "local-network"]+ );+ // The two the host does not list are granted; Local Network is not.+ assert_eq!(p.rows[0].state, RowState::Ok);+ assert_eq!(p.rows[2].state, RowState::Fix);+ assert!(+ p.rows[2]+ .settings_url+ .as_deref()+ .is_some_and(|u| u.contains("Privacy_LocalNetwork"))+ );+ assert!(p.lede.starts_with("Allow three permissions"));+ assert!(p.primary.is_none());+ // Granted: listed, and no longer in the way.+ i.host.as_mut().unwrap().permissions[0].granted = true;+ let p = view(&i).permissions.unwrap();+ assert_eq!(p.rows[2].state, RowState::Ok);+ assert_eq!(p.primary.unwrap().id, "continue");+ }+#[test]fn no_permissions_screen_without_a_shared_mac_screen() {let mut i = FirstRunInput {diff --git a/libs/cua/crates/cua-vmm/src/local_network.rs b/libs/cua/crates/cua-vmm/src/local_network.rsindex b0261bb921..ef1562277c 100644--- a/libs/cua/crates/cua-vmm/src/local_network.rs+++ b/libs/cua/crates/cua-vmm/src/local_network.rs@@ -154,10 +154,7 @@ pub async fn diagnose_unreachable(ip: &str) -> Option<cua_create_failure::preflilet iface = route.as_deref().and_then(cua_create_failure::local_network::route_interface);- let lan = match lan_host() {- Some(host) => lan_access(&host).await,- None => cua_create_failure::local_network::Access::Unknown,- };+ let lan = lan_access_now().await;let cause = cua_create_failure::local_network::unreachable_cause(iface, lan);tracing::info!(ip,@@ -169,6 +166,71 @@ pub async fn diagnose_unreachable(ip: &str) -> Option<cua_create_failure::preflicause}+/// One connect from this process to this Mac's local network (its default+/// gateway, else the first host of its subnet): the daemon's own answer to+/// "may this process reach the local network?", which is the process that+/// reaches the VMs. A first connect makes macOS ask (on this Mac's own+/// screen) for the app responsible for this process. Bounded: about 3.5 s.+pub async fn lan_access_now() -> cua_create_failure::local_network::Access {+ use cua_create_failure::local_network::Access;+ if !cfg!(target_os = "macos") {+ return Access::Unknown;+ }+ match lan_target().await {+ Some(host) => lan_access(&host).await,+ None => Access::Unknown,+ }+}++/// How long a create waits for someone to answer macOS's Local Network+/// prompt (or turn the switch on) before it stops with the fix.+pub const PROMPT_PATIENCE: Duration = Duration::from_secs(30);++/// [`lan_access_now`] again until it is allowed, or `patience` is over (then+/// the last answer). The first connect raises macOS's prompt; while it waits+/// for an answer connects fail like a denial, so a "blocked" is only believed+/// once the prompt had its time. Zero: one probe.+pub async fn wait_for_lan_access(patience: Duration) -> cua_create_failure::local_network::Access {+ use cua_create_failure::local_network::Access;+ let deadline = tokio::time::Instant::now() + patience;+ loop {+ let access = lan_access_now().await;+ if access == Access::Allowed || tokio::time::Instant::now() >= deadline {+ return access;+ }+ tokio::time::sleep(Duration::from_secs(1)).await;+ }+}++/// What to aim the local network probe at: this Mac's default gateway (the+/// router answers a connect, even to refuse it, so the answer is clear),+/// else the first host of its subnet ([`lan_host`], a guess that may be an+/// address nobody has: the connect then stalls and says nothing). Not a+/// VPN's tunnel.+async fn lan_target() -> Option<String> {+ let route = tokio::time::timeout(+ Duration::from_secs(2),+ crate::host::run("/sbin/route", &["-n", "get", "default"]),+ )+ .await+ .ok()+ .and_then(Result::ok);+ route.as_deref().and_then(default_gateway).or_else(lan_host)+}++/// The IPv4 gateway `route -n get default` names, when the default route is+/// a real network (not a VPN's tunnel, not a `link#` route).+fn default_gateway(route_get: &str) -> Option<String> {+ let iface = cua_create_failure::local_network::route_interface(route_get)?;+ if cua_create_failure::local_network::is_tunnel(iface) || iface.starts_with("bridge") {+ return None;+ }+ route_get.lines().find_map(|l| {+ let gw = l.trim().strip_prefix("gateway:")?.trim();+ gw.parse::<std::net::Ipv4Addr>().ok().map(|a| a.to_string())+ })+}+/// A connect from this process to `host` on the local network: macOS/// blocks it at once ("No route to host") when Local Network access is off/// for the app responsible for this process; anything that went out@@ -410,6 +472,18 @@ mod tests {assert_eq!(subnet_host(ip("10.8.0.6"), ip("255.255.255.255")), None);}+ #[test]+ fn the_lan_probe_prefers_the_default_gateway() {+ let wifi = " route to: default\ndestination: default\n mask: default\n gateway: 192.168.1.254\n interface: en1\n";+ assert_eq!(default_gateway(wifi).as_deref(), Some("192.168.1.254"));+ // A VPN's tunnel or a link route is no local network.+ let vpn = " gateway: 10.200.1.1\n interface: utun4\n";+ assert_eq!(default_gateway(vpn), None);+ let link = " gateway: link#24\n interface: en0\n";+ assert_eq!(default_gateway(link), None);+ assert_eq!(default_gateway(""), None);+ }+#[cfg(target_os = "macos")]#[tokio::test]async fn diagnosing_is_bounded_and_never_panics() {diff --git a/libs/cua/crates/cua-vmm/src/preflight.rs b/libs/cua/crates/cua-vmm/src/preflight.rsindex c0d911bd28..b714331f6b 100644--- a/libs/cua/crates/cua-vmm/src/preflight.rs+++ b/libs/cua/crates/cua-vmm/src/preflight.rs@@ -67,6 +67,13 @@ pub fn request(guest: Guest, runs: Runs, needed_bytes: Option<u64>) -> Request {/// Finds what `req` needs to know about this machine.pub async fn gather(req: &Request) -> Facts {+ gather_waiting(req, std::time::Duration::ZERO).await+}++/// [`gather`] for a create that is about to start: a Mac that cannot reach+/// its local network gets `patience` for someone to answer macOS's prompt+/// (the probe's own connect raises it) before it counts as blocked.+pub async fn gather_waiting(req: &Request, patience: std::time::Duration) -> Facts {let mut facts = Facts {free_bytes: crate::disk::space(&crate::host::cua_home()).ok()@@ -80,7 +87,7 @@ pub async fn gather(req: &Request) -> Facts {facts.virtualization = virtualization(req.host);}if req.host == Host::Macos && req.guest == Guest::Macos {- facts.local_network_blocked = local_network_blocked().await;+ facts.local_network_blocked = local_network_blocked(patience).await;}facts}@@ -202,18 +209,23 @@ fn windows_hypervisor_platform_off() -> bool {.exists()}-async fn local_network_blocked() -> bool {+/// Whether this process is blocked from the local network the macOS VMs+/// are on. A running VM is the best test; with none (a first create), a+/// connect to the router from this process says the same, and is what makes+/// macOS ask, in the daemon's name, before anything is pulled.+async fn local_network_blocked(patience: std::time::Duration) -> bool {+ use cua_create_failure::local_network::Access;#[cfg(feature = "lume")]{- matches!(+ use crate::local_network::Probe;+ if matches!(crate::local_network::probe(&crate::local_network::lume_base()).await,- crate::local_network::Probe::Blocked { .. }- )- }- #[cfg(not(feature = "lume"))]- {- false+ Probe::Reached { .. }+ ) {+ return false;+ }}+ crate::local_network::wait_for_lan_access(patience).await == Access::Blocked}#[cfg(test)]