Skip to content

armgit / cua

Public Imported from GitHub
0

Scale computer-use 2.0 with open-source drivers, cross-OS sandboxes, and benchmarks for training, evaluation, and data generation.

fix(cua-driver): accept element_token without pid on Windows and Linux (#4773)

Francesco Bonacci12365b36d414
diff --git a/.github/workflows/smoke-cua-driver-live.yml b/.github/workflows/smoke-cua-driver-live.yml
index 25ef0445e5..a8718f3234 100644
--- a/.github/workflows/smoke-cua-driver-live.yml
+++ b/.github/workflows/smoke-cua-driver-live.yml
@@ -2,8 +2,9 @@ name: "Smoke: Cua Driver live agent loop"
# Builds cua-driver from the checked-out commit and drives a real GUI window on
# Windows and on Linux (Xvfb): the lean get_window_state default and
-# full_output, `since` diffs, act-by-element_token, run_actions, and set_value
-# on combo boxes. The checks live in scripts/ci/cua-driver-live-smoke/smoke.py.
+# full_output, `since` diffs, act-by-element_token (with and without pid),
+# run_actions, and set_value on combo boxes (background, foreground and an
+# unknown option). The checks live in scripts/ci/cua-driver-live-smoke/smoke.py.
on:
workflow_dispatch:
@@ -13,6 +14,12 @@ on:
- "scripts/ci/cua-driver-live-smoke/**"
- "libs/cua-driver/rust/crates/cua-driver-core/src/window_state_view.rs"
- "libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs"
+ - "libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs"
+ - "libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs"
+ - "libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs"
+ - "libs/cua-driver/rust/crates/platform-windows/src/win32/combo.rs"
+ - "libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs"
+ - "libs/cua-driver/rust/crates/platform-linux/src/atspi/**"
permissions:
contents: read
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx
index 182f2eb406..9ce7df6058 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools/click.mdx
@@ -72,7 +72,7 @@ button: "left" (default), "right", or "middle". Defaults to left so the field is
| <span id="click--linux--delivery_mode"></span>`delivery_mode` | `"background" \| "foreground"` | `"background"` | Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus: Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window; a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. |
| <span id="click--linux--from_zoom"></span>`from_zoom` | `boolean` | | Set true after a zoom call to auto-translate zoom-image pixel coordinates back to full-window space. |
| <span id="click--linux--modifier"></span>`modifier` | `string[]` | | Modifier keys held during the action: cmd, shift, option/alt, ctrl. |
-| <span id="click--linux--pid"></span>`pid` | `integer` | | Target process ID. Required unless scope is "desktop". |
+| <span id="click--linux--pid"></span>`pid` | `integer` | | Target process ID. Required unless scope is "desktop" or element_token is supplied (the token carries the pid). |
| <span id="click--linux--scope"></span>`scope` | `"window" \| "desktop"` | `"window"` | Coordinate frame (default "window"). Pass "desktop" with x,y and no pid/window_id for a screen-absolute click in get_desktop_state coordinates. |
| <span id="click--linux--session"></span>`session` | `string` | | For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session. |
| <span id="click--linux--window_id"></span>`window_id` | `integer` | | Window id from list_windows. Required with x/y or element_index; optional with element_token (the token carries it). |
@@ -105,7 +105,7 @@ Windows-only convenience: `button: "left"|"right"|"middle"` switches the mouse b
| <span id="click--windows--delivery_mode"></span>`delivery_mode` | `"background" \| "foreground"` | | Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh; it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess: fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface. |
| <span id="click--windows--from_zoom"></span>`from_zoom` | `boolean` | | When true, x and y are pixel coordinates in the last `zoom` image for this pid. The driver maps them back to window coords. |
| <span id="click--windows--modifier"></span>`modifier` | `string[]` | | Modifier keys held during the action: cmd, shift, option/alt, ctrl. |
-| <span id="click--windows--pid"></span>`pid` | `integer` | | Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state. |
+| <span id="click--windows--pid"></span>`pid` | `integer` | | Target process ID for window scope. Optional with element_token (the token carries the pid). Omit with scope=desktop for screen-absolute coordinates from get_desktop_state. |
| <span id="click--windows--scope"></span>`scope` | `"window" \| "desktop"` | `"window"` | Coordinate frame (default "window"). Pass "desktop" with x,y and no pid/window_id for a screen-absolute click in get_desktop_state coordinates. |
| <span id="click--windows--session"></span>`session` | `string` | | For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session. |
| <span id="click--windows--window_id"></span>`window_id` | `integer` | | HWND of the target window. Omit when element_token is supplied (the token carries it). |
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/pointer.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/pointer.mdx
index 66e973b49e..1ae3197c4c 100644
--- a/docs/content/docs/cua-driver/reference/mcp-tools/pointer.mdx
+++ b/docs/content/docs/cua-driver/reference/mcp-tools/pointer.mdx
@@ -165,7 +165,7 @@ Scroll the target pid's focused region via XSendEvent Button4/5. direction requi
| <span id="scroll--linux--coordinate_frame"></span>`coordinate_frame` | `"window" \| "desktop"` | | Frame of x/y (and from_x/from_y/to_x/to_y). Default "window": window-local screenshot pixels as returned by get_window_state. "desktop": full-screen pixels as returned by get_desktop_state, translated to the target window. Passing scope:"desktop" together with pid/window_id means the same thing. |
| <span id="scroll--linux--cursor_id"></span>`cursor_id` | `string` | | Optional multi-cursor instance id. Default: 'default'. |
| <span id="scroll--linux--delivery_mode"></span>`delivery_mode` | `"background" \| "foreground"` | `"background"` | Input delivery mode. 'background' (default) never activates or raises the target window. On X11 it injects via XTEST / the XInput2 master pointer (no focus steal). On Wayland it goes through libei + xdg-desktop-portal, which injects to the compositor's input focus: Wayland's security model has no per-window background targeting, so a specific non-focused window cannot be aimed at; when no libei backend is available the tool returns a structured background_unavailable error. 'foreground' is the explicit escalation: activate the target (X11 _NET_ACTIVE_WINDOW; Wayland compositor activate), inject, then restore the prior active window; a brief focus swap unless the target was already active. Matches the macOS / Windows delivery_mode surface. |
-| <span id="scroll--linux--pid"></span>`pid` | `integer` | | Target process ID. Required unless scope is "desktop". |
+| <span id="scroll--linux--pid"></span>`pid` | `integer` | | Target process ID. Required unless scope is "desktop" or element_token is supplied (the token carries the pid). |
| <span id="scroll--linux--scope"></span>`scope` | `"window" \| "desktop"` | `"window"` | Use "desktop" with x,y and no pid/window_id for get_desktop_state screen coordinates. Default "window". |
| <span id="scroll--linux--session"></span>`session` | `string` | | For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session. |
| <span id="scroll--linux--window_id"></span>`window_id` | `integer` | | Window id from list_windows. Required with x/y; optional with element_token (the token carries it). |
@@ -189,7 +189,7 @@ Note: `element_token` is accepted for cross-platform parity but currently no-op
| --- | --- | --- | --- |
| <span id="scroll--windows--amount"></span>`amount` | `integer` | | Number of scroll ticks. Default 3. Range: 1 to 50. |
| <span id="scroll--windows--delivery_mode"></span>`delivery_mode` | `"background" \| "foreground"` | | Input delivery mode. 'background' (default) never swaps foreground: it routes through UIA Invoke / PostMessage and the window is never raised. For targets whose input stack silently drops posted events (Chromium/Electron content, GTK buttons, VCL/LibreOffice accelerators) the tool returns a structured background_unavailable error rather than fronting. 'foreground' is the explicit escalation: a brief SetForegroundWindow swap + SendInput, restoring the prior foreground afterward. IMPORTANT: 'background' is not a hint to weigh; it is the mandatory first attempt. Do NOT pass 'foreground' preemptively because a target 'looks like' GTK/Chromium/Electron; the DRIVER decides when background is impossible and tells you so via a background_unavailable error (or a verified no-op). Only THEN re-issue the same action with 'foreground'. The lists above are the driver's detectors, not a checklist for you to front on a guess: fronting up-front needlessly steals the user's focus and is a bug, not a shortcut. Matches the macOS delivery_mode surface. |
-| <span id="scroll--windows--pid"></span>`pid` | `integer` | | Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state. |
+| <span id="scroll--windows--pid"></span>`pid` | `integer` | | Target process ID for window scope. Optional with element_token (the token carries the pid). Omit with scope=desktop for screen-absolute coordinates from get_desktop_state. |
| <span id="scroll--windows--scope"></span>`scope` | `"window" \| "desktop"` | `"window"` | Use "desktop" with x,y and no pid/window_id for screen-absolute coordinates from get_desktop_state. Default "window". |
| <span id="scroll--windows--session"></span>`session` | `string` | | For multi-call work, prefer a short public session label and repeat it on every call that accepts it. Omit it to use the authenticated transport's implicit lifecycle session. |
| <span id="scroll--windows--window_id"></span>`window_id` | `integer` | | HWND of the target window. Omit when element_token is supplied; otherwise auto-resolves the pid's first visible window. |
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
index 8834e0f6d5..14c630bd0d 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/element_token.rs
@@ -58,6 +58,43 @@ impl<T> ResolvedElement<T> {
}
}
+/// Message for a call that names its target only by an `element_token` the
+/// runtime no longer knows (or never minted), so no pid can be derived.
+pub const STALE_TOKEN_WITHOUT_PID: &str =
+ "element_token is stale or unknown; call get_window_state again to refresh";
+
+/// The refusal for [`STALE_TOKEN_WITHOUT_PID`]: `stale_element_token`, with
+/// the hint that a current token names its own pid.
+pub fn stale_token_without_pid() -> ToolResult {
+ ToolResult::error(format!(
+ "{STALE_TOKEN_WITHOUT_PID} (a current token names its own pid)."
+ ))
+ .with_structured(serde_json::json!({
+ "status": "refused",
+ "refusal": { "code": "stale_element_token", "message": STALE_TOKEN_WITHOUT_PID },
+ }))
+}
+
+/// Fill a missing `pid` from the call's `element_token`. A token names its
+/// snapshot, and so its window and process, so a token-only call needs no
+/// pid. An explicit `pid` wins and a call without a token is left as is (the
+/// tool reports its own missing-pid error). A token whose snapshot is gone
+/// is refused as `stale_element_token` rather than as a missing pid.
+pub fn fill_pid_from_token(
+ args: &mut serde_json::Value,
+ pid_for_token: impl FnOnce(&serde_json::Value) -> Option<i32>,
+) -> Result<(), ToolResult> {
+ let present = |key: &str| args.get(key).is_some_and(|value| !value.is_null());
+ if present("pid") || !present("element_token") {
+ return Ok(());
+ }
+ let pid = pid_for_token(args).ok_or_else(stale_token_without_pid)?;
+ if let Some(object) = args.as_object_mut() {
+ object.insert("pid".to_owned(), pid.into());
+ }
+ Ok(())
+}
+
pub(crate) fn refusal(code: &str, message: String) -> ToolResult {
ToolResult::error(message.clone()).with_structured(serde_json::json!({
"status": "refused", "refusal": { "code": code, "message": message }
@@ -68,6 +105,26 @@ pub(crate) fn refusal(code: &str, message: String) -> ToolResult {
mod tests {
use super::*;
+ #[test]
+ fn fill_pid_from_token_resolves_only_token_only_calls() {
+ let mut token_only = serde_json::json!({ "element_token": "s00000001:2" });
+ fill_pid_from_token(&mut token_only, |_| Some(42)).unwrap();
+ assert_eq!(token_only["pid"], 42);
+
+ let mut explicit = serde_json::json!({ "pid": 7, "element_token": "s00000001:2" });
+ fill_pid_from_token(&mut explicit, |_| panic!("an explicit pid wins")).unwrap();
+ assert_eq!(explicit["pid"], 7);
+
+ let mut no_token = serde_json::json!({ "x": 1, "y": 2 });
+ fill_pid_from_token(&mut no_token, |_| panic!("no token, no lookup")).unwrap();
+ assert!(no_token.get("pid").is_none());
+
+ let mut stale = serde_json::json!({ "pid": null, "element_token": "s00000009:0" });
+ let refused = fill_pid_from_token(&mut stale, |_| None).unwrap_err();
+ let structured = refused.structured_content.unwrap();
+ assert_eq!(structured["refusal"]["code"], "stale_element_token");
+ }
+
#[test]
fn token_round_trips_through_format_then_parse() {
assert_eq!(token_for(0x1234, 42), "s00001234:42");
diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs
index f99b68a315..3d2839c520 100644
--- a/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs
+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/window_target.rs
@@ -69,6 +69,10 @@ pub type PidFallbackWindowResolver = Arc<dyn Fn(i64) -> Option<u64> + Send + Syn
/// `(pid, snapshot handle)` -> the window that snapshot was taken of.
pub type SnapshotWindowResolver = Arc<dyn Fn(i64, &str) -> Option<u64> + Send + Sync + 'static>;
+/// Call arguments -> the pid their `element_token` was minted for (see
+/// `SnapshotStore::pid_for_token`). `None` when the token is unknown.
+pub type TokenPidResolver = Arc<dyn Fn(&Value) -> Option<i32> + Send + Sync + 'static>;
+
/// Desktop-frame `x`/`y` of an action, when the call carries them.
fn desktop_frame_point(args: &Value) -> Option<(f64, f64)> {
let frame_is_desktop = args.get("coordinate_frame").and_then(Value::as_str) == Some("desktop")
@@ -90,6 +94,7 @@ pub struct PidOnlyWindowTargetGuard {
point_resolver: Option<DesktopPointWindowResolver>,
fallback_resolver: Option<PidFallbackWindowResolver>,
snapshot_resolver: Option<SnapshotWindowResolver>,
+ token_pid_resolver: Option<TokenPidResolver>,
}
impl PidOnlyWindowTargetGuard {
@@ -100,9 +105,18 @@ impl PidOnlyWindowTargetGuard {
point_resolver: None,
fallback_resolver: None,
snapshot_resolver: None,
+ token_pid_resolver: None,
}
}
+ /// Take a missing `pid` from the call's `element_token`, so a token-only
+ /// call reaches the tool with the pid its snapshot was taken of. A stale
+ /// or unknown token is refused as `stale_element_token`.
+ pub fn with_token_pid_resolver(mut self, resolver: TokenPidResolver) -> Self {
+ self.token_pid_resolver = Some(resolver);
+ self
+ }
+
/// Resolve an otherwise ambiguous pid-only call that carries no point
/// (keyboard actions) to the pid's active / topmost window.
pub fn with_fallback_resolver(mut self, resolver: PidFallbackWindowResolver) -> Self {
@@ -163,6 +177,13 @@ impl Tool for PidOnlyWindowTargetGuard {
}
async fn invoke(&self, mut args: Value) -> ToolResult {
+ if let Some(resolver) = &self.token_pid_resolver {
+ if let Err(refusal) =
+ crate::element_token::fill_pid_from_token(&mut args, |args| resolver(args))
+ {
+ return refusal;
+ }
+ }
// A windowless desktop-scope action needs no pid window. A desktop-
// scope action that names a pid still resolves that pid's window (the
// coordinates are desktop-frame, the target is the window).
@@ -532,6 +553,40 @@ mod tests {
}
}
+ #[tokio::test]
+ async fn a_token_only_call_takes_its_pid_from_the_token() {
+ let calls = Arc::new(AtomicUsize::new(0));
+ let guard = PidOnlyWindowTargetGuard::new(
+ Box::new(EchoTool {
+ calls: calls.clone(),
+ }),
+ Arc::new(|_| panic!("a token target must not enumerate windows")),
+ )
+ .with_token_pid_resolver(Arc::new(|args| {
+ (args["element_token"] == "s00000001:2").then_some(42)
+ }));
+
+ let result = guard
+ .invoke(serde_json::json!({"element_token": "s00000001:2"}))
+ .await;
+ assert_eq!(calls.load(Ordering::SeqCst), 1);
+ assert_eq!(result.structured_content.unwrap()["pid"], 42);
+
+ let stale = guard
+ .invoke(serde_json::json!({"element_token": "s000000ff:0"}))
+ .await;
+ assert_eq!(
+ calls.load(Ordering::SeqCst),
+ 1,
+ "a stale token never reaches the tool"
+ );
+ assert_eq!(stale.is_error, Some(true));
+ assert_eq!(
+ stale.structured_content.unwrap()["refusal"]["code"],
+ "stale_element_token"
+ );
+ }
+
#[tokio::test]
async fn ambiguous_pid_is_resolved_by_the_desktop_point_when_the_call_carries_one() {
let calls = Arc::new(AtomicUsize::new(0));
diff --git a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
index 2f971479b1..01f0e209dc 100644
--- a/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-linux/src/tools/impl_.rs
@@ -122,20 +122,28 @@ type PidWindowGuardParts = (
cua_driver_core::window_target::DesktopPointWindowResolver,
cua_driver_core::window_target::PidFallbackWindowResolver,
cua_driver_core::window_target::SnapshotWindowResolver,
+ cua_driver_core::window_target::TokenPidResolver,
);
fn pid_window_guarded<T: Tool + 'static>(
tool: T,
- (candidates, point_resolver, fallback_resolver, snapshot_resolver): &PidWindowGuardParts,
+ (candidates, point_resolver, fallback_resolver, snapshot_resolver, token_pid_resolver): &PidWindowGuardParts,
) -> Box<dyn Tool> {
Box::new(
PidOnlyWindowTargetGuard::new(Box::new(tool), candidates.clone())
.with_point_resolver(point_resolver.clone())
.with_fallback_resolver(fallback_resolver.clone())
- .with_snapshot_resolver(snapshot_resolver.clone()),
+ .with_snapshot_resolver(snapshot_resolver.clone())
+ .with_token_pid_resolver(token_pid_resolver.clone()),
)
}
+/// The pid an `element_token` was minted for, so a token-only action (no
+/// `pid`) reaches its tool with the pid the token carries.
+fn token_pid_resolver(state: Arc<ToolState>) -> cua_driver_core::window_target::TokenPidResolver {
+ Arc::new(move |args| state.snapshots.pid_for_token(args))
+}
+
/// The window a `snapshot_id` was published for (the element cache lane of
/// that pid), so pid-only element actions follow the snapshot to its popup
/// or dialog.
@@ -6300,7 +6308,7 @@ impl Tool for ClickTool {
"type":"object","required":[],"properties":{
"session": cua_driver_core::tool_schema::session_schema(),
"cursor_id":{"type":"string","description":"Optional multi-cursor instance id. Default: 'default'."},
- "pid":{"type":"integer","description":"Target process ID. Required unless scope is \"desktop\"."},
+ "pid":{"type":"integer","description":"Target process ID. Required unless scope is \"desktop\" or element_token is supplied (the token carries the pid)."},
"window_id":{"type":"integer","description":"Window id from list_windows. Required with x/y or element_index; optional with element_token (the token carries it)."},
"x":{"type":"number","description":"Window-local pixel X of the target window's own get_window_state screenshot (0..screenshot_width). For get_desktop_state pixels pass scope:\"desktop\" (or coordinate_frame:\"desktop\")."},
"y":{"type":"number","description":"Window-local pixel Y of the target window's own get_window_state screenshot (0..screenshot_height); see x."},
@@ -9453,7 +9461,7 @@ impl Tool for ScrollTool {
"type":"object","required":["direction"],"properties":{
"session": cua_driver_core::tool_schema::session_schema(),
"cursor_id":{"type":"string","description":"Optional multi-cursor instance id. Default: 'default'."},
- "pid":{"type":"integer","description":"Target process ID. Required unless scope is \"desktop\"."},
+ "pid":{"type":"integer","description":"Target process ID. Required unless scope is \"desktop\" or element_token is supplied (the token carries the pid)."},
"direction":{"type":"string","enum":["up","down","left","right"],"description":"Scroll direction."},
"by":{"type":"string","enum":["line","page"],"description":"Scroll granularity. Default: line."},
"amount":{"type":"integer","minimum":1,"maximum":50,"description":"Number of scroll steps. Default: 3."},
@@ -14374,6 +14382,7 @@ pub fn build_registry_with_provider(
desktop_point_window_resolver(),
pid_fallback_window_resolver(),
snapshot_window_resolver(state.clone()),
+ token_pid_resolver(state.clone()),
);
r.register(pid_window_guarded(BringToFrontTool, &pid_window_candidates));
r.register(Box::new(SetWindowFrameTool));
diff --git a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
index fb884da3d0..37ba3e403a 100644
--- a/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
+++ b/libs/cua-driver/rust/crates/platform-macos/src/tools/mod.rs
@@ -704,17 +704,7 @@ pub(super) fn target_pid(
.get("element_token")
.is_some_and(|token| !token.is_null())
{
- return Err(cua_driver_core::protocol::ToolResult::error(
- "element_token is stale or unknown; call get_window_state again to refresh \
- (a current token names its own pid).",
- )
- .with_structured(serde_json::json!({
- "status": "refused",
- "refusal": {
- "code": "stale_element_token",
- "message": "element_token is stale or unknown; call get_window_state again to refresh",
- },
- })));
+ return Err(cua_driver_core::element_token::stale_token_without_pid());
}
Err(cua_driver_core::protocol::ToolResult::error(
"Missing required integer field: pid. Pass pid, or pass an element_token from the \
diff --git a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
index b5152da090..06f32a3cc7 100644
--- a/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
+++ b/libs/cua-driver/rust/crates/platform-windows/src/tools/impl_.rs
@@ -533,18 +533,29 @@ impl Tool for ExactPidWindowTargetGuard {
}
}
+type PidWindowGuardParts = (
+ WindowTargetCandidates,
+ cua_driver_core::window_target::TokenPidResolver,
+);
+
fn pid_window_guarded<T: Tool + 'static>(
tool: T,
- candidates: &WindowTargetCandidates,
+ (candidates, token_pid_resolver): &PidWindowGuardParts,
) -> Box<dyn Tool> {
Box::new(ExactPidWindowTargetGuard {
- inner: Box::new(PidOnlyWindowTargetGuard::new(
- Box::new(tool),
- candidates.clone(),
- )),
+ inner: Box::new(
+ PidOnlyWindowTargetGuard::new(Box::new(tool), candidates.clone())
+ .with_token_pid_resolver(token_pid_resolver.clone()),
+ ),
})
}
+/// The pid an `element_token` was minted for, so a token-only action (no
+/// `pid`) reaches its tool with the pid the token carries.
+fn token_pid_resolver(state: Arc<ToolState>) -> cua_driver_core::window_target::TokenPidResolver {
+ Arc::new(move |args| state.snapshots.pid_for_token(args))
+}
+
/// Cursor sentinel for a direct platform call without lifecycle metadata.
/// Normal runtime dispatch supplies either a named or implicit session key.
pub(crate) const NO_CURSOR: &str = "";
@@ -3295,7 +3306,7 @@ impl Tool for ClickTool {
input_schema: json!({
"type":"object","properties":{
"session": cua_driver_core::tool_schema::session_schema(),
- "pid":{"type":"integer","description":"Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state."},
+ "pid":{"type":"integer","description":"Target process ID for window scope. Optional with element_token (the token carries the pid). Omit with scope=desktop for screen-absolute coordinates from get_desktop_state."},
"window_id":{"type":"integer","description":"HWND of the target window. Omit when element_token is supplied (the token carries it)."},
"element_token": cua_driver_core::tool_schema::element_token_schema(),
"action":{"type":"string","description":"Accessibility action for an element_token target. \"expand\" opens the element through UIA ExpandCollapsePattern, or clicks the dropdown half of an MSAA split button. Omit for the default invoke."},
@@ -6147,7 +6158,7 @@ impl Tool for ScrollTool {
input_schema: json!({
"type":"object","required":["direction"],"properties":{
"session": cua_driver_core::tool_schema::session_schema(),
- "pid":{"type":"integer","description":"Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state."},
+ "pid":{"type":"integer","description":"Target process ID for window scope. Optional with element_token (the token carries the pid). Omit with scope=desktop for screen-absolute coordinates from get_desktop_state."},
"direction":{"type":"string","enum":["up","down","left","right"],"description":"Scroll direction."},
"by":{"type":"string","enum":["line","page"],"description":"Scroll granularity. Default: line."},
"amount":{"type":"integer","minimum":1,"maximum":50,
@@ -10177,7 +10188,10 @@ pub fn build_registry_with_provider(
));
r.register(Box::new(LaunchAppTool));
r.register(Box::new(KillAppTool));
- let pid_window_candidates: WindowTargetCandidates = Arc::new(pid_window_target_candidates);
+ let pid_window_candidates: PidWindowGuardParts = (
+ Arc::new(pid_window_target_candidates),
+ token_pid_resolver(state.clone()),
+ );
r.register(pid_window_guarded(BringToFrontTool, &pid_window_candidates));
r.register(Box::new(SetWindowFrameTool));
r.register(Box::new(InvokeMenuTool));
diff --git a/scripts/ci/cua-driver-live-smoke/smoke.py b/scripts/ci/cua-driver-live-smoke/smoke.py
index afb8dc767d..0227ceffd9 100644
--- a/scripts/ci/cua-driver-live-smoke/smoke.py
+++ b/scripts/ci/cua-driver-live-smoke/smoke.py
@@ -10,11 +10,13 @@ fixture window (GTK3 on Linux, WinForms on Windows) and checks:
* run_actions (one batch with an end-of-batch observation),
* set_value on a drop-down combo box and on an editable combo box.
-The first five checks are required: each is `pass` or `fail`. set_value on
-combo boxes and the probes are best effort and never fail the job; each is
-`pass`, `not_possible` (the driver refused with an explicit error) or `bug`
-(the driver claimed success, or failed internally after acting, and the app's
-change handler never saw the value).
+Also checked: an element_token alone (no pid) acts and a stale one is
+refused as `stale_element_token`. Those are required: each is `pass` or
+`fail`. set_value on combo boxes (including delivery_mode foreground and an
+unknown option) is required on the platforms in COMBO_HARD and best effort
+elsewhere, where it is `pass`, `not_possible` (the driver refused with an
+explicit error) or `bug` (the driver claimed success, or failed internally
+after acting, and the app's change handler never saw the value).
Writes results.json, summary.md and the raw responses to --out, and appends
summary.md to $GITHUB_STEP_SUMMARY when set. Exits 1 when any check fails.
@@ -41,6 +43,10 @@ WINDOWS = sys.platform == "win32"
BUTTON = r"(push )?button"
ENTRY = r"edit" if WINDOWS else r"text|entry"
COMBO = r"combo ?box"
+# Platforms where set_value on a combo box must reach the app's change
+# handler: a failure there fails the job instead of being recorded. None yet;
+# the Windows and Linux combo-box fixes each turn on their platform.
+COMBO_HARD = False
class Mcp:
@@ -392,32 +398,107 @@ def run_checks(smoke):
# 6. set_value on combo boxes.
combo_check(smoke, "Color", "Blue", editable=False)
combo_check(smoke, "Size", "Large", editable=True)
+ unknown_option_check(smoke)
- # Probe (informational): element_token alone, no pid (#4739 on macOS).
- state = smoke.read()
- increment = find_row(tree(state), BUTTON, "Increment")
- probe = smoke.call("click", {"element_token": token(state, increment)})
- smoke.record(
- "probe: click with element_token and no pid",
- "not_possible" if probe.is_error else "pass",
- probe.first_line(),
- )
+ # 7. element_token alone, no pid: the token names its pid.
+ token_without_pid_check(smoke)
- # Probe (informational, last because it may leave a menu open): the
- # drop-down combo with delivery_mode foreground, which the background
- # refusal on Linux recommends.
+ # 8. The drop-down combo with delivery_mode foreground (last because a
+ # broken route may leave a popup open), then a click by token must still
+ # land, which it does not while a popup holds the pointer grab.
state = smoke.read()
combo = find_row(tree(state), COMBO, "Color")
status, evidence = set_value_attempt(
smoke, state, combo, "Color", "Green", delivery_mode="foreground"
)
+ if status == "pass":
+ landed, detail = click_still_lands(smoke)
+ if not landed:
+ status = "bug"
+ evidence += "; " + detail
smoke.record(
- "probe: set_value on the drop-down combo box with delivery_mode foreground",
- status,
+ "set_value on the drop-down combo box with delivery_mode foreground",
+ hard(status),
evidence,
)
+def hard(status):
+ """A combo-box status under COMBO_HARD: anything but pass fails."""
+ return "fail" if COMBO_HARD and status != "pass" else status
+
+
+def count_value(markdown):
+ match = re.search(r"Count: (\d+)", markdown)
+ return int(match.group(1)) if match else None
+
+
+def click_still_lands(smoke):
+ """Click Increment by token and check the count moves."""
+ state = smoke.read()
+ before = count_value(tree(state))
+ increment = find_row(tree(state), BUTTON, "Increment")
+ if before is None or increment is None:
+ return False, "no Increment button or Count label to probe with"
+ smoke.call("click", {"pid": smoke.pid, "element_token": token(state, increment)})
+ after = smoke.wait_for_text(f"Count: {before + 1}")
+ if f"Count: {before + 1}" in tree(after):
+ return True, f"a following click by token still lands (Count: {before + 1})"
+ return False, f"a following click by token did not land (Count stayed {before})"
+
+
+def token_without_pid_check(smoke):
+ check = "act by element_token without pid; a stale token is refused"
+ state = smoke.read()
+ before = count_value(tree(state))
+ increment = find_row(tree(state), BUTTON, "Increment")
+ args = {"element_token": token(state, increment)}
+ click = smoke.call("click", args)
+ after = smoke.wait_for_text(f"Count: {(before or 0) + 1}")
+ problems = []
+ if click.is_error:
+ problems.append(f"click {json.dumps(args)} -> {click.first_line()}")
+ elif f"Count: {(before or 0) + 1}" not in tree(after):
+ problems.append(f"click ok but the count did not move from {before}")
+ stale_args = {"element_token": "s0fffffff:0", "value": "x"}
+ stale = smoke.call("set_value", stale_args)
+ code = (stale.structured.get("refusal") or {}).get("code")
+ if not stale.is_error or code != "stale_element_token":
+ problems.append(
+ f"set_value {json.dumps(stale_args)} -> is_error={stale.is_error}, "
+ f"refusal code {code!r}: {stale.first_line()}"
+ )
+ smoke.record(
+ check,
+ "fail" if problems else "pass",
+ "; ".join(problems)
+ or f"click {json.dumps(args)} -> Count: {(before or 0) + 1}; a stale token -> "
+ f"stale_element_token ({stale.first_line()})",
+ )
+
+
+def unknown_option_check(smoke):
+ """set_value with an option the drop-down does not have is refused and
+ changes nothing."""
+ check = "set_value on a drop-down combo box refuses an unknown option"
+ state = smoke.read()
+ combo = find_row(tree(state), COMBO, "Color")
+ shown = re.search(r"Color: (\w+)", tree(state))
+ args = {"pid": smoke.pid, "element_token": token(state, combo), "value": "Purple"}
+ result = smoke.call("set_value", args)
+ fresh = smoke.read()
+ code = result.structured.get("code")
+ if not result.is_error:
+ status, evidence = "bug", f"set_value 'Purple' reported success: {result.first_line()}"
+ elif shown and shown.group(0) not in tree(fresh):
+ status, evidence = "bug", f"refused ({result.first_line()}) but the label changed"
+ elif code != "option_not_found":
+ status, evidence = "not_possible", f"refused with code {code!r}: {result.first_line()}"
+ else:
+ status, evidence = "pass", f"option_not_found: {result.first_line()}"
+ smoke.record(check, hard(status), evidence)
+
+
def row_text(markdown, index):
return next((text for i, text in rows(markdown) if i == index), "")
@@ -446,8 +527,8 @@ def set_value_attempt(smoke, state, index, name, value, **extra):
def combo_check(smoke, name, value, editable):
- """set_value on a combo box is best effort ("where possible"): it records
- pass, not_possible or bug and never fails the job."""
+ """set_value on a combo box: required under COMBO_HARD, otherwise best
+ effort (pass, not_possible or bug, never failing the job)."""
kind = "an editable combo box" if editable else "a drop-down combo box"
check = f"set_value on {kind} ({name} -> {value})"
state = smoke.read()
@@ -470,7 +551,7 @@ def combo_check(smoke, name, value, editable):
break
state = smoke.read()
status = next((s for s in ("pass", "bug", "not_possible") if any(o[0] == s for o in outcomes)))
- smoke.record(check, status, "; ".join(e for st, e in outcomes if st == status))
+ smoke.record(check, hard(status), "; ".join(e for st, e in outcomes if st == status))
def write_reports(smoke, out, platform_name):
@@ -482,7 +563,8 @@ def write_reports(smoke, out, platform_name):
"",
"`fail` fails the job. `bug` (a best-effort check where the driver claimed "
"success, or failed internally after acting, without the app seeing the "
- "change) and `not_possible` (an explicit refusal) are recorded only.",
+ "change) and `not_possible` (an explicit refusal) are recorded only. "
+ f"Combo-box checks are {'required' if COMBO_HARD else 'best effort'} here.",
"",
"| Check | Result | Evidence |",
"| --- | --- | --- |",
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
index 7200493d69..35e2a2589d 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json
@@ -558,7 +558,7 @@
"type": "array"
},
"pid": {
- "description": "Target process ID. Required unless scope is \"desktop\".",
+ "description": "Target process ID. Required unless scope is \"desktop\" or element_token is supplied (the token carries the pid).",
"type": "integer"
},
"scope": {
@@ -1700,7 +1700,7 @@
"type": "string"
},
"pid": {
- "description": "Target process ID. Required unless scope is \"desktop\".",
+ "description": "Target process ID. Required unless scope is \"desktop\" or element_token is supplied (the token carries the pid).",
"type": "integer"
},
"scope": {
diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
index 6cf59e8d36..aacae86c03 100644
--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json
@@ -596,7 +596,7 @@
"type": "array"
},
"pid": {
- "description": "Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state.",
+ "description": "Target process ID for window scope. Optional with element_token (the token carries the pid). Omit with scope=desktop for screen-absolute coordinates from get_desktop_state.",
"type": "integer"
},
"scope": {
@@ -1393,7 +1393,7 @@
"type": "string"
},
"pid": {
- "description": "Target process ID for window scope. Omit with scope=desktop for screen-absolute coordinates from get_desktop_state.",
+ "description": "Target process ID for window scope. Optional with element_token (the token carries the pid). Omit with scope=desktop for screen-absolute coordinates from get_desktop_state.",
"type": "integer"
},
"scope": {