Skip to content

Commit 91eeba6

Browse files
authored
Merge pull request #3600 from bobleer/bob/fix-macos-self-ax-deadlock
fix(desktop): restore macOS WebView self-control
2 parents 6208a06 + d959e78 commit 91eeba6

16 files changed

Lines changed: 667 additions & 113 deletions
Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,28 @@
1+
// The target is a disposable native window owned by the ComputerUse host itself.
2+
// An external watchdog also catches deadlocks that stop the main run loop.
3+
import assert from 'node:assert/strict';
4+
import { spawn } from 'node:child_process';
5+
import { fileURLToPath } from 'node:url';
6+
7+
assert.equal(process.platform, 'darwin', 'Self WebView fixture requires macOS');
8+
const root = fileURLToPath(new URL('../', import.meta.url));
9+
const run = (command, args, options = {}) => new Promise((resolve, reject) => {
10+
const child = spawn(command, args, { cwd: root, windowsHide: true, stdio: 'inherit', ...options });
11+
let output = '';
12+
child.stdout?.on('data', chunk => { output += String(chunk); });
13+
child.once('error', reject);
14+
child.once('close', (code, signal) => code === 0 ? resolve(output) : reject(new Error(`${command} failed: code=${code} signal=${signal}`)));
15+
});
16+
const args = ['test', '--locked', '-p', 'openbitfun-desktop', '--features', 'devtools', '--test', 'computer_use_native_roundtrip'];
17+
let executable = process.env.OPENBITFUN_TEST_BINARY;
18+
if (!executable) {
19+
const output = await run('cargo', [...args, '--no-run', '--message-format=json'], { stdio: ['ignore', 'pipe', 'inherit'] });
20+
executable = output.split('\n').filter(Boolean).map(line => JSON.parse(line))
21+
.find(record => record.target?.name === 'computer_use_native_roundtrip' && record.executable)?.executable;
22+
assert.ok(executable, 'Cargo must report the native harness executable');
23+
}
24+
await run(executable, [], {
25+
env: { ...process.env, OPENBITFUN_CUA_SELF_TEST: '1' },
26+
timeout: 60_000,
27+
killSignal: 'SIGKILL',
28+
});

‎src/apps/cli/tests/support/mod.rs‎

Lines changed: 14 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -572,11 +572,14 @@ fn serve_model_response(
572572
.to_string(),
573573
)
574574
.expect("write scripted tool response");
575-
write_chunk(stream, b"data: [DONE]\n\n").expect("finish scripted tool SSE");
576-
stream
577-
.write_all(b"0\r\n\r\n")
578-
.expect("finish scripted response");
579-
stream.flush().expect("flush scripted response");
575+
// The client may close as soon as it consumes the finish reason. A Windows
576+
// ConnectionAborted here must not kill the server for the next tool
577+
// response; all required SSE data was already written successfully.
578+
if write_chunk(stream, b"data: [DONE]\n\n").is_err() {
579+
return;
580+
}
581+
let _ = stream.write_all(b"0\r\n\r\n");
582+
let _ = stream.flush();
580583
return;
581584
}
582585

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

773-
write_chunk(stream, b"data: [DONE]\n\n").expect("finish product-control SSE");
774-
stream
775-
.write_all(b"0\r\n\r\n")
776-
.expect("finish product-control chunked response");
777-
stream.flush().expect("flush product-control response");
776+
// Match the ordinary streaming response: EOF after completion is normal.
777+
if write_chunk(stream, b"data: [DONE]\n\n").is_err() {
778+
return;
779+
}
780+
let _ = stream.write_all(b"0\r\n\r\n");
781+
let _ = stream.flush();
778782
}
779783

780784
fn write_http_403(stream: &mut TcpStream, reason: &str) -> std::io::Result<()> {

‎src/apps/desktop/src/computer_use/AGENTS.md‎

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,7 @@ remaining native acceptance scenarios separately.
6161
- `desktop_host/observation.rs`, `observation_cache.rs` — observation identity and bounded screenshot geometry; never input authority
6262
- `desktop_host/state.rs` — derived host feedback and view caches
6363
- `macos_*` / `windows_*` — platform AX, capture, list-apps, shortcuts
64+
- `macos_ax_dispatch` — per-element AX thread routing and native exception boundary
6465
- `windows_capture.rs` — WGC frame conversion and authoritative window bounds
6566
- `windows_wgc_capture.rs` — Windows.Graphics.Capture (Direct3D11)
6667
- `windows_window_target.rs` — Win32 window facts and portable default-target policy
@@ -111,6 +112,26 @@ inputs that can name a screenshot_id require one after a zoom.
111112

112113
## Target-local macOS focus acceptance
113114

115+
AX walks and cached-node operations run on a blocking worker. Route each native
116+
message by the element's serving PID through `macos_ax_dispatch`: same-process
117+
AppKit callbacks require main, while WebKit subprocess messages need main free
118+
to answer synchronous IPC, including AX client authentication. Never dispatch an
119+
entire walk based on its root PID; a single tree spans both processes.
120+
`AXUIElementGetPid` reports the presenter for WebKit descendants; thread routing
121+
uses dynamically resolved `_AXUIElementGetActualPid`. Keep the presenter PID for
122+
target/permission validation. If the serving-PID SPI is unavailable, report an
123+
explicit unsupported state instead of guessing a thread. Keep the
124+
control token across same-process dispatch and catch Objective-C exceptions on
125+
the executing thread. Recheck input authority there before actions or user
126+
attribute writes, because Stop may revoke a queued message. Observation-only
127+
AX enablement does not acquire input authority. Enigo / HIToolbox input retains
128+
its main-thread wrapper.
129+
130+
Cross-process AX proxies can advertise a writable `AXSelectedText` whose setter
131+
does nothing (WebKit). Select the existing directed-keyboard route before
132+
submission for these proxies; native controls retain AX insertion at the current
133+
selection. Never retry a submitted text write based only on unchanged AX state.
134+
114135
The directed-input route can change a target application's internal
115136
focus without changing the human foreground application. Its window-addressed
116137
focus pair at local `(-8,-8)` must remain outside content; the requested gesture
@@ -187,6 +208,9 @@ node scripts/test-macos-input-controls.mjs --latency
187208
node scripts/test-macos-input-controls.mjs
188209
# Full Tool -> provider -> native loop on a dedicated window, with main-thread runloop.
189210
node scripts/test-macos-control-roundtrip.mjs
211+
# Same-process AppKit + real WebKit subtree: observe, capture, image/node clicks,
212+
# exact text, actual DOM results, shortcuts and Stop; external deadlock watchdog.
213+
node scripts/test-macos-computer-use-self.mjs
190214
# Same-process popup panel over a dedicated window, once as an attached child
191215
# window (inherits layer 0) and once at the pop-up menu level: composited pixels
192216
# and auxiliary metadata, popup-routed press without focus preparation

‎src/apps/desktop/src/computer_use/desktop_host/ax_orchestration.rs‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -426,7 +426,7 @@ impl DesktopComputerUseHost {
426426
&& params.modifier_keys.is_empty();
427427
node_coordinates =
428428
crate::computer_use::control_session::spawn_blocking(move || {
429-
macos::catch_objc(|| resolve_macos_node_click(pid, idx, semantic))
429+
macos::catch_objc_local(|| resolve_macos_node_click(pid, idx, semantic))
430430
})
431431
.await
432432
.map_err(|error| OpenBitFunError::tool(error.to_string()))??;
@@ -450,7 +450,7 @@ impl DesktopComputerUseHost {
450450
)?;
451451
image_coordinates = Some((x, y));
452452
crate::computer_use::control_session::spawn_blocking(move || {
453-
macos::catch_objc(|| try_macos_point_press(pid, x, y))
453+
macos::catch_objc_local(|| try_macos_point_press(pid, x, y))
454454
})
455455
.await
456456
.map_err(|error| OpenBitFunError::tool(error.to_string()))??
@@ -670,7 +670,7 @@ impl DesktopComputerUseHost {
670670
if point.is_none() && index.is_none() {
671671
return Ok(false);
672672
}
673-
crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc(|| {
673+
crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc_local(|| {
674674
let element = if let Some(index) = index {
675675
Some(crate::computer_use::macos_ax_dump::retained_cached_target(pid, index)
676676
.ok_or_else(|| OpenBitFunError::tool("AX_NODE_STALE: text focus target is no longer in the observed snapshot"))?)
@@ -726,7 +726,7 @@ impl DesktopComputerUseHost {
726726
.flatten()
727727
.map(|point| (point.x, point.y));
728728
if let Some((x, y)) = intended_point {
729-
let mismatch = crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc(||
729+
let mismatch = crate::computer_use::control_session::spawn_blocking(move || macos::catch_objc_local(||
730730
crate::computer_use::macos_ax_dump::focused_text_target_mismatch(pid, x, y)
731731
)).await.map_err(|error| OpenBitFunError::tool(error.to_string()))??;
732732
if mismatch {
@@ -865,7 +865,7 @@ impl DesktopComputerUseHost {
865865
None => {
866866
let idx = *idx;
867867
crate::computer_use::control_session::spawn_blocking(move || {
868-
macos::catch_objc(|| resolve_macos_node_click(pid, idx, false))
868+
macos::catch_objc_local(|| resolve_macos_node_click(pid, idx, false))
869869
})
870870
.await
871871
.map_err(|error| OpenBitFunError::tool(error.to_string()))??

‎src/apps/desktop/src/computer_use/desktop_host/macos.rs‎

Lines changed: 9 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -53,22 +53,11 @@ where
5353
}
5454
}
5555

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

9180
/// Run a closure under an Objective-C `@try/@catch` **on the current
92-
/// thread** (no main-queue dispatch). Use this for closures that borrow
93-
/// non-`Send` data and that are guaranteed not to reach AppKit's
94-
/// main-thread-only AX callbacks (e.g. Vision OCR on an in-memory
95-
/// screenshot buffer).
81+
/// thread** (no main-queue dispatch). AX work routes individual messages through
82+
/// `macos_ax_dispatch`; Vision OCR can also run here with borrowed image data.
9683
pub(super) fn catch_objc_local<F, T>(f: F) -> OpenBitFunResult<T>
9784
where
9885
F: FnOnce() -> OpenBitFunResult<T>,
@@ -166,7 +153,8 @@ pub(super) fn request_screen_capture() -> bool {
166153
/// owns the explicit request and the OS owns its outcome.
167154
pub(super) fn require_ax_trust_for(retry_hint: &str) -> OpenBitFunResult<()> {
168155
if ax_trusted() {
169-
return Ok(());
156+
return crate::computer_use::macos_ax_dispatch::require_process_routing()
157+
.map_err(OpenBitFunError::tool);
170158
}
171159
Err(OpenBitFunError::tool(format!(
172160
"[PERMISSION_DENIED] macOS Accessibility permission not granted to OpenBitFun. \

‎src/apps/desktop/src/computer_use/desktop_host/mod.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -817,7 +817,7 @@ impl DesktopComputerUseHost {
817817
let pid = resolve_pid_macos(self, &app).await?;
818818
let (shortcuts, menu_items_without_shortcut) =
819819
crate::computer_use::control_session::spawn_blocking(move || {
820-
macos::catch_objc(|| {
820+
macos::catch_objc_local(|| {
821821
crate::computer_use::macos_ax_shortcuts::dump_app_menu_shortcuts(pid)
822822
})
823823
})
@@ -1402,7 +1402,7 @@ impl ComputerUseHost for DesktopComputerUseHost {
14021402
// AX tree traversal can throw `NSException` from a misbehaving
14031403
// frontmost app; the @try/@catch wrapper turns that into a
14041404
// missing UI-tree text rather than crashing the whole process.
1405-
macos::catch_objc(|| {
1405+
macos::catch_objc_local(|| {
14061406
Ok(
14071407
crate::computer_use::macos_ax_ui::enumerate_ui_tree_text_for_pid(
14081408
pid,

0 commit comments

Comments
 (0)