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
fix(cua-driver): make run_actions take the shapes models send and recover from stale targets (#4859)
Francesco Bonacci6e74bfadd827
diff --git a/docs/content/docs/cua-driver/reference/mcp-tools/batch.mdx b/docs/content/docs/cua-driver/reference/mcp-tools/batch.mdxindex 1223f2a4e8..0a289b357a 100644--- a/docs/content/docs/cua-driver/reference/mcp-tools/batch.mdx+++ b/docs/content/docs/cua-driver/reference/mcp-tools/batch.mdx@@ -14,9 +14,9 @@ Served by `cua-driver mcp`; see [MCP tools](/cua-driver/reference/mcp-tools) for## `run_actions`-The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.+The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag, move_cursor and `args` are exactly that tool's arguments. `pid` and `window_id` (or `app`/`window`) on run_actions itself are the default window of every step that names none. Reads (get_window_state, zoom) do not run between steps: one there is skipped; a get_window_state last is the `observe`, a zoom last runs after it. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or target later steps by role/name. A token that went stale is retried once on the element with the same role and label, if exactly one matches.-Returns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. That read is a `since:"latest"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.+Returns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step (after a failure caused by a dialog holding focus, that dialog is read, even without `observe`). That read is a `since:"latest"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.TARGET BY NAME (no earlier read needed, so one batch can cross screens): a step can be written `{"click": {...args}}` as well as `{tool, args}`, and its args may name the target instead of carrying a token: `role` (button, textfield, link, checkbox, menuitem, ...; AX/UIA/AT-SPI names also work), `name` (the element's label; exact match wins over substring, case-insensitive), `nth` (0-based, when several match), and `app` (app name or bundle id) and/or `window` (title substring) instead of pid/window_id. The batch reads the window fresh, waits up to 3 s (step `timeout_ms`, max 10000) for the element to appear, and acts on it; with only `app` it uses that app's frontmost window, so a dialog that opened on top is found. Later steps inherit the window, so name `app` once. The first lookup in a window also reads it once for `observe`, so the end diff shows what the batch changed even in a window you never read. Several matches fail with the candidates listed; add `nth` or a fuller name.@@ -29,10 +29,14 @@ Effect: destructive. Platforms: macOS, Linux, Windows.| Parameter | Type | Default | Description || --- | --- | --- | --- |+| <span id="run_actions--app"></span>`app` | `string` | | Default app (name or bundle id) for steps that name no window. || <span id="run_actions--delay_ms"></span>`delay_ms` | `integer` | | Pause between steps in milliseconds (not after the last). Default 0. Range: 0 to 2000. || <span id="run_actions--observe"></span>`observe` | `object \| boolean` | | Optional end-of-batch observation: `true`, or arguments for ONE get_window_state call. `pid` and `window_id` default to those of the last step that names both. Defaults to since="latest" (only what changed since your last read of that window with the same query/max_elements/max_depth; a full read when there is none), include_screenshot=false and max_elements=250; pass include_screenshot=true to see the window, or since=null for a full read. Omit to read nothing. |+| <span id="run_actions--pid"></span>`pid` | `integer` | | Default pid for steps that name no window (a step's own pid/window_id/app/window wins). || <span id="run_actions--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="run_actions--steps"></span>`steps` | `object[]` | required | Ordered actions. Execution stops at the first failing step. Each step is {tool, args} or {<tool>: args}, plus optional wait_for / expect / timeout_ms; a step may also be only a wait_for or expect check. Items: 1 to 32. |+| <span id="run_actions--window"></span>`window` | `string` | | Default window title substring for steps that name no window. |+| <span id="run_actions--window_id"></span>`window_id` | `integer` | | Default window_id for steps that name no window, with `pid`. |**Example arguments**diff --git a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.mdindex 2babd4ebed..c75b6cc0c1 100644--- a/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md+++ b/libs/cua-driver/rust/Skills/cua-driver/WORKFLOW.md@@ -90,11 +90,13 @@ cua-driver run_actions '{"session":"run-1","steps":[],"delay_ms":100,"observe":true}'```-- `tool` is one of `click`, `double_click`, `right_click`, `set_value`, `type_text`, `press_key`, `hotkey`, `scroll`, `drag` (`press` and `type` are accepted for `press_key` and `type_text`); `args` are exactly that tool's arguments. Observation tools cannot run inside a batch: use `observe`. A `get_window_state` as the last step, with no `observe`, is taken as the observation. Run `describe run_actions` and `describe <tool>` for schemas. Up to 32 steps.+- `tool` is one of `click`, `double_click`, `right_click`, `set_value`, `type_text`, `press_key`, `hotkey`, `scroll`, `drag`, `move_cursor` (`press` and `type` are accepted for `press_key` and `type_text`, `triple_click` is a click with `count:3`, and a key name such as `down` as the tool is a `press_key`); `args` are exactly that tool's arguments. Observation tools do not run inside a batch: a read between actions is skipped (it could not change the later steps), a `get_window_state` as the last step is the observation (merged with `observe`), and a trailing `zoom` runs after it. Run `describe run_actions` and `describe <tool>` for schemas. Up to 32 steps.+- Name the window once: `pid` and `window_id` (or `app`/`window`) on `run_actions` itself are the default for every step that names none.+- A step whose `element_token` went stale because an earlier step re-rendered the window is retried once on the element with the same role and label in a fresh read, when exactly one matches; the step's line says so.- Every step is validated before the first runs, so a malformed step changes nothing. Each step then passes the same session, permission, capability-manifest and approval checks as a direct call; a batch grants nothing a single call lacks, and a refused step ends the batch like any other failure.- A batch has one session. Set `session` on `run_actions`; a step may repeat it but not name another.- `observe` is optional and reads once, after the last executed step (also after a failure). Pass `true` or `get_window_state` arguments; `pid`/`window_id` come from the last step that names both. Defaults: `since:"latest"` (only what changed since your last read of that window with the same view; a full read if there is none), `include_screenshot:false`, `max_elements:250`. Pass `include_screenshot:true` to see the window, or `since:null` for a full read. Omit `observe` to read nothing.-- Read `steps[].ok` and `failed_step`. Steps before a failure did run and are not rolled back; steps after it did not. Observe before repairing, as for a single `unverifiable` action.+- Read `steps[].ok` and `failed_step`. Steps before a failure did run and are not rolled back; steps after it did not. Observe before repairing, as for a single `unverifiable` action. When a step fails because another window of the app holds focus (a dialog opened mid-batch), the end read is of that window, even without `observe`; when a pixel step names a window with no screenshot yet, the end read includes its screenshot.## Pixel coordinatesdiff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rsindex 32ad113414..134838fc54 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools.rs@@ -39,6 +39,7 @@ pub const BATCHABLE_TOOLS: &[&str] = &["hotkey","scroll","drag",+ "move_cursor",];/// Most steps one call may carry. Keeps a batch inside client call timeouts.@@ -55,7 +56,67 @@ const TOOL_ALIASES: &[(&str, &str)] = &[("keypress", "press_key"),("type", "type_text"),("set", "set_value"),+ ("hover", "move_cursor"),+ ("mouse_move", "move_cursor"),];+/// Key names models write as a step's tool (`{"tool": "down"}`); such a step+/// is a press_key of that key.+const KEY_TOOL_NAMES: &[&str] = &[+ "return",+ "enter",+ "tab",+ "escape",+ "esc",+ "space",+ "backspace",+ "up",+ "down",+ "left",+ "right",+ "home",+ "end",+ "pageup",+ "pagedown",+];+/// Names of printable symbols models send to press_key. They are text, not+/// keys (most need shift), so the step types them.+const SYMBOL_KEY_NAMES: &[(&str, &str)] = &[+ ("asterisk", "*"),+ ("star", "*"),+ ("plus", "+"),+ ("at", "@"),+ ("hash", "#"),+ ("numbersign", "#"),+ ("pound", "#"),+ ("dollar", "$"),+ ("percent", "%"),+ ("caret", "^"),+ ("ampersand", "&"),+ ("exclamation", "!"),+ ("exclam", "!"),+ ("question", "?"),+ ("questionmark", "?"),+ ("underscore", "_"),+ ("tilde", "~"),+ ("colon", ":"),+ ("pipe", "|"),+ ("bar", "|"),+ ("less", "<"),+ ("lessthan", "<"),+ ("greater", ">"),+ ("greaterthan", ">"),+ ("parenleft", "("),+ ("leftparen", "("),+ ("parenright", ")"),+ ("rightparen", ")"),+ ("braceleft", "{"),+ ("braceright", "}"),+ ("quotedbl", "\""),+ ("doublequote", "\""),+];+/// Printable characters that are not a plain key on a US layout (they need+/// shift), so press_key cannot send them but type_text can.+const SHIFTED_SYMBOLS: &str = "*+@#$%^&!?_~:|<>(){}\"";const MESSAGE_LIMIT: usize = 300;/// Read-only tools models put in a batch; refused with a pointer to `observe`.const OBSERVATION_TOOLS: &[&str] = &[@@ -75,6 +136,10 @@ pub const MAX_BATCH_MS: u64 = 60_000;/// Fields a step object may carry besides one action.const STEP_KEYS: &[&str] = &["tool", "args", "wait_for", "expect", "timeout_ms"];const OBSERVE_TOOL: &str = "get_window_state";+/// Batch-level fields that name the window every step inherits.+const BATCH_WINDOW_KEYS: &[&str] = &["pid", "window_id", "app", "window"];+/// How long a stale element target may take to be found again by its label.+const REFIND_TIMEOUT: Duration = Duration::from_millis(1_500);pub struct RunActionsTool {registry: ReplayRegistrySlot,@@ -100,16 +165,24 @@ impl Tool for RunActionsTool {one call instead of five. Even a single step plus `observe:true` replaces an \action call followed by a get_window_state call. \Each step is `{tool, args}` where `tool` is one of click, double_click, \- right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` \- are exactly that tool's arguments. Every step goes through the same session, \- permission and approval checks as a direct call; a batch grants nothing extra. \+ right_click, set_value, type_text, press_key, hotkey, scroll, drag, move_cursor \+ and `args` are exactly that tool's arguments. `pid` and `window_id` (or `app`/\+ `window`) on run_actions itself are the default window of every step that names \+ none. Reads (get_window_state, zoom) do not run between steps: one there is \+ skipped; a get_window_state last is the `observe`, a zoom last runs after it. \+ Every step goes through the same session, permission and approval checks as a \+ direct call; a batch grants nothing extra. \All steps are validated before the first one runs, so a malformed step 4 \changes nothing. Element tokens and element_index values come from a \get_window_state read before the batch; a step that changes the UI can \invalidate later element targets, so put element-targeted actions before the \- actions that reshuffle the window, or use pixel targets after them.\n\n\+ actions that reshuffle the window, or target later steps by role/name. A token \+ that went stale is retried once on the element with the same role and label, if \+ exactly one matches.\n\n\Returns per-step status (`ok` or the error message) and, when `observe` is \- given, ONE bounded get_window_state read after the last executed step. That \+ given, ONE bounded get_window_state read after the last executed step (after a \+ failure caused by a dialog holding focus, that dialog is read, even without \+ `observe`). That \read is a `since:\"latest\"` diff by default: only the rows that changed \since your last read of the window, plus a new snapshot_id. Without \`observe` nothing is read. The batch uses one session: steps may \@@ -186,8 +259,23 @@ impl Tool for RunActionsTool {"maximum": MAX_DELAY_MS,"description": "Pause between steps in milliseconds (not after the last). Default 0."},+ "pid": {+ "type": "integer",+ "description": "Default pid for steps that name no window (a step's own pid/window_id/app/window wins)."+ },+ "window_id": {+ "type": "integer",+ "description": "Default window_id for steps that name no window, with `pid`."+ },+ "app": {+ "type": "string",+ "description": "Default app (name or bundle id) for steps that name no window."+ },+ "window": {+ "type": "string",+ "description": "Default window title substring for steps that name no window."+ },"observe": {- "type": "object","type": ["object", "boolean"],"description": "Optional end-of-batch observation: `true`, or arguments for ONE get_window_state call. `pid` and `window_id` default to those of the last step that names both. Defaults to since=\"latest\" (only what changed since your last read of that window with the same query/max_elements/max_depth; a full read when there is none), include_screenshot=false and max_elements=250; pass include_screenshot=true to see the window, or since=null for a full read. Omit to read nothing."}@@ -235,14 +323,18 @@ struct Step {action: Option<Action>,wait_for: Option<Check>,expect: Vec<Check>,+ /// A read-only tool placed between actions. It cannot change what later+ /// steps do, so it is skipped (with a note) instead of failing the batch.+ skipped_read: Option<&'static str>,}impl Step {fn label(&self) -> &'static str {- match &self.action {- Some(action) => action.tool,- None if self.wait_for.is_some() => "wait_for",- None => "expect",+ match (&self.action, self.skipped_read) {+ (Some(action), _) => action.tool,+ (None, Some(read)) => read,+ (None, None) if self.wait_for.is_some() => "wait_for",+ (None, None) => "expect",}}}@@ -251,6 +343,10 @@ struct Plan {steps: Vec<Step>,delay: Duration,observe: Option<Value>,+ /// Read-only calls (zoom) the batch ended with, run after `observe`.+ tail_reads: Vec<(&'static str, Value)>,+ /// The window steps inherit when they name none.+ default_window: WindowSpec,session: Option<String>,}@@ -353,28 +449,78 @@ impl Plan {.and_then(Value::as_str).map(str::to_owned);- // A trailing get_window_state step is what `observe` is for: take it as- // the observation when the batch has none.+ let default_window = batch_window(object)?;++ // Reads the batch ends with are what `observe` is for: a trailing+ // get_window_state (or screenshot) becomes the observation, merged+ // with an explicit `observe`, and a trailing zoom runs after it.let mut raw_steps = raw_steps.as_slice();- let mut trailing_observe = None;- if let [actions @ .., last] = raw_steps {- let observe_given = !matches!(- object.get("observe"),- None | Some(Value::Null) | Some(Value::Bool(false))- );- if !actions.is_empty() && !observe_given {- if let Some(args) = observation_step_args(last) {- trailing_observe = Some(args);- raw_steps = actions;+ let mut observe_value = match object.get("observe") {+ None | Some(Value::Null) | Some(Value::Bool(false)) => None,+ Some(value) => Some(value.clone()),+ };+ let mut trailing_observe: Option<Value> = None;+ let mut tail_reads = Vec::new();+ while let [rest @ .., last] = raw_steps {+ if !rest.iter().any(|step| read_step(step).is_none()) {+ break;+ }+ let Some((tool, args)) = read_step(last) else {+ break;+ };+ match tool {+ OBSERVE_TOOL | "screenshot" => {+ // The latest trailing read wins; earlier ones are dropped.+ if trailing_observe.is_none() {+ let mut args = args;+ if tool == "screenshot" {+ args = json!({ "include_screenshot": true });+ }+ trailing_observe = Some(args);+ }}+ "zoom" => tail_reads.insert(0, ("zoom", args)),+ // Other reads at the end (list_windows, verify_state, ...)+ // add nothing a final observation does not show.+ _ => {}}+ raw_steps = rest;+ }+ if let Some(step_args) = trailing_observe {+ observe_value = Some(match observe_value {+ Some(Value::Object(explicit)) => {+ let mut merged = step_args.as_object().cloned().unwrap_or_default();+ merged.extend(explicit);+ Value::Object(merged)+ }+ _ => step_args,+ });}let mut steps = Vec::with_capacity(raw_steps.len());- // Whether some earlier step names a window a later step can inherit.- let mut has_window = false;+ // Whether some earlier step (or the batch itself) names a window a+ // later step can inherit.+ let mut has_window = !default_window.is_empty();+ // A batch of reads only is refused by parse_step, pointing at the+ // direct call; reads between actions are skipped.+ let acts = raw_steps.iter().any(|step| read_step(step).is_none());+ // The last skipped get_window_state: with no `observe`, it says the+ // caller wants to look, so it becomes the end read.+ let mut skipped_observe = None;for (index, raw) in raw_steps.iter().enumerate() {- let step = parse_step(registry, index, raw, session.as_deref())?;+ if let Some((tool, args)) = read_step(raw).filter(|_| acts) {+ if tool == OBSERVE_TOOL {+ skipped_observe = Some(args);+ }+ steps.push(Step {+ action: None,+ wait_for: None,+ expect: Vec::new(),+ skipped_read: Some(tool),+ });+ continue;+ }+ let step = parse_step(registry, index, raw, session.as_deref(), has_window)?;let names_window = step.action.as_ref()@@ -403,25 +549,43 @@ impl Plan {steps.push(step);}- let observe = match (trailing_observe.as_ref(), object.get("observe")) {- (Some(value), _) => Some(parse_observe(- registry,- value,- has_window,- session.as_deref(),- )?),- (None, None | Some(Value::Null) | Some(Value::Bool(false))) => None,- (None, Some(value)) => Some(parse_observe(+ if observe_value.is_none() && has_window {+ observe_value = skipped_observe;+ }+ // zoom crops the window's latest screenshot, so the end read before+ // it must take one.+ if !tail_reads.is_empty() && has_window {+ let mut with_screenshot = match observe_value.take() {+ Some(Value::Object(object)) => object,+ _ => Map::new(),+ };+ with_screenshot.insert("include_screenshot".into(), Value::Bool(true));+ observe_value = Some(Value::Object(with_screenshot));+ }+ let observe = match observe_value.as_ref() {+ None => None,+ Some(value) => Some(parse_observe(registry,value,has_window,session.as_deref(),)?),};+ for (tool, args) in &mut tail_reads {+ if let Some(def) = registry.get_def(tool) {+ crate::tool::coerce_string_scalars(&def.input_schema, args);+ }+ prepare_args(args, session.as_deref())+ .map_err(|message| PlanError::batch(format!("{tool}: {message}")))?;+ crate::tool::normalize_argument_aliases(tool, args)+ .map_err(|message| PlanError::batch(format!("{tool}: {message}")))?;+ }Ok(Self {steps,delay: Duration::from_millis(delay_ms),observe,+ tail_reads,+ default_window,session,})}@@ -452,8 +616,21 @@ impl Plan {let mut lines = Vec::with_capacity(total + 2);let mut failed_step = None;// The window later steps inherit, and the last concrete window used.- let mut context = WindowSpec::default();- let mut last_window: Option<Window> = None;+ let mut context = self.default_window.clone();+ let mut last_window: Option<Window> = match (context.pid, context.window_id) {+ (Some(pid), Some(window_id)) => Some(Window {+ pid,+ window_id,+ app: None,+ title: None,+ on_screen: true,+ }),+ _ => None,+ };+ // A failure that names the window to look at next (a dialog holding+ // focus, a window never captured) gets that window read at the end+ // even without `observe`, so the caller can act without another read.+ let mut recovery: Option<Recovery> = None;for (index, step) in self.steps.into_iter().enumerate() {if index > 0 && !self.delay.is_zero() {@@ -482,6 +659,12 @@ impl Plan {).await};+ if !outcome.ok {+ recovery = Recovery::after(&outcome.report, last_window.as_ref());+ if let Some(Recovery { window, .. }) = &recovery {+ last_window = Some(window.clone());+ }+ }lines.push(outcome.line);reports.push(outcome.report);if !outcome.ok {@@ -512,7 +695,37 @@ impl Plan {// One observation at the end, also after a failure so the caller can// see where the app was left.let mut observation_content = Vec::new();- if let Some(mut args) = self.observe {+ let observe = match (self.observe, recovery) {+ (Some(mut args), Some(recovery)) => {+ // The window to recover in replaces the step's own window.+ lines.push(format!("recovery read: {}", recovery.why));+ if let Some(object) = args.as_object_mut() {+ object.insert("pid".into(), json!(recovery.window.pid));+ object.insert("window_id".into(), json!(recovery.window.window_id));+ if recovery.screenshot {+ object.insert("include_screenshot".into(), json!(true));+ }+ }+ Some(args)+ }+ (Some(args), None) => Some(args),+ (None, Some(recovery)) => {+ let mut args = json!({+ "pid": recovery.window.pid,+ "window_id": recovery.window.window_id,+ "include_screenshot": recovery.screenshot,+ "max_elements": DEFAULT_OBSERVE_MAX_ELEMENTS,+ "since": crate::window_state_view::SINCE_LATEST,+ });+ if let Some(session) = &self.session {+ args["session"] = json!(session);+ }+ lines.push(format!("recovery read: {}", recovery.why));+ Some(args)+ }+ (None, None) => None,+ };+ if let Some(mut args) = observe {let filled = fill_observed_window(&mut args, last_window.as_ref());let result = if filled {registry.invoke(OBSERVE_TOOL, args).await@@ -547,8 +760,28 @@ impl Plan {structured["observation"] = report;}+ let mut tail_content = Vec::new();+ let mut tail_reports = Vec::new();+ for (tool, mut args) in self.tail_reads {+ fill_observed_window(&mut args, last_window.as_ref());+ let result = registry.invoke(tool, args).await;+ let ok = result.is_error != Some(true);+ let message = bounded_message(&result);+ if ok {+ lines.push(format!("{tool}: ok (below)"));+ tail_content.extend(result.content);+ } else {+ lines.push(format!("{tool}: ERROR: {message}"));+ }+ tail_reports.push(json!({ "tool": tool, "ok": ok, "message": message }));+ }+ if !tail_reports.is_empty() {+ structured["reads"] = Value::Array(tail_reports);+ }+let mut content = vec![Content::text(lines.join("\n"))];content.append(&mut observation_content);+ content.append(&mut tail_content);ToolResult {content,is_error: failed_step.map(|_| true),@@ -571,6 +804,20 @@ async fn run_step(let mut report = json!({ "index": index, "tool": label });let mut notes: Vec<String> = Vec::new();+ if step.skipped_read.is_some() {+ let note = "skipped: a read between actions cannot change the later steps; the \+ end read shows the result (use wait_for/expect to check a state \+ mid-batch)";+ report["ok"] = json!(true);+ report["skipped"] = json!(true);+ report["message"] = json!(note);+ return StepOutcome {+ line: format!("{}. {label} {note}", index + 1),+ report,+ ok: true,+ };+ }+if let Some(check) = &step.wait_for {match locator.check(check, context).await {Ok(checked) => {@@ -680,9 +927,23 @@ async fn run_step(});}- let result = registry.invoke(tool, args).await;+ let mut result = registry.invoke(tool, args.clone()).await;+ let mut refound_note = None;+ if result.is_error == Some(true) {+ if let Some((retry, note)) = refind_stale_target(locator, &args, &result).await {+ report["refound"] = json!(note);+ result = registry.invoke(tool, retry).await;+ refound_note = Some(note);+ }+ }let ok = result.is_error != Some(true);- let message = bounded_message(&result);+ let mut message = bounded_message(&result);+ if let (false, Some(note)) = (ok, &refound_note) {+ message = format!("{note}, but: {message}");+ }+ if let (true, Some(note)) = (ok, refound_note) {+ notes.push(note);+ }report["ok"] = json!(ok);report["message"] = json!(message);if !ok {@@ -859,21 +1120,226 @@ fn observation_summary(state: &Value) -> String {}}-/// The arguments of a get_window_state step, in either step form.-fn observation_step_args(step: &Value) -> Option<Value> {+/// A step that only reads (get_window_state, zoom, a "screenshot", ...), in+/// either step form, as (read tool, its arguments). A read with its own+/// wait_for/expect is left to `parse_step`.+fn read_step(step: &Value) -> Option<(&'static str, Value)> {let object = step.as_object()?;- let args = if object.get("tool").and_then(Value::as_str) == Some(OBSERVE_TOOL) {- object.get("args")- } else if object.len() == 1 && object.contains_key(OBSERVE_TOOL) {- object.get(OBSERVE_TOOL)- } else {+ if object.contains_key("wait_for") || object.contains_key("expect") {return None;+ }+ let (name, args) = match object.get("tool") {+ Some(tool) => (tool.as_str()?, object.get("args")),+ None => {+ let mut keys = object+ .keys()+ .filter(|key| !STEP_KEYS.contains(&key.as_str()));+ let key = keys.next()?;+ if keys.next().is_some() {+ return None;+ }+ (key.as_str(), object.get(key.as_str()))+ }+ };+ let tool = match OBSERVATION_TOOLS.iter().find(|tool| **tool == name) {+ Some(tool) => *tool,+ None if name.to_ascii_lowercase().contains("screenshot") => "screenshot",+ None => return None,};- Some(- args.cloned()- .filter(Value::is_object)- .unwrap_or_else(|| Value::Object(Map::new())),- )+ let args = args+ .cloned()+ .filter(Value::is_object)+ .unwrap_or_else(|| Value::Object(Map::new()));+ Some((tool, args))+}++/// The batch-level `pid`/`window_id`/`app`/`window` steps inherit.+fn batch_window(object: &Map<String, Value>) -> Result<WindowSpec, PlanError> {+ let mut picked = Map::new();+ for key in BATCH_WINDOW_KEYS {+ if let Some(value) = object.get(*key) {+ picked.insert((*key).to_owned(), value.clone());+ }+ }+ let (window, _) = locate::take_selector(&mut picked).map_err(PlanError::batch)?;+ // take_selector reads pid/window_id from what it leaves behind.+ Ok(WindowSpec {+ pid: object.get("pid").and_then(Value::as_i64),+ window_id: object.get("window_id").and_then(Value::as_u64),+ ..window+ })+}++/// What to read after a failed step, and why.+struct Recovery {+ window: Window,+ screenshot: bool,+ why: String,+}++impl Recovery {+ /// A failure that names where to look next: another window of the app+ /// holds focus (read that dialog), or a pixel target in a window with no+ /// screenshot yet (capture it, so the next pixel step has a frame).+ fn after(report: &Value, last: Option<&Window>) -> Option<Self> {+ let message = report.get("message").and_then(Value::as_str)?;+ let last = last?;+ if let Some(holder) = focus_holder(message).filter(|id| *id != last.window_id) {+ return Some(Self {+ window: Window {+ pid: last.pid,+ window_id: holder,+ app: None,+ title: None,+ on_screen: true,+ },+ screenshot: false,+ why: format!(+ "window {holder} of the same app holds focus; its state follows, act on window_id {holder}"+ ),+ });+ }+ let code = report.get("code").and_then(Value::as_str);+ if code == Some("screenshot_context_missing") || message.starts_with("No screenshot") {+ return Some(Self {+ window: last.clone(),+ screenshot: true,+ why: format!(+ "window {} had no screenshot; one follows, take x,y from it",+ last.window_id+ ),+ });+ }+ None+ }+}++/// The window id in "window_id N \"β¦\" of the same app holds focus".+fn focus_holder(message: &str) -> Option<u64> {+ let end = message.find("of the same app holds focus")?;+ let start = message[..end].rfind("window_id ")? + "window_id ".len();+ let digits: String = message[start..]+ .chars()+ .take_while(char::is_ascii_digit)+ .collect();+ digits.parse().ok()+}++/// Whether an action failed because its element target died: the element+/// was re-rendered or its snapshot was replaced.+fn stale_element(result: &ToolResult) -> bool {+ let code = result.structured_content.as_ref().and_then(|value| {+ value+ .get("code")+ .or_else(|| value.pointer("/refusal/code"))+ .and_then(Value::as_str)+ });+ if matches!(+ code,+ Some("element_outside_target_window" | "stale_element_token")+ ) {+ return true;+ }+ let message = bounded_message(result);+ [+ "element_outside_target_window",+ "element_token is stale",+ "-25202",+ ]+ .iter()+ .any(|needle| message.contains(needle))+}++/// Act again on a target whose element token went stale: find the element+/// with the same role and label (exact, and unique) in the same window, and+/// return the arguments with its fresh token plus a note saying so.+async fn refind_stale_target(+ locator: &Locator<'_>,+ args: &Value,+ result: &ToolResult,+) -> Option<(Value, String)> {+ if !stale_element(result) {+ return None;+ }+ let token = args.get("element_token").and_then(Value::as_str)?;+ let (snapshot_id, row) = token.split_once(':')?;+ let row: u64 = row.parse().ok()?;+ let stored = crate::window_state_view::snapshot_row(snapshot_id, row)?;+ let (role, label) = row_role_and_label(&stored.line)?;+ let window = WindowSpec {+ pid: Some(+ args.get("pid")+ .and_then(Value::as_i64)+ .unwrap_or(stored.pid),+ ),+ window_id: Some(+ args.get("window_id")+ .and_then(Value::as_u64)+ .unwrap_or(stored.window_id),+ ),+ ..Default::default()+ };+ let element = ElementSpec {+ role: Some(role.clone()),+ name: Some(label.clone()),+ text: None,+ nth: None,+ };+ let found = locator.find(&window, &element, REFIND_TIMEOUT).await.ok()?;+ let same_label = found+ .element+ .get("label")+ .and_then(Value::as_str)+ .is_some_and(|found| found.trim().to_lowercase() == label.trim().to_lowercase());+ if !same_label {+ return None;+ }+ let fresh = found.token()?.to_owned();+ let mut retry = args.clone();+ let object = retry.as_object_mut()?;+ object.insert("element_token".into(), json!(fresh));+ object.remove("element_index");+ Some((+ retry,+ format!(+ "element {token} went stale (the window changed); acted on the same {role} \"{label}\", found again as {}",+ found.describe()+ ),+ ))+}++/// Role and label of one tree row: `[14] AXButton "Save"` or+/// `[17] AXButton (Delete draft)`. None for a row without a label.+fn row_role_and_label(line: &str) -> Option<(String, String)> {+ let rest = line.trim().strip_prefix("- ")?.trim_start();+ let rest = rest.strip_prefix('[')?;+ let (_, rest) = rest.split_once(']')?;+ let rest = rest.trim_start();+ let role_end = rest.find(char::is_whitespace)?;+ let role = rest[..role_end].to_owned();+ let rest = rest[role_end..].trim_start();+ let label = if let Some(quoted) = rest.strip_prefix('"') {+ quoted[..quoted.find('"')?].to_owned()+ } else {+ let inner = rest.strip_prefix('(')?;+ let mut depth = 1usize;+ let mut end = None;+ for (at, c) in inner.char_indices() {+ match c {+ '(' => depth += 1,+ ')' => {+ depth -= 1;+ if depth == 0 {+ end = Some(at);+ break;+ }+ }+ _ => {}+ }+ }+ inner[..end?].to_owned()+ };+ (!label.trim().is_empty()).then_some((role, label))}fn parse_step(@@ -881,6 +1347,7 @@ fn parse_step(index: usize,raw: &Value,session: Option<&str>,+ inherits_window: bool,) -> Result<Step, PlanError> {let object = raw.as_object().ok_or_else(|| {PlanError::step(index, "must be an object: {tool, args} or {<tool>: args}")@@ -993,12 +1460,14 @@ fn parse_step(raw_args,find_timeout,session,+ inherits_window,)?),};Ok(Step {action,wait_for,expect,+ skipped_read: None,})}@@ -1009,11 +1478,18 @@ fn parse_action(raw_args: Option<&Value>,find_timeout: u64,session: Option<&str>,+ inherits_window: bool,) -> Result<Action, PlanError> {+ let mut args = match raw_args {+ None | Some(Value::Null) => Value::Object(Map::new()),+ Some(value @ Value::Object(_)) => value.clone(),+ Some(_) => return Err(PlanError::step(index, "`args` must be an object")),+ };let name = TOOL_ALIASES.iter().find(|(alias, _)| *alias == name).map_or(name, |(_, tool)| *tool);+ let name = rewrite_step(name, &mut args);let tool = BATCHABLE_TOOLS.iter().copied()@@ -1035,11 +1511,9 @@ fn parse_action(};PlanError::step(index, message)})?;- let mut args = match raw_args {- None | Some(Value::Null) => Value::Object(Map::new()),- Some(value @ Value::Object(_)) => value.clone(),- Some(_) => return Err(PlanError::step(index, "`args` must be an object")),- };+ if let Some(schema) = registry.get_def(tool).map(|def| def.input_schema.clone()) {+ crate::tool::coerce_string_scalars(&schema, &mut args);+ }prepare_args(&mut args, session).map_err(|message| PlanError::step(index, message))?;let (window, element) = locate::take_selector(args.as_object_mut().expect("object")).map_err(|message| PlanError::step(index, format!("{tool}: {message}")))?;@@ -1066,7 +1540,10 @@ fn parse_action(let mut probe = args.clone();if let Some(object) = probe.as_object_mut() {let needs_window = !element.is_empty() || window.app.is_some() || window.title.is_some();- if needs_window {+ // A step that names no window takes the one an earlier step (or the+ // batch) named; the run fills it in.+ let inherits = inherits_window && window.is_empty() && accepts(registry, tool, "pid");+ if needs_window || inherits {object.entry("pid").or_insert(json!(1));if accepts(registry, tool, "window_id") {object.entry("window_id").or_insert(json!(1));@@ -1102,6 +1579,9 @@ fn parse_observe())}};+ if let Some(def) = registry.get_def(OBSERVE_TOOL) {+ crate::tool::coerce_string_scalars(&def.input_schema, &mut args);+ }prepare_args(&mut args, session).map_err(|message| PlanError::batch(format!("observe: {message}")))?;let object = args.as_object_mut().expect("object");@@ -1144,6 +1624,67 @@ fn parse_observe(Ok(args)}+/// Rewrite step shapes models send into the batchable tool they mean:+/// `triple_click` is a click with count 3, a key name used as the tool+/// (`{"tool": "down"}`) is a press_key of it, a one-key hotkey is a+/// press_key, and a press_key of a printable symbol ("asterisk", "*") types+/// it, since most symbols need shift and are text rather than keys.+fn rewrite_step<'a>(name: &'a str, args: &mut Value) -> &'a str {+ let Some(object) = args.as_object_mut() else {+ return name;+ };+ let lower = name.to_ascii_lowercase();+ if lower == "triple_click" {+ object.entry("count").or_insert(json!(3));+ return "click";+ }+ if let Some(key) = KEY_TOOL_NAMES.iter().find(|key| **key == lower) {+ object.entry("key").or_insert(json!(key));+ return "press_key";+ }+ let mut name = name;+ if name == "hotkey" {+ let single = match object.get("keys") {+ Some(Value::Array(keys)) if keys.len() == 1 => keys[0].as_str().map(str::to_owned),+ Some(Value::String(key)) if !key.contains('+') => Some(key.clone()),+ _ => None,+ };+ if let Some(key) = single {+ object.remove("keys");+ object.insert("key".into(), json!(key));+ name = "press_key";+ }+ }+ if name == "press_key" {+ let no_modifiers = object+ .get("modifiers")+ .and_then(Value::as_array)+ .is_none_or(|modifiers| modifiers.is_empty());+ let text = object.get("key").and_then(Value::as_str).and_then(|key| {+ let key = key.trim();+ let folded = key.to_ascii_lowercase().replace(['_', '-', ' '], "");+ SYMBOL_KEY_NAMES+ .iter()+ .find(|(symbol, _)| *symbol == folded)+ .map(|(_, text)| (*text).to_owned())+ .or_else(|| {+ let mut chars = key.chars();+ match (chars.next(), chars.next()) {+ (Some(c), None) if SHIFTED_SYMBOLS.contains(c) => Some(c.to_string()),+ _ => None,+ }+ })+ });+ if let (true, Some(text)) = (no_modifiers, text) {+ object.remove("key");+ object.remove("modifiers");+ object.insert("text".into(), json!(text));+ return "type_text";+ }+ }+ name+}+/// Reject runtime-private fields and pin the step to the batch's session.fn prepare_args(args: &mut Value, session: Option<&str>) -> Result<(), String> {let object = args.as_object_mut().expect("object");diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/locate.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/locate.rsindex bcd2e2ede2..f6d577192c 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/locate.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/locate.rs@@ -1253,22 +1253,56 @@ fn near_misses(read: &Read, spec: &ElementSpec) -> String {};let pool: Vec<&Value> = if spec.role.is_some() {matches(read, &relaxed)- } else if let Some(name) = &spec.name {- let first_word = fold(name.split_whitespace().next().unwrap_or(name));+ } else if spec.name.is_some() {+ // Any role: only elements sharing a word with the name (below).read.elements.iter()- .filter(|element| {- label_of(element).is_some_and(|label| fold(label).contains(&first_word))- })+ .filter(|element| element.get("display_only").and_then(Value::as_bool) != Some(true)).collect()} else {Vec::new()};- let named: Vec<String> = pool+ // Rank by the words a label shares with the wanted name, so "Update+ // event" is offered for "Create event" ahead of unrelated buttons, and+ // look across roles too: the element may be a link, not a button.+ let shared = |element: &Value| -> usize {+ let Some(name) = &spec.name else {+ return 0;+ };+ let Some(label) = label_of(element) else {+ return 0;+ };+ let label_words = words(label);+ words(name)+ .iter()+ .filter(|word| label_words.contains(word))+ .count()+ };+ let mut ranked: Vec<(usize, &Value)> = pool.iter()+ .copied().filter(|element| label_of(element).is_some())+ .map(|element| (shared(element), element))+ .collect();+ if spec.role.is_some() && spec.name.is_some() {+ for element in &read.elements {+ let score = shared(element);+ if score > 0+ && element.get("display_only").and_then(Value::as_bool) != Some(true)+ && !ranked.iter().any(|(_, seen)| std::ptr::eq(*seen, element))+ {+ ranked.push((score, element));+ }+ }+ }+ if spec.role.is_none() {+ ranked.retain(|(score, _)| *score > 0);+ }+ ranked.sort_by_key(|(score, _)| std::cmp::Reverse(*score));+ let named: Vec<String> = ranked+ .iter().take(CANDIDATES_SHOWN)- .map(|element| describe_element(element))+ .map(|(_, element)| describe_element(element)).collect();if named.is_empty() {if read.elements.is_empty() {@@ -1307,6 +1341,15 @@ pub(crate) fn describe_element(element: &Value) -> String {out}+/// Lowercase words of two or more characters.+fn words(text: &str) -> Vec<String> {+ fold(text)+ .split(|c: char| !c.is_alphanumeric())+ .filter(|word| word.chars().count() >= 2)+ .map(str::to_owned)+ .collect()+}+fn label_of(element: &Value) -> Option<&str> {element.get("label")@@ -1509,6 +1552,46 @@ mod tests {assert_eq!(pick(&read, &second).unwrap().element["element_index"], 9);}+ #[test]+ fn a_miss_lists_labels_sharing_a_word_first_across_roles() {+ // v036: "Create event" had become "Update event"; the miss listed+ // the first five buttons instead.+ let mut elements: Vec<Value> = [+ "Aster kickoff",+ "Boreal review",+ "Cinder decision",+ "Dune handoff",+ "Lighthouse lunch",+ "Update event",+ ]+ .iter()+ .enumerate()+ .map(|(at, label)| element(at as u64 + 1, "AXButton", label))+ .collect();+ elements.push(element(9, "AXLink", "Event history"));+ let read = read(elements, "");+ let spec = ElementSpec {+ role: Some("button".into()),+ name: Some("Create event".into()),+ ..Default::default()+ };+ let miss = pick(&read, &spec).unwrap_err();+ let nearest = miss.message.split("nearest: ").nth(1).unwrap();+ assert!(+ nearest.starts_with("[6] AXButton \"Update event\"; [9] AXLink \"Event history\""),+ "{nearest}"+ );++ // With no role, only labels sharing a word are offered.+ let any_role = ElementSpec {+ name: Some("event log".into()),+ ..Default::default()+ };+ let miss = pick(&read, &any_role).unwrap_err();+ assert!(!miss.message.contains("Aster"), "{}", miss.message);+ assert!(miss.message.contains("Update event"), "{}", miss.message);+ }+#[test]fn a_miss_names_the_nearest_elements() {let read = read(vec![element(1, "AXButton", "Save Draft")], "");diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/reliability_tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/reliability_tests.rsnew file mode 100644index 0000000000..23a13ee7a3--- /dev/null+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/reliability_tests.rs@@ -0,0 +1,405 @@+//! One test per run_actions failure class seen in bench run v036: the call+//! shapes models sent, and what the batch does with them now.++use std::sync::{Arc, Mutex};++use async_trait::async_trait;+use serde_json::{json, Value};++use super::{text, Harness};+use crate::{+ protocol::ToolResult,+ tool::{Tool, ToolDef, ToolRegistry},+};++// ββ schema leniency ββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn observe_sent_as_a_string_is_read_as_the_boolean() {+ let harness = Harness::new();+ // 21 of the 102 failed v036 calls: `"observe": "true"`.+ let result = harness+ .run(json!({"steps": [{"tool": "click", "args": {"pid": 7, "window_id": 3}}], "observe": "true"}))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ assert_eq!(harness.hits("get_window_state"), 1);++ // `"observe": "false"` with a trailing read: the read is the observation.+ let result = harness+ .run(json!({"steps": [+ {"tool": "click", "args": {"pid": 7, "window_id": 3}},+ {"tool": "get_window_state", "args": {"pid": 7, "window_id": 3, "max_elements": 100}}+ ], "observe": "false"}))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ assert_eq!(harness.last("get_window_state")["max_elements"], 100);+}++#[tokio::test]+async fn string_scalars_in_step_args_are_coerced_before_validation() {+ let harness = Harness::new();+ let result = harness+ .run(json!({"steps": [+ {"tool": "click", "args": {"pid": "7", "window_id": "3", "x": "10.5", "y": "4"}}+ ], "observe": {"include_screenshot": "false"}}))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ let click = harness.last("click");+ assert_eq!(click["pid"], 7);+ assert_eq!(click["window_id"], 3);+ assert_eq!(click["x"], 10.5);+ let observed = harness.last("get_window_state");+ assert_eq!(observed["include_screenshot"], false);+}++#[tokio::test]+async fn batch_level_pid_and_window_id_are_the_default_window() {+ let harness = Harness::new();+ // The v036 shape: pid/window_id once (as strings) on run_actions itself.+ let result = harness+ .run(json!({+ "pid": "37641",+ "window_id": "2126",+ "observe": "false",+ "steps": [+ {"tool": "set_value", "args": {"element_token": "s0000000a:46", "value": "12:00"}},+ {"tool": "set_value", "args": {"element_token": "s0000000a:48", "value": "Juniper"}},+ {"tool": "click", "args": {"pid": 5, "window_id": 6}}+ ]+ }))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ let calls = harness.calls["set_value"].lock().unwrap().clone();+ assert_eq!(calls.len(), 2);+ for call in &calls {+ assert_eq!(+ (call["pid"].clone(), call["window_id"].clone()),+ (json!(37641), json!(2126))+ );+ }+ // A step's own window wins over the batch default.+ let click = harness.last("click");+ assert_eq!(+ (click["pid"].clone(), click["window_id"].clone()),+ (json!(5), json!(6))+ );++ // Observe needs no window of its own when the batch names one.+ let result = harness+ .run(json!({"pid": 1, "window_id": 2, "steps": [{"press_key": {"key": "down"}}], "observe": true}))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ let observed = harness.last("get_window_state");+ assert_eq!(+ (observed["pid"].clone(), observed["window_id"].clone()),+ (json!(1), json!(2))+ );+}++// ββ read steps βββββββββββββββββββββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn a_trailing_zoom_runs_after_the_batch_and_a_screenshot_step_is_observe() {+ let harness = Harness::new();+ let result = harness+ .run(json!({"steps": [+ {"tool": "click", "args": {"pid": 7, "window_id": 3}},+ {"tool": "zoom", "args": {"pid": 7, "window_id": 3, "x": 340, "y": 80, "width": 640, "height": 340}}+ ]}))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ assert_eq!(harness.hits("zoom"), 1);+ // zoom crops the latest screenshot, so the end read took one first.+ assert_eq!(harness.last("get_window_state")["include_screenshot"], true);+ let zoom = harness.last("zoom");+ assert_eq!(+ zoom["x2"], 980.0,+ "zoom's own x/y/width/height aliases apply"+ );+ assert!(text(&result).contains("zoom: ok"), "{}", text(&result));++ let result = harness+ .run(json!({"steps": [+ {"tool": "click", "args": {"pid": 7, "window_id": 3, "x": 1, "y": 1}},+ {"tool": "screenshot_placeholder", "args": {}}+ ]}))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ assert_eq!(harness.last("get_window_state")["include_screenshot"], true);+}++// ββ tool and key shapes ββββββββββββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn tool_name_slips_become_the_action_they_mean() {+ let harness = Harness::new();+ let result = harness+ .run(json!({"pid": 9, "window_id": 4, "steps": [+ {"tool": "triple_click", "args": {"x": 186, "y": 254}},+ {"tool": "down", "args": {}},+ {"tool": "hotkey", "args": {"keys": ["Right"]}},+ {"tool": "press_key", "args": {"key": "asterisk"}},+ {"tool": "press_key", "args": {"key": "shift+Right"}},+ {"tool": "hotkey", "args": {"keys": ["ctrl", "Page_Down"]}},+ {"tool": "move_cursor", "args": {"x": 640, "y": 190}}+ ]}))+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ assert_eq!(harness.last("click")["count"], 3);+ let presses = harness.calls["press_key"].lock().unwrap().clone();+ assert_eq!(presses.len(), 3);+ assert_eq!(presses[0]["key"], "down");+ assert_eq!(presses[1]["key"], "Right");+ assert_eq!(presses[2]["key"], "Right");+ assert_eq!(presses[2]["modifiers"], json!(["shift"]));+ assert_eq!(harness.last("type_text")["text"], "*");+ assert_eq!(harness.last("hotkey")["keys"], json!(["ctrl", "pagedown"]));+ assert_eq!(harness.hits("move_cursor"), 1);+}++// ββ recovery after a failed step βββββββββββββββββββββββββββββββββββββββββ++#[tokio::test]+async fn a_dialog_holding_focus_is_read_after_the_failure() {+ let harness = Harness::new();+ let message = "press_key delivery failed: exact target window did not become focused for \+ foreground HID delivery: window_id 1112 \"Delete Contents\" of the same app \+ holds focus (an open dialog or panel); act on that window_id, or close it first";+ let result = harness+ .run(json!({"steps": [+ {"tool": "press_key", "args": {"pid": 13051, "window_id": 1069, "key": "tab", "fail_message": message}},+ {"tool": "press_key", "args": {"pid": 13051, "window_id": 1069, "key": "tab"}}+ ]}))+ .await;+ assert_eq!(result.is_error, Some(true));+ let observed = harness.last("get_window_state");+ assert_eq!(observed["pid"], 13051);+ assert_eq!(+ observed["window_id"], 1112,+ "the dialog, not the blocked window"+ );+ assert!(+ text(&result).contains("recovery read: window 1112"),+ "{}",+ text(&result)+ );+}++#[tokio::test]+async fn a_window_never_captured_gets_a_screenshot_after_a_pixel_failure() {+ let harness = Harness::new();+ let message = "No screenshot of window 1320 in this session: it has not been read yet.";+ let result = harness+ .run(json!({"steps": [+ {"tool": "click", "args": {"pid": 19316, "window_id": 1320, "x": 1128, "y": 612, "fail_message": message}}+ ], "observe": {"query": "AXTextField"}}))+ .await;+ assert_eq!(result.is_error, Some(true));+ let observed = harness.last("get_window_state");+ assert_eq!(observed["window_id"], 1320);+ assert_eq!(observed["include_screenshot"], true);+ assert_eq!(+ observed["query"], "AXTextField",+ "the caller's observe is kept"+ );+}++#[test]+fn focus_holder_and_row_parsing() {+ assert_eq!(+ super::super::focus_holder(+ "click failed: ...: window_id 5256 \"Welcome to LibreOffice!\" of the same app holds focus (an open dialog)"+ ),+ Some(5256)+ );+ assert_eq!(+ super::super::focus_holder("exact target window did not become focused"),+ None+ );+ assert_eq!(+ super::super::row_role_and_label(+ " - [14] AXButton \"Cinder decision LHP-CINDER\" [actions=[press]]"+ ),+ Some((+ "AXButton".to_owned(),+ "Cinder decision LHP-CINDER".to_owned()+ ))+ );+ assert_eq!(+ super::super::row_role_and_label(+ "- [17] AXButton (Lighthouse lunch hold (protected)) [actions=[press]]"+ ),+ Some((+ "AXButton".to_owned(),+ "Lighthouse lunch hold (protected)".to_owned()+ ))+ );+ assert_eq!(+ super::super::row_role_and_label("- [12] AXStaticText = \"Boreal review\""),+ None,+ "a row without a label cannot be found again safely"+ );+}++// ββ stale element targets ββββββββββββββββββββββββββββββββββββββββββββββββ++/// A window whose list re-renders on every click: element handles from an+/// older snapshot are dead, as in Chromium/Electron web content.+struct Rerender {+ def: ToolDef,+ state: Arc<Mutex<RerenderState>>,+}++#[derive(Default)]+struct RerenderState {+ snapshot: u32,+ /// Labels of the current snapshot, by row.+ rows: Vec<(&'static str, &'static str)>,+ clicked: Vec<String>,+}++#[async_trait]+impl Tool for Rerender {+ fn def(&self) -> &ToolDef {+ &self.def+ }++ async fn invoke(&self, args: Value) -> ToolResult {+ let mut state = self.state.lock().unwrap();+ match self.def.name.as_str() {+ "get_window_state" => {+ state.snapshot += 1;+ let snapshot = format!("s{:08x}", state.snapshot);+ let elements: Vec<Value> = state+ .rows+ .iter()+ .enumerate()+ .map(|(index, (role, label))| {+ json!({+ "element_index": index + 1,+ "element_token": format!("{snapshot}:{}", index + 1),+ "role": role,+ "depth": 1,+ "label": label,+ })+ })+ .collect();+ ToolResult::text("read").with_structured(json!({+ "pid": 42, "window_id": 7, "snapshot_id": snapshot,+ "elements": elements, "tree_markdown": "",+ }))+ }+ "click" => {+ let token = args["element_token"]+ .as_str()+ .unwrap_or_default()+ .to_owned();+ let current = format!("s{:08x}:", state.snapshot);+ if !token.starts_with(¤t) {+ return ToolResult::error(+ "Background input refused (element_outside_target_window): the addressed \+ element could not be proven to belong to window 7; take a fresh \+ get_window_state snapshot and re-address it",+ );+ }+ let row: usize = token[current.len()..].parse().unwrap();+ let label = state.rows[row - 1].1.to_owned();+ state.clicked.push(label.clone());+ ToolResult::text(format!("clicked {label}"))+ }+ "list_windows" => ToolResult::text("windows").with_structured(json!({"windows": [{+ "pid": 42, "window_id": 7, "app_name": "Daymark", "title": "Daymark",+ "z_index": 1, "is_on_screen": true,+ "bounds": {"x": 0.0, "y": 0.0, "width": 800.0, "height": 600.0}+ }]})),+ _ => ToolResult::text("ok"),+ }+ }+}++fn rerender_registry(+ rows: Vec<(&'static str, &'static str)>,+) -> (Arc<ToolRegistry>, Arc<Mutex<RerenderState>>) {+ let state = Arc::new(Mutex::new(RerenderState {+ snapshot: 40,+ rows,+ ..Default::default()+ }));+ let mut registry = ToolRegistry::new();+ for name in ["click", "get_window_state", "list_windows", "list_apps"] {+ registry.register(Box::new(Rerender {+ def: ToolDef {+ name: name.into(),+ description: "fake".into(),+ input_schema: json!({"type": "object", "properties": {+ "pid": {"type": "integer"}, "window_id": {"type": "integer"},+ "element_token": {"type": "string"}+ }}),+ read_only: name != "click",+ destructive: false,+ idempotent: false,+ open_world: false,+ },+ state: state.clone(),+ }));+ }+ registry.register_session_tools();+ let registry = Arc::new(registry);+ registry.init_self_weak();+ (registry, state)+}++#[tokio::test]+async fn a_stale_element_token_is_found_again_by_its_role_and_label() {+ let (registry, state) = rerender_registry(vec![+ ("AXButton", "Update event"),+ ("AXButton", "Aster kickoff"),+ ("AXButton", "Cinder decision LHP-CINDER"),+ ]);+ // The read the model took its token from (snapshot s0000002c, row 14),+ // remembered as get_window_state remembers every read.+ crate::window_state_view::remember_for_test(+ "s0000002c",+ 42,+ 7,+ "- [0] AXWindow \"Daymark\"\n - [14] AXButton \"Cinder decision LHP-CINDER\" [actions=[press]]\n",+ );+ let result = registry+ .invoke(+ super::super::RUN_ACTIONS_TOOL,+ json!({"steps": [{"tool": "click", "args": {"pid": 42, "window_id": 7, "element_token": "s0000002c:14"}}]}),+ )+ .await;+ assert_ne!(result.is_error, Some(true), "{}", text(&result));+ assert_eq!(+ state.lock().unwrap().clicked,+ vec!["Cinder decision LHP-CINDER"]+ );+ assert!(text(&result).contains("went stale"), "{}", text(&result));+}++#[tokio::test]+async fn a_stale_token_is_not_retried_when_its_label_is_ambiguous_or_unknown() {+ let (registry, state) = rerender_registry(vec![("AXButton", "OK"), ("AXButton", "OK")]);+ crate::window_state_view::remember_for_test(+ "s0000002d",+ 42,+ 7,+ "- [3] AXButton \"OK\"\n- [4] AXStaticText = \"no label\"\n",+ );+ for token in ["s0000002d:3", "s0000002d:4", "s0000002d:99", "s0000777f:3"] {+ let result = registry+ .invoke(+ super::super::RUN_ACTIONS_TOOL,+ json!({"steps": [{"tool": "click", "args": {"pid": 42, "window_id": 7, "element_token": token}}]}),+ )+ .await;+ assert_eq!(result.is_error, Some(true), "{token}");+ assert!(+ text(&result).contains("element_outside_target_window"),+ "{token}: {}",+ text(&result)+ );+ }+ assert!(state.lock().unwrap().clicked.is_empty());+}diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rsindex b7dc14c8b6..bfa3712ced 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/batch_tools/tests.rs@@ -29,6 +29,9 @@ impl Tool for Probe {async fn invoke(&self, args: Value) -> ToolResult {self.calls.lock().unwrap().push(args.clone());+ if let Some(message) = args["fail_message"].as_str() {+ return ToolResult::error(message.to_owned());+ }if args["fail"] == true {ToolResult::error(format!("{} refused: probe asked to fail", self.def.name))} else {@@ -49,7 +52,7 @@ impl Harness {for name in super::BATCHABLE_TOOLS.iter().copied()- .chain(["get_window_state"])+ .chain(["get_window_state", "zoom"]){let log = Arc::new(Mutex::new(Vec::new()));calls.insert(name, log.clone());@@ -64,6 +67,16 @@ impl Harness {"window_id": {"type": "integer"},"text": {"type": "string"},"fail": {"type": "boolean"},+ "fail_message": {"type": "string"},+ "element_token": {"type": "string"},+ "value": {"type": "string"},+ "key": {"type": "string"},+ "keys": {"type": "array", "items": {"type": "string"}, "minItems": 2},+ "modifiers": {"type": "array", "items": {"type": "string"}},+ "count": {"type": "integer", "minimum": 1},+ "query": {"type": "string"},+ "x1": {"type": "number"}, "y1": {"type": "number"},+ "x2": {"type": "number"}, "y2": {"type": "number"},"include_screenshot": {"type": "boolean"},"since": {"type": "string"},"direction": {"type": "string", "enum": ["up", "down", "left", "right"]},@@ -75,7 +88,7 @@ impl Harness {},"additionalProperties": false}),- read_only: name == "get_window_state",+ read_only: matches!(name, "get_window_state" | "zoom"),destructive: false,idempotent: false,open_world: false,@@ -205,10 +218,6 @@ async fn stops_at_the_first_failure_and_still_observes() {async fn validates_every_step_before_running_any() {let harness = Harness::new();let cases = [- (- json!({"tool": "zoom", "args": {}}),- "reads state and a batch only acts",- ),(json!({"tool": "run_actions", "args": {}}),"cannot run in a batch",@@ -518,28 +527,60 @@ async fn a_trailing_read_becomes_the_observation_and_a_middle_one_points_to_obseassert_eq!(observed["since"], "latest");assert_eq!(harness.hits("click"), 2);- let refused = harness+ // v036: a read between actions (act, read, act, read) is skipped with a+ // note instead of rejecting the whole batch; the last read is `observe`.+ let skipped = harness.run(json!({"steps": [{"tool": "click", "args": {"pid": 7, "window_id": 3}},- {"tool": "get_window_state", "args": {"pid": 7, "window_id": 3}},+ {"tool": "get_window_state", "args": {"pid": 7, "window_id": 3, "query": "AXTextField"}},{"tool": "click", "args": {"pid": 7, "window_id": 3}},+ {"tool": "get_window_state", "args": {"pid": 7, "window_id": 3, "max_elements": 90}},]})).await;- assert_eq!(refused.is_error, Some(true));- let message = text(&refused);- assert!(message.contains("step 2 of the batch"), "{message}");- assert!(- message.contains("Put get_window_state arguments in `observe`"),- "{message}"- );+ assert_ne!(skipped.is_error, Some(true), "{}", text(&skipped));+ let message = text(&skipped);+ assert!(message.contains("2. get_window_state skipped"), "{message}");+ assert_eq!(harness.hits("click"), 4);+ assert_eq!(harness.hits("get_window_state"), 2, "only the end read ran");+ assert_eq!(harness.last("get_window_state")["max_elements"], 90);++ // With no read at the end, the last skipped read is the end read.+ let looked = harness+ .run(json!({"steps": [+ {"tool": "click", "args": {"pid": 7, "window_id": 3}},+ {"tool": "get_window_state", "args": {"pid": 7, "window_id": 3, "query": "Wiki"}},+ {"tool": "click", "args": {"pid": 7, "window_id": 3}},+ ]}))+ .await;+ assert_ne!(looked.is_error, Some(true), "{}", text(&looked));+ assert_eq!(harness.hits("get_window_state"), 3);+ assert_eq!(harness.last("get_window_state")["query"], "Wiki");- // With an explicit observe, a trailing read is not silently dropped.+ // v036: a trailing read plus an explicit observe merge; observe wins.let both = harness.run(json!({"steps": [{"tool": "click", "args": {"pid": 7, "window_id": 3}},- {"tool": "get_window_state", "args": {"pid": 7, "window_id": 3}},- ], "observe": true}))+ {"tool": "get_window_state", "args": {"pid": 7, "window_id": 3, "max_elements": 40}},+ ], "observe": {"include_screenshot": true, "max_elements": 60}})).await;- assert_eq!(both.is_error, Some(true));- assert_eq!(harness.hits("get_window_state"), 1);+ assert_ne!(both.is_error, Some(true), "{}", text(&both));+ assert_eq!(harness.hits("get_window_state"), 4);+ let observed = harness.last("get_window_state");+ assert_eq!(observed["max_elements"], 60);+ assert_eq!(observed["include_screenshot"], true);++ // A batch of reads only still points at the direct call.+ let refused = harness+ .run(json!({"steps": [{"tool": "get_window_state", "args": {"pid": 7, "window_id": 3}}]}))+ .await;+ assert_eq!(refused.is_error, Some(true));+ assert!(+ text(&refused).contains("reads state and a batch only acts"),+ "{}",+ text(&refused)+ );}++#[cfg(test)]+#[path = "reliability_tests.rs"]+mod reliability_tests;diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rsindex dd730c93a4..35fa8dd7a7 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/tool.rs@@ -241,9 +241,174 @@ fn unknown_argument(def: &ToolDef, args: &Value) -> Option<String> {/// refusal detail for an alias that cannot be translated.pub(crate) fn normalize_argument_aliases(tool_name: &str, args: &mut Value) -> Result<(), String> {normalize_zoom_args(tool_name, args);+ normalize_key_args(tool_name, args);normalize_scroll_args(tool_name, args)}+/// The JSON types a property schema admits, from `type` (a string or a list)+/// and the `type` of each `anyOf`/`oneOf` branch. Empty when the schema+/// declares none.+fn declared_types(schema: &Value) -> Vec<&str> {+ fn add<'v>(types: &mut Vec<&'v str>, value: Option<&'v Value>) {+ match value {+ Some(Value::String(name)) => types.push(name.as_str()),+ Some(Value::Array(names)) => types.extend(names.iter().filter_map(Value::as_str)),+ _ => {}+ }+ }+ let mut types = Vec::new();+ add(&mut types, schema.get("type"));+ for key in ["anyOf", "oneOf"] {+ if let Some(branches) = schema.get(key).and_then(Value::as_array) {+ for branch in branches {+ add(&mut types, branch.get("type"));+ }+ }+ }+ types+}++/// Models sometimes send scalars as strings (`"include_screenshot": "false"`,+/// `"observe": "true"`, `"pid": "4211"`). A tool reading `as_bool()` would+/// silently take `"false"` as absent and use the default, which is the+/// opposite of what was asked. Rewrite a top-level string argument into the+/// boolean, integer or number its schema declares, but only when the schema+/// does not also admit a string, so no string-valued field is reinterpreted.+pub(crate) fn coerce_string_scalars(schema: &Value, args: &mut Value) {+ let Some(properties) = schema.get("properties").and_then(Value::as_object) else {+ return;+ };+ let Some(arguments) = args.as_object_mut() else {+ return;+ };+ for (name, value) in arguments.iter_mut() {+ let Value::String(text) = value else {+ continue;+ };+ let Some(property) = properties.get(name) else {+ continue;+ };+ let types = declared_types(property);+ if types.is_empty() || types.contains(&"string") {+ continue;+ }+ let text = text.trim();+ let coerced = if types.contains(&"boolean") && text.eq_ignore_ascii_case("true") {+ Some(Value::Bool(true))+ } else if types.contains(&"boolean") && text.eq_ignore_ascii_case("false") {+ Some(Value::Bool(false))+ } else if types.contains(&"integer") {+ text.parse::<i64>()+ .map(Value::from)+ .or_else(|_| text.parse::<u64>().map(Value::from))+ .ok()+ } else if types.contains(&"number") {+ text.parse::<f64>()+ .ok()+ .filter(|number| number.is_finite())+ .and_then(|number| serde_json::Number::from_f64(number).map(Value::Number))+ } else {+ None+ };+ if let Some(coerced) = coerced {+ *value = coerced;+ }+ }+}++/// Key spellings models reach for that every platform's key table spells+/// differently. Only unambiguous renames: `delete` itself means backspace on+/// macOS and forward delete elsewhere, so it is left alone.+fn canonical_key_name(key: &str) -> Option<&'static str> {+ let folded: String = key+ .chars()+ .filter(|c| !matches!(c, '_' | '-' | ' '))+ .flat_map(char::to_lowercase)+ .collect();+ Some(match folded.as_str() {+ "pagedown" | "pgdn" | "pgdown" | "pagedn" => "pagedown",+ "pageup" | "pgup" => "pageup",+ "arrowleft" | "leftarrow" => "left",+ "arrowright" | "rightarrow" => "right",+ "arrowup" | "uparrow" => "up",+ "arrowdown" | "downarrow" => "down",+ "forwarddelete" | "fwddelete" | "deleteforward" => {+ if cfg!(target_os = "macos") {+ "forward_delete"+ } else {+ "delete"+ }+ }+ _ => return None,+ })+}++/// `press_key` takes one key plus `modifiers`, `hotkey` a list of keys.+/// Rewrite the shapes models send instead: a combination in `key`+/// ("shift+Right" becomes key "Right" with modifiers ["shift"]), `hotkey`+/// keys as one "cmd+s" string, and spellings such as "Page_Down".+fn normalize_key_args(tool_name: &str, args: &mut Value) {+ let Some(arguments) = args.as_object_mut() else {+ return;+ };+ match tool_name {+ "press_key" => {+ let Some(key) = arguments+ .get("key")+ .and_then(Value::as_str)+ .map(str::to_owned)+ else {+ return;+ };+ let mut key = key.trim().to_owned();+ if key.chars().count() > 1 && key.contains('+') && !key.ends_with('+') {+ let parts: Vec<String> =+ key.split('+').map(|part| part.trim().to_owned()).collect();+ if parts.iter().all(|part| !part.is_empty()) {+ let (modifiers, last) = parts.split_at(parts.len() - 1);+ let existing = arguments+ .get("modifiers")+ .and_then(Value::as_array)+ .cloned()+ .unwrap_or_default();+ let mut merged: Vec<Value> = existing;+ for modifier in modifiers {+ let modifier = Value::String(modifier.to_lowercase());+ if !merged.contains(&modifier) {+ merged.push(modifier);+ }+ }+ arguments.insert("modifiers".to_owned(), Value::Array(merged));+ key = last[0].clone();+ }+ }+ if let Some(canonical) = canonical_key_name(&key) {+ key = canonical.to_owned();+ }+ arguments.insert("key".to_owned(), Value::String(key));+ }+ "hotkey" => {+ if let Some(Value::String(combo)) = arguments.get("keys") {+ let keys: Vec<Value> = combo+ .split('+')+ .map(str::trim)+ .filter(|part| !part.is_empty())+ .map(|part| Value::String(part.to_owned()))+ .collect();+ arguments.insert("keys".to_owned(), Value::Array(keys));+ }+ if let Some(Value::Array(keys)) = arguments.get_mut("keys") {+ for key in keys.iter_mut() {+ if let Some(canonical) = key.as_str().and_then(canonical_key_name) {+ *key = Value::String(canonical.to_owned());+ }+ }+ }+ }+ _ => {}+ }+}+/// A larger `dx`/`dy` magnitude than this many notches is read as pixels.const SCROLL_MAX_NOTCHES: f64 = 50.0;/// Pixels per wheel notch when `dx`/`dy` is given in pixels (a Chromium@@ -284,12 +449,17 @@ fn normalize_scroll_args(tool_name: &str, args: &mut Value) -> Result<(), Stringlet (direction, delta) = match (dx != 0.0, dy != 0.0) {(true, true) => {return Err(format!(- "scroll moves along one axis per call, got dx={dx} and dy={dy}. Pass only dx or dy (or direction and amount), or use two scroll steps in run_actions."+ "scroll moves along one axis per call, got dx={dx} and dy={dy}. Pass only dx or \+ dy (or direction and amount), or use two scroll steps in run_actions."))}(false, false) => {- return Err("dx and dy are both 0, so there is nothing to scroll. Pass direction (up, down, left or right) and amount (wheel notches)."- .to_owned())+ return Err(+ "dx and dy are both 0, so there is nothing to scroll. Pass direction \+ (up, down, left or right) and amount (wheel notches). To hover without \+ scrolling, use move_cursor."+ .to_owned(),+ )}(false, true) => (if dy > 0.0 { "down" } else { "up" }, dy),(true, false) => (if dx > 0.0 { "right" } else { "left" }, dx),@@ -1445,6 +1615,7 @@ impl ToolRegistry {// Normalize deprecated public argument spellings before any policy,// consent, recording, or implementation layer interprets the call.+ coerce_string_scalars(&tool.def().input_schema, &mut args);normalize_delivery_mode_args(tool.def(), &mut args);if let Err(detail) = normalize_argument_aliases(resolved_name, &mut args) {return ToolResult::error(format!("{resolved_name}: {detail}")).with_structured(@@ -6638,9 +6809,89 @@ mod capability_tests {#[cfg(test)]mod argument_shape_tests {- use super::{normalize_argument_aliases, normalize_zoom_args, unknown_argument, ToolDef};+ use super::{+ coerce_string_scalars, normalize_argument_aliases, normalize_zoom_args, unknown_argument,+ ToolDef,+ };use serde_json::json;+ #[test]+ fn string_scalars_follow_the_declared_type() {+ // v036: "include_screenshot": "false" was read as absent, so the+ // screenshot the model declined was sent anyway.+ let schema = json!({"type": "object", "properties": {+ "include_screenshot": {"type": "boolean"},+ "observe": {"type": ["object", "boolean"]},+ "pid": {"type": "integer"},+ "x": {"type": "number"},+ "text": {"type": "string"},+ "value": {"anyOf": [{"type": "string"}, {"type": "boolean"}]},+ "since": {"type": ["string", "null"]},+ "untyped": {}+ }});+ let mut args = json!({+ "include_screenshot": "False", "observe": " true", "pid": "4211", "x": "12.5",+ "text": "true", "value": "false", "since": "1", "untyped": "true", "extra": "true"+ });+ coerce_string_scalars(&schema, &mut args);+ assert_eq!(+ args,+ json!({+ "include_screenshot": false, "observe": true, "pid": 4211, "x": 12.5,+ "text": "true", "value": "false", "since": "1", "untyped": "true", "extra": "true"+ })+ );+ // Not a number or boolean: left for the schema check to name.+ let mut junk = json!({"pid": "forty-two", "include_screenshot": "yes", "x": "NaN"});+ coerce_string_scalars(&schema, &mut junk);+ assert_eq!(+ junk,+ json!({"pid": "forty-two", "include_screenshot": "yes", "x": "NaN"})+ );+ }++ #[test]+ fn key_combinations_and_spellings_are_normalized() {+ let press = |args: serde_json::Value| {+ let mut args = args;+ normalize_argument_aliases("press_key", &mut args).unwrap();+ args+ };+ assert_eq!(+ press(json!({"key": "shift+Right"})),+ json!({"key": "Right", "modifiers": ["shift"]})+ );+ assert_eq!(+ press(json!({"key": "cmd+shift+z", "modifiers": ["shift"]})),+ json!({"key": "z", "modifiers": ["shift", "cmd"]})+ );+ assert_eq!(+ press(json!({"key": "Page_Down"})),+ json!({"key": "pagedown"})+ );+ assert_eq!(press(json!({"key": "ArrowLeft"})), json!({"key": "left"}));+ let forward = if cfg!(target_os = "macos") {+ "forward_delete"+ } else {+ "delete"+ };+ assert_eq!(+ press(json!({"key": "forwarddelete"})),+ json!({"key": forward})+ );+ // A bare "+" and plain names stay as sent.+ assert_eq!(press(json!({"key": "+"})), json!({"key": "+"}));+ assert_eq!(press(json!({"key": "Return"})), json!({"key": "Return"}));+ assert_eq!(press(json!({"key": "delete"})), json!({"key": "delete"}));++ let mut hotkey = json!({"keys": ["ctrl", "Page_Down"]});+ normalize_argument_aliases("hotkey", &mut hotkey).unwrap();+ assert_eq!(hotkey, json!({"keys": ["ctrl", "pagedown"]}));+ let mut combo = json!({"keys": "cmd+s"});+ normalize_argument_aliases("hotkey", &mut combo).unwrap();+ assert_eq!(combo, json!({"keys": ["cmd", "s"]}));+ }+fn zoom_def() -> ToolDef {ToolDef {name: "zoom".into(),diff --git a/libs/cua-driver/rust/crates/cua-driver-core/src/window_state_view.rs b/libs/cua-driver/rust/crates/cua-driver-core/src/window_state_view.rsindex b04a95a9c5..af06ebea1a 100644--- a/libs/cua-driver/rust/crates/cua-driver-core/src/window_state_view.rs+++ b/libs/cua-driver/rust/crates/cua-driver-core/src/window_state_view.rs@@ -558,6 +558,57 @@ fn remember(snapshot_id: &str, ctx: &ViewContext<'_>, md: &str) {}}+/// One row of an earlier read, as that read rendered it.+pub(crate) struct StoredRow {+ pub pid: i64,+ pub window_id: u64,+ /// The markdown row, e.g. `- [14] AXButton "Save" [actions=[press]]`.+ pub line: String,+}++/// Row `[index]` of the read that produced `snapshot_id`, while that read is+/// still remembered. Lets a caller holding a stale element token find the+/// same element again by what it was.+pub(crate) fn snapshot_row(snapshot_id: &str, index: u64) -> Option<StoredRow> {+ let snapshot = {+ let mut guard = store().lock().unwrap_or_else(|e| e.into_inner());+ guard.retain(|s| s.at.elapsed() <= STORE_TTL);+ guard.iter().find(|s| s.snapshot_id == snapshot_id).cloned()+ }?;+ let marker = format!("[{index}] ");+ let line = snapshot+ .markdown+ .lines()+ .map(str::trim)+ .find(|line| {+ line.strip_prefix("- ")+ .is_some_and(|rest| rest.starts_with(&marker))+ })?+ .to_owned();+ Some(StoredRow {+ pid: snapshot.pid,+ window_id: snapshot.window_id,+ line,+ })+}++/// Remember a read's markdown as `apply` does, for tests elsewhere in the+/// crate that drive a fake get_window_state.+#[cfg(test)]+pub(crate) fn remember_for_test(snapshot_id: &str, pid: i64, window_id: u64, markdown: &str) {+ let ctx = ViewContext {+ pid,+ window_id,+ key: ViewKey {+ query: None,+ max_elements: DEFAULT_MAX_ELEMENTS,+ max_depth: None,+ },+ focus_probe: None,+ };+ remember(snapshot_id, &ctx, markdown);+}+fn resolve_since(since: &str,current_id: Option<&str>,diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.jsonindex 747298151c..ea5beeda3d 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-linux.json@@ -3467,12 +3467,16 @@"read_only": false},{- "description": "The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. That read is a `since:\"latest\"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.\n\nTARGET BY NAME (no earlier read needed, so one batch can cross screens): a step can be written `{\"click\": {...args}}` as well as `{tool, args}`, and its args may name the target instead of carrying a token: `role` (button, textfield, link, checkbox, menuitem, ...; AX/UIA/AT-SPI names also work), `name` (the element's label; exact match wins over substring, case-insensitive), `nth` (0-based, when several match), and `app` (app name or bundle id) and/or `window` (title substring) instead of pid/window_id. The batch reads the window fresh, waits up to 3 s (step `timeout_ms`, max 10000) for the element to appear, and acts on it; with only `app` it uses that app's frontmost window, so a dialog that opened on top is found. Later steps inherit the window, so name `app` once. The first lookup in a window also reads it once for `observe`, so the end diff shows what the batch changed even in a window you never read. Several matches fail with the candidates listed; add `nth` or a fuller name.\n\nWAITS AND CHECKS: a step may add `wait_for` (checked before its action) and `expect` (one check or up to 4, checked after it); a step may also be only a check. A check is {role?, name?, text?, gone?, value?, value_contains?, enabled?, selected?, app?, window?, timeout_ms?}: `text` matches any row of the tree, static text included; `gone:true` waits for it to disappear. Checks poll until they hold or time out (wait_for 5 s, expect 2 s, max 10 s), and a check that does not hold fails the step with what was found instead. The report says which step failed, in which phase (wait_for, find, action, expect) and why. Whole batch: at most 60 s.\n\nExample (fill a form, submit, confirm the dialog, check the result):\n{\"steps\":[{\"set_value\":{\"app\":\"Safari\",\"role\":\"textfield\",\"name\":\"Email\",\"value\":\"[email protected]\"}},{\"click\":{\"role\":\"button\",\"name\":\"Submit\"},\"expect\":{\"role\":\"button\",\"name\":\"Confirm\"}},{\"click\":{\"role\":\"button\",\"name\":\"Confirm\"},\"expect\":[{\"name\":\"Confirm\",\"gone\":true},{\"text\":\"Thanks\"}]}],\"observe\":true}",+ "description": "The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag, move_cursor and `args` are exactly that tool's arguments. `pid` and `window_id` (or `app`/`window`) on run_actions itself are the default window of every step that names none. Reads (get_window_state, zoom) do not run between steps: one there is skipped; a get_window_state last is the `observe`, a zoom last runs after it. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or target later steps by role/name. A token that went stale is retried once on the element with the same role and label, if exactly one matches.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step (after a failure caused by a dialog holding focus, that dialog is read, even without `observe`). That read is a `since:\"latest\"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.\n\nTARGET BY NAME (no earlier read needed, so one batch can cross screens): a step can be written `{\"click\": {...args}}` as well as `{tool, args}`, and its args may name the target instead of carrying a token: `role` (button, textfield, link, checkbox, menuitem, ...; AX/UIA/AT-SPI names also work), `name` (the element's label; exact match wins over substring, case-insensitive), `nth` (0-based, when several match), and `app` (app name or bundle id) and/or `window` (title substring) instead of pid/window_id. The batch reads the window fresh, waits up to 3 s (step `timeout_ms`, max 10000) for the element to appear, and acts on it; with only `app` it uses that app's frontmost window, so a dialog that opened on top is found. Later steps inherit the window, so name `app` once. The first lookup in a window also reads it once for `observe`, so the end diff shows what the batch changed even in a window you never read. Several matches fail with the candidates listed; add `nth` or a fuller name.\n\nWAITS AND CHECKS: a step may add `wait_for` (checked before its action) and `expect` (one check or up to 4, checked after it); a step may also be only a check. A check is {role?, name?, text?, gone?, value?, value_contains?, enabled?, selected?, app?, window?, timeout_ms?}: `text` matches any row of the tree, static text included; `gone:true` waits for it to disappear. Checks poll until they hold or time out (wait_for 5 s, expect 2 s, max 10 s), and a check that does not hold fails the step with what was found instead. The report says which step failed, in which phase (wait_for, find, action, expect) and why. Whole batch: at most 60 s.\n\nExample (fill a form, submit, confirm the dialog, check the result):\n{\"steps\":[{\"set_value\":{\"app\":\"Safari\",\"role\":\"textfield\",\"name\":\"Email\",\"value\":\"[email protected]\"}},{\"click\":{\"role\":\"button\",\"name\":\"Submit\"},\"expect\":{\"role\":\"button\",\"name\":\"Confirm\"}},{\"click\":{\"role\":\"button\",\"name\":\"Confirm\"},\"expect\":[{\"name\":\"Confirm\",\"gone\":true},{\"text\":\"Thanks\"}]}],\"observe\":true}","destructive": true,"idempotent": false,"input_schema": {"additionalProperties": false,"properties": {+ "app": {+ "description": "Default app (name or bundle id) for steps that name no window.",+ "type": "string"+ },"delay_ms": {"description": "Pause between steps in milliseconds (not after the last). Default 0.","maximum": 2000,@@ -3486,6 +3490,10 @@"boolean"]},+ "pid": {+ "description": "Default pid for steps that name no window (a step's own pid/window_id/app/window wins).",+ "type": "integer"+ },"session": {"description": "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.","type": "string"@@ -3525,7 +3533,8 @@"press_key","hotkey","scroll",- "drag"+ "drag",+ "move_cursor"],"type": "string"},@@ -3565,6 +3574,14 @@"maxItems": 32,"minItems": 1,"type": "array"+ },+ "window": {+ "description": "Default window title substring for steps that name no window.",+ "type": "string"+ },+ "window_id": {+ "description": "Default window_id for steps that name no window, with `pid`.",+ "type": "integer"}},"required": [diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.jsonindex 00c24e6a87..9a6d4955a3 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-macos.json@@ -3103,12 +3103,16 @@"read_only": false},{- "description": "The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. That read is a `since:\"latest\"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.\n\nTARGET BY NAME (no earlier read needed, so one batch can cross screens): a step can be written `{\"click\": {...args}}` as well as `{tool, args}`, and its args may name the target instead of carrying a token: `role` (button, textfield, link, checkbox, menuitem, ...; AX/UIA/AT-SPI names also work), `name` (the element's label; exact match wins over substring, case-insensitive), `nth` (0-based, when several match), and `app` (app name or bundle id) and/or `window` (title substring) instead of pid/window_id. The batch reads the window fresh, waits up to 3 s (step `timeout_ms`, max 10000) for the element to appear, and acts on it; with only `app` it uses that app's frontmost window, so a dialog that opened on top is found. Later steps inherit the window, so name `app` once. The first lookup in a window also reads it once for `observe`, so the end diff shows what the batch changed even in a window you never read. Several matches fail with the candidates listed; add `nth` or a fuller name.\n\nWAITS AND CHECKS: a step may add `wait_for` (checked before its action) and `expect` (one check or up to 4, checked after it); a step may also be only a check. A check is {role?, name?, text?, gone?, value?, value_contains?, enabled?, selected?, app?, window?, timeout_ms?}: `text` matches any row of the tree, static text included; `gone:true` waits for it to disappear. Checks poll until they hold or time out (wait_for 5 s, expect 2 s, max 10 s), and a check that does not hold fails the step with what was found instead. The report says which step failed, in which phase (wait_for, find, action, expect) and why. Whole batch: at most 60 s.\n\nExample (fill a form, submit, confirm the dialog, check the result):\n{\"steps\":[{\"set_value\":{\"app\":\"Safari\",\"role\":\"textfield\",\"name\":\"Email\",\"value\":\"[email protected]\"}},{\"click\":{\"role\":\"button\",\"name\":\"Submit\"},\"expect\":{\"role\":\"button\",\"name\":\"Confirm\"}},{\"click\":{\"role\":\"button\",\"name\":\"Confirm\"},\"expect\":[{\"name\":\"Confirm\",\"gone\":true},{\"text\":\"Thanks\"}]}],\"observe\":true}",+ "description": "The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag, move_cursor and `args` are exactly that tool's arguments. `pid` and `window_id` (or `app`/`window`) on run_actions itself are the default window of every step that names none. Reads (get_window_state, zoom) do not run between steps: one there is skipped; a get_window_state last is the `observe`, a zoom last runs after it. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or target later steps by role/name. A token that went stale is retried once on the element with the same role and label, if exactly one matches.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step (after a failure caused by a dialog holding focus, that dialog is read, even without `observe`). That read is a `since:\"latest\"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.\n\nTARGET BY NAME (no earlier read needed, so one batch can cross screens): a step can be written `{\"click\": {...args}}` as well as `{tool, args}`, and its args may name the target instead of carrying a token: `role` (button, textfield, link, checkbox, menuitem, ...; AX/UIA/AT-SPI names also work), `name` (the element's label; exact match wins over substring, case-insensitive), `nth` (0-based, when several match), and `app` (app name or bundle id) and/or `window` (title substring) instead of pid/window_id. The batch reads the window fresh, waits up to 3 s (step `timeout_ms`, max 10000) for the element to appear, and acts on it; with only `app` it uses that app's frontmost window, so a dialog that opened on top is found. Later steps inherit the window, so name `app` once. The first lookup in a window also reads it once for `observe`, so the end diff shows what the batch changed even in a window you never read. Several matches fail with the candidates listed; add `nth` or a fuller name.\n\nWAITS AND CHECKS: a step may add `wait_for` (checked before its action) and `expect` (one check or up to 4, checked after it); a step may also be only a check. A check is {role?, name?, text?, gone?, value?, value_contains?, enabled?, selected?, app?, window?, timeout_ms?}: `text` matches any row of the tree, static text included; `gone:true` waits for it to disappear. Checks poll until they hold or time out (wait_for 5 s, expect 2 s, max 10 s), and a check that does not hold fails the step with what was found instead. The report says which step failed, in which phase (wait_for, find, action, expect) and why. Whole batch: at most 60 s.\n\nExample (fill a form, submit, confirm the dialog, check the result):\n{\"steps\":[{\"set_value\":{\"app\":\"Safari\",\"role\":\"textfield\",\"name\":\"Email\",\"value\":\"[email protected]\"}},{\"click\":{\"role\":\"button\",\"name\":\"Submit\"},\"expect\":{\"role\":\"button\",\"name\":\"Confirm\"}},{\"click\":{\"role\":\"button\",\"name\":\"Confirm\"},\"expect\":[{\"name\":\"Confirm\",\"gone\":true},{\"text\":\"Thanks\"}]}],\"observe\":true}","destructive": true,"idempotent": false,"input_schema": {"additionalProperties": false,"properties": {+ "app": {+ "description": "Default app (name or bundle id) for steps that name no window.",+ "type": "string"+ },"delay_ms": {"description": "Pause between steps in milliseconds (not after the last). Default 0.","maximum": 2000,@@ -3122,6 +3126,10 @@"boolean"]},+ "pid": {+ "description": "Default pid for steps that name no window (a step's own pid/window_id/app/window wins).",+ "type": "integer"+ },"session": {"description": "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.","type": "string"@@ -3161,7 +3169,8 @@"press_key","hotkey","scroll",- "drag"+ "drag",+ "move_cursor"],"type": "string"},@@ -3201,6 +3210,14 @@"maxItems": 32,"minItems": 1,"type": "array"+ },+ "window": {+ "description": "Default window title substring for steps that name no window.",+ "type": "string"+ },+ "window_id": {+ "description": "Default window_id for steps that name no window, with `pid`.",+ "type": "integer"}},"required": [diff --git a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.jsonindex 65227c254d..1599f4b114 100644--- a/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json+++ b/scripts/docs-generators/cli-specs/cua-driver-mcp-windows.json@@ -3159,12 +3159,16 @@"read_only": false},{- "description": "The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag and `args` are exactly that tool's arguments. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or use pixel targets after them.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step. That read is a `since:\"latest\"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.\n\nTARGET BY NAME (no earlier read needed, so one batch can cross screens): a step can be written `{\"click\": {...args}}` as well as `{tool, args}`, and its args may name the target instead of carrying a token: `role` (button, textfield, link, checkbox, menuitem, ...; AX/UIA/AT-SPI names also work), `name` (the element's label; exact match wins over substring, case-insensitive), `nth` (0-based, when several match), and `app` (app name or bundle id) and/or `window` (title substring) instead of pid/window_id. The batch reads the window fresh, waits up to 3 s (step `timeout_ms`, max 10000) for the element to appear, and acts on it; with only `app` it uses that app's frontmost window, so a dialog that opened on top is found. Later steps inherit the window, so name `app` once. The first lookup in a window also reads it once for `observe`, so the end diff shows what the batch changed even in a window you never read. Several matches fail with the candidates listed; add `nth` or a fuller name.\n\nWAITS AND CHECKS: a step may add `wait_for` (checked before its action) and `expect` (one check or up to 4, checked after it); a step may also be only a check. A check is {role?, name?, text?, gone?, value?, value_contains?, enabled?, selected?, app?, window?, timeout_ms?}: `text` matches any row of the tree, static text included; `gone:true` waits for it to disappear. Checks poll until they hold or time out (wait_for 5 s, expect 2 s, max 10 s), and a check that does not hold fails the step with what was found instead. The report says which step failed, in which phase (wait_for, find, action, expect) and why. Whole batch: at most 60 s.\n\nExample (fill a form, submit, confirm the dialog, check the result):\n{\"steps\":[{\"set_value\":{\"app\":\"Safari\",\"role\":\"textfield\",\"name\":\"Email\",\"value\":\"[email protected]\"}},{\"click\":{\"role\":\"button\",\"name\":\"Submit\"},\"expect\":{\"role\":\"button\",\"name\":\"Confirm\"}},{\"click\":{\"role\":\"button\",\"name\":\"Confirm\"},\"expect\":[{\"name\":\"Confirm\",\"gone\":true},{\"text\":\"Thanks\"}]}],\"observe\":true}",+ "description": "The default way to act: run one or more action tools in ONE call, in order, stop at the first failure, and (with `observe`) get what changed in the same response. Use it whenever you know the next action(s) and would otherwise re-read the window after them: fill three fields, click, and see the result in one call instead of five. Even a single step plus `observe:true` replaces an action call followed by a get_window_state call. Each step is `{tool, args}` where `tool` is one of click, double_click, right_click, set_value, type_text, press_key, hotkey, scroll, drag, move_cursor and `args` are exactly that tool's arguments. `pid` and `window_id` (or `app`/`window`) on run_actions itself are the default window of every step that names none. Reads (get_window_state, zoom) do not run between steps: one there is skipped; a get_window_state last is the `observe`, a zoom last runs after it. Every step goes through the same session, permission and approval checks as a direct call; a batch grants nothing extra. All steps are validated before the first one runs, so a malformed step 4 changes nothing. Element tokens and element_index values come from a get_window_state read before the batch; a step that changes the UI can invalidate later element targets, so put element-targeted actions before the actions that reshuffle the window, or target later steps by role/name. A token that went stale is retried once on the element with the same role and label, if exactly one matches.\n\nReturns per-step status (`ok` or the error message) and, when `observe` is given, ONE bounded get_window_state read after the last executed step (after a failure caused by a dialog holding focus, that dialog is read, even without `observe`). That read is a `since:\"latest\"` diff by default: only the rows that changed since your last read of the window, plus a new snapshot_id. Without `observe` nothing is read. The batch uses one session: steps may omit `session` or repeat the batch's. `delay_ms` pauses between steps (max 2000). At most 32 steps.\n\nTARGET BY NAME (no earlier read needed, so one batch can cross screens): a step can be written `{\"click\": {...args}}` as well as `{tool, args}`, and its args may name the target instead of carrying a token: `role` (button, textfield, link, checkbox, menuitem, ...; AX/UIA/AT-SPI names also work), `name` (the element's label; exact match wins over substring, case-insensitive), `nth` (0-based, when several match), and `app` (app name or bundle id) and/or `window` (title substring) instead of pid/window_id. The batch reads the window fresh, waits up to 3 s (step `timeout_ms`, max 10000) for the element to appear, and acts on it; with only `app` it uses that app's frontmost window, so a dialog that opened on top is found. Later steps inherit the window, so name `app` once. The first lookup in a window also reads it once for `observe`, so the end diff shows what the batch changed even in a window you never read. Several matches fail with the candidates listed; add `nth` or a fuller name.\n\nWAITS AND CHECKS: a step may add `wait_for` (checked before its action) and `expect` (one check or up to 4, checked after it); a step may also be only a check. A check is {role?, name?, text?, gone?, value?, value_contains?, enabled?, selected?, app?, window?, timeout_ms?}: `text` matches any row of the tree, static text included; `gone:true` waits for it to disappear. Checks poll until they hold or time out (wait_for 5 s, expect 2 s, max 10 s), and a check that does not hold fails the step with what was found instead. The report says which step failed, in which phase (wait_for, find, action, expect) and why. Whole batch: at most 60 s.\n\nExample (fill a form, submit, confirm the dialog, check the result):\n{\"steps\":[{\"set_value\":{\"app\":\"Safari\",\"role\":\"textfield\",\"name\":\"Email\",\"value\":\"[email protected]\"}},{\"click\":{\"role\":\"button\",\"name\":\"Submit\"},\"expect\":{\"role\":\"button\",\"name\":\"Confirm\"}},{\"click\":{\"role\":\"button\",\"name\":\"Confirm\"},\"expect\":[{\"name\":\"Confirm\",\"gone\":true},{\"text\":\"Thanks\"}]}],\"observe\":true}","destructive": true,"idempotent": false,"input_schema": {"additionalProperties": false,"properties": {+ "app": {+ "description": "Default app (name or bundle id) for steps that name no window.",+ "type": "string"+ },"delay_ms": {"description": "Pause between steps in milliseconds (not after the last). Default 0.","maximum": 2000,@@ -3178,6 +3182,10 @@"boolean"]},+ "pid": {+ "description": "Default pid for steps that name no window (a step's own pid/window_id/app/window wins).",+ "type": "integer"+ },"session": {"description": "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.","type": "string"@@ -3217,7 +3225,8 @@"press_key","hotkey","scroll",- "drag"+ "drag",+ "move_cursor"],"type": "string"},@@ -3257,6 +3266,14 @@"maxItems": 32,"minItems": 1,"type": "array"+ },+ "window": {+ "description": "Default window title substring for steps that name no window.",+ "type": "string"+ },+ "window_id": {+ "description": "Default window_id for steps that name no window, with `pid`.",+ "type": "integer"}},"required": [