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
feat(spaces): second-agent and risky-action prompts for This Mac (#5459)
Francesco Bonacci41648bc84e65
diff --git a/apps/cua-spaces-desktop/src/bridge/index.ts b/apps/cua-spaces-desktop/src/bridge/index.tsindex 7fe350bc33..d243fa74c8 100644--- a/apps/cua-spaces-desktop/src/bridge/index.ts+++ b/apps/cua-spaces-desktop/src/bridge/index.ts@@ -25,6 +25,7 @@ import { keyvaultMethods } from "./keyvault";import { hostStatus, machinesMethods } from "./machines";import { ELECTRON_METHODS, METHODS } from "./methods";import { notificationsMethods } from "./notifications";+import { nudgesMethods } from "./nudges";import { onboardingMethods } from "./onboarding";import { presenceMethods } from "./presence";import { relayUsageMethods } from "./relay-usage";@@ -70,6 +71,7 @@ export const AREAS = [streamMethods,onboardingMethods,relayUsageMethods,+ nudgesMethods,resourcesMethods,checklistMethods,presenceMethods,diff --git a/apps/cua-spaces-desktop/src/bridge/methods.ts b/apps/cua-spaces-desktop/src/bridge/methods.tsindex 3e6dd1bf64..03751c4f6a 100644--- a/apps/cua-spaces-desktop/src/bridge/methods.ts+++ b/apps/cua-spaces-desktop/src/bridge/methods.ts@@ -44,6 +44,7 @@ export const METHODS = ["window.setBackgroundColor", "window.setDragRegions", "window.setDropTargets","startup.get", "startup.act","relay.usage",+ "nudges.pending", "nudges.answer","resources.get","checklist.get", "checklist.send",] as const;diff --git a/apps/cua-spaces-desktop/src/bridge/nudges.ts b/apps/cua-spaces-desktop/src/bridge/nudges.tsnew file mode 100644index 0000000000..0f230dc471--- /dev/null+++ b/apps/cua-spaces-desktop/src/bridge/nudges.ts@@ -0,0 +1,67 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The risky-action question's files (`cua config set nudges.risky_actions+// on`): `cua mcp` writes `$CUA_HOME/nudges/<id>.json` and waits for+// `<id>.answer` (`separate` or `here`); with no answer in time it runs the+// call here (`libs/cua/crates/cua-cli/src/risky.rs`). The same reads and+// writes as the SwiftUI host's `NudgeRequests`.+import { existsSync, readdirSync, readFileSync, writeFileSync } from "node:fs";+import path from "node:path";++import { cuaHome } from "../model/daemon";+import type { BridgeContext } from "./context";+import { Failure, type Handlers } from "./host";++const ID = /^risky-[0-9]+-[0-9]+$/;++export interface RiskyRequest {+ id: string;+ agent: string;+ action: string;+ atMs: number;+ expiresMs: number;+}++/** Requests still waiting (no answer, not past their deadline), oldest first. */+export function pendingRequests(dir: string, nowMs = Date.now()): RiskyRequest[] {+ let names: string[];+ try {+ names = readdirSync(dir);+ } catch {+ return [];+ }+ const out: RiskyRequest[] = [];+ for (const name of names) {+ if (!name.endsWith(".json")) continue;+ const id = name.slice(0, -5);+ if (!ID.test(id) || existsSync(path.join(dir, `${id}.answer`))) continue;+ try {+ const r = JSON.parse(readFileSync(path.join(dir, name), "utf8")) as Partial<RiskyRequest>;+ if (typeof r.expiresMs !== "number" || r.expiresMs <= nowMs) continue;+ out.push({ id, agent: String(r.agent ?? ""), action: String(r.action ?? ""), atMs: Number(r.atMs ?? 0), expiresMs: r.expiresMs });+ } catch {+ // Being written, or not ours: skip it.+ }+ }+ return out.sort((a, b) => a.atMs - b.atMs);+}++/** Answers a waiting request; one that is gone (it ran here already) is left alone. */+export function answerRequest(dir: string, id: string, choice: string): void {+ if (!ID.test(id) || (choice !== "separate" && choice !== "here")) return;+ if (!existsSync(path.join(dir, `${id}.json`))) return;+ writeFileSync(path.join(dir, `${id}.answer`), choice);+}++export function nudgesMethods(_ctx: BridgeContext, dir: () => string = () => path.join(cuaHome(), "nudges")): Handlers {+ return {+ "nudges.pending": async () => pendingRequests(dir()),+ "nudges.answer": async (args) => {+ const { id, choice } = args;+ if (typeof id !== "string" || typeof choice !== "string") throw Failure.badArgs("id: string, choice: separate or here");+ answerRequest(dir(), id, choice);+ return null;+ },+ };+}diff --git a/apps/cua-spaces-desktop/test/nudges.test.ts b/apps/cua-spaces-desktop/test/nudges.test.tsnew file mode 100644index 0000000000..baedd25319--- /dev/null+++ b/apps/cua-spaces-desktop/test/nudges.test.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";+import { tmpdir } from "node:os";+import path from "node:path";+import { afterEach, describe, expect, it } from "vitest";++import { answerRequest, pendingRequests } from "../src/bridge/nudges";++const dirs: string[] = [];+const fresh = () => {+ const d = mkdtempSync(path.join(tmpdir(), "nudges-"));+ dirs.push(d);+ return d;+};+const request = (dir: string, id: string, expiresMs: number) =>+ writeFileSync(path.join(dir, `${id}.json`), JSON.stringify({ id, agent: "Codex", action: "uninstall an app", atMs: 1, expiresMs }));++afterEach(() => {+ for (const d of dirs.splice(0)) rmSync(d, { recursive: true, force: true });+});++describe("the risky-action question's files", () => {+ it("lists waiting requests and writes the answer next to one", () => {+ const dir = fresh();+ request(dir, "risky-1-100", 5_000);+ request(dir, "risky-2-200", 500);+ expect(pendingRequests(dir, 1_000).map((r) => r.id)).toEqual(["risky-1-100"]);+ answerRequest(dir, "risky-1-100", "separate");+ expect(readFileSync(path.join(dir, "risky-1-100.answer"), "utf8")).toBe("separate");+ expect(pendingRequests(dir, 1_000)).toEqual([]);+ });++ it("leaves anything else alone", () => {+ const dir = fresh();+ answerRequest(dir, "risky-3-300", "here");+ expect(existsSync(path.join(dir, "risky-3-300.answer"))).toBe(false);+ request(dir, "risky-4-400", 5_000);+ answerRequest(dir, "../risky-4-400", "here");+ answerRequest(dir, "risky-4-400", "delete");+ expect(existsSync(path.join(dir, "risky-4-400.answer"))).toBe(false);+ expect(pendingRequests(path.join(dir, "missing"))).toEqual([]);+ });+});diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Nudges.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Nudges.swiftnew file mode 100644index 0000000000..b4da00d88f--- /dev/null+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge+Nudges.swift@@ -0,0 +1,77 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation++/// The risky-action question's files (`cua config set nudges.risky_actions+/// on`): `cua mcp` writes `$CUA_HOME/nudges/<id>.json` and waits for+/// `<id>.answer` (`separate` or `here`); with no answer in time it runs the+/// call here (`libs/cua/crates/cua-cli/src/risky.rs`). The web page asks+/// through `nudges.pending` and `nudges.answer` and draws the question.+struct NudgeRequests {+ let dir: URL++ init(home: URL = NudgeRequests.cuaHome) {+ dir = home.appendingPathComponent("nudges", isDirectory: true)+ }++ /// The cua home `cua mcp` uses: `CUA_HOME`, else `~/.cua`+ /// (`~/.cua/envs/staging` under `CUA_ENV=staging`, as `cua_home()`).+ static var cuaHome: URL {+ let env = ProcessInfo.processInfo.environment+ if let home = env["CUA_HOME"], !home.isEmpty { return URL(fileURLWithPath: home, isDirectory: true) }+ let base = URL(fileURLWithPath: env["HOME"] ?? NSHomeDirectory(), isDirectory: true)+ .appendingPathComponent(".cua", isDirectory: true)+ let staging = (env["CUA_ENV"] ?? "").trimmingCharacters(in: .whitespaces).lowercased() == "staging"+ return staging ? base.appendingPathComponent("envs/staging", isDirectory: true) : base+ }++ /// An id as `cua mcp` writes it, so no path can hide in one.+ static func validId(_ id: String) -> Bool {+ id.range(of: #"^risky-[0-9]+-[0-9]+$"#, options: .regularExpression) != nil+ }++ /// Requests still waiting (no answer, not past their deadline), oldest+ /// first, as the page reads them (`RiskyRequest`).+ func pending(nowMs: Double = Date().timeIntervalSince1970 * 1000) -> [[String: Any]] {+ let names = (try? FileManager.default.contentsOfDirectory(atPath: dir.path)) ?? []+ return names.compactMap { name -> [String: Any]? in+ guard name.hasSuffix(".json") else { return nil }+ let id = String(name.dropLast(5))+ guard Self.validId(id),+ !FileManager.default.fileExists(atPath: dir.appendingPathComponent("\(id).answer").path),+ let data = try? Data(contentsOf: dir.appendingPathComponent(name)),+ let obj = try? JSONSerialization.jsonObject(with: data) as? [String: Any],+ let expires = (obj["expiresMs"] as? NSNumber)?.doubleValue, expires > nowMs+ else { return nil }+ return ["id": id, "agent": obj["agent"] as? String ?? "", "action": obj["action"] as? String ?? "",+ "atMs": (obj["atMs"] as? NSNumber)?.doubleValue ?? 0, "expiresMs": expires]+ }+ .sorted { ($0["atMs"] as? Double ?? 0) < ($1["atMs"] as? Double ?? 0) }+ }++ /// Answers a waiting request. One that is gone (it ran here already)+ /// is left alone.+ func answer(id: String, choice: String) throws {+ guard Self.validId(id), choice == "separate" || choice == "here" else { return }+ guard FileManager.default.fileExists(atPath: dir.appendingPathComponent("\(id).json").path) else { return }+ try Data(choice.utf8).write(to: dir.appendingPathComponent("\(id).answer"), options: .atomic)+ }+}++extension WebUIBridge {+ func routeNudges(_ method: String, _ args: [String: Any]) throws -> Any? {+ switch method {+ case "nudges.pending":+ return NudgeRequests().pending()+ case "nudges.answer":+ guard let id = args["id"] as? String, let choice = args["choice"] as? String else {+ throw Failure.badArgs("id: string, choice: separate or here")+ }+ try NudgeRequests().answer(id: id, choice: choice)+ return NSNull()+ default:+ return nil+ }+ }+}diff --git a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swiftindex e7fb661a3c..ab41f88866 100644--- a/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift+++ b/apps/cua-spaces-macos/Sources/CuaSpacesMacKit/WebHost/WebUIBridge.swift@@ -112,6 +112,8 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {"startup.get", "startup.act",// The relay allowance this month (WebUIBridge+Pages.swift)."relay.usage",+ // The risky-action question's request files (WebUIBridge+Nudges.swift).+ "nudges.pending", "nudges.answer",// Processor, memory and disk (WebUIBridge+Pages.swift)."resources.get",// The getting-started checklist: the app's one copy (`ChecklistModel`).@@ -391,6 +393,7 @@ final class WebUIBridge: NSObject, WKScriptMessageHandlerWithReply {if let result = try await routeThumbnail(method, args) { return result }if let result = try await routeFiles(method, args) { return result }if let result = try await routePage(method, args) { return result }+ if let result = try routeNudges(method, args) { return result }throw Failure.unimplemented(method)}}diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swiftindex cc743855fb..d565e364e8 100644--- a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/BridgeContractTests.swift@@ -200,6 +200,9 @@ struct BridgeContractTests {func cases(space: String) -> [(String, [String: Any])] {[// The relay allowance before the sign-out below (signed out, it is null).+ ("app.info", [:]), ("session.get", [:]), ("relay.usage", [:]), ("session.signOut", [:]),+ // No request is waiting on the fixtures: an answer to none is left alone.+ ("nudges.pending", [:]), ("nudges.answer", ["id": "risky-1-1", "choice": "here"]),("app.info", [:]), ("session.get", [:]), ("relay.usage", [:]), ("resources.get", ["visible": true]), ("session.signOut", [:]),("checklist.get", [:]), ("checklist.send", ["action": ["type": "done", "step": "teleport"]]),("spaces.list", [:]),diff --git a/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/NudgeRequestsTests.swift b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/NudgeRequestsTests.swiftnew file mode 100644index 0000000000..f5ed3d3388--- /dev/null+++ b/apps/cua-spaces-macos/Tests/CuaSpacesMacTests/NudgeRequestsTests.swift@@ -0,0 +1,50 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import Foundation+import Testing+@testable import CuaSpacesMacKit++struct NudgeRequestsTests {+ func home() throws -> URL {+ let dir = FileManager.default.temporaryDirectory.appendingPathComponent("nudges-\(UUID().uuidString)")+ try FileManager.default.createDirectory(at: dir.appendingPathComponent("nudges"), withIntermediateDirectories: true)+ return dir+ }++ func write(_ home: URL, _ id: String, expiresMs: Double) throws {+ let body: [String: Any] = ["id": id, "agent": "Claude Code", "action": "empty the Trash", "atMs": 1, "expiresMs": expiresMs]+ try JSONSerialization.data(withJSONObject: body)+ .write(to: home.appendingPathComponent("nudges/\(id).json"))+ }++ @Test func listsWaitingRequestsAndWritesTheAnswer() throws {+ let home = try home()+ defer { try? FileManager.default.removeItem(at: home) }+ let requests = NudgeRequests(home: home)+ try write(home, "risky-1-100", expiresMs: 5_000)+ try write(home, "risky-2-200", expiresMs: 500) // past its deadline+ let pending = requests.pending(nowMs: 1_000)+ #expect(pending.map { $0["id"] as? String } == ["risky-1-100"])+ #expect(pending.first?["action"] as? String == "empty the Trash")++ try requests.answer(id: "risky-1-100", choice: "separate")+ let answer = try String(contentsOf: home.appendingPathComponent("nudges/risky-1-100.answer"), encoding: .utf8)+ #expect(answer == "separate")+ #expect(requests.pending(nowMs: 1_000).isEmpty)+ }++ @Test func leavesAnythingElseAlone() throws {+ let home = try home()+ defer { try? FileManager.default.removeItem(at: home) }+ let requests = NudgeRequests(home: home)+ // No request with this id: nothing is written.+ try requests.answer(id: "risky-3-300", choice: "here")+ #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("nudges/risky-3-300.answer").path))+ // An id that names a path, or an unknown choice, is refused.+ #expect(!NudgeRequests.validId("../settings"))+ try write(home, "risky-4-400", expiresMs: 5_000)+ try requests.answer(id: "risky-4-400", choice: "delete")+ #expect(!FileManager.default.fileExists(atPath: home.appendingPathComponent("nudges/risky-4-400.answer").path))+ }+}diff --git a/apps/cua-spaces-web/src/__tests__/this-mac-nudges.test.tsx b/apps/cua-spaces-web/src/__tests__/this-mac-nudges.test.tsxnew file mode 100644index 0000000000..9f07b5452d--- /dev/null+++ b/apps/cua-spaces-web/src/__tests__/this-mac-nudges.test.tsx@@ -0,0 +1,143 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++// The two This Mac prompts on the real app and the wasm core: a second+// agent on this Mac's desktop (from the access log `host.status` carries),+// and the risky-action question `cua mcp` holds (`nudges.pending`). The+// moments, rules and words are the core's `nudges`.++import { act, cleanup, fireEvent, waitFor } from "@testing-library/react";+import { afterEach, describe, expect, it } from "vitest";++import { wasmBuilt } from "@/bridge/__tests__/testCore";+import type { HostAccess } from "@/bridge/contracts/host";+import { localDay, resetNudgeMemory } from "@/bridge/nudges";+import type { RiskyRequest } from "@/bridge/ops/nudges";+import { mountApp, stubBrowserApis, type TestHost } from "./app-harness";++afterEach(() => {+ cleanup();+ localStorage.clear();+ resetNudgeMemory("This Mac");+});+stubBrowserApis();++const agent = (name: string, id: string) => `[email protected] (acct-ada) · agent ${name} (${id})`;++function twoAgents(now = Date.now()): HostAccess[] {+ return [+ { atMs: now - 5_000, via: "relay", who: agent("Codex", "agent:codex-5120"), what: "DriverService" },+ { atMs: now - 20_000, via: "relay", who: agent("Claude Code", "agent:claude-code-4242"), what: "ComputerService" },+ { atMs: now - 12 * 60_000, via: "relay", who: agent("Claude Code", "agent:claude-code-4242"), what: "DriverService" },+ ];+}++interface Calls {+ creates: { os?: string }[];+ answers: { id: string; choice: string }[];+}++function host(calls: Calls, opts: { access?: HostAccess[]; pending?: RiskyRequest[] } = {}): TestHost {+ let pending = opts.pending ?? [];+ return {+ failsCreates: false,+ listsGhost: false,+ answer: (op, out) => (op === "host.status" && opts.access ? { ...(out as object), recentAccess: opts.access } : out),+ intercept: (op, args) => {+ if (op === "spaces.create") calls.creates.push(args as { os?: string });+ if (op === "nudges.pending") return pending;+ if (op === "nudges.answer") {+ const a = args as { id: string; choice: string };+ calls.answers.push(a);+ pending = pending.filter((r) => r.id !== a.id);+ return null;+ }+ return undefined;+ },+ };+}++const card = (kind: string) =>+ waitFor(() => {+ const el = document.querySelector(`[data-nudge=${kind}]`);+ expect(el).toBeTruthy();+ return el as HTMLElement;+ });++const settle = () => act(() => new Promise((r) => setTimeout(r, 60)));++describe.skipIf(!wasmBuilt)("This Mac prompts (real routes, wasm core)", () => {+ it("a second agent on the desktop: shared mouse, Add a Space starts macOS in the background", async () => {+ const calls: Calls = { creates: [], answers: [] };+ const { router } = await mountApp("/spaces", host(calls, { access: twoAgents() }));+ await router.load();+ const el = await card("second-agent");+ expect(el.textContent).toContain("Codex just started on this Mac");+ expect(el.textContent).toContain("Claude Code is already working here.");+ expect(el.textContent).toContain("They'll share your mouse. Add a Space so they each get their own?");+ expect(el.querySelector("[data-nudge-secondary]")?.textContent).toBe("Keep sharing");+ fireEvent.click(el.querySelector("[data-nudge-primary]")!);+ expect(document.querySelector("[data-nudge]")).toBeNull();+ await waitFor(() => expect(calls.creates.length).toBe(1), { timeout: 4_000 });+ expect(calls.creates[0]?.os).toBe("macos");+ });++ it("once a day per computer, and never after Don't ask again", async () => {+ const calls: Calls = { creates: [], answers: [] };+ const first = await mountApp("/spaces", host(calls, { access: twoAgents() }));+ await first.router.load();+ fireEvent.click((await card("second-agent")).querySelector("[data-nudge-secondary]")!);+ expect(JSON.parse(localStorage.getItem("cua.nudge.secondAgent.This Mac")!).shownDay).toBe(localDay());+ cleanup();+ // Same day: not again.+ const again = await mountApp("/spaces", host(calls, { access: twoAgents() }));+ await again.router.load();+ await settle();+ expect(document.querySelector("[data-nudge]")).toBeNull();+ cleanup();+ // Another day it may show; Don't ask again turns it off for good.+ localStorage.setItem("cua.nudge.secondAgent.This Mac", JSON.stringify({ shownDay: "2000-01-01", off: false }));+ const later = await mountApp("/spaces", host(calls, { access: twoAgents() }));+ await later.router.load();+ fireEvent.click((await card("second-agent")).querySelector("[data-nudge-never]")!);+ expect(JSON.parse(localStorage.getItem("cua.nudge.secondAgent.This Mac")!).off).toBe(true);+ expect(calls.creates).toEqual([]);+ });++ it("no prompt for one agent", async () => {+ const calls: Calls = { creates: [], answers: [] };+ const { router } = await mountApp("/spaces", host(calls, { access: twoAgents().slice(1) }));+ await router.load();+ await settle();+ expect(document.querySelector("[data-nudge]")).toBeNull();+ });++ it("a risky action: Run it here answers here; a separate Space answers separate and starts one", async () => {+ const calls: Calls = { creates: [], answers: [] };+ const now = Date.now();+ const pending: RiskyRequest[] = [+ { id: "risky-4242-1", agent: "Claude Code", action: "run an installer", atMs: now, expiresMs: now + 30_000 },+ { id: "risky-4242-2", agent: "Claude Code", action: "empty the Trash", atMs: now + 1, expiresMs: now + 30_000 },+ ];+ const { router } = await mountApp("/spaces", host(calls, { pending }));+ await router.load();+ const el = await card("risky-action");+ expect(el.textContent).toContain("Claude Code wants to run an installer on your desktop");+ expect(el.textContent).toContain("Run this in a separate Space instead?");+ expect(el.textContent).toMatch(/If you don't choose, it runs here in \d+ seconds\./);+ expect(el.querySelector("[data-nudge-never]")).toBeNull();+ fireEvent.click(el.querySelector("[data-nudge-secondary]")!);+ expect(calls.answers).toEqual([{ id: "risky-4242-1", choice: "here" }]);+ const next = await waitFor(+ () => {+ const n = document.querySelector("[data-nudge=risky-action]");+ expect(n?.textContent).toContain("empty the Trash");+ return n as HTMLElement;+ },+ { timeout: 3_000 },+ );+ fireEvent.click(next.querySelector("[data-nudge-primary]")!);+ expect(calls.answers[1]).toEqual({ id: "risky-4242-2", choice: "separate" });+ await waitFor(() => expect(calls.creates.length).toBe(1), { timeout: 4_000 });+ });+});diff --git a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.tsindex 85a8ccc1d7..f5a5167e98 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/contract-args.ts@@ -95,6 +95,8 @@ export const DEMO_ARGS: { [K in OpName]: OpArgs<K> } = {"agents.setupDriver": { agents: ["codex"] },"spaces.openStream": { spaceId: SPACE, tier: "tile" },"relay.usage": {},+ "nudges.pending": {},+ "nudges.answer": { id: "risky-1-1", choice: "here" },"resources.get": { visible: true },"checklist.get": {},"checklist.send": { action: { type: "done", step: "teleport" } },diff --git a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.tsindex d6bdae8d47..9a5a1ec57f 100644--- a/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts+++ b/apps/cua-spaces-web/src/bridge/__tests__/coverage.test.ts@@ -15,6 +15,7 @@ import { KEYVAULT_MANAGE_ARGS } from "../ops/keyvault-manage";import { KEYVAULT_SETUP_ARGS } from "../ops/keyvault-setup";import { STREAM_ARGS } from "../ops/stream";import { RELAY_USAGE_ARGS } from "../ops/relay-usage";+import { NUDGES_ARGS } from "../ops/nudges";import { RESOURCES_ARGS } from "../ops/resources";import { CHECKLIST_ARGS } from "../ops/checklist";import { PRESENCE_ARGS } from "../ops/presence";@@ -128,6 +129,7 @@ const ARGS: { [K in OpName]: OpArgs<K> } = {"startup.act": { action: "allowAccess" },...STREAM_ARGS,...RELAY_USAGE_ARGS,+ ...NUDGES_ARGS,...RESOURCES_ARGS,...CHECKLIST_ARGS,...PRESENCE_ARGS,diff --git a/apps/cua-spaces-web/src/bridge/adapters/demo.ts b/apps/cua-spaces-web/src/bridge/adapters/demo.tsindex 76411c0937..432d1c138d 100644--- a/apps/cua-spaces-web/src/bridge/adapters/demo.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/demo.ts@@ -7,6 +7,7 @@* sign-in finishes in the "browser"). Used when no host is detected.*/+import type { RiskyRequest } from "../ops/nudges";import { Emitter, HostError, UnsupportedOperationError, type DataAdapter } from "../adapter";import type { AgentSetupRow, PersistentAgent } from "../contracts/agents";import type { MachineRow, OnboardingState } from "../contracts/host";@@ -85,6 +86,8 @@ export interface DemoOptions {platform?: DemoPlatform;/** Where the updater is at start (`?demo=update-ready`, `?demo=update-downloading`). */update?: Partial<UpdateState>;+ /** A This Mac prompt to show (`?demo=nudge-second-agent`, `?demo=nudge-risky`). */+ nudge?: "second-agent" | "risky";}const DEMO_NOTES = "https://github.com/trycua/cua/releases/tag/cua-spaces-v0.9.3";@@ -109,6 +112,7 @@ export function demoOptionsFromSearch(search: string): DemoOptions {macHost: flags.has("mac-host"),unenrolled: flags.has("unenrolled"),usage: (["idle", "warn", "limit", "pro", "teams"] as const).find((u) => flags.has(`usage-${u}`)),+ nudge: (["second-agent", "risky"] as const).find((n) => flags.has(`nudge-${n}`)),disk: flags.has("disk-full") ? "full" : flags.has("low-disk") ? "low" : undefined,...(flags.has("update-ready")? { update: { status: "downloaded" as const, version: "0.9.3", percent: 100, notesUrl: DEMO_NOTES } }@@ -179,6 +183,22 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re};if (state.platform.os !== "macos") state.host = { ...state.host, name: demoMachine(state.platform).name };+ // Claude Code has been on the desktop for a while; Codex just started.+ if (options.nudge === "second-agent") {+ const t = now();+ const agent = (name: string, id: string) => `${DEMO_IDENTITY} (acct-ada) \u00b7 agent ${name} (${id})`;+ state.host = {+ ...state.host,+ recentAccess: [+ { atMs: t - 5_000, via: "relay", who: agent("Codex", "agent:codex-5120"), what: "DriverService" },+ { atMs: t - 20_000, via: "relay", who: agent("Claude Code", "agent:claude-code-4242"), what: "ComputerService" },+ { atMs: t - 12 * 60_000, via: "relay", who: agent("Claude Code", "agent:claude-code-4242"), what: "DriverService" },+ ...(state.host.recentAccess ?? []),+ ],+ };+ }+ let risky: RiskyRequest[] =+ options.nudge === "risky" ? [{ id: "risky-4242-1", agent: "Claude Code", action: "run an installer", atMs: now(), expiresMs: now() + 30_000 }] : [];const later = (ms: number, f: () => void) => {const t = setTimeout(() => {@@ -504,6 +524,11 @@ export function createDemoAdapter(options: DemoOptions = {}): DataAdapter & { re...createDemoSettings({ now, wait, emit, stepMs: step, platform: state.platform, unenrolled: options.unenrolled, update: options.update, experiments: state.volume.experiments, signedIn: () => Boolean(state.identity), settings: () => state.settings, setSettings: (p) => ((state.settings = { ...state.settings, ...p }), emit({ type: "settings.changed" })), addMachine: (m) => ((state.paired = [...state.paired, m]), emit({ type: "machines.changed" })) }),...demoTelemetryHandlers(ctx),...demoRelayUsageHandlers(ctx),+ "nudges.pending": () => risky.filter((r) => r.expiresMs > now()).map((r) => ({ ...r })),+ "nudges.answer": ({ id }) => {+ risky = risky.filter((r) => r.id !== id);+ return null;+ },...demoResourcesHandlers(ctx),...demoSpaceDetailHandlers(ctx),...demoHostSetupHandlers(ctx),diff --git a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts b/apps/cua-spaces-web/src/bridge/adapters/tauri.tsindex 7a6f634b41..686c0b46ed 100644--- a/apps/cua-spaces-web/src/bridge/adapters/tauri.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/tauri.ts@@ -57,6 +57,7 @@ import { tauriHostSetupOps } from "../ops/host-setup";import { TAURI_SPACE_DETAIL_UNSUPPORTED, tauriSpaceDetailOps } from "../ops/space-detail";import { STREAM_OPERATIONS } from "../ops/stream";import { RELAY_USAGE_OPERATIONS } from "../ops/relay-usage";+import { NUDGES_OPERATIONS } from "../ops/nudges";import { RESOURCES_OPERATIONS } from "../ops/resources";import { CHECKLIST_OPERATIONS } from "../ops/checklist";import { PRESENCE_OPERATIONS } from "../ops/presence";@@ -93,6 +94,7 @@ export const TAURI_UNSUPPORTED: readonly OpName[] = [...TAURI_SPACE_DETAIL_UNSUPPORTED,...STREAM_OPERATIONS,...RELAY_USAGE_OPERATIONS,+ ...NUDGES_OPERATIONS,...RESOURCES_OPERATIONS,...CHECKLIST_OPERATIONS,...PRESENCE_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts b/apps/cua-spaces-web/src/bridge/adapters/webkit.tsindex 1fea21e8a2..6c34807a50 100644--- a/apps/cua-spaces-web/src/bridge/adapters/webkit.ts+++ b/apps/cua-spaces-web/src/bridge/adapters/webkit.ts@@ -58,6 +58,7 @@ import { webkitSettingsOps } from "../ops/settings";import { startupFromHost, webkitStartupOps } from "../ops/startup";import { unsupportedStreamOps, type StreamTicket } from "../ops/stream";import type { RelayUsage } from "../ops/relay-usage";+import type { RiskyRequest } from "../ops/nudges";import type { ResourcesSnapshot } from "../ops/resources";import type { HostChecklistState } from "../ops/checklist";import { unsupportedPresenceOps, type PresenceJoinInfo } from "../ops/presence";@@ -644,6 +645,8 @@ export function createWebkitAdapter(? { "spaces.openStream": (target: OpArgs<"spaces.openStream">) => request<StreamTicket>("spaces.openStream", { ...target }) }: unsupportedStreamOps("webkit")),"relay.usage": () => request<RelayUsage | null>("relay.usage"),+ "nudges.pending": () => request<RiskyRequest[]>("nudges.pending"),+ "nudges.answer": ({ id, choice }) => request<null>("nudges.answer", { id, choice }),"resources.get": ({ visible }) => request<ResourcesSnapshot | null>("resources.get", { visible }),"checklist.get": () => request<{ state: HostChecklistState }>("checklist.get"),"checklist.send": ({ action }) => request<{ state: HostChecklistState }>("checklist.send", { action }),diff --git a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.jsonindex f171322708..ea13c57b5b 100644--- a/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json+++ b/apps/cua-spaces-web/src/bridge/contracts/bridge-shapes.json@@ -4849,6 +4849,39 @@"notifications.markRead": {"type": "null"},+ "nudges.answer": {+ "type": "null"+ },+ "nudges.pending": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "agent": {+ "type": "string"+ },+ "action": {+ "type": "string"+ },+ "atMs": {+ "type": "number"+ },+ "expiresMs": {+ "type": "number"+ }+ },+ "required": [+ "id",+ "agent",+ "action",+ "atMs",+ "expiresMs"+ ]+ }+ },"presence.join": {"type": "object","properties": {@@ -6424,6 +6457,39 @@"notifications.markRead": {"type": "null"},+ "nudges.answer": {+ "type": "null"+ },+ "nudges.pending": {+ "type": "array",+ "items": {+ "type": "object",+ "properties": {+ "id": {+ "type": "string"+ },+ "agent": {+ "type": "string"+ },+ "action": {+ "type": "string"+ },+ "atMs": {+ "type": "number"+ },+ "expiresMs": {+ "type": "number"+ }+ },+ "required": [+ "id",+ "agent",+ "action",+ "atMs",+ "expiresMs"+ ]+ }+ },"onboarding.complete": {"$ref": "#/$defs/WkOnboarding"},diff --git a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts b/apps/cua-spaces-web/src/bridge/contracts/shapes.tsindex 7676d44848..f2bbed4169 100644--- a/apps/cua-spaces-web/src/bridge/contracts/shapes.ts+++ b/apps/cua-spaces-web/src/bridge/contracts/shapes.ts@@ -60,6 +60,7 @@ import type { AgentSetupOutcome, DriveGrantInput, DriveMountInput, DriveRequestIimport type { AgentKeysReport } from "../ops/agent-keys";import type { SentFileInfo, SpaceThumbnail, SpaceUsage, SpaceWindows } from "../ops/space-detail";import type { RelayUsage } from "../ops/relay-usage";+import type { RiskyRequest } from "../ops/nudges";import type { ComputerResources, DiskOnHost, DiskWarning, GuestUsage, ResourcesSnapshot, SpaceResources } from "../ops/resources";import type { HostChecklistState } from "../ops/checklist";import type { PresenceCursorWire, PresenceJoinInfo, PresenceParticipantWire } from "../ops/presence";@@ -852,6 +853,8 @@ export const OP_SHAPES: Record<OpName, Schema> = {"agents.setupDriver": list(obj<AgentSetupOutcome>()({ agents: strings, target: str, item: str, change: str, detail: str })),"spaces.openStream": obj<StreamTicket>()({ wsUrl: str, expiresAt: nullable(str) }),+ "nudges.pending": list(obj<RiskyRequest>()({ id: str, agent: str, action: str, atMs: num, expiresMs: num })),+ "nudges.answer": nul,"relay.usage": nullable(obj<RelayUsage>()({metered: bool,@@ -1288,6 +1291,8 @@ export const WEBKIT_SHAPES: Partial<Record<WebkitMethod, Schema>> = {"startup.get": StartupShape,"startup.act": StartupShape,"relay.usage": OP_SHAPES["relay.usage"],+ "nudges.pending": OP_SHAPES["nudges.pending"],+ "nudges.answer": nul,"resources.get": OP_SHAPES["resources.get"],"checklist.get": OP_SHAPES["checklist.get"],"checklist.send": OP_SHAPES["checklist.send"],diff --git a/apps/cua-spaces-web/src/bridge/coverage.ts b/apps/cua-spaces-web/src/bridge/coverage.tsindex 14fd4705b5..822cc9ef51 100644--- a/apps/cua-spaces-web/src/bridge/coverage.ts+++ b/apps/cua-spaces-web/src/bridge/coverage.ts@@ -40,6 +40,7 @@ import { HOST_SETUP_COVERAGE } from "./ops/host-setup";import { SPACE_DETAIL_COVERAGE } from "./ops/space-detail";import { STREAM_COVERAGE } from "./ops/stream";import { RELAY_USAGE_COVERAGE } from "./ops/relay-usage";+import { NUDGES_COVERAGE } from "./ops/nudges";import { RESOURCES_COVERAGE } from "./ops/resources";import { CHECKLIST_COVERAGE } from "./ops/checklist";import { PRESENCE_COVERAGE } from "./ops/presence";@@ -165,6 +166,7 @@ export const HOST_COVERAGE = {...STARTUP_COVERAGE,...STREAM_COVERAGE,...RELAY_USAGE_COVERAGE,+ ...NUDGES_COVERAGE,...RESOURCES_COVERAGE,...CHECKLIST_COVERAGE,...PRESENCE_COVERAGE,diff --git a/apps/cua-spaces-web/src/bridge/nudges.ts b/apps/cua-spaces-web/src/bridge/nudges.tsnew file mode 100644index 0000000000..71ddc3553c--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/nudges.ts@@ -0,0 +1,219 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The two This Mac prompts. The moments, rules and words are the app+ * core's (`nudge.secondAgent`, `nudge.riskyAction`,+ * `cua-spaces-app-core/src/nudges.rs`); this reads what they need, keeps+ * what the page remembers, and draws nothing.+ *+ * - A second agent: this Mac's access log (`host.status` → `recentAccess`),+ * read every {@link SECOND_AGENT_POLL_MS}. Shown at most once a day per+ * computer; "Don't ask again" turns it off for that computer.+ * - A risky action: the requests `cua mcp` holds (`nudges.pending`), read+ * every {@link RISKY_POLL_MS} where the host answers it.+ *+ * "Add a Space" and "Use a separate Space" start the same one-click create+ * the first run offers ({@link useAddSpaceWhenReady} over+ * `useFirstSpaceOffers`): macOS first, Linux when this Mac can't make+ * macOS, in the background. Nothing waits on it.+ */++import { useContext, useEffect, useRef, useState } from "react";++import { isUnsupported } from "./adapter";+import { BridgeContext } from "./BridgeProvider";+import type { HostAccess } from "./contracts/host";+import { useSpaces } from "./hooks";+import { useFirstSpaceOffers } from "./new-space-hooks";+import type { RiskyChoice, RiskyRequest } from "./ops/nudges";++/** `nudges::Nudge`. */+export interface Nudge {+ kind: "second-agent" | "risky-action";+ key: string;+ eyebrow: string;+ title: string;+ body: string;+ note: string | null;+ primary: string;+ secondary: string;+ never: string | null;+}++/** `nudges::NudgeMemory`. */+interface NudgeMemory {+ shownDay: string | null;+ off: boolean;+}++export const SECOND_AGENT_POLL_MS = 15_000;+export const RISKY_POLL_MS = 1_000;++const memoryKey = (computer: string) => `cua.nudge.secondAgent.${computer}`;++function readMemory(computer: string): NudgeMemory {+ try {+ const raw = JSON.parse(globalThis.localStorage?.getItem(memoryKey(computer)) ?? "null") as Partial<NudgeMemory> | null;+ return { shownDay: typeof raw?.shownDay === "string" ? raw.shownDay : null, off: raw?.off === true };+ } catch {+ return { shownDay: null, off: false };+ }+}++function writeMemory(computer: string, memory: NudgeMemory): void {+ try {+ globalThis.localStorage?.setItem(memoryKey(computer), JSON.stringify(memory));+ } catch {+ // Not kept: it may show again tomorrow, never twice today in this window.+ }+}++/** The local day, `2026-10-18`. */+export function localDay(at = new Date()): string {+ const p = (n: number) => String(n).padStart(2, "0");+ return `${at.getFullYear()}-${p(at.getMonth() + 1)}-${p(at.getDate())}`;+}++/** Forget what was shown and turned off (tests). */+export function resetNudgeMemory(computer: string): void {+ try {+ globalThis.localStorage?.removeItem(memoryKey(computer));+ } catch {+ // Nothing kept.+ }+}++/**+ * Starts a Space on this Mac the way the first run's one-click offer does,+ * once this Mac's options are in: macOS when it can make it, else Linux.+ * Mount it only while a Space is wanted (it loads the host's options).+ * `onDone` gets the OS started, or null when this Mac can make neither now.+ */+export function useAddSpaceWhenReady(onDone: (os: "macos" | "linux" | null) => void): void {+ const first = useFirstSpaceOffers();+ const { createSpace } = useSpaces();+ const started = useRef(false);+ useEffect(() => {+ if (started.current) return;+ const offer = first.offers.find((o) => o.os === "macos" && !o.blocked) ?? first.offers.find((o) => o.os === "linux" && !o.blocked);+ if (offer) {+ started.current = true;+ // The create runs in the background service; its row shows progress.+ createSpace({ ...offer.args, os: offer.os }).catch(() => undefined);+ onDone(offer.os);+ } else if (first.known) {+ started.current = true;+ onDone(null);+ }+ }, [first.offers, first.known, createSpace, onDone]);+}++export interface SecondAgentNudge {+ nudge: Nudge | null;+ /** Closes it; the caller starts the Space ({@link useAddSpaceWhenReady}). */+ addSpace(): void;+ keepSharing(): void;+ dontAskAgain(): void;+}++/** The second-agent prompt for this Mac, when it is the moment. */+export function useSecondAgentNudge(): SecondAgentNudge {+ const ctx = useContext(BridgeContext);+ const adapter = ctx?.adapter ?? null;+ const core = ctx?.core;+ const [shown, setShown] = useState<{ nudge: Nudge; computer: string } | null>(null);+ const shownRef = useRef(shown);+ shownRef.current = shown;++ useEffect(() => {+ if (!adapter || !core) return;+ let live = true;+ const read = () => {+ if (shownRef.current) return;+ adapter+ .call("host.status", {})+ .then((status) => {+ if (!live || !status || shownRef.current) return;+ const computer = status.name?.trim() || "this-mac";+ const today = localDay();+ const recentAccess: HostAccess[] = status.recentAccess ?? [];+ const nudge = core.tryCall<Nudge | null>("nudge.secondAgent", { recentAccess, nowMs: Date.now(), today, memory: readMemory(computer) }) ?? null;+ if (!nudge) return;+ // Once a day: counted when it shows, whatever the answer.+ writeMemory(computer, { ...readMemory(computer), shownDay: today });+ setShown({ nudge, computer });+ })+ .catch(() => undefined);+ };+ read();+ const timer = setInterval(read, SECOND_AGENT_POLL_MS);+ return () => {+ live = false;+ clearInterval(timer);+ };+ }, [adapter, core]);++ return {+ nudge: shown?.nudge ?? null,+ addSpace: () => setShown(null),+ keepSharing: () => setShown(null),+ dontAskAgain: () => {+ if (shown) writeMemory(shown.computer, { ...readMemory(shown.computer), off: true });+ setShown(null);+ },+ };+}++export interface RiskyNudge {+ nudge: Nudge | null;+ /** "Use a separate Space": the call doesn't run here; the caller starts+ * the Space ({@link useAddSpaceWhenReady}). */+ separate(): void;+ /** "Run it here". */+ here(): void;+}++/** The risky-action question, while `cua mcp` waits for an answer. */+export function useRiskyNudge(): RiskyNudge {+ const ctx = useContext(BridgeContext);+ const adapter = ctx?.adapter ?? null;+ const core = ctx?.core;+ const [request, setRequest] = useState<RiskyRequest | null>(null);+ const [now, setNow] = useState(() => Date.now());+ const answered = useRef(new Set<string>());++ useEffect(() => {+ if (!adapter) return;+ let live = true;+ let timer: ReturnType<typeof setInterval> | undefined;+ const read = () => {+ setNow(Date.now());+ adapter+ .call("nudges.pending", {})+ .then((pending) => {+ if (!live) return;+ setRequest(pending.find((r) => !answered.current.has(r.id) && r.expiresMs > Date.now()) ?? null);+ })+ .catch((e: unknown) => {+ // A host without the question never asks again this session.+ if (isUnsupported(e) && timer) clearInterval(timer);+ });+ };+ timer = setInterval(read, RISKY_POLL_MS);+ read();+ return () => {+ live = false;+ clearInterval(timer);+ };+ }, [adapter]);++ const nudge = request && core ? (core.tryCall<Nudge | null>("nudge.riskyAction", { request, nowMs: now }) ?? null) : null;+ const answer = (choice: RiskyChoice) => {+ if (!request || !adapter) return;+ answered.current.add(request.id);+ void adapter.call("nudges.answer", { id: request.id, choice }).catch(() => undefined);+ setRequest(null);+ };+ return { nudge, separate: () => answer("separate"), here: () => answer("here") };+}diff --git a/apps/cua-spaces-web/src/bridge/ops/nudges.ts b/apps/cua-spaces-web/src/bridge/ops/nudges.tsnew file mode 100644index 0000000000..c3757cae3b--- /dev/null+++ b/apps/cua-spaces-web/src/bridge/ops/nudges.ts@@ -0,0 +1,56 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++/**+ * The risky-action question (`cua config set nudges.risky_actions on`): the+ * requests `cua mcp` is holding for an answer, and the answer.+ *+ * | Operation | Electron | SwiftUI | Tauri |+ * |---|---|---|---|+ * | `nudges.pending` | the host method `nudges.pending` | the host method `nudges.pending` | unsupported |+ * | `nudges.answer` | the host method `nudges.answer` | the host method `nudges.answer` | unsupported |+ *+ * Both native hosts read `$CUA_HOME/nudges/<id>.json` and write the answer+ * next to it (`<id>.answer`: `separate` or `here`); `cua mcp` waits for it+ * (`cua-cli/src/risky.rs`), and runs the call here when none comes. Where+ * unsupported, the question never shows and every call runs as before.+ */++import type { OpCoverage } from "../coverage";++/** `nudges::RiskyRequest`: one request file. */+export interface RiskyRequest {+ id: string;+ /** "Claude Code". */+ agent: string;+ /** "empty the Trash". */+ action: string;+ atMs: number;+ /** When it runs here without an answer. */+ expiresMs: number;+}++export type RiskyChoice = "separate" | "here";++export interface NudgesOps {+ /** Requests waiting for an answer, oldest first. */+ "nudges.pending": { args: Record<string, never>; result: RiskyRequest[] };+ "nudges.answer": { args: { id: string; choice: RiskyChoice }; result: null };+}++export const NUDGES_OPERATIONS = ["nudges.pending", "nudges.answer"] as const satisfies readonly (keyof NudgesOps)[];++const TAURI = "the Tauri app does not answer the risky-action question (calls run as before)";++export const NUDGES_COVERAGE = {+ "nudges.pending": { webkit: { methods: ["nudges.pending"] }, tauri: [], unsupported: { tauri: TAURI } },+ "nudges.answer": { webkit: { methods: ["nudges.answer"] }, tauri: [], unsupported: { tauri: TAURI } },+} as const satisfies Record<keyof NudgesOps, OpCoverage>;++/** Arguments that take each down its usual path (coverage tests). */+export const NUDGES_ARGS = { "nudges.pending": {}, "nudges.answer": { id: "risky-1-1", choice: "here" as RiskyChoice } };++/** A request id as `cua mcp` writes it: no path can hide in one. */+export function validRequestId(id: string): boolean {+ return /^risky-[0-9]+-[0-9]+$/.test(id);+}diff --git a/apps/cua-spaces-web/src/bridge/protocol.ts b/apps/cua-spaces-web/src/bridge/protocol.tsindex f3fb0c84de..f70d3a9e98 100644--- a/apps/cua-spaces-web/src/bridge/protocol.ts+++ b/apps/cua-spaces-web/src/bridge/protocol.ts@@ -45,6 +45,7 @@ import type { HostSetupOps } from "./ops/host-setup";import type { SpaceDetailOps } from "./ops/space-detail";import { STREAM_OPERATIONS, type StreamOps } from "./ops/stream";import { RELAY_USAGE_OPERATIONS, type RelayUsageOps } from "./ops/relay-usage";+import { NUDGES_OPERATIONS, type NudgesOps } from "./ops/nudges";import { RESOURCES_OPERATIONS, type ResourcesOps } from "./ops/resources";import { CHECKLIST_OPERATIONS, type ChecklistOps } from "./ops/checklist";import { PRESENCE_OPERATIONS, type PresenceOps } from "./ops/presence";@@ -187,6 +188,7 @@ export interface HostOperationsStartupOps,StreamOps,RelayUsageOps,+ NudgesOps,ResourcesOps,ChecklistOps,PresenceOps,@@ -292,6 +294,7 @@ export const OPERATIONS = [...VOLUME_OPERATIONS,...STREAM_OPERATIONS,...RELAY_USAGE_OPERATIONS,+ ...NUDGES_OPERATIONS,...RESOURCES_OPERATIONS,...CHECKLIST_OPERATIONS,...PRESENCE_OPERATIONS,diff --git a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts b/apps/cua-spaces-web/src/bridge/webkit-protocol.tsindex 58a4769a6c..25723d55c7 100644--- a/apps/cua-spaces-web/src/bridge/webkit-protocol.ts+++ b/apps/cua-spaces-web/src/bridge/webkit-protocol.ts@@ -154,6 +154,8 @@ export const WEBKIT_METHODS = ["startup.get","startup.act","relay.usage",+ "nudges.pending",+ "nudges.answer","resources.get","checklist.get","checklist.send",diff --git a/apps/cua-spaces-web/src/components/this-mac-nudges.tsx b/apps/cua-spaces-web/src/components/this-mac-nudges.tsxnew file mode 100644index 0000000000..4a1b6ae5c1--- /dev/null+++ b/apps/cua-spaces-web/src/components/this-mac-nudges.tsx@@ -0,0 +1,97 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++import { useCallback, useState } from "react";++import { useAddSpaceWhenReady, useRiskyNudge, useSecondAgentNudge, type Nudge } from "@/bridge/nudges";+import { CuaKey } from "@/components/cua-key";+import { Button } from "@/components/ui/button";+import { toast } from "@/components/ui/toast";++/**+ * The two This Mac prompts, in the top-right corner over whatever page is+ * open: a second agent started on this Mac's desktop, or an agent is about+ * to do something risky there. One main button and one way out; neither+ * stops an agent. The moments and words are the app core's+ * (`bridge/nudges.ts`).+ */+export function ThisMacNudges() {+ const second = useSecondAgentNudge();+ const risky = useRiskyNudge();+ const [wantSpace, setWantSpace] = useState(false);+ const started = useCallback((os: "macos" | "linux" | null) => {+ setWantSpace(false);+ if (os) toast(`Making a ${os === "macos" ? "macOS" : "Linux"} Space`, { description: "It shows in Spaces with its progress. You can keep working." });+ else toast("This Mac can't make a Space right now", { description: "Open New Space to see why." });+ }, []);++ // The risky question waits on an agent: it goes first.+ const card = risky.nudge ? (+ <NudgeCard+ nudge={risky.nudge}+ onPrimary={() => {+ risky.separate();+ setWantSpace(true);+ }}+ onSecondary={risky.here}+ />+ ) : second.nudge ? (+ <NudgeCard+ nudge={second.nudge}+ onPrimary={() => {+ second.addSpace();+ setWantSpace(true);+ }}+ onSecondary={second.keepSharing}+ onNever={second.dontAskAgain}+ />+ ) : null;++ return (+ <>+ {wantSpace ? <AddSpace onDone={started} /> : null}+ {card}+ </>+ );+}++function AddSpace({ onDone }: { onDone: (os: "macos" | "linux" | null) => void }) {+ useAddSpaceWhenReady(onDone);+ return null;+}++export function NudgeCard({ nudge, onPrimary, onSecondary, onNever }: { nudge: Nudge; onPrimary(): void; onSecondary(): void; onNever?: () => void }) {+ const titleId = `nudge-${nudge.kind}-title`;+ return (+ <div+ role="alertdialog"+ aria-modal="false"+ aria-labelledby={titleId}+ data-nudge={nudge.kind}+ className="fixed top-[calc(var(--titlebar-height,0px)+12px)] right-4 z-50 w-[392px] max-w-[calc(100vw-2rem)] rounded-2xl border bg-popover p-5 text-popover-foreground shadow-xl"+ >+ <p className="flex items-start gap-2 text-[13px] leading-snug text-muted-foreground">+ <CuaKey size={18} />+ <span className="min-w-0">{nudge.eyebrow}</span>+ </p>+ <h2 id={titleId} className="mt-2 text-[17px] leading-snug font-semibold tracking-tight">+ {nudge.title}+ </h2>+ <p className="mt-1.5 text-sm leading-relaxed">{nudge.body}</p>+ {nudge.note ? <p className="mt-2 text-xs text-muted-foreground">{nudge.note}</p> : null}+ <div className="mt-4 flex flex-wrap items-center gap-2">+ <Button data-nudge-primary="" onClick={onPrimary}>+ {nudge.primary}+ </Button>+ <Button variant="outline" data-nudge-secondary="" onClick={onSecondary}>+ {nudge.secondary}+ </Button>+ {nudge.never && onNever ? (+ <Button variant="ghost" size="sm" className="ml-auto text-muted-foreground" data-nudge-never="" onClick={onNever}>+ {nudge.never}+ </Button>+ ) : null}+ </div>+ </div>+ );+}diff --git a/apps/cua-spaces-web/src/routes/__root.tsx b/apps/cua-spaces-web/src/routes/__root.tsxindex 9881046ce6..ed528ce49e 100644--- a/apps/cua-spaces-web/src/routes/__root.tsx+++ b/apps/cua-spaces-web/src/routes/__root.tsx@@ -15,6 +15,7 @@ import { RelayAllowanceNotice } from "@/components/shell/relay-allowance-notice"import { SpacesNotice } from "@/components/shell/spaces-notice";import { SpaceSheets } from "@/components/space-sheets";import { TopBar } from "@/components/shell/top-bar";+import { ThisMacNudges } from "@/components/this-mac-nudges";import { useGlobalKeybindings } from "@/hooks/use-global-keybindings";import { useNotificationToasts } from "@/hooks/use-notification-toasts";import { useThemeHostSync, useThemeSync } from "@/lib/theme";@@ -77,6 +78,7 @@ function RootLayout() {<ChecklistTracker /><NewSpace /><SpaceSheets />+ <ThisMacNudges /></div>);}diff --git a/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs b/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rsindex dc4965a514..f161bca044 100644--- a/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs+++ b/libs/cua-spacesd/crates/cua-spacesd-server/src/auth.rs@@ -697,6 +697,40 @@ pub fn token_label(claimed: Option<Principal>) -> String {}}+/// Separates an access line's caller from the agent session that made the+/// call (` · agent Claude Code (agent:claude-code-4242)`).+pub const AGENT_SESSION_TAG: &str = " \u{b7} agent ";++/// The agent session a caller says it is, as an access line's suffix:+/// ` · agent <name> (<id>)` for an agent principal (`agent:<label>-<pid>`,+/// one per `cua mcp` process), empty for anything else. The name and id+/// are the client's claim; the line's caller before the tag stays the+/// verified identity. Readers use it to tell two agents of one account+/// apart (the second-agent prompt in the apps).+pub fn agent_session_suffix(claimed: Option<&Principal>) -> String {+ let Some(p) = claimed.filter(|p| {+ p.kind == cua_proto::env::v1::PrincipalKind::Agent as i32 && p.id.starts_with("agent:")+ }) else {+ return String::new();+ };+ let clean = |s: &str| -> String {+ s.chars()+ .filter(|c| !c.is_control() && !matches!(c, '(' | ')'))+ .take(64)+ .collect::<String>()+ .trim()+ .to_string()+ };+ let id = clean(&p.id);+ let name = clean(&p.display_name);+ let name = if name.is_empty() {+ "Agent".to_string()+ } else {+ name+ };+ format!("{AGENT_SESSION_TAG}{name} ({id})")+}+/// The gRPC service of a `/pkg.Service/Method` path (`ProcessService`).pub fn grpc_service(path: &str) -> &str {let service = path.trim_start_matches('/').split('/').next().unwrap_or("");@@ -978,10 +1012,19 @@ wherereturn Box::pin(async move { Ok(response) });}let owner = grant.account.as_ref().is_some_and(|a| a.role == "owner");+ // Only an owner keeps the agent kind (`principal_for`):+ // name which of its agent sessions this is.+ let session = if grant.principal.kind+ == cua_proto::env::v1::PrincipalKind::Agent as i32+ {+ agent_session_suffix(principal_from_headers(req.headers()).as_ref())+ } else {+ String::new()+ };self.auth.record_call(req.extensions_mut(),"relay",- &principal_label(&grant.principal),+ &format!("{}{session}", principal_label(&grant.principal)),&path,owner,);@@ -1093,13 +1136,13 @@ wherelet principal = principal_from_headers(req.headers());if token_verified {let path = req.uri().path().to_owned();- self.auth.record_call(- req.extensions_mut(),- "token",- &token_label(principal.clone()),- &path,- true,+ let who = format!(+ "{}{}",+ token_label(principal.clone()),+ agent_session_suffix(principal.as_ref()));+ self.auth+ .record_call(req.extensions_mut(), "token", &who, &path, true);}req.extensions_mut().insert(CallerIdentity {principal,@@ -1349,6 +1392,33 @@ mod tests {assert_eq!(found.subprotocol.as_deref(), Some("cua.ticket.v1.c.d"));}+ #[test]+ fn an_agent_caller_names_its_session_on_the_access_line() {+ let agent = |id: &str, name: &str| Principal {+ id: id.into(),+ display_name: name.into(),+ color: String::new(),+ kind: cua_proto::env::v1::PrincipalKind::Agent as i32,+ };+ assert_eq!(+ agent_session_suffix(Some(&agent("agent:claude-code-4242", "Claude Code"))),+ " \u{b7} agent Claude Code (agent:claude-code-4242)"+ );+ // A person, a non-agent id, or nobody: nothing added.+ let human = Principal {+ kind: cua_proto::env::v1::PrincipalKind::Human as i32,+ ..agent("agent:x-1", "Ada")+ };+ assert_eq!(agent_session_suffix(Some(&human)), "");+ assert_eq!(agent_session_suffix(Some(&agent("u1", "Codex"))), "");+ assert_eq!(agent_session_suffix(None), "");+ // The claim can't break the line's shape.+ assert_eq!(+ agent_session_suffix(Some(&agent("agent:a-1", "Evil) (x\n"))),+ " \u{b7} agent Evil x (agent:a-1)"+ );+ }+#[test]fn principal_header_round_trips() {let principal = Principal {diff --git a/libs/cua/crates/cua-cli/src/lib.rs b/libs/cua/crates/cua-cli/src/lib.rsindex 08cdccdd47..164a3bc481 100644--- a/libs/cua/crates/cua-cli/src/lib.rs+++ b/libs/cua/crates/cua-cli/src/lib.rs@@ -45,6 +45,7 @@ mod mcp;mod persistent_cmd;mod providers;mod resources_view;+mod risky;pub mod sandbox;mod shell;mod skills;diff --git a/libs/cua/crates/cua-cli/src/mcp.rs b/libs/cua/crates/cua-cli/src/mcp.rsindex 7a2b5f008a..3dc225f974 100644--- a/libs/cua/crates/cua-cli/src/mcp.rs+++ b/libs/cua/crates/cua-cli/src/mcp.rs@@ -1492,9 +1492,43 @@ impl SdkTools {}}+/// The agent this process serves ("Claude Code"), once its client said.+static AGENT_LABEL: Mutex<Option<String>> = Mutex::new(None);++/// Before a risky call on This Mac, when the user turned the question on+/// (`crate::risky`): the result to give the agent instead of running it,+/// when they chose a separate Space. `None`: run it as before.+async fn risky_detour(tool: &str, arguments: &Value) -> Option<ToolOutcome> {+ let action = crate::risky::tool_risk(tool, arguments)?;+ if !crate::risky::enabled() {+ return None;+ }+ let home = cua_home::cua_home();+ if !crate::risky::targets_this_mac(arguments, &crate::risky::this_mac_names(&home)) {+ return None;+ }+ let agent = AGENT_LABEL+ .lock()+ .ok()+ .and_then(|l| l.clone())+ .unwrap_or_else(|| "An agent".into());+ match crate::risky::ask(&home, &agent, action, crate::risky::ASK_FOR).await {+ crate::risky::Answer::Separate => Some(ToolOutcome {+ content: vec![json!({"type": "text", "text": crate::risky::separate_result(action)})],+ structured: Some(json!({"ran": false, "reason": "user_chose_separate_space"})),+ is_error: false,+ meta: None,+ }),+ crate::risky::Answer::Here => None,+ }+}+#[async_trait::async_trait]impl cua_spaces::mcp::ToolBackend for SdkTools {async fn call(&self, tool: &str, arguments: Value) -> ToolOutcome {+ if let Some(out) = risky_detour(tool, &arguments).await {+ return out;+ }bounded(tool, &arguments, self.forward(tool, arguments.clone())).await}}@@ -1614,6 +1648,9 @@ pub fn server(cua: Arc<Cua>, permissions: BTreeSet<String>, default_sandbox: Strlet allowed = permissions.clone();McpServer::remote(Arc::new(SdkTools(spaces))).with_client_info_hook(Arc::new(|info: &Value| {+ if let Ok(mut l) = AGENT_LABEL.lock() {+ *l = Some(agent_label(info));+ }cua_spacesd_client::set_process_principal(Some(agent_principal(info)));})).with_name("cua")diff --git a/libs/cua/crates/cua-cli/src/risky.rs b/libs/cua/crates/cua-cli/src/risky.rsnew file mode 100644index 0000000000..f1cb7dc88a--- /dev/null+++ b/libs/cua/crates/cua-cli/src/risky.rs@@ -0,0 +1,480 @@+//! Risky actions on This Mac: `cua mcp` offers a separate Space before it+//! runs one (`cua config set nudges.risky_actions on`; off by default).+//!+//! **What counts as risky** is kept narrow on purpose, so the question is+//! rare and means something. A call is risky only when it targets This+//! Mac itself (the user's real desktop, not an extra Space) and it would:+//!+//! - delete files outside a project folder: `rm -r` of an absolute path,+//! the home folder (`~`, `$HOME`), a parent folder (`..`) or everything+//! (`*`, `.`); `rm -r node_modules` inside a project is not asked about;+//! - empty the Trash;+//! - uninstall apps (`brew uninstall`, deleting from `/Applications`);+//! - run an installer (`installer -pkg`, opening a `.pkg`);+//! - change system settings (`sudo`, `defaults write`, `systemsetup`,+//! `networksetup -set…`, `pmset`, `launchctl` unload/bootout/disable,+//! `tccutil reset`, `csrutil`, `spctl`), or open System Settings;+//! - touch sign-ins and passwords (the `security` keychain tool,+//! `passwd`, `dscl … passwd`, `sysadminctl`, deleting `~/.ssh` or the+//! keychains), or open Keychain Access or Passwords;+//! - erase a disk (`diskutil erase…`, `dd of=/dev/…`, `mkfs`).+//!+//! The commands come from `space_bash` and the apps from the driver's+//! `launch_app` through `call_tool`. Anything else (clicks, typing, a+//! command line this can't read) is not asked about: a click on "Delete"+//! in Finder looks like any other click. That's why it is off by default.+//!+//! **Asking never blocks for long.** `cua mcp` writes a request file+//! (`$CUA_HOME/nudges/<id>.json`); the Cua app shows "Run this in a+//! separate Space instead?" and writes the answer next to it+//! (`<id>.answer`: `separate` or `here`). With no answer within+//! [`ASK_FOR`], or with no app to ask, the call runs here as before.+//! "Use a separate Space" returns a plain result to the agent instead of+//! running the call, so it can move the work to a Space.++use serde_json::Value;+use std::path::{Path, PathBuf};+use std::time::Duration;++/// How long a risky call waits for an answer before it runs here.+pub const ASK_FOR: Duration = Duration::from_secs(30);++/// How often the answer file is looked for.+const POLL: Duration = Duration::from_millis(300);++/// The config key and its environment variable.+pub const SETTING: &str = "nudges.risky_actions";++/// Whether the user turned the question on (`cua config`, or+/// `CUA_NUDGE_RISKY_ACTIONS`). Off when unset or unreadable.+pub fn enabled() -> bool {+ let Ok(key) = cua_sandbox_core::settings::key(SETTING) else {+ return false;+ };+ cua_sandbox_core::settings::Settings::load()+ .map(|s| s.entry(key).value == "on")+ .unwrap_or(false)+}++/// The words after "wants to …" for a risky shell command, or `None`.+pub fn command_risk(command: &str) -> Option<&'static str> {+ // One rule per simple command (`a && b; c | d`).+ command+ .split(['\n', ';', '|', '&'])+ .find_map(|part| simple_risk(&words(part)))+}++fn words(part: &str) -> Vec<String> {+ part.split_whitespace()+ .map(|w| {+ w.trim_matches(|c| c == '"' || c == '\'' || c == '(' || c == ')')+ .to_string()+ })+ .filter(|w| !w.is_empty())+ .collect()+}++fn simple_risk(w: &[String]) -> Option<&'static str> {+ let w: Vec<&str> = w.iter().map(String::as_str).collect();+ let (&cmd, args) = w.split_first()?;+ let cmd = cmd.rsplit('/').next().unwrap_or(cmd);+ let any = |p: &dyn Fn(&str) -> bool| args.iter().any(|a| p(a));+ match cmd {+ "sudo" | "doas" => Some("make changes as an administrator"),+ "rm" | "rmdir" | "trash" => {+ if any(&|a| a.contains(".Trash")) {+ return Some("empty the Trash");+ }+ if any(&|a| a.contains("/Applications/") || a.ends_with(".app") || a.ends_with(".app/"))+ {+ return Some("uninstall an app");+ }+ if any(&|a| a.contains(".ssh") || a.contains("Library/Keychains")) {+ return Some("delete saved sign-ins and keys");+ }+ let recursive = cmd == "rmdir"+ || any(&|a| {+ a == "--recursive"+ || (a.starts_with('-')+ && !a.starts_with("--")+ && (a.contains('r') || a.contains('R')))+ });+ let outside = any(&|a| {+ !a.starts_with('-')+ && (a.starts_with('/')+ || a.starts_with('~')+ || a.starts_with("$HOME")+ || a.starts_with("${HOME}")+ || a == ".."+ || a.starts_with("../")+ || a == "*"+ || a == "."+ || a == "./")+ });+ (recursive && outside).then_some("delete files outside a project folder")+ }+ "osascript" => {+ let script = args.join(" ").to_ascii_lowercase();+ if script.contains("empty trash") || script.contains("empty the trash") {+ Some("empty the Trash")+ } else if script.contains("system settings") || script.contains("system preferences") {+ Some("change system settings")+ } else {+ None+ }+ }+ "brew" if any(&|a| matches!(a, "uninstall" | "remove" | "rm" | "zap")) => {+ Some("uninstall an app")+ }+ "mas" | "pkgutil" if any(&|a| matches!(a, "uninstall" | "--forget")) => {+ Some("uninstall an app")+ }+ "installer" => Some("run an installer"),+ "open" if any(&|a| a.ends_with(".pkg") || a.ends_with(".mpkg")) => Some("run an installer"),+ "open" if is_settings_app(&args.join(" ")) => Some("change system settings"),+ "open" if is_passwords_app(&args.join(" ")) => Some("open your saved passwords"),+ "defaults" if any(&|a| matches!(a, "write" | "delete")) => Some("change system settings"),+ "systemsetup" | "pmset" | "csrutil" | "spctl" | "nvram" | "scutil" => {+ Some("change system settings")+ }+ "networksetup" if any(&|a| a.starts_with("-set") || a.starts_with("-remove")) => {+ Some("change system settings")+ }+ "launchctl" if any(&|a| matches!(a, "unload" | "bootout" | "disable" | "remove")) => {+ Some("change system settings")+ }+ "tccutil" => Some("change privacy settings"),+ "security" => Some("use your saved passwords and sign-ins"),+ "passwd" | "sysadminctl" => Some("change a password"),+ "dscl" if any(&|a| a.contains("passwd")) => Some("change a password"),+ "diskutil"+ if any(&|a| {+ a.starts_with("erase") || a.starts_with("zero") || a == "partitionDisk"+ }) =>+ {+ Some("erase a disk")+ }+ "dd" if any(&|a| a.starts_with("of=/dev/")) => Some("erase a disk"),+ c if c.starts_with("mkfs") || c == "newfs_apfs" || c == "newfs_hfs" => Some("erase a disk"),+ _ => None,+ }+}++fn is_settings_app(name: &str) -> bool {+ let n = name.to_ascii_lowercase();+ n.contains("system settings")+ || n.contains("system preferences")+ || n.contains("com.apple.systempreferences")+ || n.contains("com.apple.settings")+ || n.starts_with("x-apple.systempreferences:")+}++fn is_passwords_app(name: &str) -> bool {+ let n = name.to_ascii_lowercase();+ n.contains("keychain access")+ || n.contains("com.apple.keychainaccess")+ || n == "passwords"+ || n.ends_with(" passwords")+ || n.contains("com.apple.passwords")+ || n.contains("passwords.app")+}++/// The words for a risky contract tool call (`space_bash`, or the+/// driver's `launch_app` through `call_tool`), or `None`.+pub fn tool_risk(tool: &str, arguments: &Value) -> Option<&'static str> {+ match tool {+ "space_bash" => command_risk(arguments["command"].as_str()?),+ "call_tool" => {+ let inner = arguments["tool"].as_str()?;+ let args = &arguments["arguments"];+ match inner {+ "launch_app" | "activate_app" => {+ let names = ["bundle_id", "name", "app", "path"]+ .iter()+ .filter_map(|k| args[*k].as_str())+ .collect::<Vec<_>>();+ if names.iter().any(|n| is_settings_app(n)) {+ Some("change system settings")+ } else if names.iter().any(|n| is_passwords_app(n)) {+ Some("open your saved passwords")+ } else if names+ .iter()+ .any(|n| n.ends_with(".pkg") || n.ends_with(".mpkg"))+ {+ Some("run an installer")+ } else {+ None+ }+ }+ "shell" | "run_shell" | "bash" | "exec" => {+ command_risk(args["command"].as_str().or(args["cmd"].as_str())?)+ }+ _ => None,+ }+ }+ _ => None,+ }+}++/// The Space ids and names that mean This Mac: its own relay machine+/// (`relay:<id>` and the bare id), its host name, and the names the apps+/// give it.+pub fn this_mac_names(home: &Path) -> Vec<String> {+ let mut names: Vec<String> = ["this-mac", "this mac", "this-machine", "this machine"]+ .iter()+ .map(|s| s.to_string())+ .collect();+ if let Ok(Some(c)) = cua_host::Host::new(home.to_path_buf()).config() {+ if let Some(id) = c.machine_id.filter(|id| !id.is_empty()) {+ names.push(format!("relay:{id}"));+ names.push(id);+ }+ if !c.name.trim().is_empty() {+ names.push(c.name.trim().to_string());+ }+ }+ names.into_iter().map(|n| n.to_ascii_lowercase()).collect()+}++/// Whether `arguments` name This Mac as the Space.+pub fn targets_this_mac(arguments: &Value, names: &[String]) -> bool {+ arguments["space"]+ .as_str()+ .map(|s| s.trim().to_ascii_lowercase())+ .is_some_and(|s| names.contains(&s))+}++/// The user's answer.+#[derive(Debug, Clone, Copy, PartialEq, Eq)]+pub enum Answer {+ /// "Use a separate Space": don't run it here.+ Separate,+ /// "Run it here", no answer in time, or nobody to ask.+ Here,+}++fn now_ms() -> u64 {+ std::time::SystemTime::now()+ .duration_since(std::time::UNIX_EPOCH)+ .map(|d| d.as_millis() as u64)+ .unwrap_or(0)+}++/// The folder requests and answers live in.+pub fn dir(home: &Path) -> PathBuf {+ home.join("nudges")+}++/// Asks the app and waits up to `wait` for the answer. Any failure to ask+/// (no folder, a write error) is "Run it here": the question never stops+/// the agent.+pub async fn ask(home: &Path, agent: &str, action: &str, wait: Duration) -> Answer {+ let dir = dir(home);+ let now = now_ms();+ let id = format!("risky-{}-{now}", std::process::id());+ let request = dir.join(format!("{id}.json"));+ let answer = dir.join(format!("{id}.answer"));+ let body = serde_json::json!({+ "id": id,+ "agent": agent,+ "action": action,+ "atMs": now,+ "expiresMs": now + wait.as_millis() as u64,+ });+ if std::fs::create_dir_all(&dir).is_err()+ || cua_home::write_private(&request, body.to_string().as_bytes()).is_err()+ {+ return Answer::Here;+ }+ let deadline = tokio::time::Instant::now() + wait;+ let mut out = Answer::Here;+ while tokio::time::Instant::now() < deadline {+ if let Ok(text) = std::fs::read_to_string(&answer) {+ if text.trim() == "separate" {+ out = Answer::Separate;+ }+ break;+ }+ tokio::time::sleep(POLL).await;+ }+ let _ = std::fs::remove_file(&request);+ let _ = std::fs::remove_file(&answer);+ out+}++/// What the agent reads when the user chose a separate Space.+pub fn separate_result(action: &str) -> String {+ format!(+ "Not run. This would {action} on the user's own Mac, and they asked to do it in a \+ separate Space instead. Cua is making one now (list_spaces shows it). Run this there \+ once it is ready, or ask the user what to do next."+ )+}++#[cfg(test)]+mod tests {+ use super::*;+ use serde_json::json;++ #[test]+ fn risky_commands_are_named_in_plain_words() {+ for (cmd, want) in [+ (+ "rm -rf ~/Documents",+ "delete files outside a project folder",+ ),+ (+ "rm -r /Users/ada/Desktop/old",+ "delete files outside a project folder",+ ),+ (+ "cd x && rm -fr ../other",+ "delete files outside a project folder",+ ),+ ("rm -rf *", "delete files outside a project folder"),+ ("rm -rf ~/.Trash/*", "empty the Trash"),+ (+ "osascript -e 'tell app \"Finder\" to empty trash'",+ "empty the Trash",+ ),+ ("rm -rf /Applications/Slack.app", "uninstall an app"),+ ("brew uninstall --cask slack", "uninstall an app"),+ (+ "sudo installer -pkg Recorder.pkg -target /",+ "make changes as an administrator",+ ),+ ("installer -pkg Recorder.pkg -target /", "run an installer"),+ ("open ~/Downloads/Recorder.pkg", "run an installer"),+ (+ "defaults write -g AppleShowAllExtensions -bool true",+ "change system settings",+ ),+ ("open -a 'System Settings'", "change system settings"),+ (+ "security find-generic-password -s github",+ "use your saved passwords and sign-ins",+ ),+ ("rm -rf ~/.ssh", "delete saved sign-ins and keys"),+ ("diskutil eraseDisk APFS X disk4", "erase a disk"),+ ("/usr/bin/tccutil reset All", "change privacy settings"),+ ] {+ assert_eq!(command_risk(cmd), Some(want), "{cmd}");+ }+ }++ #[test]+ fn everyday_commands_are_not_asked_about() {+ for cmd in [+ "rm -rf node_modules",+ "rm -rf build dist",+ "rm notes.txt",+ "rm /tmp/x.log",+ "ls -la ~",+ "git status && npm test",+ "brew install jq",+ "defaults read com.apple.dock",+ "open https://example.com",+ "launchctl list",+ "echo rm -rf",+ ] {+ assert_eq!(command_risk(cmd), None, "{cmd}");+ }+ }++ #[test]+ fn driver_launches_of_settings_and_passwords_count() {+ let call =+ |tool: &str, args: Value| json!({"space": "this-mac", "tool": tool, "arguments": args});+ assert_eq!(+ tool_risk(+ "call_tool",+ &call(+ "launch_app",+ json!({"bundle_id": "com.apple.systempreferences"})+ )+ ),+ Some("change system settings")+ );+ assert_eq!(+ tool_risk(+ "call_tool",+ &call("launch_app", json!({"name": "Passwords"}))+ ),+ Some("open your saved passwords")+ );+ assert_eq!(+ tool_risk("call_tool", &call("launch_app", json!({"name": "Safari"}))),+ None+ );+ assert_eq!(+ tool_risk("call_tool", &call("click", json!({"x": 1, "y": 2}))),+ None+ );+ assert_eq!(+ tool_risk(+ "space_bash",+ &json!({"space": "this-mac", "command": "brew zap slack"})+ ),+ Some("uninstall an app")+ );+ assert_eq!(tool_risk("list_spaces", &json!({})), None);+ }++ #[test]+ fn only_this_mac_is_this_mac() {+ let names = vec!["this-mac".to_string(), "relay:m-1".to_string()];+ assert!(targets_this_mac(&json!({"space": "relay:m-1"}), &names));+ assert!(targets_this_mac(&json!({"space": "This-Mac"}), &names));+ assert!(!targets_this_mac(+ &json!({"space": "local:linux-1"}),+ &names+ ));+ assert!(!targets_this_mac(&json!({}), &names));+ }++ #[tokio::test]+ async fn no_answer_runs_it_here_and_an_answer_is_followed() {+ let home = tempfile::tempdir().unwrap();+ let started = std::time::Instant::now();+ assert_eq!(+ ask(+ home.path(),+ "Codex",+ "empty the Trash",+ Duration::from_millis(400)+ )+ .await,+ Answer::Here+ );+ assert!(started.elapsed() < Duration::from_secs(3));+ // Nothing is left behind.+ assert_eq!(std::fs::read_dir(dir(home.path())).unwrap().count(), 0);++ // The app answers "separate" while the call waits.+ let d = dir(home.path());+ let answering = tokio::spawn(async move {+ for _ in 0..50 {+ if let Some(req) = std::fs::read_dir(&d)+ .ok()+ .and_then(|mut r| r.find_map(|e| e.ok()))+ .map(|e| e.path())+ {+ std::fs::write(req.with_extension("answer"), "separate").unwrap();+ return;+ }+ tokio::time::sleep(Duration::from_millis(50)).await;+ }+ });+ assert_eq!(+ ask(+ home.path(),+ "Codex",+ "empty the Trash",+ Duration::from_secs(5)+ )+ .await,+ Answer::Separate+ );+ answering.await.unwrap();+ }+}diff --git a/libs/cua/crates/cua-sandbox-core/src/settings.rs b/libs/cua/crates/cua-sandbox-core/src/settings.rsindex 82f53fa74e..3510b95491 100644--- a/libs/cua/crates/cua-sandbox-core/src/settings.rs+++ b/libs/cua/crates/cua-sandbox-core/src/settings.rs@@ -36,7 +36,7 @@ pub struct Key {}/// Every setting, in display order.-pub const KEYS: [Key; 9] = [+pub const KEYS: [Key; 10] = [Key {name: "default.on",env: "CUA_DEFAULT_ON",@@ -91,6 +91,12 @@ pub const KEYS: [Key; 9] = [default: "auto",description: "the engine local Linux Spaces run on, on a Mac: auto (a working Docker engine on this Mac, else built-in; built-in once it exists), builtin (cua's own VM with Docker and gVisor, set up on first use) or system (only this Mac's own engine; nothing is downloaded)",},+ Key {+ name: "nudges.risky_actions",+ env: "CUA_NUDGE_RISKY_ACTIONS",+ default: "off",+ description: "before an agent does something risky on this Mac's own desktop through `cua mcp` (deleting files outside a project, emptying the Trash, uninstalling apps, system settings, passwords), the Cua app offers to run it in a separate Space (on, off). No answer in 30 s runs it here",+ },];/// Short names `cua config` accepts for a setting.@@ -445,6 +451,15 @@ pub fn normalize(key: Key, value: &str) -> Result<String, SettingsError> {})?.as_str().to_string(),+ "nudges.risky_actions" => match v.to_ascii_lowercase().as_str() {+ "1" | "true" | "yes" | "on" => "on".into(),+ "0" | "false" | "no" | "off" => "off".into(),+ _ => {+ return Err(SettingsError(format!(+ "nudges.risky_actions: expected on or off, got {v:?}"+ )));+ }+ },"telemetry.enabled" => match v.to_ascii_lowercase().as_str() {"1" | "true" | "yes" | "on" => "on".into(),"0" | "false" | "no" | "off" => "off".into(),diff --git a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rsindex c40c0d5dce..f9942cbe5b 100644--- a/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/dispatch.rs@@ -16,8 +16,9 @@ use crate::teleport::{drag, flow, grid, transfer, windows};use crate::{CoreError, about, agent_keys, agents, checklist, cloud_connect, devices, diagnostics,drive_mount_preview, drive_page, drive_settings, driver_preview, experiments, host, login_item,- machines, notch, notifications, onboarding, onboarding_preview, palette, paths, persistent,- presence, relay_usage, resources, settings, share, telemetry, upsell, window, wizard,+ machines, notch, notifications, nudges, onboarding, onboarding_preview, palette, paths,+ persistent, presence, relay_usage, resources, settings, share, telemetry, upsell, window,+ wizard,};use serde::Serialize;use serde::de::DeserializeOwned;@@ -301,6 +302,8 @@ pub const METHODS: &[&str] = &["firstRun.agentUsed","firstRun.leadAgent","telemetry.upsell",+ "nudge.secondAgent",+ "nudge.riskyAction",];struct Args(Value);@@ -525,6 +528,15 @@ pub fn call_value(method: &str, args: Value) -> Result<Value, CoreError> {"firstRun.leadAgent" => out(crate::first_run::lead_agent(&a.get::<Vec<crate::first_run::FirstRunAgent>>("agents")?,)),+ // The This Mac prompts: the moments, rules and words are `nudges`'.+ "nudge.secondAgent" => out(nudges::second_agent(+ &a.get::<Vec<host::HostAccess>>("recentAccess")?,+ a.get("nowMs")?,+ &a.get::<String>("today")?,+ &a.get::<Option<nudges::NudgeMemory>>("memory")?+ .unwrap_or_default(),+ )),+ "nudge.riskyAction" => out(nudges::risky_action(&a.get("request")?, a.get("nowMs")?)),"telemetry.upsell" => out(telemetry::upsell(&a.get::<String>("surface")?,&a.get::<String>("action")?,diff --git a/libs/cua/crates/cua-spaces-app-core/src/host.rs b/libs/cua/crates/cua-spaces-app-core/src/host.rsindex 01a3cc6644..b2c869cc5f 100644--- a/libs/cua/crates/cua-spaces-app-core/src/host.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/host.rs@@ -809,6 +809,16 @@ pub fn access_what(what: &str) -> String {/// Who, in words: the token holder is named by the credential (a name it/// sends is only its claim).pub fn access_who(via: &str, who: &str) -> String {+ // An agent's call names its session after the caller+ // (`crate::nudges::agent_session`): say which agent, not its id.+ if let (caller, Some((agent, _))) = crate::nudges::agent_session(who) {+ let caller = access_who(via, caller);+ return if via == "token" {+ caller+ } else {+ format!("{agent} for {caller}")+ };+ }if via == "token" {if let Some(claimed) = who.strip_prefix("token (claims ")diff --git a/libs/cua/crates/cua-spaces-app-core/src/lib.rs b/libs/cua/crates/cua-spaces-app-core/src/lib.rsindex 993f67fc93..f4427375d9 100644--- a/libs/cua/crates/cua-spaces-app-core/src/lib.rs+++ b/libs/cua/crates/cua-spaces-app-core/src/lib.rs@@ -78,6 +78,7 @@ pub mod machines;pub mod model;pub mod notch;pub mod notifications;+pub mod nudges;pub mod onboarding;pub mod onboarding_preview;pub mod palette;diff --git a/libs/cua/crates/cua-spaces-app-core/src/nudges.rs b/libs/cua/crates/cua-spaces-app-core/src/nudges.rsnew file mode 100644index 0000000000..5f1d2ff0c0--- /dev/null+++ b/libs/cua/crates/cua-spaces-app-core/src/nudges.rs@@ -0,0 +1,543 @@+// SPDX-License-Identifier: FSL-1.1-MIT+// Copyright (c) 2026 Cua AI, Inc.++//! Two small prompts about This Mac, the user's real desktop, as every app+//! shows them. Each has one main button and one way out, and neither ever+//! stops an agent.+//!+//! * **A second agent** ([`second_agent`]). An agent starts using This+//! Mac's screen, mouse or keyboard while another one is already using+//! them: "They'll share your mouse. Add a Space so they each get their+//! own?" Detected from this Mac's access log, which the host already+//! reads for the app (`host.status` → `recentAccess`): `cua-spacesd`+//! ends the line of an agent's call with the agent session that made it+//! (` · agent Claude Code (agent:claude-code-4242)`, one per `cua mcp`+//! process). Two sessions on the desktop services within+//! [`ACTIVE_MS`], the newer one first seen in that window, is the+//! moment. Shown at most once a day per computer, never after "Don't+//! ask again" ([`NudgeMemory`]).+//! * **A risky action** ([`risky_action`]). `cua mcp` asks before it runs+//! something risky on This Mac (`cua config set nudges.risky_actions+//! on`; off by default): "Run this in a separate Space instead?" The app+//! draws the question; no answer in time means "Run it here".+//!+//! What this can't see: an agent that drives the desktop with its own Cua+//! Driver (not through Cua Spaces) writes no access line, and the agent's+//! name and session are its own claim (the account before the tag is+//! verified).++use serde::{Deserialize, Serialize};++use crate::host::HostAccess;++/// How recent a desktop access must be for its agent to count as working+/// now. The host writes at most one line per caller and service a minute+/// while it keeps calling, so three minutes covers a working session.+pub const ACTIVE_MS: i64 = 3 * 60_000;++/// The tag `cua-spacesd` puts before the agent session on an access line+/// (`cua-spacesd-server`'s `auth::AGENT_SESSION_TAG`; keep in sync).+pub const AGENT_SESSION_TAG: &str = " \u{b7} agent ";++/// The services that move the mouse, type or read the screen: two agents+/// on these share one pointer. A shell, files or watching a stream do not.+const DESKTOP_SERVICES: &[&str] = &[+ "ComputerService",+ "DriverService",+ "DesktopService",+ "AccessibilityService",+ "WindowsService",+ "MCP",+];++/// The caller before the tag and the agent session after it (`Claude+/// Code`, `agent:claude-code-4242`), when the line names one.+pub fn agent_session(who: &str) -> (&str, Option<(&str, &str)>) {+ let Some((caller, rest)) = who.rsplit_once(AGENT_SESSION_TAG) else {+ return (who, None);+ };+ let session = rest+ .strip_suffix(')')+ .and_then(|r| r.rsplit_once(" ("))+ .filter(|(name, id)| !name.is_empty() && id.starts_with("agent:"));+ match session {+ Some(s) => (caller, Some(s)),+ None => (who, None),+ }+}++/// Whether an access line used the desktop (the screen, mouse or keyboard).+pub fn uses_desktop(who: &str, what: &str) -> bool {+ if crate::host::access_kind(who, what) != crate::host::HostAccessKind::Connection {+ return false;+ }+ let service = what.split(" (").next().unwrap_or(what);+ let service = service.split('/').next().unwrap_or(service);+ DESKTOP_SERVICES.contains(&service)+}++/// One agent session on This Mac's desktop.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct DesktopAgent {+ /// `agent:claude-code-4242`.+ pub session: String,+ /// "Claude Code".+ pub name: String,+ /// Its first desktop access in the log (epoch ms).+ pub first_ms: i64,+ /// Its latest one.+ pub last_ms: i64,+}++/// The agent sessions that used This Mac's desktop and are still working+/// at `now_ms` (a desktop access in the last [`ACTIVE_MS`]), the one that+/// started last first.+pub fn desktop_agents(recent: &[HostAccess], now_ms: i64) -> Vec<DesktopAgent> {+ let mut agents: Vec<DesktopAgent> = vec![];+ for a in recent {+ if !uses_desktop(&a.who, &a.what) {+ continue;+ }+ let (_, Some((name, session))) = agent_session(&a.who) else {+ continue;+ };+ match agents.iter_mut().find(|x| x.session == session) {+ Some(x) => {+ x.first_ms = x.first_ms.min(a.at_ms);+ x.last_ms = x.last_ms.max(a.at_ms);+ }+ None => agents.push(DesktopAgent {+ session: session.into(),+ name: name.into(),+ first_ms: a.at_ms,+ last_ms: a.at_ms,+ }),+ }+ }+ agents.retain(|x| x.last_ms >= now_ms - ACTIVE_MS);+ agents.sort_by(|a, b| b.first_ms.cmp(&a.first_ms).then(a.session.cmp(&b.session)));+ agents+}++/// What an app remembers about the second-agent prompt, for one computer.+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct NudgeMemory {+ /// The local day (`2026-10-18`) it was last shown on this computer.+ pub shown_day: Option<String>,+ /// "Don't ask again".+ pub off: bool,+}++/// Whether the prompt may show `today` (the local day, `2026-10-18`):+/// not turned off, and not shown today on this computer.+pub fn allows(memory: &NudgeMemory, today: &str) -> bool {+ !memory.off && memory.shown_day.as_deref() != Some(today)+}++/// A prompt as drawn: a line saying what happened, a short question, one+/// main button and one way out.+#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase")]+pub struct Nudge {+ /// `second-agent` or `risky-action`.+ pub kind: String,+ /// What it is about: the two sessions, or the request id. The same+ /// moment keeps the same key.+ pub key: String,+ /// The small line on top: "Codex just started on this Mac".+ pub eyebrow: String,+ /// "Claude Code is already working here."+ pub title: String,+ pub body: String,+ /// A quieter line under the body, if any.+ pub note: Option<String>,+ /// The main button.+ pub primary: String,+ /// The way out.+ pub secondary: String,+ /// "Don't ask again", when the prompt has one.+ pub never: Option<String>,+}++/// The second-agent prompt's moment, if this is one: two agent sessions+/// are using This Mac's desktop and the newer one started in the last+/// [`ACTIVE_MS`]. `None` too when [`allows`] says no.+pub fn second_agent(+ recent: &[HostAccess],+ now_ms: i64,+ today: &str,+ memory: &NudgeMemory,+) -> Option<Nudge> {+ if !allows(memory, today) {+ return None;+ }+ let agents = desktop_agents(recent, now_ms);+ let [newer, other, ..] = agents.as_slice() else {+ return None;+ };+ if newer.first_ms < now_ms - ACTIVE_MS || newer.first_ms <= other.first_ms {+ return None;+ }+ let same = newer.name == other.name;+ Some(Nudge {+ kind: "second-agent".into(),+ key: format!("{}+{}", other.session, newer.session),+ eyebrow: if same {+ format!("Another {} just started on this Mac", newer.name)+ } else {+ format!("{} just started on this Mac", newer.name)+ },+ title: format!("{} is already working here.", other.name),+ body: "They'll share your mouse. Add a Space so they each get their own?".into(),+ note: Some("It's made in the background. You can keep working.".into()),+ primary: "Add a Space".into(),+ secondary: "Keep sharing".into(),+ never: Some("Don't ask again".into()),+ })+}++/// A risky action `cua mcp` is holding for an answer (its request file).+#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "camelCase", default)]+pub struct RiskyRequest {+ pub id: String,+ /// "Claude Code".+ pub agent: String,+ /// What it wants to do, in plain words: "empty the Trash".+ pub action: String,+ /// When it asked (epoch ms).+ pub at_ms: i64,+ /// When it goes ahead without an answer (epoch ms).+ pub expires_ms: i64,+}++/// The risky-action prompt for `request`, or `None` once it has gone ahead+/// on its own (`now_ms` past its deadline).+pub fn risky_action(request: &RiskyRequest, now_ms: i64) -> Option<Nudge> {+ if request.id.is_empty() || now_ms >= request.expires_ms {+ return None;+ }+ let agent = if request.agent.trim().is_empty() {+ "An agent"+ } else {+ request.agent.trim()+ };+ let action = request.action.trim().trim_end_matches('.');+ let secs = ((request.expires_ms - now_ms) as f64 / 1000.0).ceil() as i64;+ Some(Nudge {+ kind: "risky-action".into(),+ key: request.id.clone(),+ eyebrow: format!("{agent} wants to {action} on your desktop"),+ title: "Run this in a separate Space instead?".into(),+ body: "A fresh computer inside this Mac. If something goes wrong there, your files and settings stay safe.".into(),+ note: Some(format!(+ "If you don't choose, it runs here in {secs} second{}.",+ if secs == 1 { "" } else { "s" }+ )),+ primary: "Use a separate Space".into(),+ secondary: "Run it here".into(),+ never: None,+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ const NOW: i64 = 1_000_000_000;++ fn line(at_ms: i64, who: &str, what: &str) -> HostAccess {+ HostAccess {+ at_ms,+ via: "relay".into(),+ who: who.into(),+ what: what.into(),+ }+ }++ fn agent(name: &str, session: &str) -> String {+ format!("[email protected] (u1){AGENT_SESSION_TAG}{name} ({session})")+ }++ #[test]+ fn an_access_line_names_its_agent_session() {+ assert_eq!(+ agent_session(&agent("Claude Code", "agent:claude-code-4242")),+ (+ "[email protected] (u1)",+ Some(("Claude Code", "agent:claude-code-4242"))+ )+ );+ assert_eq!(+ agent_session("[email protected] (u1)"),+ ("[email protected] (u1)", None)+ );+ // A tag without a real session is just text.+ let odd = format!("x{AGENT_SESSION_TAG}nobody");+ assert_eq!(agent_session(&odd), (odd.as_str(), None));+ }++ #[test]+ fn only_screen_mouse_and_keyboard_count() {+ let who = agent("Codex", "agent:codex-1");+ assert!(uses_desktop(&who, "DriverService"));+ assert!(uses_desktop(&who, "ComputerService"));+ assert!(!uses_desktop(&who, "ProcessService"));+ assert!(!uses_desktop(&who, "FilesystemService"));+ assert!(!uses_desktop(+ &who,+ "ComputerService/Screenshot (thumbnail)"+ ));+ assert!(!uses_desktop(&who, "DriverService/ListTools (background)"));+ assert!(!uses_desktop(+ &who,+ "refused DriverService (view-only share)"+ ));+ }++ #[test]+ fn a_second_agent_on_the_desktop_is_the_moment() {+ let log = vec![+ // Newest first, as the host gives it.+ line(+ NOW - 10_000,+ &agent("Codex", "agent:codex-77"),+ "DriverService",+ ),+ line(+ NOW - 20_000,+ &agent("Claude Code", "agent:claude-code-4242"),+ "ComputerService",+ ),+ line(+ NOW - 30 * 60_000,+ &agent("Claude Code", "agent:claude-code-4242"),+ "DriverService",+ ),+ ];+ let n = second_agent(&log, NOW, "2026-10-18", &NudgeMemory::default()).unwrap();+ assert_eq!(n.kind, "second-agent");+ assert_eq!(n.eyebrow, "Codex just started on this Mac");+ assert_eq!(n.title, "Claude Code is already working here.");+ assert_eq!(+ n.body,+ "They'll share your mouse. Add a Space so they each get their own?"+ );+ assert_eq!(+ (n.primary.as_str(), n.secondary.as_str()),+ ("Add a Space", "Keep sharing")+ );+ assert_eq!(n.never.as_deref(), Some("Don't ask again"));+ assert_eq!(n.key, "agent:claude-code-4242+agent:codex-77");+ }++ #[test]+ fn two_sessions_of_one_agent_count_too() {+ let log = vec![+ line(+ NOW - 5_000,+ &agent("Claude Code", "agent:claude-code-2"),+ "DriverService",+ ),+ line(+ NOW - 50_000,+ &agent("Claude Code", "agent:claude-code-1"),+ "DriverService",+ ),+ line(+ NOW - 9 * 60_000,+ &agent("Claude Code", "agent:claude-code-1"),+ "DriverService",+ ),+ ];+ let n = second_agent(&log, NOW, "d", &NudgeMemory::default()).unwrap();+ assert_eq!(n.eyebrow, "Another Claude Code just started on this Mac");+ }++ #[test]+ fn no_moment_without_two_working_agents_or_a_new_one() {+ let mem = NudgeMemory::default();+ // One agent.+ let one = vec![line(+ NOW - 1_000,+ &agent("Codex", "agent:codex-1"),+ "DriverService",+ )];+ assert!(second_agent(&one, NOW, "d", &mem).is_none());+ // The other one stopped a while ago.+ let stopped = vec![+ line(+ NOW - 1_000,+ &agent("Codex", "agent:codex-1"),+ "DriverService",+ ),+ line(+ NOW - ACTIVE_MS - 1,+ &agent("Claude Code", "agent:cc-1"),+ "DriverService",+ ),+ ];+ assert!(second_agent(&stopped, NOW, "d", &mem).is_none());+ // Both have been at it for a long time: not a start.+ let long = vec![+ line(+ NOW - 1_000,+ &agent("Codex", "agent:codex-1"),+ "DriverService",+ ),+ line(+ NOW - 2_000,+ &agent("Claude Code", "agent:cc-1"),+ "DriverService",+ ),+ line(+ NOW - 20 * 60_000,+ &agent("Codex", "agent:codex-1"),+ "DriverService",+ ),+ line(+ NOW - 30 * 60_000,+ &agent("Claude Code", "agent:cc-1"),+ "DriverService",+ ),+ ];+ assert!(second_agent(&long, NOW, "d", &mem).is_none());+ // The second one only runs commands: it doesn't share the mouse.+ let shell = vec![+ line(+ NOW - 1_000,+ &agent("Codex", "agent:codex-1"),+ "ProcessService",+ ),+ line(+ NOW - 2_000,+ &agent("Claude Code", "agent:cc-1"),+ "DriverService",+ ),+ ];+ assert!(second_agent(&shell, NOW, "d", &mem).is_none());+ // Lines from before the session tag existed name no agent.+ let old = vec![+ line(NOW - 1_000, "[email protected] (u1)", "DriverService"),+ line(NOW - 2_000, "token (claims Codex)", "DriverService"),+ ];+ assert!(second_agent(&old, NOW, "d", &mem).is_none());+ }++ #[test]+ fn once_a_day_per_computer_and_never_after_dont_ask_again() {+ let log = vec![+ line(+ NOW - 1_000,+ &agent("Codex", "agent:codex-1"),+ "DriverService",+ ),+ line(+ NOW - 2_000,+ &agent("Claude Code", "agent:cc-1"),+ "DriverService",+ ),+ line(+ NOW - 60_000,+ &agent("Claude Code", "agent:cc-1"),+ "DriverService",+ ),+ ];+ let shown = NudgeMemory {+ shown_day: Some("2026-10-18".into()),+ off: false,+ };+ assert!(second_agent(&log, NOW, "2026-10-18", &shown).is_none());+ assert!(second_agent(&log, NOW, "2026-10-19", &shown).is_some());+ let off = NudgeMemory {+ shown_day: None,+ off: true,+ };+ assert!(second_agent(&log, NOW, "2026-10-19", &off).is_none());+ }++ #[test]+ fn recent_access_names_the_agent_not_its_session() {+ assert_eq!(+ crate::host::access_who("relay", &agent("Codex", "agent:codex-1")),+ "Codex for [email protected] (u1)"+ );+ assert_eq!(+ crate::host::access_who(+ "token",+ &format!("token (claims Codex){AGENT_SESSION_TAG}Codex (agent:codex-1)")+ ),+ "Codex (access token)"+ );+ }++ #[test]+ fn the_prompts_answer_through_dispatch() {+ use serde_json::json;+ let log = json!([+ {"atMs": NOW - 1_000, "via": "relay", "who": agent("Codex", "agent:codex-1"), "what": "DriverService"},+ {"atMs": NOW - 2_000, "via": "relay", "who": agent("Claude Code", "agent:cc-1"), "what": "DriverService"},+ {"atMs": NOW - 60_000, "via": "relay", "who": agent("Claude Code", "agent:cc-1"), "what": "DriverService"},+ ]);+ let n = crate::dispatch::call_value(+ "nudge.secondAgent",+ json!({"recentAccess": log, "nowMs": NOW, "today": "2026-10-18"}),+ )+ .unwrap();+ assert_eq!(n["primary"], "Add a Space");+ let off = crate::dispatch::call_value(+ "nudge.secondAgent",+ json!({"recentAccess": log, "nowMs": NOW, "today": "2026-10-18", "memory": {"off": true}}),+ )+ .unwrap();+ assert!(off.is_null());+ let r = crate::dispatch::call_value(+ "nudge.riskyAction",+ json!({"request": {"id": "r", "agent": "Codex", "action": "uninstall an app", "atMs": NOW, "expiresMs": NOW + 9_000}, "nowMs": NOW}),+ )+ .unwrap();+ assert_eq!(+ r["eyebrow"],+ "Codex wants to uninstall an app on your desktop"+ );+ }++ #[test]+ fn the_risky_prompt_says_what_and_runs_here_by_default() {+ let r = RiskyRequest {+ id: "r1".into(),+ agent: "Claude Code".into(),+ action: "empty the Trash".into(),+ at_ms: NOW,+ expires_ms: NOW + 30_000,+ };+ let n = risky_action(&r, NOW + 500).unwrap();+ assert_eq!(+ n.eyebrow,+ "Claude Code wants to empty the Trash on your desktop"+ );+ assert_eq!(n.title, "Run this in a separate Space instead?");+ assert_eq!(+ (n.primary.as_str(), n.secondary.as_str()),+ ("Use a separate Space", "Run it here")+ );+ assert_eq!(+ n.note.as_deref(),+ Some("If you don't choose, it runs here in 30 seconds.")+ );+ assert!(n.never.is_none());+ assert!(risky_action(&r, NOW + 30_000).is_none());+ let nameless = RiskyRequest {+ agent: " ".into(),+ ..r+ };+ assert!(+ risky_action(&nameless, NOW)+ .unwrap()+ .eyebrow+ .starts_with("An agent wants to")+ );+ }+}