diff --git a/docs/architecture/computer-use-control.md b/docs/architecture/computer-use-control.md index 9098006907..ebdd7e3836 100644 --- a/docs/architecture/computer-use-control.md +++ b/docs/architecture/computer-use-control.md @@ -590,6 +590,17 @@ their AX subtrees (popup AXWindows, and open application AXMenus matched to their window by frame) as extra top-level nodes, and AX target validation accepts elements of those windows. +macOS remote AppKit file-panel controls may report an off-screen proxy window +ID. Resolve the nearest native `AXWindow`/`AXSheet`/`AXDrawer` in their AX parent +chain before comparing the identity with the bound window and its live overlays. +Stop at that first surface; do not admit another window by title, matching bounds, +or by climbing past an unrelated window. Semantic writes, pointer hit/focus checks +and foreground destination checks use the same live overlay membership. Closing +the panel or stopping control revokes access even to retained AX references. +`node scripts/test-macos-file-panel.mjs` exercises a disposable real NSOpenPanel, +its proxy descendants, semantic Cancel, same-app sibling rejection and revocation; +it requires macOS Accessibility and screen-capture access, not user project files. + Pointer input follows physical hit testing: a press, move or scroll whose point is inside such a window is routed to the front-most one there, using its own window-local coordinates. Drag and release stay with the window that received diff --git a/scripts/fixtures/computer-use-file-panel.m b/scripts/fixtures/computer-use-file-panel.m new file mode 100644 index 0000000000..834e0b40fa --- /dev/null +++ b/scripts/fixtures/computer-use-file-panel.m @@ -0,0 +1,42 @@ +// Disposable native file chooser: exercise the real remote AppKit panel tree. +#import + +int main(int argc, const char **argv) { + @autoreleasepool { + if (argc != 3) return 2; + NSApplication *app = NSApplication.sharedApplication; + app.activationPolicy = NSApplicationActivationPolicyRegular; + NSWindow *window = [[NSWindow alloc] initWithContentRect:NSMakeRect(100, 200, 1000, 700) + styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; + window.title = @"OpenBitFun File Panel Fixture"; + window.releasedWhenClosed = NO; + window.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary; + [window orderFrontRegardless]; + NSWindow *sibling = [[NSWindow alloc] initWithContentRect:NSMakeRect(1100, 200, 250, 200) + styleMask:NSWindowStyleMaskTitled backing:NSBackingStoreBuffered defer:NO]; + sibling.title = @"Unbound File Panel Fixture"; + sibling.releasedWhenClosed = NO; + NSButton *unbound = [NSButton buttonWithTitle:@"Unbound semantic action" target:nil action:nil]; + unbound.frame = NSMakeRect(10, 50, 230, 32); + [sibling.contentView addSubview:unbound]; + sibling.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary; + [sibling orderFrontRegardless]; + NSOpenPanel *panel = NSOpenPanel.openPanel; + panel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorFullScreenAuxiliary; + panel.title = @"OpenBitFun Directory Fixture"; + panel.canChooseFiles = NO; + panel.canChooseDirectories = YES; + panel.directoryURL = [NSURL fileURLWithPath:[NSString stringWithUTF8String:argv[2]]]; + [panel beginSheetModalForWindow:window completionHandler:^(NSModalResponse response) {}]; + dispatch_after(dispatch_time(DISPATCH_TIME_NOW, NSEC_PER_SEC), dispatch_get_main_queue(), ^{ + NSDictionary *state = @{@"pid": @(getpid()), @"window_id": @(window.windowNumber), + @"panel_window_id": @(panel.windowNumber), @"sibling_window_id": @(sibling.windowNumber)}; + [[NSJSONSerialization dataWithJSONObject:state options:0 error:nil] + writeToFile:[NSString stringWithUTF8String:argv[1]] atomically:YES]; + printf("READY %d\n", getpid()); + fflush(stdout); + }); + [app run]; + } + return 0; +} diff --git a/scripts/test-macos-file-panel.mjs b/scripts/test-macos-file-panel.mjs new file mode 100644 index 0000000000..2d7c12dcca --- /dev/null +++ b/scripts/test-macos-file-panel.mjs @@ -0,0 +1,47 @@ +// Real NSOpenPanel proxy identity, semantic input, sibling isolation and Stop. +import assert from 'node:assert/strict'; +import { spawn } from 'node:child_process'; +import { mkdtemp, mkdir, rm } from 'node:fs/promises'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +assert.equal(process.platform, 'darwin', 'file panel fixture requires macOS'); +const root = fileURLToPath(new URL('../', import.meta.url)); +const directory = await mkdtemp(join(process.env.OPENBITFUN_FIXTURE_DIR || tmpdir(), 'openbitfun-file-panel-')); +const run = (command, args, env = process.env) => new Promise((resolve, reject) => { + const child = spawn(command, args, { cwd: root, stdio: 'inherit', windowsHide: true, env, timeout: 120000, killSignal: 'SIGKILL' }); + child.once('error', reject); + child.once('close', code => code === 0 ? resolve() : reject(new Error(`${command} exited ${code}`))); +}); +let fixture; +try { + const binary = join(directory, 'file-panel-fixture'); + const state = join(directory, 'state.json'); + const media = join(directory, 'media'); + await mkdir(join(media, 'fixture-child'), { recursive: true }); + await run('xcrun', ['clang', '-fobjc-arc', '-Wall', '-Werror', 'scripts/fixtures/computer-use-file-panel.m', '-framework', 'AppKit', '-o', binary]); + const test = ['native_file_panel_target_fixture', '--ignored', '--nocapture', '--test-threads=1']; + if (!process.env.OPENBITFUN_TEST_BINARY) { + await run('cargo', ['test', '--locked', '-p', 'openbitfun-computer-use', '--lib', test[0], '--no-run']); + } + fixture = spawn(binary, [state, media], { cwd: root, stdio: ['ignore', 'pipe', 'inherit'], windowsHide: true }); + await new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error('File panel fixture did not become ready')), 15000); + let output = ''; + fixture.once('error', error => { clearTimeout(timer); reject(error); }); + fixture.once('exit', code => { clearTimeout(timer); reject(new Error(`Fixture exited ${code}`)); }); + fixture.stdout.on('data', chunk => { + output += String(chunk); + if (/READY \d+/.test(output)) { clearTimeout(timer); resolve(); } + }); + }); + await run(process.env.OPENBITFUN_TEST_BINARY || 'cargo', + process.env.OPENBITFUN_TEST_BINARY ? test : ['test', '--locked', '-p', 'openbitfun-computer-use', '--lib', test[0], '--', ...test.slice(1)], + { ...process.env, OPENBITFUN_FILE_PANEL_STATE: state }); +} finally { + if (fixture && fixture.exitCode === null) { + await new Promise(resolve => { fixture.once('exit', resolve); fixture.kill('SIGTERM'); }); + } + await rm(directory, { recursive: true, force: true }); +} diff --git a/src/crates/services/computer-use/src/computer_use/desktop_host/foreground.rs b/src/crates/services/computer-use/src/computer_use/desktop_host/foreground.rs index 734830b344..1e4eab9acc 100644 --- a/src/crates/services/computer-use/src/computer_use/desktop_host/foreground.rs +++ b/src/crates/services/computer-use/src/computer_use/desktop_host/foreground.rs @@ -34,7 +34,13 @@ impl NativeComputerUseHost { Ok( crate::computer_use::macos_bg_input::frontmost_pid_macos() == Some(pid) && u32::try_from(window).ok().is_some_and(|window| { - crate::computer_use::macos_ax_ui::focused_window_id(pid) == Some(window) + crate::computer_use::macos_ax_ui::focused_window_id(pid).is_some_and( + |actual| { + crate::computer_use::macos_ax_dump::window_belongs_to_capture( + pid, window, actual, + ) + }, + ) }), ) })?; diff --git a/src/crates/services/computer-use/src/computer_use/macos_ax_dump.rs b/src/crates/services/computer-use/src/computer_use/macos_ax_dump.rs index 24a8e6d1c8..07470e284d 100644 --- a/src/crates/services/computer-use/src/computer_use/macos_ax_dump.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_ax_dump.rs @@ -232,11 +232,7 @@ pub(crate) fn validate_bound_target(pid: i32, target: AxRef) -> OpenBitFunResult // An open menu or popup of the bound window is a separate window of the // same process; physical input there reaches it, so its elements qualify. let allowed = match element_window_id(target) { - Some(actual) => { - actual == bound - || super::macos_capture::overlays(pid, bound) - .is_ok_and(|overlays| overlays.iter().any(|o| o.window_id == actual as u64)) - } + Some(actual) => window_belongs_to_capture(pid, bound, actual), None => is_application_menu_item(target), }; if !allowed { @@ -248,6 +244,148 @@ pub(crate) fn validate_bound_target(pid: i32, target: AxRef) -> OpenBitFunResult .map_err(OpenBitFunError::tool) } +/// Live window identity, shared by semantic, pointer-focus and foreground +/// checks. Same-process sibling windows do not inherit the capture's scope. +pub(super) fn window_belongs_to_capture(pid: i32, bound: u32, actual: u32) -> bool { + actual == bound + || super::macos_capture::overlays(pid, bound) + .is_ok_and(|overlays| overlays.iter().any(|o| o.window_id == actual as u64)) +} + +#[cfg(test)] +mod file_panel_tests { + use super::*; + + fn find_target( + roots: &[RetainedCachedTarget], + attribute: &str, + value: &str, + ) -> Option { + // Reading each display attribute from the remote panel is slow. + // For this fixture, keep its real AX tree and read only the lookup key. + let mut queue: VecDeque<_> = roots + .iter() + .map(|root| RetainedCachedTarget(AxRef(unsafe { CFRetain(root.reference().0) }))) + .collect(); + for _ in 0..512 { + let target = queue.pop_front()?; + let element = target.reference().0; + unsafe { + if read_cf_string_attr(element, attribute).as_deref() == Some(value) { + return Some(target); + } + let Some(children) = ax_copy_attr(element, "AXChildren") else { + continue; + }; + if CFGetTypeID(children) != core_foundation::array::CFArrayGetTypeID() { + ax_release(children); + continue; + } + let children = + CFArray::::wrap_under_create_rule(children as CFArrayRef); + for child in children + .iter() + .map(|child| *child) + .filter(|child| !child.is_null()) + { + queue.push_back(RetainedCachedTarget(AxRef(CFRetain(child)))); + } + } + } + None + } + + #[test] + #[ignore = "requires the disposable native file-panel fixture and Accessibility permission"] + fn native_file_panel_target_fixture() { + let state: serde_json::Value = serde_json::from_str( + &std::fs::read_to_string(std::env::var("OPENBITFUN_FILE_PANEL_STATE").unwrap()) + .unwrap(), + ) + .unwrap(); + let pid = state["pid"].as_i64().unwrap() as i32; + let window = state["window_id"].as_u64().unwrap() as u32; + let panel = state["panel_window_id"].as_u64().unwrap() as u32; + let sibling = state["sibling_window_id"].as_u64().unwrap() as u32; + let owner = "native-file-panel-fixture"; + super::super::control_session::start( + owner, + openbitfun_agent_tools::computer_use_control::ControlMode::Background, + ) + .unwrap(); + let lease = super::super::control_session::acquire(owner, "app_click").unwrap(); + let frame = super::super::macos_capture::capture_frame(pid, Some(window)).unwrap(); + assert!(frame + .auxiliary + .iter() + .any(|overlay| overlay.window.window_id == panel as u64)); + let app = RetainedCachedTarget(AxRef(unsafe { AXUIElementCreateApplication(pid) })); + let bound_root = unsafe { + super::super::macos_ax_ui::try_window_element_by_id(app.reference().0, window) + } + .expect("bound window must have an AX root"); + let roots: Vec<_> = std::iter::once(bound_root) + .chain(unsafe { popup_ax_roots(app.reference().0, pid, window) }) + .map(|root| RetainedCachedTarget(AxRef(root))) + .collect(); + // Search is present in each file-list layout and served by the same proxy. + let search = find_target(&roots, "AXIdentifier", "Search") + .expect("fixture search field must be in the observed panel"); + let proxy = unsafe { super::super::macos_ax_ui::ax_window_id(search.reference().0) }; + assert_ne!( + proxy, + Some(panel), + "exercise a real file-panel proxy identity" + ); + assert_eq!(element_window_id(search.reference()), Some(panel)); + validate_bound_target(pid, search.reference()).unwrap(); + assert!(window_belongs_to_capture(pid, window, panel)); + assert!(!window_belongs_to_capture(pid, window, sibling)); + + let cancel = find_target(&roots, "AXIdentifier", "CancelButton") + .expect("native file panel cancel button"); + let sibling_root = unsafe { + super::super::macos_ax_ui::try_window_element_by_id(app.reference().0, sibling) + } + .map(|root| RetainedCachedTarget(AxRef(root))) + .expect("unbound sibling window"); + let foreign = find_target(&[sibling_root], "AXTitle", "Unbound semantic action") + .expect("unbound sibling button"); + assert!(validate_bound_target(pid, foreign.reference()).is_err()); + assert!(matches!( + super::super::macos_ax_write::try_ax_press(foreign.reference()), + super::super::macos_ax_write::AxWriteOutcome::Unavailable(_) + )); + assert!( + matches!( + super::super::macos_ax_write::try_ax_press(cancel.reference()), + super::super::macos_ax_write::AxWriteOutcome::Ok + ), + "semantic input must accept the same panel as observation" + ); + for _ in 0..20 { + if !window_belongs_to_capture(pid, window, panel) { + break; + } + thread::sleep(Duration::from_millis(25)); + } + assert!( + !window_belongs_to_capture(pid, window, panel), + "closed panel loses input scope" + ); + assert!(validate_bound_target(pid, search.reference()).is_err()); + let bound_target = roots[0].reference(); + validate_bound_target(pid, bound_target) + .expect("closing the panel leaves the bound window active"); + drop(lease); + super::super::control_session::stop(Some(owner), "fixture_done").unwrap(); + assert!( + validate_bound_target(pid, bound_target).is_err(), + "Stop must still revoke retained targets" + ); + } +} + const WEB_AREA_ANCESTOR_LIMIT: usize = 64; /// Whether a parent chain reaches a web area within the depth bound. An @@ -276,7 +414,45 @@ unsafe fn has_web_area_ancestor(element: AXUIElementRef) -> bool { } pub(crate) fn element_window_id(target: AxRef) -> Option { + if target.0.is_null() { + return None; + } unsafe { + // Remote AppKit file-panel descendants report an off-screen proxy's + // window ID. Resolve their enclosing AXSheet/AXWindow first: its ID is + // the visible WindowServer surface. Never infer ownership from bounds + // or walk past the first native surface into another window. + let mut current = CFRetain(target.0) as AXUIElementRef; + for depth in 0..64 { + let role = read_cf_string_attr(current, "AXRole"); + if matches!(role.as_deref(), Some("AXWindow" | "AXSheet" | "AXDrawer")) { + let id = super::macos_ax_ui::ax_window_id(current).filter(|id| *id != 0); + ax_release(current); + return id; + } + if role.as_deref() == Some("AXApplication") { + ax_release(current); + break; + } + if depth == 63 { + ax_release(current); + return None; + } + let parent = ax_copy_attr(current, "AXParent"); + let same = parent.is_some_and(|p| CFEqual(p, current) != 0); + ax_release(current); + match parent { + Some(parent) if !same && CFGetTypeID(parent) == AXUIElementGetTypeID() => { + current = parent as AXUIElementRef; + } + Some(parent) => { + ax_release(parent); + break; + } + None => break, + } + } + // Providers without a parent hierarchy retain the exact-ID path. super::macos_ax_ui::ax_window_id(target.0) .filter(|id| *id != 0) .or_else(|| { @@ -359,7 +535,7 @@ pub(crate) fn retained_target_at_point( return Ok(None); } let owning_window = element_window_id(target.reference()); - if owning_window != Some(window_id) { + if !owning_window.is_some_and(|actual| window_belongs_to_capture(pid, window_id, actual)) { return Ok(None); } let Some((left, top, width, height)) = target.frame_global() else { @@ -407,7 +583,9 @@ pub(crate) fn focused_text_target_mismatch(pid: i32, x: f64, y: f64) -> OpenBitF if !target.is_text_input() { return Ok(false); } - if element_window_id(target.reference()).is_some_and(|window| window != bound) { + if element_window_id(target.reference()) + .is_some_and(|window| !window_belongs_to_capture(pid, bound, window)) + { return Ok(true); } if let Some((left, top, width, height)) = target.frame_global() { diff --git a/src/crates/services/computer-use/src/computer_use/macos_ax_write.rs b/src/crates/services/computer-use/src/computer_use/macos_ax_write.rs index b0d6b8d7a4..822dc542a0 100644 --- a/src/crates/services/computer-use/src/computer_use/macos_ax_write.rs +++ b/src/crates/services/computer-use/src/computer_use/macos_ax_write.rs @@ -47,17 +47,7 @@ fn can_write(target: AxRef) -> bool { if unsafe { AXUIElementGetPid(target.0, &mut pid) } != 0 { return false; } - let Ok(window) = super::macos_capture::bound_window_id(pid) else { - return false; - }; - let same_window = match super::macos_ax_dump::element_window_id(target) { - Some(actual) => actual == window, - // Menu-bar actions have application scope and no window. Arbitrary - // controls with an unknown owning window cannot inherit that exception. - None => super::macos_ax_dump::is_application_menu_item(target), - }; - same_window - && super::control_session::target_allowed(&format!("pid:{pid}/window:{window}")).is_ok() + super::macos_ax_dump::validate_bound_target(pid, target).is_ok() } fn note_dispatched_input(target: AxRef) {