Skip to content
Merged
28 changes: 28 additions & 0 deletions scripts/test-macos-computer-use-self.mjs
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
// The target is a disposable native window owned by the ComputerUse host itself.
// An external watchdog also catches deadlocks that stop the main run loop.
import assert from 'node:assert/strict';
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';

assert.equal(process.platform, 'darwin', 'Self WebView fixture requires macOS');
const root = fileURLToPath(new URL('../', import.meta.url));
const run = (command, args, options = {}) => new Promise((resolve, reject) => {
const child = spawn(command, args, { cwd: root, windowsHide: true, stdio: 'inherit', ...options });
let output = '';
child.stdout?.on('data', chunk => { output += String(chunk); });
child.once('error', reject);
child.once('close', (code, signal) => code === 0 ? resolve(output) : reject(new Error(`${command} failed: code=${code} signal=${signal}`)));
});
const args = ['test', '--locked', '-p', 'openbitfun-desktop', '--features', 'devtools', '--test', 'computer_use_native_roundtrip'];
let executable = process.env.OPENBITFUN_TEST_BINARY;
if (!executable) {
const output = await run('cargo', [...args, '--no-run', '--message-format=json'], { stdio: ['ignore', 'pipe', 'inherit'] });
executable = output.split('\n').filter(Boolean).map(line => JSON.parse(line))
.find(record => record.target?.name === 'computer_use_native_roundtrip' && record.executable)?.executable;
assert.ok(executable, 'Cargo must report the native harness executable');
}
await run(executable, [], {
env: { ...process.env, OPENBITFUN_CUA_SELF_TEST: '1' },
timeout: 60_000,
killSignal: 'SIGKILL',
});
24 changes: 14 additions & 10 deletions src/apps/cli/tests/support/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -572,11 +572,14 @@ fn serve_model_response(
.to_string(),
)
.expect("write scripted tool response");
write_chunk(stream, b"data: [DONE]\n\n").expect("finish scripted tool SSE");
stream
.write_all(b"0\r\n\r\n")
.expect("finish scripted response");
stream.flush().expect("flush scripted response");
// The client may close as soon as it consumes the finish reason. A Windows
// ConnectionAborted here must not kill the server for the next tool
// response; all required SSE data was already written successfully.
if write_chunk(stream, b"data: [DONE]\n\n").is_err() {
return;
}
let _ = stream.write_all(b"0\r\n\r\n");
let _ = stream.flush();
return;
}

Expand Down Expand Up @@ -770,11 +773,12 @@ fn serve_product_control_response(stream: &mut TcpStream, attempt: usize) {
.expect("write product-control completion chunk");
}

write_chunk(stream, b"data: [DONE]\n\n").expect("finish product-control SSE");
stream
.write_all(b"0\r\n\r\n")
.expect("finish product-control chunked response");
stream.flush().expect("flush product-control response");
// Match the ordinary streaming response: EOF after completion is normal.
if write_chunk(stream, b"data: [DONE]\n\n").is_err() {
return;
}
let _ = stream.write_all(b"0\r\n\r\n");
let _ = stream.flush();
}

fn write_http_403(stream: &mut TcpStream, reason: &str) -> std::io::Result<()> {
Expand Down
24 changes: 24 additions & 0 deletions src/apps/desktop/src/computer_use/AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ remaining native acceptance scenarios separately.
- `desktop_host/observation.rs`, `observation_cache.rs` — observation identity and bounded screenshot geometry; never input authority
- `desktop_host/state.rs` — derived host feedback and view caches
- `macos_*` / `windows_*` — platform AX, capture, list-apps, shortcuts
- `macos_ax_dispatch` — per-element AX thread routing and native exception boundary
- `windows_capture.rs` — WGC frame conversion and authoritative window bounds
- `windows_wgc_capture.rs` — Windows.Graphics.Capture (Direct3D11)
- `windows_window_target.rs` — Win32 window facts and portable default-target policy
Expand Down Expand Up @@ -111,6 +112,26 @@ inputs that can name a screenshot_id require one after a zoom.

## Target-local macOS focus acceptance

AX walks and cached-node operations run on a blocking worker. Route each native
message by the element's serving PID through `macos_ax_dispatch`: same-process
AppKit callbacks require main, while WebKit subprocess messages need main free
to answer synchronous IPC, including AX client authentication. Never dispatch an
entire walk based on its root PID; a single tree spans both processes.
`AXUIElementGetPid` reports the presenter for WebKit descendants; thread routing
uses dynamically resolved `_AXUIElementGetActualPid`. Keep the presenter PID for
target/permission validation. If the serving-PID SPI is unavailable, report an
explicit unsupported state instead of guessing a thread. Keep the
control token across same-process dispatch and catch Objective-C exceptions on
the executing thread. Recheck input authority there before actions or user
attribute writes, because Stop may revoke a queued message. Observation-only
AX enablement does not acquire input authority. Enigo / HIToolbox input retains
its main-thread wrapper.

Cross-process AX proxies can advertise a writable `AXSelectedText` whose setter
does nothing (WebKit). Select the existing directed-keyboard route before
submission for these proxies; native controls retain AX insertion at the current
selection. Never retry a submitted text write based only on unchanged AX state.

The directed-input route can change a target application's internal
focus without changing the human foreground application. Its window-addressed
focus pair at local `(-8,-8)` must remain outside content; the requested gesture
Expand Down Expand Up @@ -187,6 +208,9 @@ node scripts/test-macos-input-controls.mjs --latency
node scripts/test-macos-input-controls.mjs
# Full Tool -> provider -> native loop on a dedicated window, with main-thread runloop.
node scripts/test-macos-control-roundtrip.mjs
# Same-process AppKit + real WebKit subtree: observe, capture, image/node clicks,
# exact text, actual DOM results, shortcuts and Stop; external deadlock watchdog.
node scripts/test-macos-computer-use-self.mjs
# Same-process popup panel over a dedicated window, once as an attached child
# window (inherits layer 0) and once at the pop-up menu level: composited pixels
# and auxiliary metadata, popup-routed press without focus preparation
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -426,7 +426,7 @@ impl DesktopComputerUseHost {
&& params.modifier_keys.is_empty();
node_coordinates =
crate::computer_use::control_session::spawn_blocking(move || {
macos::catch_objc(|| resolve_macos_node_click(pid, idx, semantic))
macos::catch_objc_local(|| resolve_macos_node_click(pid, idx, semantic))
})
.await
.map_err(|error| OpenBitFunError::tool(error.to_string()))??;
Expand All @@ -450,7 +450,7 @@ impl DesktopComputerUseHost {
)?;
image_coordinates = Some((x, y));
crate::computer_use::control_session::spawn_blocking(move || {
macos::catch_objc(|| try_macos_point_press(pid, x, y))
macos::catch_objc_local(|| try_macos_point_press(pid, x, y))
})
.await
.map_err(|error| OpenBitFunError::tool(error.to_string()))??
Expand Down Expand Up @@ -670,7 +670,7 @@ impl DesktopComputerUseHost {
if point.is_none() && index.is_none() {
return Ok(false);
}
crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc(|| {
crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc_local(|| {
let element = if let Some(index) = index {
Some(crate::computer_use::macos_ax_dump::retained_cached_target(pid, index)
.ok_or_else(|| OpenBitFunError::tool("AX_NODE_STALE: text focus target is no longer in the observed snapshot"))?)
Expand Down Expand Up @@ -726,7 +726,7 @@ impl DesktopComputerUseHost {
.flatten()
.map(|point| (point.x, point.y));
if let Some((x, y)) = intended_point {
let mismatch = crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc(||
let mismatch = crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc_local(||
crate::computer_use::macos_ax_dump::focused_text_target_mismatch(pid, x, y)
)).await.map_err(|error| OpenBitFunError::tool(error.to_string()))??;
if mismatch {
Expand Down Expand Up @@ -865,7 +865,7 @@ impl DesktopComputerUseHost {
None => {
let idx = *idx;
crate::computer_use::control_session::spawn_blocking(move || {
macos::catch_objc(|| resolve_macos_node_click(pid, idx, false))
macos::catch_objc_local(|| resolve_macos_node_click(pid, idx, false))
})
.await
.map_err(|error| OpenBitFunError::tool(error.to_string()))??
Expand Down
30 changes: 9 additions & 21 deletions src/apps/desktop/src/computer_use/desktop_host/macos.rs
Original file line number Diff line number Diff line change
Expand Up @@ -53,22 +53,11 @@ where
}
}

/// Run a closure on the main dispatch queue under an Objective-C
/// `@try/@catch`. This is the correct wrapper for calls that may reach
/// AppKit / HIToolbox / Accessibility code paths from a background
/// (`tokio::spawn_blocking`) worker thread.
///
/// Two failure modes are defended against simultaneously:
///
/// 1. `NSException` thrown by the framework (caught and converted into
/// `OpenBitFunError`).
/// 2. AppKit's `__assert_rtn` "Must only be used from the main thread"
/// `SIGTRAP` which fires when AX cross-process callbacks (e.g.
/// `AXUIElementCopyActionNames` → `_NSThemeWidgetCell.accessibility…`
/// → `_WMWindow performUpdatesUsingBlock:`) are evaluated off the
/// main thread. `objc2::exception::catch` cannot intercept this
/// trap; the only fix is to actually run the closure on the main
/// thread, which is what this helper does.
/// Run AppKit / HIToolbox input work on main under an Objective-C catch.
/// Never wrap AX traversal or cached-node actions here: a same-process tree
/// also contains WebKit subprocess elements whose IPC needs main to stay free.
/// Use `catch_objc_local` for AX work; `macos_ax_dispatch` sends each individual
/// same-process message to main to preserve AppKit's thread requirement.
///
/// If we're already on the main thread we run inline (avoids
/// `dispatch_sync(main)` deadlock).
Expand All @@ -89,10 +78,8 @@ where
}

/// Run a closure under an Objective-C `@try/@catch` **on the current
/// thread** (no main-queue dispatch). Use this for closures that borrow
/// non-`Send` data and that are guaranteed not to reach AppKit's
/// main-thread-only AX callbacks (e.g. Vision OCR on an in-memory
/// screenshot buffer).
/// thread** (no main-queue dispatch). AX work routes individual messages through
/// `macos_ax_dispatch`; Vision OCR can also run here with borrowed image data.
pub(super) fn catch_objc_local<F, T>(f: F) -> OpenBitFunResult<T>
where
F: FnOnce() -> OpenBitFunResult<T>,
Expand Down Expand Up @@ -166,7 +153,8 @@ pub(super) fn request_screen_capture() -> bool {
/// owns the explicit request and the OS owns its outcome.
pub(super) fn require_ax_trust_for(retry_hint: &str) -> OpenBitFunResult<()> {
if ax_trusted() {
return Ok(());
return crate::computer_use::macos_ax_dispatch::require_process_routing()
.map_err(OpenBitFunError::tool);
}
Err(OpenBitFunError::tool(format!(
"[PERMISSION_DENIED] macOS Accessibility permission not granted to OpenBitFun. \
Expand Down
4 changes: 2 additions & 2 deletions src/apps/desktop/src/computer_use/desktop_host/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -817,7 +817,7 @@ impl DesktopComputerUseHost {
let pid = resolve_pid_macos(self, &app).await?;
let (shortcuts, menu_items_without_shortcut) =
crate::computer_use::control_session::spawn_blocking(move || {
macos::catch_objc(|| {
macos::catch_objc_local(|| {
crate::computer_use::macos_ax_shortcuts::dump_app_menu_shortcuts(pid)
})
})
Expand Down Expand Up @@ -1402,7 +1402,7 @@ impl ComputerUseHost for DesktopComputerUseHost {
// AX tree traversal can throw `NSException` from a misbehaving
// frontmost app; the @try/@catch wrapper turns that into a
// missing UI-tree text rather than crashing the whole process.
macos::catch_objc(|| {
macos::catch_objc_local(|| {
Ok(
crate::computer_use::macos_ax_ui::enumerate_ui_tree_text_for_pid(
pid,
Expand Down
Loading
Loading