Computer use CLI for AI agents
Rust accessibilityaccessibility-apiai-agentsautomationclicomputer-usecomputer-use-agentcomputer-use-agentsdesktop-automationmacosmcprust
feat: add `type --interval-ms` to type at a steady pace (#348)
Chris Tate4075c76833ef
diff --git a/apps/docs/content/docs/commands/interaction.mdx b/apps/docs/content/docs/commands/interaction.mdxindex 092591bd2..1d8ef6bfd 100644--- a/apps/docs/content/docs/commands/interaction.mdx+++ b/apps/docs/content/docs/commands/interaction.mdx@@ -155,7 +155,7 @@ Platform limits: Windows always needs `--headed`. See [Windows](/desktop/platforInserts text into a text target at its insertion point, then reads the field back.```bash-agent-desktop type <REF> <TEXT> [--timeout-ms MS]+agent-desktop type <REF> <TEXT> [--timeout-ms MS] [--interval-ms MS]```<table>@@ -164,7 +164,8 @@ agent-desktop type <REF> <TEXT> [--timeout-ms MS]</thead><tbody><tr><td><code>TEXT</code></td><td>required</td><td>The text, up to 10,000 bytes. A value that starts with a hyphen is accepted.</td></tr>- <tr><td><code>--timeout-ms MS</code></td><td><code>5000</code> plus <code>30</code> per character</td><td>Covers resolution, actionability, and delivery. An explicit value wins.</td></tr>+ <tr><td><code>--timeout-ms MS</code></td><td><code>5000</code> plus <code>30</code> per character</td><td>Covers resolution, actionability, and delivery. An explicit value wins. With <code>--interval-ms</code>, it applies to each keystroke, and <code>0</code> makes each keystroke try once.</td></tr>+ <tr><td><code>--interval-ms MS</code></td><td>off</td><td>Types one keystroke every <code>MS</code> milliseconds, 1 to 2000, instead of inserting the text at once.</td></tr></tbody></table>@@ -180,6 +181,12 @@ agent-desktop type <REF> <TEXT> [--timeout-ms MS]}```+`--interval-ms` types at a steady pace inside one command. A keystroke is one character together with the combining marks, emoji modifiers, and joined characters drawn with it, and CR LF counts as one. The first keystroke runs as a full ref action, and a headed one also focuses the target's window. The rest go to the same element, each taking the interaction lease only while it is delivered, so other agents can act between keystrokes. A headed keystroke is posted only while the target's process and focused element are unchanged, so a burst that loses focus stops with an error. The result adds `keystrokes` and `interval_ms`, and its `post_state` reads the field after the last keystroke. It stays `delivered_verified` only when that read shows the whole text; otherwise it is `delivered_unverified` with `verification_reason` set to `postcondition_mismatch`, `insufficient_evidence` (the text went in part way through the field), or `final_read_failed` (with no `post_state`). A `--wait-for` condition is waited on once, after the last keystroke. A failure after the first keystroke carries `details.typed_keystrokes` and `details.keystrokes` with a `delivered_unverified` disposition, because part of the text landed.++```bash+agent-desktop type @s8f3k2p9:e2 "hello world" --interval-ms 60+```+To set a field's whole content, use [`set-value`](#set-value). Keystroke delivery that settles on other text returns `delivered_unverified` with `verification_reason: "postcondition_mismatch"`; read the field with `get` before you write again.Platform limits: Windows needs `--headed` and returns `POLICY_DENIED` headless; use `set-value` there. See [Windows](/desktop/platforms/windows).diff --git a/crates/core/src/commands/mod.rs b/crates/core/src/commands/mod.rsindex e8d69e2ac..b6964f835 100644--- a/crates/core/src/commands/mod.rs+++ b/crates/core/src/commands/mod.rs@@ -70,6 +70,8 @@ pub mod toggle;pub mod trace;pub mod triple_click;pub mod type_text;+mod type_text_interval;+mod type_text_interval_verify;pub mod uncheck;pub mod version;pub mod wait;diff --git a/crates/core/src/commands/ref_policy_tests.rs b/crates/core/src/commands/ref_policy_tests.rsindex e6a0d4fe9..fa9463e1c 100644--- a/crates/core/src/commands/ref_policy_tests.rs+++ b/crates/core/src/commands/ref_policy_tests.rs@@ -36,6 +36,7 @@ const POLICY_TESTED_COMMANDS: &[&str] = &["toggle","triple_click","type_text",+ "type_text_interval","uncheck",];@@ -243,6 +244,7 @@ fn default_ref_commands_use_least_permissive_supported_policy() {ref_id: format!("@{}:e1", snapshot_id.clone()),text: "text".into(),timeout_ms: None,+ interval_ms: None,},&adapter,&context,@@ -330,6 +332,7 @@ fn headed_context_reaches_every_ref_action_without_policy_downgrade() {ref_id: format!("@{}:e1", snapshot_id.clone()),text: "text".into(),timeout_ms: None,+ interval_ms: None,},&adapter,&context,diff --git a/crates/core/src/commands/type_text.rs b/crates/core/src/commands/type_text.rsindex b7bdf4c63..7d9660398 100644--- a/crates/core/src/commands/type_text.rs+++ b/crates/core/src/commands/type_text.rs@@ -9,6 +9,7 @@ use serde_json::Value;const MAX_TEXT_LEN: usize = 10_000;const TYPING_BUDGET_PER_CHAR_MS: u64 = 30;+const MAX_INTERVAL_MS: u64 = 2_000;/// The budget in milliseconds for typing `text` when the caller names none:/// the standard operation budget plus a fixed allowance for each character,@@ -20,10 +21,29 @@ pub fn default_timeout_ms(text: &str) -> u64 {.saturating_add(characters.saturating_mul(TYPING_BUDGET_PER_CHAR_MS))}+/// The whole-command budget for `type --interval-ms`: the time the keystrokes+/// are spread over, plus each keystroke's own budget when the caller names one,+/// or the default budget for the text otherwise. A per-keystroke budget of `0`+/// means each keystroke tries once without waiting, under the default budget.+pub fn interval_budget_ms(text: &str, interval_ms: u64, per_keystroke_ms: Option<u64>) -> u64 {+ let per_keystroke_ms = per_keystroke_ms.filter(|per_keystroke_ms| *per_keystroke_ms > 0);+ let keystrokes =+ u64::try_from(super::type_text_interval::keystroke_units(text).len()).unwrap_or(u64::MAX);+ let spread = keystrokes.saturating_mul(interval_ms);+ match per_keystroke_ms {+ Some(per_keystroke_ms) => {+ spread.saturating_add(keystrokes.saturating_mul(per_keystroke_ms))+ }+ None => spread.saturating_add(default_timeout_ms(text)),+ }+}+pub struct TypeArgs {pub ref_id: String,pub text: String,pub timeout_ms: Option<u64>,+ /// Types one keystroke unit per interval instead of inserting the text at once.+ pub interval_ms: Option<u64>,}pub fn execute(@@ -37,6 +57,16 @@ pub fn execute()));}+ if let Some(interval_ms) = args.interval_ms {+ if !(1..=MAX_INTERVAL_MS).contains(&interval_ms) {+ return Err(AppError::invalid_input(format!(+ "interval_ms must be between 1 and {MAX_INTERVAL_MS}"+ )));+ }+ if !args.text.is_empty() {+ return super::type_text_interval::execute(args, interval_ms, adapter, context);+ }+ }let request = context.request_base(Action::TypeText(args.text));execute_ref_action_with_context(RefArgs {diff --git a/crates/core/src/commands/type_text_interval.rs b/crates/core/src/commands/type_text_interval.rsnew file mode 100644index 000000000..bdfd000da--- /dev/null+++ b/crates/core/src/commands/type_text_interval.rs@@ -0,0 +1,238 @@+//! `type --interval-ms`: types text one keystroke unit at a time on a steady+//! clock, inside one command. The first unit is a full ref action: strict+//! resolution, actionability, cursor travel and verification, and a headed one+//! also focuses the target's window. The burst then keeps that element for the+//! remaining units and takes the interaction lease only while each unit is+//! delivered, so other callers act between keystrokes and per-keystroke+//! resolution cannot make the rhythm uneven. Each unit still goes through the+//! adapter's own delivery checks, which for physical keystrokes confirm that the+//! target's process and focused element are unchanged before a key is posted.+//! The result is verified against the field as the last keystroke left it, and+//! a `--wait-for` condition is waited on once, after the last keystroke.++use std::time::{Duration, Instant};++use serde_json::{Value, json};++use crate::{+ AdapterError, AppError, DeliverySemantics,+ actions::action::Action,+ adapter::PlatformAdapter,+ commands::helpers::{RefArgs, execute_ref_action_with_context},+ commands::type_text::{TypeArgs, default_timeout_ms},+ context::CommandContext,+};++pub(crate) fn execute(+ args: TypeArgs,+ interval_ms: u64,+ adapter: &dyn PlatformAdapter,+ context: &CommandContext,+) -> Result<Value, AppError> {+ crate::commands::helpers::validate_post_action_wait(context)?;+ let per_keystroke = context.clone().with_wait_selector(None);+ let units = keystroke_units(&args.text);+ let mut clock = Clock {+ interval: Duration::from_millis(interval_ms),+ due: None,+ };+ let waits = args.timeout_ms != Some(0);+ let budget = |unit: &str| {+ args.timeout_ms+ .filter(|timeout_ms| *timeout_ms > 0)+ .unwrap_or_else(|| default_timeout_ms(unit))+ };+ let mut last = Value::Null;+ let mut burst: Option<Burst> = None;+ for (index, unit) in units.iter().enumerate() {+ let slot = clock.wait();+ let request = context.request_base(Action::TypeText(unit.clone()));+ let delivered = match &burst {+ Some(burst) => deliver(adapter, burst, request, budget(unit)).map(|_| ()),+ None => execute_ref_action_with_context(+ RefArgs {+ ref_id: args.ref_id.clone(),+ timeout_ms: waits.then(|| budget(unit)),+ },+ adapter,+ request,+ &per_keystroke,+ )+ .map(|value| last = value),+ };+ delivered.map_err(|error| after_partial_delivery(error, index, units.len()))?;+ clock.delivered(slot);+ if burst.is_none() && index + 1 < units.len() {+ burst = Some(+ resolve_for_burst(adapter, &args.ref_id, context, budget(unit))+ .map_err(|error| after_partial_delivery(error, index + 1, units.len()))?,+ );+ }+ }+ if let Some(burst) = &burst {+ let expected = expected_final_value(&last, &units);+ super::type_text_interval_verify::verify_burst(+ &mut last,+ adapter,+ &burst.handle,+ expected.as_deref(),+ );+ }+ let value = with_keystrokes(last, units.len(), interval_ms);+ if context.wait_selector().is_none() {+ return Ok(value);+ }+ let entry = crate::commands::helpers::load_ref_entry(&args.ref_id, context)?;+ crate::commands::helpers::apply_post_action_wait(value, Some(&entry), adapter, context)+}++/// What the field should read once every keystroke has landed, when the first+/// keystroke's readback shows it was typed at the end of the field: that value+/// with the rest of the text after it. `None` when the field was not readable+/// or the text went in part way through it.+fn expected_final_value(first: &Value, units: &[String]) -> Option<String> {+ let after_first = first.pointer("/post_state/value")?.as_str()?;+ after_first+ .ends_with(units.first()?.as_str())+ .then(|| format!("{after_first}{}", units[1..].concat()))+}++/// Spaces keystrokes an interval apart. The grid slides rather than catching+/// up: a keystroke that is slow to land, or waits for the interaction lease,+/// pushes the rest back instead of letting them go out in a rush.+struct Clock {+ interval: Duration,+ due: Option<Instant>,+}++impl Clock {+ /// Waits until the next keystroke is due, and returns the slot it goes+ /// out in. The first keystroke goes at once.+ fn wait(&mut self) -> Instant {+ let Some(due) = self.due else {+ return Instant::now();+ };+ if let Some(wait) = due.checked_duration_since(Instant::now()) {+ std::thread::sleep(wait);+ }+ due+ }++ /// Schedules the next keystroke once the one sent in `slot` has landed.+ fn delivered(&mut self, slot: Instant) {+ self.due = Some(next_due(slot, Instant::now(), self.interval));+ }+}++/// When the keystroke after the one sent in `slot` is due, given that it+/// landed at `now`: an interval after its slot, or half an interval after it+/// landed when it landed late, so two keystrokes never land a frame apart.+fn next_due(slot: Instant, now: Instant, interval: Duration) -> Instant {+ (slot + interval).max(now + interval / 2)+}++/// The element the first keystroke resolved, and the process instance it+/// belongs to, which every later keystroke must still reach.+struct Burst {+ handle: crate::NativeHandle,+ process: Option<crate::ProcessIdentity>,+}++fn resolve_for_burst(+ adapter: &dyn PlatformAdapter,+ ref_id: &str,+ context: &CommandContext,+ timeout_ms: u64,+) -> Result<Burst, AppError> {+ let entry = crate::commands::helpers::load_ref_entry(ref_id, context)?;+ let deadline = crate::Deadline::after(timeout_ms)?;+ let handle = adapter.resolve_element_strict(&entry, deadline)?;+ let process = entry+ .process+ .process_instance+ .as_deref()+ .filter(|instance| !instance.is_empty())+ .map(|instance| crate::ProcessIdentity::new(entry.process.pid, instance));+ Ok(Burst { handle, process })+}++fn deliver(+ adapter: &dyn PlatformAdapter,+ burst: &Burst,+ request: crate::ActionRequest,+ timeout_ms: u64,+) -> Result<crate::ActionResult, AppError> {+ let request = match &burst.process {+ Some(process) => request.with_expected_process(process.clone()),+ None => request,+ };+ let deadline = crate::Deadline::after(timeout_ms)?;+ let lease = adapter.acquire_interaction_lease(deadline)?;+ Ok(adapter.execute_action(&burst.handle, request, &lease)?)+}++/// Splits text into the units one keystroke produces: a character together+/// with the combining marks, variation selectors, emoji modifiers and+/// zero-width-joined characters that render with it, and CR LF as one unit.+pub(crate) fn keystroke_units(text: &str) -> Vec<String> {+ let mut units: Vec<String> = Vec::new();+ let mut joining = false;+ for character in text.chars() {+ let attaches = joining+ || extends_previous(character)+ || (character == '\n' && units.last().is_some_and(|unit| unit == "\r"));+ match units.last_mut() {+ Some(unit) if attaches => unit.push(character),+ _ => units.push(character.to_string()),+ }+ joining = character == '\u{200D}';+ }+ units+}++fn extends_previous(character: char) -> bool {+ matches!(+ u32::from(character),+ 0x0300..=0x036F+ | 0x1AB0..=0x1AFF+ | 0x1DC0..=0x1DFF+ | 0x20D0..=0x20FF+ | 0xFE00..=0xFE0F+ | 0xFE20..=0xFE2F+ | 0x200D+ | 0x1F3FB..=0x1F3FF+ | 0xE0020..=0xE007F+ )+}++fn after_partial_delivery(error: AppError, typed: usize, total: usize) -> AppError {+ if typed == 0 {+ return error;+ }+ let adapter_error = match error {+ AppError::Adapter(error) => error,+ other => AdapterError::internal(other.to_string()),+ };+ let mut details = adapter_error.details.clone().unwrap_or_else(|| json!({}));+ if let Some(object) = details.as_object_mut() {+ object.insert("typed_keystrokes".into(), json!(typed));+ object.insert("keystrokes".into(), json!(total));+ }+ AppError::Adapter(+ adapter_error+ .with_details(details)+ .with_disposition(DeliverySemantics::delivered_unverified()),+ )+}++fn with_keystrokes(mut value: Value, keystrokes: usize, interval_ms: u64) -> Value {+ if let Some(object) = value.as_object_mut() {+ object.insert("keystrokes".into(), json!(keystrokes));+ object.insert("interval_ms".into(), json!(interval_ms));+ }+ value+}++#[cfg(test)]+#[path = "type_text_interval_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/type_text_interval_clock_tests.rs b/crates/core/src/commands/type_text_interval_clock_tests.rsnew file mode 100644index 000000000..c223e7fdc--- /dev/null+++ b/crates/core/src/commands/type_text_interval_clock_tests.rs@@ -0,0 +1,98 @@+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps};+use crate::commands::type_text::{TypeArgs, execute};+use crate::refs::refs_test_support::HomeGuard;+use crate::{ActionRequest, ActionResult, AdapterError, CommandContext, RefEntry};+use std::sync::Mutex;+use std::time::{Duration, Instant};++/// A field whose first keystroke is slow to land, as when the interaction+/// lease or the app stalls, recording when each keystroke arrived.+#[derive(Default)]+struct SlowFirstKeystroke {+ typed: Mutex<String>,+ landed: Mutex<Vec<Instant>>,+}++impl ObservationOps for SlowFirstKeystroke {+ fn resolve_element_strict(+ &self,+ _entry: &RefEntry,+ _deadline: crate::Deadline,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ crate::adapter::complete_live_observation!(+ "textfield",+ "Target",+ [crate::actions::capability::TYPE_TEXT],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: Some(adapter.typed.lock().unwrap().clone()),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ }+ );+}++impl ActionOps for SlowFirstKeystroke {+ fn execute_action(+ &self,+ _handle: &NativeHandle,+ request: ActionRequest,+ _lease: &crate::InteractionLease,+ ) -> Result<ActionResult, AdapterError> {+ if self.landed.lock().unwrap().is_empty() {+ std::thread::sleep(Duration::from_millis(600));+ }+ if let crate::Action::TypeText(text) = request.action {+ self.typed.lock().unwrap().push_str(&text);+ }+ self.landed.lock().unwrap().push(Instant::now());+ Ok(ActionResult::delivered_unverified("type_text"))+ }+}++impl InputOps for SlowFirstKeystroke {}++impl SystemOps for SlowFirstKeystroke {+ crate::adapter::guarded_interaction_lease!();+}++/// A slow first keystroke pushes the grid back rather than leaving the rest+/// to catch up half an interval apart.+#[test]+fn a_slow_first_keystroke_does_not_rush_the_rest() {+ let _guard = HomeGuard::new();+ let snapshot_id =+ crate::commands::helpers::test_support::save_one_ref_snapshot("textfield", "SetValue");+ let adapter = SlowFirstKeystroke::default();++ execute(+ TypeArgs {+ ref_id: format!("@{snapshot_id}:e1"),+ text: "abcd".into(),+ timeout_ms: None,+ interval_ms: Some(200),+ },+ &adapter,+ &CommandContext::default(),+ )+ .expect("typing succeeds");++ assert_eq!(*adapter.typed.lock().unwrap(), "abcd");+ let landed = adapter.landed.lock().unwrap();+ let after_slow = landed[2] - landed[1];+ assert!(+ after_slow >= Duration::from_millis(90),+ "keystrokes landed {after_slow:?} apart"+ );+ let spread = landed[3] - landed[1];+ assert!(+ spread >= Duration::from_millis(300),+ "the last three keystrokes landed within {spread:?}, so the grid caught up \+ instead of sliding back"+ );+}diff --git a/crates/core/src/commands/type_text_interval_tests.rs b/crates/core/src/commands/type_text_interval_tests.rsnew file mode 100644index 000000000..4cbc5e902--- /dev/null+++ b/crates/core/src/commands/type_text_interval_tests.rs@@ -0,0 +1,52 @@+use super::keystroke_units;++#[test]+fn plain_text_types_one_character_per_keystroke() {+ assert_eq!(+ keystroke_units("hi there"),+ ["h", "i", " ", "t", "h", "e", "r", "e"]+ );+}++#[test]+fn a_combining_mark_types_with_its_base_character() {+ assert_eq!(+ keystroke_units("e\u{0301}t\u{00E9}"),+ ["e\u{0301}", "t", "\u{00E9}"]+ );+}++#[test]+fn joined_emoji_and_modifiers_type_as_one_keystroke() {+ let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}";+ let wave = "\u{1F44B}\u{1F3FD}";+ assert_eq!(+ keystroke_units(&format!("{family}{wave}!")),+ [family, wave, "!"]+ );+}++#[test]+fn crlf_types_as_one_keystroke_and_lf_alone_stays_alone() {+ assert_eq!(keystroke_units("a\r\nb\nc"), ["a", "\r\n", "b", "\n", "c"]);+}++#[path = "type_text_interval_wait_tests.rs"]+mod wait;++#[test]+fn the_next_keystroke_is_due_an_interval_after_its_slot_or_half_one_after_a_late_landing() {+ use std::time::{Duration, Instant};+ let slot = Instant::now();+ let interval = Duration::from_millis(100);++ assert_eq!(+ super::next_due(slot, slot + Duration::from_millis(10), interval),+ slot + interval+ );+ let late = slot + Duration::from_millis(350);+ assert_eq!(super::next_due(slot, late, interval), late + interval / 2);+}++#[path = "type_text_interval_clock_tests.rs"]+mod clock;diff --git a/crates/core/src/commands/type_text_interval_verify.rs b/crates/core/src/commands/type_text_interval_verify.rsnew file mode 100644index 000000000..d9206dc84--- /dev/null+++ b/crates/core/src/commands/type_text_interval_verify.rs@@ -0,0 +1,73 @@+//! Verifies a `type --interval-ms` burst against the field it typed into.+//!+//! The burst's result starts as the first keystroke's, verified against the+//! field as that keystroke left it. The later keystrokes go straight to the+//! adapter, so the field is read once more after the last one: a verified+//! result stays verified only when that read shows the whole text, and is+//! otherwise reported `delivered_unverified` with the reason. A failed read+//! drops the first keystroke's field rather than reporting it as the last.++use serde_json::{Value, json};+use std::time::Duration;++use crate::{DeliverySemantics, adapter::PlatformAdapter};++/// How long keystrokes still in the app's event queue may take to show up in+/// the field before the burst is reported unverified.+const SETTLE: Duration = Duration::from_millis(500);+const POLL: Duration = Duration::from_millis(25);++pub(crate) fn verify_burst(+ result: &mut Value,+ adapter: &dyn PlatformAdapter,+ handle: &crate::NativeHandle,+ expected: Option<&str>,+) {+ let read = || {+ let deadline = crate::Deadline::after(1_000).ok()?;+ adapter.get_live_element(handle, deadline).ok()+ };+ let started = std::time::Instant::now();+ let mut live = read();+ while expected.is_some()+ && live.as_ref().and_then(|live| live.state.value.as_deref()) != expected+ && started.elapsed() < SETTLE+ {+ std::thread::sleep(POLL);+ live = read();+ }+ let Some(object) = result.as_object_mut() else {+ return;+ };+ let reason = match &live {+ Some(live) => {+ object.insert("post_state".into(), json!(live.state));+ match expected {+ Some(text) if live.state.value.as_deref() == Some(text) => return,+ Some(_) => "postcondition_mismatch",+ None => "insufficient_evidence",+ }+ }+ None => {+ object.remove("post_state");+ "final_read_failed"+ }+ };+ let verified = json!(DeliverySemantics::delivered_verified());+ if object.get("disposition") != Some(&verified) {+ return;+ }+ object.insert(+ "disposition".into(),+ json!(DeliverySemantics::delivered_unverified()),+ );+ let details = object.entry("details").or_insert_with(|| json!({}));+ if let Some(details) = details.as_object_mut() {+ details.insert("verification_scope".into(), "unavailable".into());+ details.insert("verification_reason".into(), reason.into());+ }+}++#[cfg(test)]+#[path = "type_text_interval_verify_tests.rs"]+mod tests;diff --git a/crates/core/src/commands/type_text_interval_verify_tests.rs b/crates/core/src/commands/type_text_interval_verify_tests.rsnew file mode 100644index 000000000..99d030331--- /dev/null+++ b/crates/core/src/commands/type_text_interval_verify_tests.rs@@ -0,0 +1,125 @@+use super::verify_burst;+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps};+use crate::{AdapterError, DeliverySemantics, actions::capability};+use serde_json::{Value, json};++struct FieldAdapter {+ value: Option<&'static str>,+}++impl ObservationOps for FieldAdapter {+ fn get_live_element(+ &self,+ _handle: &NativeHandle,+ _deadline: crate::Deadline,+ ) -> Result<crate::LiveElement, AdapterError> {+ let Some(value) = self.value else {+ return Err(AdapterError::internal("the field could not be read"));+ };+ Ok(crate::LiveElement {+ identity: crate::adapter::live_identity("Target"),+ state: crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: Some(value.into()),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ },+ states_complete: true,+ bounds: None,+ available_actions: vec![capability::TYPE_TEXT.into()],+ })+ }+}+impl ActionOps for FieldAdapter {}+impl InputOps for FieldAdapter {}+impl SystemOps for FieldAdapter {}++fn first_keystroke_verified() -> Value {+ json!({+ "action": "type_text",+ "post_state": { "role": "textfield", "value": "h" },+ "disposition": DeliverySemantics::delivered_verified(),+ "details": { "verification_scope": "element_value" },+ })+}++fn verified(adapter: &FieldAdapter, expected: Option<&str>) -> Value {+ let mut result = first_keystroke_verified();+ verify_burst(&mut result, adapter, &NativeHandle::null(), expected);+ result+}++#[test]+fn a_burst_that_left_the_whole_text_stays_verified_with_the_final_field() {+ let result = verified(+ &FieldAdapter {+ value: Some("hello"),+ },+ Some("hello"),+ );++ assert_eq!(+ result["disposition"],+ json!(DeliverySemantics::delivered_verified())+ );+ assert_eq!(result["post_state"]["value"], "hello");+}++#[test]+fn a_burst_whose_field_reads_otherwise_is_reported_unverified() {+ let result = verified(+ &FieldAdapter {+ value: Some("helo"),+ },+ Some("hello"),+ );++ assert_eq!(+ result["disposition"],+ json!(DeliverySemantics::delivered_unverified())+ );+ assert_eq!(+ result["details"]["verification_reason"],+ "postcondition_mismatch"+ );+ assert_eq!(result["post_state"]["value"], "helo");+}++#[test]+fn a_failed_final_read_drops_the_stale_field_and_says_so() {+ let result = verified(&FieldAdapter { value: None }, Some("hello"));++ assert_eq!(+ result["disposition"],+ json!(DeliverySemantics::delivered_unverified())+ );+ assert_eq!(+ result["details"]["verification_reason"],+ "final_read_failed"+ );+ assert!(+ result.get("post_state").is_none(),+ "keystroke 1's field is not the last"+ );+}++#[test]+fn text_typed_part_way_through_the_field_cannot_be_verified() {+ let result = verified(+ &FieldAdapter {+ value: Some("ahellob"),+ },+ None,+ );++ assert_eq!(+ result["disposition"],+ json!(DeliverySemantics::delivered_unverified())+ );+ assert_eq!(+ result["details"]["verification_reason"],+ "insufficient_evidence"+ );+}diff --git a/crates/core/src/commands/type_text_interval_wait_tests.rs b/crates/core/src/commands/type_text_interval_wait_tests.rsnew file mode 100644index 000000000..b5de2c245--- /dev/null+++ b/crates/core/src/commands/type_text_interval_wait_tests.rs@@ -0,0 +1,144 @@+use crate::adapter::{ActionOps, InputOps, NativeHandle, ObservationOps, SystemOps, WindowFilter};+use crate::commands::type_text::{TypeArgs, execute};+use crate::context::WaitSelector;+use crate::refs::refs_test_support::HomeGuard;+use crate::{+ AccessibilityNode, ActionRequest, ActionResult, AdapterError, CommandContext, RefEntry,+ WindowInfo,+};+use std::sync::Mutex;++/// A field whose window title reads back whatever has been typed so far, so a+/// `--wait-for` on the title passes only once the whole text is in.+#[derive(Default)]+struct TitledField {+ typed: Mutex<String>,+}++impl TitledField {+ fn window(&self) -> AccessibilityNode {+ AccessibilityNode {+ ref_id: None,+ role: "window".into(),+ identity: crate::NodeIdentity {+ name: Some(self.typed.lock().unwrap().clone()),+ ..Default::default()+ },+ presentation: Default::default(),+ children_count: None,+ subtree_truncated: false,+ children: vec![],+ }+ }+}++impl ObservationOps for TitledField {+ fn observe_tree(+ &self,+ root: crate::locator::live_locator::ObservationRoot<'_>,+ _request: &crate::locator::live_locator::ObservationRequest,+ ) -> Result<crate::locator::live_locator::ObservedTree, AdapterError> {+ crate::adapter::observed_tree(&root, self.window())+ }++ fn get_tree(+ &self,+ _window: &WindowInfo,+ _options: &crate::adapter::TreeOptions,+ _deadline: crate::Deadline,+ ) -> Result<AccessibilityNode, AdapterError> {+ Ok(self.window())+ }++ fn list_windows(+ &self,+ _filter: &WindowFilter,+ _deadline: crate::Deadline,+ ) -> Result<Vec<WindowInfo>, AdapterError> {+ Ok(vec![WindowInfo {+ id: "w-1".into(),+ title: "Doc".into(),+ app: "Fixture".into(),+ pid: crate::ProcessId::new(1),+ process_instance: Some("test-instance".into()),+ bounds: None,+ state: crate::WindowState {+ is_focused: true,+ ..Default::default()+ },+ }])+ }++ fn resolve_element_strict(+ &self,+ _entry: &RefEntry,+ _deadline: crate::Deadline,+ ) -> Result<NativeHandle, AdapterError> {+ Ok(NativeHandle::null())+ }++ crate::adapter::complete_live_observation!(+ "textfield",+ "Target",+ [crate::actions::capability::TYPE_TEXT],+ adapter => crate::ElementState {+ role: "textfield".into(),+ states: Vec::new(),+ value: Some(adapter.typed.lock().unwrap().clone()),+ enabled: Some(true),+ hidden: Some(false),+ offscreen: Some(false),+ }+ );+}++impl ActionOps for TitledField {+ fn execute_action(+ &self,+ _handle: &NativeHandle,+ request: ActionRequest,+ _lease: &crate::InteractionLease,+ ) -> Result<ActionResult, AdapterError> {+ if let crate::Action::TypeText(text) = request.action {+ self.typed.lock().unwrap().push_str(&text);+ }+ Ok(ActionResult::delivered_unverified("type_text"))+ }+}++impl InputOps for TitledField {}++impl SystemOps for TitledField {+ crate::adapter::guarded_interaction_lease!();+}++/// A wait for the whole text would time out if it ran after the first+/// keystroke, and the rest would never be typed. It runs once, after the last.+#[test]+fn a_wait_for_runs_once_after_the_last_keystroke() {+ let _guard = HomeGuard::new();+ let snapshot_id =+ crate::commands::helpers::test_support::save_one_ref_snapshot("textfield", "SetValue");+ let adapter = TitledField::default();+ let context = CommandContext::default().with_wait_selector(Some(WaitSelector {+ query_raw: ":abc".into(),+ gone: false,+ timeout_ms: 300,+ }));++ let value = execute(+ TypeArgs {+ ref_id: format!("@{snapshot_id}:e1"),+ text: "abc".into(),+ timeout_ms: None,+ interval_ms: Some(10),+ },+ &adapter,+ &context,+ )+ .expect("the wait is met once every keystroke has landed");++ assert_eq!(*adapter.typed.lock().unwrap(), "abc");+ assert_eq!(value["matched_selector"], ":abc");+ assert_eq!(value["after_action"]["keystrokes"], 3);+}diff --git a/crates/core/src/commands/type_text_tests.rs b/crates/core/src/commands/type_text_tests.rsindex 3e83665dd..003e33074 100644--- a/crates/core/src/commands/type_text_tests.rs+++ b/crates/core/src/commands/type_text_tests.rs@@ -11,6 +11,8 @@ use std::sync::Mutex;struct StaleThenOkAdapter {retry: StaleRetryCounter,value: Mutex<String>,+ policies: Mutex<Vec<crate::InteractionPolicy>>,+ expected_processes: Mutex<Vec<bool>>,}impl StaleThenOkAdapter {@@ -18,6 +20,8 @@ impl StaleThenOkAdapter {Self {retry: StaleRetryCounter::new(fail_until),value: Mutex::new(String::new()),+ policies: Mutex::new(Vec::new()),+ expected_processes: Mutex::new(Vec::new()),}}}@@ -51,8 +55,14 @@ impl ActionOps for StaleThenOkAdapter {&self,_handle: &NativeHandle,request: ActionRequest,- _lease: &crate::InteractionLease,+ lease: &crate::InteractionLease,) -> Result<ActionResult, AdapterError> {+ lease.deadline().ensure_remaining()?;+ self.policies.lock().unwrap().push(request.policy);+ self.expected_processes+ .lock()+ .unwrap()+ .push(request.expected_process().is_some());if let crate::Action::TypeText(text) = request.action {self.value.lock().unwrap().push_str(&text);}@@ -63,6 +73,7 @@ impl ActionOps for StaleThenOkAdapter {impl InputOps for StaleThenOkAdapter {}impl SystemOps for StaleThenOkAdapter {crate::adapter::guarded_interaction_lease!();+ crate::adapter::exact_window_focus!();}fn snapshot_id() -> String {@@ -85,6 +96,7 @@ fn transient_stale_ref_retries_then_succeeds_when_timeout_wired() {ref_id: format!("@{}:e1", snapshot_id),text: "hi".into(),timeout_ms: Some(5_000),+ interval_ms: None,},&adapter,&CommandContext::default(),@@ -106,6 +118,7 @@ fn timeout_none_makes_exactly_one_resolve_attempt() {ref_id: format!("@{}:e1", snapshot_id),text: "hi".into(),timeout_ms: None,+ interval_ms: None,},&adapter,&CommandContext::default(),@@ -123,3 +136,141 @@ fn default_budget_grows_with_the_payload() {assert_eq!(default_timeout_ms("é你"), 5_060);assert_eq!(default_timeout_ms(&"x".repeat(2_000)), 65_000);}++#[test]+fn an_interval_types_each_keystroke_as_its_own_action_on_a_steady_clock() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_id();+ let adapter = StaleThenOkAdapter::new(0);+ let started = std::time::Instant::now();++ let value = execute(+ TypeArgs {+ ref_id: format!("@{}:e1", snapshot_id),+ text: "abc".into(),+ timeout_ms: None,+ interval_ms: Some(40),+ },+ &adapter,+ &CommandContext::default(),+ )+ .unwrap();++ assert_eq!(*adapter.value.lock().unwrap(), "abc");+ let policies = adapter.policies.lock().unwrap();+ assert_eq!(*policies, vec![crate::InteractionPolicy::headless(); 3]);+ assert_eq!(value["keystrokes"], 3);+ assert_eq!(value["interval_ms"], 40);+ assert!(started.elapsed() >= std::time::Duration::from_millis(80));+}++#[test]+fn an_interval_outside_the_cli_range_is_refused_before_anything_is_typed() {+ let _guard = HomeGuard::new();+ let snapshot_id = snapshot_id();+ let adapter = StaleThenOkAdapter::new(0);++ for interval_ms in [0, 2_001] {+ let error = execute(+ TypeArgs {+ ref_id: format!("@{}:e1", snapshot_id),+ text: "abc".into(),+ timeout_ms: None,+ interval_ms: Some(interval_ms),+ },+ &adapter,+ &CommandContext::default(),+ )+ .unwrap_err();+ assert_eq!(error.code(), "INVALID_ARGS", "{interval_ms}");+ }+ assert!(adapter.value.lock().unwrap().is_empty());+}++/// A text field ref that headed input can target: it names its window.+fn windowed_snapshot_id() -> String {+ let bounds = crate::Rect {+ x: 1.0,+ y: 1.0,+ width: 20.0,+ height: 20.0,+ };+ let mut entry = crate::adapter::minimal_ref_entry("textfield", Some("Target"));+ entry.geometry.bounds = Some(bounds);+ entry.geometry.bounds_hash = bounds.bounds_hash();+ entry.capabilities.available_actions = vec!["SetValue".into()];+ entry.source.source_app = Some("Fixture".into());+ entry.source.source_window_id = Some("w-42".into());+ entry.source.source_window_title = Some("Fixture".into());+ let mut refmap = crate::refs::RefMap::new();+ refmap.allocate(entry);+ crate::refs::refs_store::RefStore::new()+ .unwrap()+ .save_new_snapshot(&refmap)+ .unwrap()+}++fn type_paced(adapter: &StaleThenOkAdapter, text: &str, context: &CommandContext) -> Value {+ execute(+ TypeArgs {+ ref_id: format!("@{}:e1", windowed_snapshot_id()),+ text: text.into(),+ timeout_ms: None,+ interval_ms: Some(30),+ },+ adapter,+ context,+ )+ .unwrap()+}++#[test]+fn a_headed_interval_resolves_the_field_once_then_posts_each_keystroke_to_it() {+ let _guard = HomeGuard::new();+ let headed = CommandContext::default().with_headed(true);+ let single = StaleThenOkAdapter::new(0);+ type_paced(&single, "a", &headed);+ let burst = StaleThenOkAdapter::new(0);+ let started = std::time::Instant::now();++ let value = type_paced(&burst, "abcd", &headed);++ assert_eq!(*burst.value.lock().unwrap(), "abcd");+ assert_eq!(+ *burst.policies.lock().unwrap(),+ vec![crate::InteractionPolicy::headed(); 4]+ );+ assert_eq!(+ burst.retry.calls(),+ single.retry.calls() + 1,+ "only the first keystroke runs the full ref action; the burst resolves once more"+ );+ assert_eq!(+ *burst.expected_processes.lock().unwrap(),+ vec![true; 4],+ "every keystroke names the process it must reach"+ );+ assert_eq!(value["keystrokes"], 4);+ assert!(started.elapsed() >= std::time::Duration::from_millis(90));+}++#[test]+fn a_zero_timeout_with_an_interval_tries_each_keystroke_once_instead_of_failing() {+ let _guard = HomeGuard::new();+ let adapter = StaleThenOkAdapter::new(0);++ let value = execute(+ TypeArgs {+ ref_id: format!("@{}:e1", snapshot_id()),+ text: "abc".into(),+ timeout_ms: Some(0),+ interval_ms: Some(20),+ },+ &adapter,+ &CommandContext::default(),+ )+ .unwrap();++ assert_eq!(*adapter.value.lock().unwrap(), "abc");+ assert_eq!(value["keystrokes"], 3);+}diff --git a/skills/agent-desktop/references/commands-interaction.md b/skills/agent-desktop/references/commands-interaction.mdindex ba75a625d..2f17a40e3 100644--- a/skills/agent-desktop/references/commands-interaction.md+++ b/skills/agent-desktop/references/commands-interaction.md@@ -95,6 +95,7 @@ agent-desktop right-click @s8f3k2p9:e5```bashagent-desktop type @s8f3k2p9:e2 "[email protected]"+agent-desktop type @s8f3k2p9:e2 "hello world" --interval-ms 60agent-desktop set-value @s8f3k2p9:e2 "new value"agent-desktop clear @s8f3k2p9:e2agent-desktop focus @s8f3k2p9:e2@@ -102,6 +103,7 @@ agent-desktop focus @s8f3k2p9:e2- `type` inserts text and checks the result when value and selection are readable. A readable mismatch returns `ACTION_FAILED`, and an unreadable result succeeds as `delivered_unverified`. Text sent as keystrokes reaches the field through the app's event queue, so the check re-reads the field while it changes, inside the `--timeout-ms` budget. If it settles on other text, or never settles, the result is `delivered_unverified` with `verification_reason: postcondition_mismatch`. Headed typing that focuses an inactive field can change the selection, and the result then stays unverified. Read the field with `get` before you write again.- The default `--timeout-ms` of `type` is 5000 plus 30 ms per character of the text. An explicit `--timeout-ms` wins.+- `type --interval-ms N` (1 to 2000) types one keystroke every N ms inside one command; `--timeout-ms` then applies to each keystroke, and `0` makes each keystroke try once. A keystroke keeps combining marks, emoji sequences and CR LF together. The first keystroke is a full ref action (headed, it also focuses the window), and the rest go to the same element, taking the interaction lease one keystroke at a time. A headed keystroke is posted only while the target's process and focused element are unchanged; if focus moves, the burst stops with an error. The result adds `keystrokes` and `interval_ms`, and `post_state` is the field after the last keystroke. It stays `delivered_verified` only when that read shows the whole text; otherwise it is `delivered_unverified` with `verification_reason` `postcondition_mismatch`, `insufficient_evidence` (typed part way through the field) or `final_read_failed` (no `post_state`). `--wait-for` waits once, after the last keystroke. A failure part way through adds `details.typed_keystrokes` and `details.keystrokes` and is `delivered_unverified`: read the field before you type again.- `set-value` writes the value directly through the semantic value path. It is faster than `type`, but it may not fire every UI callback. Use it for text fields, text areas and sliders.- A cell that exposes no value write is not directly editable. Activate it, take a fresh snapshot, and target the editor that appears. Some apps expose no editor and accept only keyboard input.- `clear` empties the element. `focus` sets keyboard focus without clicking.diff --git a/src/cli/contract_command_surface_tests.rs b/src/cli/contract_command_surface_tests.rsindex 58de04883..0ea311683 100644--- a/src/cli/contract_command_surface_tests.rs+++ b/src/cli/contract_command_surface_tests.rs@@ -20,6 +20,8 @@ const NON_COMMAND_MODULES: &[&str] = &["query","find_live_test_support","surface_scope",+ "type_text_interval",+ "type_text_interval_verify","stale_retry_test_support","wait_element","wait_latest_ref_cache",diff --git a/src/cli_args/actions.rs b/src/cli_args/actions.rsindex d5f89adbe..0aeb00f61 100644--- a/src/cli_args/actions.rs+++ b/src/cli_args/actions.rs@@ -37,10 +37,24 @@ pub(crate) struct TypeArgs {)]#[serde(default)]pub timeout_ms: Option<u64>,+ #[arg(+ long = "interval-ms",+ value_parser = clap::value_parser!(u64).range(1..=2000),+ help = "Type one keystroke every N ms (1-2000) instead of inserting TEXT at once; --timeout-ms then applies to each keystroke, and 0 makes each keystroke try once"+ )]+ #[serde(default)]+ pub interval_ms: Option<u64>,}impl TypeArgs {pub(crate) fn effective_timeout_ms(&self) -> u64 {+ if let Some(interval_ms) = self.interval_ms {+ return agent_desktop_core::commands::type_text::interval_budget_ms(+ &self.text,+ interval_ms,+ self.timeout_ms,+ );+ }self.timeout_ms.unwrap_or_else(|| {agent_desktop_core::commands::type_text::default_timeout_ms(&self.text)})diff --git a/src/cli_args/actions_tests.rs b/src/cli_args/actions_tests.rsindex dd6227e98..58a24de83 100644--- a/src/cli_args/actions_tests.rs+++ b/src/cli_args/actions_tests.rs@@ -156,3 +156,35 @@ fn mouse_point_args_batch_json_without_modifiers_key_still_deserializes() {serde_json::from_value(serde_json::json!({ "xy": "10,20" })).unwrap();assert!(args.modifiers.is_empty());}++#[test]+fn type_args_with_an_interval_budget_the_spread_plus_each_keystroke() {+ let paced = TypeArgs::try_parse_from(["type", "@e1", "abc", "--interval-ms", "100"]).unwrap();+ assert_eq!(paced.effective_timeout_ms(), 300 + 5_090);++ let explicit = TypeArgs::try_parse_from([+ "type",+ "@e1",+ "abc",+ "--interval-ms",+ "100",+ "--timeout-ms",+ "500",+ ])+ .unwrap();+ assert_eq!(explicit.effective_timeout_ms(), 300 + 3 * 500);++ let untimed = TypeArgs::try_parse_from([+ "type",+ "@e1",+ "abc",+ "--interval-ms",+ "100",+ "--timeout-ms",+ "0",+ ])+ .unwrap();+ assert_eq!(untimed.effective_timeout_ms(), 300 + 5_090);++ assert!(TypeArgs::try_parse_from(["type", "@e1", "abc", "--interval-ms", "0"]).is_err());+}diff --git a/src/dispatch/interaction.rs b/src/dispatch/interaction.rsindex 57ffb3412..8dad6a3e6 100644--- a/src/dispatch/interaction.rs+++ b/src/dispatch/interaction.rs@@ -56,12 +56,16 @@ pub(super) fn type_text(adapter: &dyn PlatformAdapter,context: &CommandContext,) -> Result<Value, AppError> {- let timeout_ms = helpers::normalize_action_timeout_ms(args.effective_timeout_ms());+ let timeout_ms = match args.interval_ms {+ Some(_) => args.timeout_ms,+ None => helpers::normalize_action_timeout_ms(args.effective_timeout_ms()),+ };type_text_command::execute(type_text_command::TypeArgs {ref_id: args.ref_id,text: args.text,timeout_ms,+ interval_ms: args.interval_ms,},adapter,context,