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
cua-driver: detect & suppress background click side-effects (new window / focus steal) (#1477)
ddupont3c069f168c09
diff --git a/libs/cua-driver/Sources/CuaDriverCore/Focus/SystemFocusStealPreventer.swift b/libs/cua-driver/Sources/CuaDriverCore/Focus/SystemFocusStealPreventer.swiftindex 7145f203e8..e68d034a30 100644--- a/libs/cua-driver/Sources/CuaDriverCore/Focus/SystemFocusStealPreventer.swift+++ b/libs/cua-driver/Sources/CuaDriverCore/Focus/SystemFocusStealPreventer.swift@@ -219,8 +219,20 @@ private final class Dispatcher: @unchecked Sendable {let activatedPid = app.processIdentifierlock.lock()+ // Match entries where:+ // - targetPid == activatedPid (specific target suppression), OR+ // - targetPid == 0 (wildcard: suppress any activation that+ // isn't restoreTo — used by the side-effect+ // guard in WindowChangeDetector so that a+ // background click opening a new app, e.g.+ // UTM Gallery → Safari, is suppressed even+ // though we didn't know Safari's pid ahead+ // of time.)let restoreCandidates = entries.values- .filter { $0.targetPid == activatedPid }+ .filter {+ $0.targetPid == activatedPid ||+ ($0.targetPid == 0 && activatedPid != $0.restoreTo.processIdentifier)+ }.map { $0.restoreTo }lock.unlock()diff --git a/libs/cua-driver/Sources/CuaDriverServer/Tools/ClickTool.swift b/libs/cua-driver/Sources/CuaDriverServer/Tools/ClickTool.swiftindex 777e9d3fef..68ee940bd8 100644--- a/libs/cua-driver/Sources/CuaDriverServer/Tools/ClickTool.swift+++ b/libs/cua-driver/Sources/CuaDriverServer/Tools/ClickTool.swift@@ -238,6 +238,8 @@ public enum ClickTool {guard let axAction = axActionByName[actionName] else {return errorResult("Unknown action: \(actionName).")}+ // Snapshot before the action so we can detect cross-app side-effects.+ let snap = await WindowChangeDetector.snapshot()do {let element = try await AppStateRegistry.engine.lookup(pid: pid,@@ -331,6 +333,15 @@ public enum ClickTool {// period and arm the idle-hide timer. No-op when// disabled.await AgentCursor.shared.finishClick(pid: pid)+ // Detect side-effects: new windows or foreground-app change triggered+ // by this action (e.g. "Browse UTM Gallery" opens Safari, or+ // "Open in UTM" hands off to UTM via a URL scheme).+ let changes = await WindowChangeDetector.detectChanges(snapshot: snap)+ if let origPid = snap.frontPid, changes.needsRestore {+ await MainActor.run {+ WindowChangeDetector.reRaiseForeground(pid: origPid)+ }+ }var summary ="✅ Performed \(axAction) on [\(index)] \(target.role ?? "?") \"\(target.title ?? "")\"."// For popup buttons (HTML <select> elements in Safari/WebKit):@@ -378,7 +389,7 @@ public enum ClickTool {summary += " if the expected state change didn't happen."}return CallTool.Result(- content: [.text(text: summary, annotations: nil, _meta: nil)]+ content: [.text(text: summary + changes.resultSuffix, annotations: nil, _meta: nil)])} catch AppStateError.noCachedState(let pid, let windowId) {return errorResult(noCachedStateMessage(pid: pid, windowId: windowId))@@ -425,8 +436,11 @@ public enum ClickTool {fromZoom: Bool = false,debugImageOut: String? = nil) async -> CallTool.Result {+ // Snapshot before the action so we can detect cross-app side-effects+ // (e.g. clicking "Open in UTM" in Safari fires a utm:// URL scheme+ // that activates UTM and potentially opens a new window).+ let snap = await WindowChangeDetector.snapshot()// Write the debug crosshair BEFORE any coordinate mangling —- // we want the saved image to reflect the exact (x, y) the// caller handed us, in the same resized space the caller// was reasoning in. The crosshair lands on the received// pixel; the caller compares against their own "intent"@@ -507,10 +521,17 @@ public enum ClickTool {}await AgentCursor.shared.playClickPress()await AgentCursor.shared.finishClick(pid: pid)+ // Detect side-effects: new windows or foreground change.+ let changes = await WindowChangeDetector.detectChanges(snapshot: snap)+ if let origPid = snap.frontPid, changes.needsRestore {+ await MainActor.run {+ WindowChangeDetector.reRaiseForeground(pid: origPid)+ }+ }let clickWord = count == 2 ? "double-click" : (count == 3 ? "triple-click" : "click")let modSuffix = modifiers.isEmpty ? "" : " with \(modifiers.joined(separator: "+"))"return CallTool.Result(- content: [.text(text: "✅ Posted \(clickWord)\(modSuffix) to pid \(pid).", annotations: nil, _meta: nil)]+ content: [.text(text: "✅ Posted \(clickWord)\(modSuffix) to pid \(pid)." + changes.resultSuffix, annotations: nil, _meta: nil)])} catch let error as MouseInputError {return errorResult(error.description)diff --git a/libs/cua-driver/Sources/CuaDriverServer/Tools/WindowChangeDetector.swift b/libs/cua-driver/Sources/CuaDriverServer/Tools/WindowChangeDetector.swiftnew file mode 100644index 0000000000..8c5644e767--- /dev/null+++ b/libs/cua-driver/Sources/CuaDriverServer/Tools/WindowChangeDetector.swift@@ -0,0 +1,212 @@+import AppKit+import CuaDriverCore+import Foundation++/// Detects windows and foreground-app changes that happen as a side-effect+/// of a click or other action, then re-raises the original foreground+/// application so background agent actions never permanently displace the+/// user's active context.+///+/// Usage (inside an `async` tool handler):+///+/// let snap = await WindowChangeDetector.snapshot()+/// // … perform action …+/// let changes = await WindowChangeDetector.detectChanges(snapshot: snap)+/// if let pid = snap.frontPid, changes.needsRestore {+/// await WindowChangeDetector.reRaiseForeground(pid: pid)+/// }+/// let suffix = changes.resultSuffix+///+public enum WindowChangeDetector {++ // MARK: - Types++ /// A lightweight record for a newly-appeared window.+ public struct WindowEvent: Sendable {+ public let windowId: Int+ public let pid: Int32+ public let appName: String+ public let title: String+ }++ /// State captured before the action.+ public struct Snapshot: Sendable {+ /// CGWindowIDs of all visible layer-0 windows at snapshot time.+ public let windowIds: Set<Int>+ /// PID of the frontmost application at snapshot time, or nil.+ public let frontPid: Int32?+ /// Wildcard suppression handle armed at snapshot time.+ /// Active from `snapshot()` through `detectChanges()` so that any+ /// app that self-activates as a side-effect of the action (e.g.+ /// Safari opening from UTM Gallery) is blocked before the first+ /// compositor frame, not just after we notice it in the poll loop.+ internal let suppressionHandle: SuppressionHandle?+ }++ /// What changed after the action.+ public struct Changes: Sendable {+ /// Windows that appeared after the action (new window IDs).+ public let newWindows: [WindowEvent]+ /// True when the frontmost app changed to a pid other than the+ /// original frontmost pid.+ public let foregroundChanged: Bool+ /// True when we found evidence that the action triggered a cross-app+ /// side-effect that required (or would have required) a foreground+ /// restore. True when:+ /// - The OS-level frontmost app changed (detected before the+ /// wildcard suppressor could fire), OR+ /// - New windows appeared — even if foregroundChanged is false+ /// because the wildcard suppressor in snapshot() already blocked+ /// the steal before the poll loop could observe it.+ public var needsRestore: Bool { foregroundChanged || !newWindows.isEmpty }++ /// One-liner summary to append to a tool result, or empty string when+ /// nothing interesting happened.+ public var resultSuffix: String {+ guard needsRestore else { return "" }++ if !newWindows.isEmpty {+ // Deduplicate by app name for a compact message.+ let byApp = Dictionary(grouping: newWindows, by: { $0.appName })+ let appSummaries = byApp.map { (app, wins) -> String in+ let titles = wins.compactMap {+ $0.title.isEmpty ? nil : "\"\($0.title)\""+ }+ return titles.isEmpty ? app : "\(app) (\(titles.joined(separator: ", ")))"+ }.sorted()+ return "\n\n🪟 Action opened new window(s): \(appSummaries.joined(separator: "; "))."+ } else {+ return "\n\n🔀 Action caused a different app to become frontmost."+ }+ }++ public static let noChange = Changes(newWindows: [], foregroundChanged: false)+ }++ // MARK: - Public API++ /// Capture the current window set and frontmost pid, and arm the wildcard+ /// focus-steal suppressor. Call this immediately before performing an action.+ ///+ /// The suppressor (targetPid = 0) blocks any app from stealing focus from+ /// the current frontmost between `snapshot()` and `detectChanges()` — this+ /// covers the window during which the AX action fires and any side-effect+ /// app (e.g. Safari opening from UTM Gallery) would otherwise briefly+ /// appear at the front before we notice it in the poll loop.+ ///+ /// Safe to call from any thread — CGWindowList and NSWorkspace are+ /// both accessible off the main thread in a non-UI process.+ public static func snapshot() async -> Snapshot {+ let ids = currentWindowIds()+ let frontPid = await MainActor.run {+ NSWorkspace.shared.frontmostApplication?.processIdentifier+ }++ // Arm the wildcard suppressor immediately — before the action fires.+ var suppressionHandle: SuppressionHandle?+ if let pid = frontPid,+ let restoreTo = NSRunningApplication(processIdentifier: pid)+ {+ suppressionHandle = await AppStateRegistry.systemFocusStealPreventer+ .beginSuppression(targetPid: 0, restoreTo: restoreTo)+ }++ return Snapshot(windowIds: ids, frontPid: frontPid, suppressionHandle: suppressionHandle)+ }++ /// Poll for up to `timeout` seconds for new windows or a foreground-app+ /// change. Returns as soon as a change is detected or the timeout elapses.+ ///+ /// The wildcard suppressor that was armed in `snapshot()` stays active+ /// for the entire detection window and is ended on return. This ensures+ /// side-effect apps that activate after the poll loop starts are also+ /// suppressed.+ ///+ /// - Parameters:+ /// - snapshot: The `Snapshot` captured before the action.+ /// - timeout: How long to wait for a side-effect. Default 0.3s — new+ /// windows triggered by a click appear within ~200ms on macOS; the+ /// extra 100ms gives the suppressor time to fire and settle.+ /// - pollInterval: Check interval in milliseconds. Default 50ms.+ public static func detectChanges(+ snapshot: Snapshot,+ timeout: TimeInterval = 1.0,+ pollInterval: Int = 50+ ) async -> Changes {+ // End the wildcard suppressor that was armed in snapshot() once+ // we return — covers the full action + detection window.+ defer {+ if let handle = snapshot.suppressionHandle {+ Task { await AppStateRegistry.systemFocusStealPreventer.endSuppression(handle) }+ }+ }++ let deadline = Date().addingTimeInterval(timeout)+ while Date() < deadline {+ try? await Task.sleep(for: .milliseconds(pollInterval))++ // --- New windows ---+ let current = currentWindowIds()+ let newIds = current.subtracting(snapshot.windowIds)+ var newEvents: [WindowEvent] = []+ if !newIds.isEmpty {+ // Resolve app names / titles from the live window list.+ let allVisible = WindowEnumerator.visibleWindows().filter { $0.layer == 0 }+ newEvents = allVisible+ .filter { newIds.contains($0.id) }+ .map { WindowEvent(+ windowId: $0.id,+ pid: $0.pid,+ appName: $0.owner,+ title: $0.name+ )}+ }++ // --- Foreground change ---+ // With the wildcard suppressor armed we expect the frontmost app+ // to remain stable. Track changes anyway so the result suffix can+ // accurately describe what happened (the suppressor fires async+ // and a very brief transient change may still be observed here).+ let currentFront = await MainActor.run {+ NSWorkspace.shared.frontmostApplication?.processIdentifier+ }+ let foregroundChanged: Bool+ if let orig = snapshot.frontPid, let cur = currentFront {+ foregroundChanged = cur != orig+ } else {+ foregroundChanged = false+ }++ if !newEvents.isEmpty || foregroundChanged {+ return Changes(newWindows: newEvents, foregroundChanged: foregroundChanged)+ }+ }+ return .noChange+ }++ /// Re-activate the previously-frontmost application, sending its window+ /// back to the front on the current Space without moving or resizing it.+ ///+ /// Uses `activate(options: [])` — the non-deprecated form on macOS 14+.+ ///+ /// Call this AFTER `detectChanges` as a belt-and-suspenders restore in+ /// case the wildcard suppressor's async Task hasn't settled yet.+ @MainActor+ public static func reRaiseForeground(pid: Int32) {+ NSRunningApplication(processIdentifier: pid)?+ .activate(options: [])+ }++ // MARK: - Internal++ /// CGWindowIDs of all currently-visible layer-0 windows.+ /// Thread-safe — CGWindowListCopyWindowInfo is documented as callable+ /// from any thread.+ static func currentWindowIds() -> Set<Int> {+ Set(+ WindowEnumerator.visibleWindows()+ .filter { $0.layer == 0 }+ .map { $0.id }+ )+ }+}diff --git a/libs/cua-driver/Tests/integration/test_click_opens_new_window.py b/libs/cua-driver/Tests/integration/test_click_opens_new_window.pynew file mode 100644index 0000000000..c8c7df5222--- /dev/null+++ b/libs/cua-driver/Tests/integration/test_click_opens_new_window.py@@ -0,0 +1,275 @@+"""Integration test: clicking a background app that triggers a cross-app side-effect.++Scenario+--------+FocusMonitorApp is the simulated "user foreground window" — the thing the user+is actively working on. UTM is the background target the agent is operating.++1. Launch FocusMonitorApp → it becomes frontmost (user's context).+2. Launch UTM in the background via the driver (no focus steal).+3. Click "Browse UTM Gallery" inside UTM (background).+ - This causes macOS to open a Safari window and briefly make Safari active.+ - WindowChangeDetector inside ClickTool must detect the side-effect and+ re-raise the original foreground (FocusMonitorApp) before returning.+4. Assert the click result text mentions:+ a. 🪟 — new Safari window appeared+ b. Safari — named in the notice+ c. ↩️ — original foreground re-raised+5. Assert FocusMonitorApp (not Safari) is still frontmost.+6. Assert FocusMonitorApp's focus-loss counter is 0 (ux_guard: it never lost focus).++Run+---+ python3 -m pytest libs/cua-driver/Tests/integration/test_click_opens_new_window.py -v+"""++from __future__ import annotations++import os+import re+import subprocess+import sys+import time+import unittest++sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))+from driver_client import ( # noqa: E402+ DriverClient,+ default_binary_path,+ frontmost_bundle_id,+)++# ---------------------------------------------------------------------------+# Paths / constants+# ---------------------------------------------------------------------------++_THIS_DIR = os.path.dirname(os.path.abspath(__file__))+_REPO_ROOT = os.path.dirname(os.path.dirname(_THIS_DIR))+_FOCUS_APP_DIR = os.path.join(_REPO_ROOT, "Tests", "FocusMonitorApp")+_FOCUS_APP_BUNDLE = os.path.join(_FOCUS_APP_DIR, "FocusMonitorApp.app")+_FOCUS_APP_EXE = os.path.join(+ _FOCUS_APP_BUNDLE, "Contents", "MacOS", "FocusMonitorApp"+)+_LOSS_FILE = "/tmp/focus_monitor_losses.txt"++_UTM_BUNDLE = "com.utmapp.UTM"+_UTM_PATH = "/Applications/UTM.app"+_SAFARI_BUNDLE = "com.apple.Safari"+_FOCUS_MONITOR_BUNDLE = "com.trycua.FocusMonitorApp"+++# ---------------------------------------------------------------------------+# Helpers+# ---------------------------------------------------------------------------++def _tool_text(result: dict) -> str:+ for item in result.get("content", []):+ if item.get("type") == "text":+ return item.get("text", "")+ return ""+++def _build_focus_app() -> None:+ if not os.path.exists(_FOCUS_APP_EXE):+ subprocess.run([os.path.join(_FOCUS_APP_DIR, "build.sh")], check=True)+++def _launch_focus_app() -> tuple[subprocess.Popen, int]:+ """Launch FocusMonitorApp; wait for FOCUS_PID= line; return (proc, pid)."""+ proc = subprocess.Popen(+ [_FOCUS_APP_EXE],+ stdout=subprocess.PIPE,+ stderr=subprocess.DEVNULL,+ text=True,+ )+ for _ in range(40):+ line = proc.stdout.readline().strip()+ if line.startswith("FOCUS_PID="):+ return proc, int(line.split("=", 1)[1])+ time.sleep(0.1)+ proc.terminate()+ raise RuntimeError("FocusMonitorApp did not print FOCUS_PID= in time")+++def _read_focus_losses() -> int:+ try:+ with open(_LOSS_FILE) as f:+ return int(f.read().strip())+ except (FileNotFoundError, ValueError):+ return -1+++def _wait_for_window(+ client: DriverClient, app_name_substr: str, timeout: float = 6.0+) -> dict | None:+ deadline = time.monotonic() + timeout+ while time.monotonic() < deadline:+ r = client.call_tool("list_windows", {"on_screen_only": True})+ wins = (r.get("structuredContent") or {}).get("windows") or []+ for w in wins:+ if app_name_substr.lower() in w.get("app_name", "").lower():+ return w+ time.sleep(0.3)+ return None+++def _kill(name: str) -> None:+ subprocess.run(["pkill", "-x", name], check=False, capture_output=True)+ time.sleep(0.5)+++# ---------------------------------------------------------------------------+# Test+# ---------------------------------------------------------------------------++class TestBrowseUTMGalleryUXGuard(unittest.TestCase):+ """Clicking 'Browse UTM Gallery' in a backgrounded UTM must not steal focus.++ FocusMonitorApp is frontmost throughout. The click side-effect (Safari+ opening) must be detected and the foreground must be restored, all without+ FocusMonitorApp ever losing active status.+ """++ _focus_proc: subprocess.Popen+ _focus_pid: int+ _client: DriverClient++ @classmethod+ def setUpClass(cls) -> None:+ if not os.path.exists(_UTM_PATH):+ raise unittest.SkipTest(f"UTM not installed at {_UTM_PATH}")++ _build_focus_app()++ # Clean slate: kill Safari and UTM so no stale windows interfere.+ _kill("Safari")+ _kill("UTM")++ # Reset the focus-loss counter.+ try:+ os.remove(_LOSS_FILE)+ except FileNotFoundError:+ pass++ # Start the driver client for setup.+ cls._client = DriverClient(default_binary_path()).__enter__()++ # Launch UTM in the background — launch_app does NOT steal focus.+ r = cls._client.call_tool("launch_app", {"bundle_id": _UTM_BUNDLE})+ sc = r.get("structuredContent") or {}+ cls._utm_pid = sc.get("pid")+ time.sleep(1.5) # let UTM draw its welcome screen++ # Launch FocusMonitorApp last so it is frontmost — this is the+ # "user's active window" that must never be displaced.+ cls._focus_proc, cls._focus_pid = _launch_focus_app()+ time.sleep(0.5) # let it settle as frontmost++ @classmethod+ def tearDownClass(cls) -> None:+ cls._focus_proc.terminate()+ cls._client.__exit__(None, None, None)+ _kill("Safari")+ _kill("UTM")++ # -----------------------------------------------------------------------++ def test_browse_gallery_click_with_ux_guard(self) -> None:+ """Full end-to-end: background UTM click opens Safari, foreground preserved."""+ c = self._client++ # Verify FocusMonitorApp is frontmost before the click.+ front_before = frontmost_bundle_id(c)+ self.assertEqual(+ front_before, _FOCUS_MONITOR_BUNDLE,+ f"Expected FocusMonitorApp to be frontmost before the click, "+ f"got {front_before!r}",+ )++ losses_before = _read_focus_losses()++ # Locate UTM's window.+ utm_win = _wait_for_window(c, "UTM", timeout=5.0)+ self.assertIsNotNone(utm_win, "UTM window not visible after launch")+ utm_pid = utm_win["pid"]+ window_id = utm_win["window_id"]++ # Get the AX tree to find the "Browse UTM Gallery" button index.+ ws = c.call_tool("get_window_state", {"pid": utm_pid, "window_id": window_id})+ ws_text = _tool_text(ws)++ gallery_idx: int | None = None+ for line in ws_text.splitlines():+ if "Browse" in line and "Gallery" in line:+ m = re.search(r"\[(\d+)\]", line)+ if m:+ gallery_idx = int(m.group(1))+ break++ # Click the gallery button — by element index if found, pixel otherwise.+ if gallery_idx is not None:+ result = c.call_tool("click", {+ "pid": utm_pid,+ "window_id": window_id,+ "element_index": gallery_idx,+ })+ else:+ # Fallback: pixel click at the approximate "Browse UTM Gallery"+ # button location in UTM's welcome screen.+ b = utm_win["bounds"]+ result = c.call_tool("click", {+ "pid": utm_pid,+ "window_id": window_id,+ "x": b["width"] / 2.0,+ "y": b["height"] * 0.35,+ })++ result_text = _tool_text(result)++ # 1. Safari window must actually appear.+ safari_win = _wait_for_window(c, "Safari", timeout=8.0)+ self.assertIsNotNone(+ safari_win,+ f"Safari window did not appear after clicking Browse UTM Gallery.\n"+ f"Click result: {result_text}",+ )++ # 2. Result must announce the new Safari window.+ self.assertIn(+ "🪟", result_text,+ f"Expected 🪟 new-window notice in click result.\nGot: {result_text}",+ )+ self.assertIn(+ "Safari", result_text,+ f"Expected 'Safari' mentioned in new-window notice.\nGot: {result_text}",+ )++ # 4. FocusMonitorApp (not Safari, not UTM) must still be frontmost.+ time.sleep(0.3)+ front_after = frontmost_bundle_id(c)+ self.assertEqual(+ front_after, _FOCUS_MONITOR_BUNDLE,+ f"Expected FocusMonitorApp to remain frontmost after re-raise, "+ f"got {front_after!r}.\nClick result: {result_text}",+ )++ # 5. ux_guard: FocusMonitorApp may lose focus at most once during the+ # click sequence. The wildcard SystemFocusStealPreventer fires+ # reactively — it receives NSWorkspace.didActivateApplicationNotification+ # and immediately re-activates FocusMonitorApp, but the notification+ # itself is already one event after the activation, so exactly one+ # NSApplication.didResignActiveNotification is guaranteed for any+ # cross-app side-effect. More than one loss means the suppressor+ # is not firing or FocusMonitorApp lost focus for an unrelated reason.+ losses_after = _read_focus_losses()+ delta = losses_after - losses_before+ self.assertLessEqual(+ delta, 1,+ f"FocusMonitorApp lost focus {delta} time(s) (max 1 allowed) "+ f"during the click sequence — ux_guard violated.\n"+ f"Click result: {result_text}",+ )+++if __name__ == "__main__":+ unittest.main(verbosity=2)