Skip to main content

eoka/action/
types.rs

1use std::{future::Future, pin::Pin, sync::Arc, time::Duration};
2
3use serde::{Deserialize, Serialize};
4
5use crate::Result;
6
7/// A query evaluated afresh immediately before an action.
8#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
9#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
10#[serde(tag = "kind", rename_all = "snake_case")]
11pub enum LocatorQuery {
12    /// Resolve a pinned frontend node from an Element handle.
13    Node {
14        /// Chrome DOM node identifier for the original document.
15        id: i32,
16    },
17    /// Match a CSS selector.
18    Css {
19        /// CSS selector evaluated when the action runs.
20        selector: String,
21    },
22    /// Match element text.
23    Text {
24        /// Text to match or insert.
25        text: String,
26        #[serde(default)]
27        /// Require an exact, trimmed text match.
28        exact: bool,
29    },
30    /// Match an exact placeholder attribute.
31    Placeholder {
32        /// Text to match or insert.
33        text: String,
34    },
35    /// Match an explicit ARIA role.
36    Role {
37        /// Explicit ARIA role to match.
38        role: String,
39    },
40    /// Resolve a pinned node without retargeting a replacement.
41    BackendNode {
42        /// Pinned Chrome backend node identifier.
43        id: i64,
44    },
45}
46
47/// A serializable locator. Frame identifiers and backend nodes are pinned identities.
48#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
49#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Eq)]
50pub struct LocatorSpec {
51    /// Query used to resolve the target.
52    pub query: LocatorQuery,
53    #[serde(default)]
54    /// Pinned frame identifier, or the main frame when absent.
55    pub frame_id: Option<String>,
56    #[serde(default)]
57    /// Explicit zero-based match index; absence requires a unique match.
58    pub index: Option<usize>,
59}
60
61impl LocatorSpec {
62    /// Create a strict CSS locator specification.
63    pub fn css(selector: impl Into<String>) -> Self {
64        Self {
65            query: LocatorQuery::Css {
66                selector: selector.into(),
67            },
68            frame_id: None,
69            index: None,
70        }
71    }
72
73    /// Create a strict text locator specification.
74    pub fn text(text: impl Into<String>) -> Self {
75        Self {
76            query: LocatorQuery::Text {
77                text: text.into(),
78                exact: false,
79            },
80            frame_id: None,
81            index: None,
82        }
83    }
84}
85
86/// An observable completion condition. Values are not copied into receipts, and
87/// `Debug` prints only the kind.
88#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
89#[derive(Clone, Serialize, Deserialize, PartialEq, Eq)]
90#[serde(tag = "kind", rename_all = "snake_case")]
91pub enum Expectation {
92    /// Wait for the document to be interactive or complete, without claiming application readiness.
93    DocumentReady,
94    /// Require every supplied condition in the same observation pass.
95    All {
96        /// Conditions that must all hold.
97        conditions: Vec<Expectation>,
98    },
99    /// Wait for a visible control to become enabled or disabled.
100    Enabled {
101        /// Control to inspect.
102        target: LocatorSpec,
103        /// Required enabled state.
104        enabled: bool,
105    },
106    /// Observe a new native download originating from this page.
107    DownloadStarted,
108    /// Wait for a target to hold focus.
109    Focused {
110        /// Target that must receive focus.
111        target: LocatorSpec,
112    },
113    /// Wait for the page URL.
114    Url {
115        /// Expected or requested value.
116        value: String,
117        #[serde(default)]
118        /// Accept a substring instead of an exact match.
119        contains: bool,
120    },
121    /// Wait for a rendered target.
122    Visible {
123        /// Locator resolved at execution time.
124        target: LocatorSpec,
125    },
126    /// Wait for a target to disappear or stop rendering.
127    Hidden {
128        /// Locator resolved at execution time.
129        target: LocatorSpec,
130    },
131    /// Match element text.
132    Text {
133        /// Locator resolved at execution time.
134        target: LocatorSpec,
135        /// Expected or requested value.
136        value: String,
137        #[serde(default)]
138        /// Accept a substring instead of an exact match.
139        contains: bool,
140    },
141    /// Wait for a form value.
142    Value {
143        /// Locator resolved at execution time.
144        target: LocatorSpec,
145        /// Expected or requested value.
146        value: String,
147    },
148    /// Wait for a checked state.
149    Checked {
150        /// Locator resolved at execution time.
151        target: LocatorSpec,
152        /// Expected checked state.
153        checked: bool,
154    },
155    /// Wait for selected option values.
156    Selected {
157        /// Locator resolved at execution time.
158        target: LocatorSpec,
159        /// Requested option values.
160        values: Vec<String>,
161    },
162}
163
164impl std::fmt::Debug for Expectation {
165    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
166        f.debug_struct("Expectation")
167            .field("kind", &self.kind())
168            .finish_non_exhaustive()
169    }
170}
171
172impl std::fmt::Debug for Action {
173    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
174        f.debug_struct("Action")
175            .field("kind", &self.kind())
176            .field("target", &self.target())
177            .finish_non_exhaustive()
178    }
179}
180
181impl Expectation {
182    /// Return the stable kind name without sensitive values.
183    pub fn kind(&self) -> &'static str {
184        match self {
185            Self::DocumentReady => "document_ready",
186            Self::All { .. } => "all",
187            Self::Enabled { .. } => "enabled",
188            Self::DownloadStarted => "download_started",
189            Self::Focused { .. } => "focused",
190            Self::Url { .. } => "url",
191            Self::Visible { .. } => "visible",
192            Self::Hidden { .. } => "hidden",
193            Self::Text { .. } => "text",
194            Self::Value { .. } => "value",
195            Self::Checked { .. } => "checked",
196            Self::Selected { .. } => "selected",
197        }
198    }
199}
200
201/// Text event delivery, independent of pointer pacing.
202#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
203#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
204#[serde(rename_all = "snake_case")]
205pub enum InputMode {
206    /// Deliver one native input event per Unicode scalar, 30ms apart.
207    #[default]
208    Sequential,
209    /// Insert the whole string in one native input event.
210    Bulk,
211    /// Type like a person: a `keydown`/`keyup` pair per character (US layout
212    /// codes where one exists) at irregular 50–150ms intervals. Used by
213    /// `human_type` and `human_fill`.
214    Human,
215}
216
217/// Which page may satisfy an action's completion expectation.
218#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
219#[derive(Debug, Clone, Copy, Default, Serialize, Deserialize, PartialEq, Eq)]
220#[serde(rename_all = "snake_case")]
221pub enum Destination {
222    /// Only the originating page.
223    Current,
224    /// A new page with the originating page as its opener.
225    NewTab,
226    /// The originating page or one uniquely matching new child page.
227    #[default]
228    CurrentOrNew,
229}
230
231/// Native input or document action to perform once. `Debug` prints only the kind
232/// and target, because values and headers can hold secrets.
233#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
234#[derive(Clone, Serialize, Deserialize)]
235#[serde(tag = "kind", rename_all = "snake_case")]
236pub enum Action {
237    /// Navigate by a relative history offset; zero reloads the current document.
238    History {
239        /// Signed history offset.
240        delta: i32,
241    },
242    /// Select one option by value, falling back to an exact visible label.
243    SelectOption {
244        /// Select control resolved at execution time.
245        target: LocatorSpec,
246        /// Preferred value or exact option label.
247        value: String,
248    },
249    /// Navigate with temporary headers, restoring empty headers even on cancellation.
250    NavigateWithHeaders {
251        /// Destination URL.
252        url: String,
253        /// Temporary request headers; omitted from receipts.
254        headers: std::collections::HashMap<String, String>,
255    },
256    /// Drag an actionable target by a viewport offset.
257    Drag {
258        /// Target at which to begin the drag.
259        target: LocatorSpec,
260        /// Horizontal offset in CSS pixels.
261        dx: f64,
262        /// Vertical offset in CSS pixels.
263        dy: f64,
264    },
265    /// Insert text into the currently focused control.
266    InsertText {
267        /// Text to insert.
268        text: String,
269    },
270    /// Select an option by its exact visible label.
271    SelectText {
272        /// Select control to resolve.
273        target: LocatorSpec,
274        /// Visible label of the option.
275        text: String,
276    },
277    /// Click an actionable target once.
278    Click {
279        /// Locator resolved at execution time.
280        target: LocatorSpec,
281        #[serde(default)]
282        /// Use paced native input.
283        human: bool,
284        #[serde(default)]
285        /// Dispatch a native double click.
286        double: bool,
287    },
288    /// Replace a form value and verify it.
289    Fill {
290        /// Locator resolved at execution time.
291        target: LocatorSpec,
292        /// Expected or requested value.
293        value: String,
294        #[serde(default)]
295        /// Choose sequential or bulk native text delivery.
296        input_mode: InputMode,
297    },
298    /// Insert text into a target and verify an explicit condition.
299    Type {
300        /// Locator resolved at execution time.
301        target: LocatorSpec,
302        /// Text to match or insert.
303        text: String,
304        #[serde(default)]
305        /// Choose sequential or bulk native text delivery.
306        input_mode: InputMode,
307    },
308    /// Select options and verify their values.
309    Select {
310        /// Locator resolved at execution time.
311        target: LocatorSpec,
312        /// Requested option values.
313        values: Vec<String>,
314    },
315    /// Set file inputs and verify file names and sizes.
316    Upload {
317        /// Locator resolved at execution time.
318        target: LocatorSpec,
319        /// Local file paths to upload.
320        files: Vec<String>,
321    },
322    /// Send a key combination and verify an explicit condition.
323    PressKey {
324        /// Key or modifier combination, such as Ctrl+Enter.
325        key: String,
326    },
327    /// Focus a target and press Enter.
328    Submit {
329        /// Locator resolved at execution time.
330        target: LocatorSpec,
331    },
332    /// Move the pointer to a target and verify hover.
333    Hover {
334        /// Locator resolved at execution time.
335        target: LocatorSpec,
336        #[serde(default)]
337        /// Use paced native input.
338        human: bool,
339    },
340    /// Focus a target and verify focus.
341    Focus {
342        /// Locator resolved at execution time.
343        target: LocatorSpec,
344    },
345    /// Scroll a target into the viewport.
346    ScrollIntoView {
347        /// Locator resolved at execution time.
348        target: LocatorSpec,
349    },
350    /// Navigate and verify a document commit.
351    Navigate {
352        /// Destination URL.
353        url: String,
354        #[serde(default)]
355        /// Optional navigation referrer.
356        referrer: Option<String>,
357    },
358    /// Reload and verify a document commit.
359    Reload,
360    /// Navigate to the previous history entry.
361    Back,
362    /// Navigate to the next history entry.
363    Forward,
364}
365
366impl Action {
367    /// Return the stable kind name without sensitive values.
368    pub fn kind(&self) -> &'static str {
369        match self {
370            Self::Drag { .. } => "drag",
371            Self::InsertText { .. } => "insert_text",
372            Self::SelectText { .. } => "select_text",
373            Self::SelectOption { .. } => "select_option",
374            Self::Click { double: true, .. } => "double_click",
375            Self::Click { .. } => "click",
376            Self::Fill { .. } => "fill",
377            Self::Type { .. } => "type",
378            Self::Select { .. } => "select",
379            Self::Upload { .. } => "upload",
380            Self::PressKey { .. } => "press_key",
381            Self::Submit { .. } => "submit",
382            Self::Hover { .. } => "hover",
383            Self::Focus { .. } => "focus",
384            Self::ScrollIntoView { .. } => "scroll_into_view",
385            Self::Navigate { .. } | Self::NavigateWithHeaders { .. } => "navigate",
386            Self::Reload => "reload",
387            Self::History { .. } => "history",
388            Self::Back => "back",
389            Self::Forward => "forward",
390        }
391    }
392
393    /// Return the action target, if any.
394    pub fn target(&self) -> Option<&LocatorSpec> {
395        match self {
396            Self::Drag { target, .. }
397            | Self::SelectText { target, .. }
398            | Self::SelectOption { target, .. }
399            | Self::Click { target, .. }
400            | Self::Fill { target, .. }
401            | Self::Type { target, .. }
402            | Self::Select { target, .. }
403            | Self::Upload { target, .. }
404            | Self::Submit { target }
405            | Self::Hover { target, .. }
406            | Self::Focus { target }
407            | Self::ScrollIntoView { target } => Some(target),
408            _ => None,
409        }
410    }
411
412    /// Whether this action requires caller-supplied completion evidence.
413    pub fn requires_expectation(&self) -> bool {
414        matches!(
415            self,
416            Self::Click { .. }
417                | Self::Type { .. }
418                | Self::PressKey { .. }
419                | Self::Submit { .. }
420                | Self::Drag { .. }
421                | Self::InsertText { .. }
422        )
423    }
424}
425
426/// Persist dispatch intent before allowing any potentially mutating command.
427/// Implementations must return an error when intent cannot be made durable.
428pub trait DispatchObserver: Send + Sync {
429    /// Persist intent before a command can execute; preparation is tracked separately.
430    fn before_dispatch(
431        &self,
432        preparation: bool,
433    ) -> Pin<Box<dyn Future<Output = Result<()>> + Send + '_>>;
434}
435
436/// One deadline includes queueing, preparation, dispatch and verification.
437#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
438#[derive(Clone, Serialize, Deserialize)]
439pub struct ActionOptions {
440    /// Scope of the completion expectation. Does not change the input target.
441    #[serde(default)]
442    pub destination: Destination,
443    /// Wait for target actionability; false makes try-actions skip immediately.
444    #[serde(default = "wait_for_target")]
445    pub wait_for_target: bool,
446    #[serde(default = "default_timeout")]
447    // Plain text on one line: this doc is also the JSON schema description,
448    // where a line break would show up as a literal newline.
449    /// Total action deadline in milliseconds, including queueing, from 1 to 86400000 (24 hours).
450    pub timeout_ms: u64,
451    #[serde(default)]
452    /// Completion condition; required for actions without an intrinsic result.
453    pub expect: Option<Expectation>,
454    #[serde(skip)]
455    /// Optional durable intent hook, invoked before mutation.
456    pub observer: Option<Arc<dyn DispatchObserver>>,
457}
458
459/// Settings shared by every action started from one page handle.
460///
461/// Deliberately has no expectation: an expectation describes one operation, so
462/// set it per call with [`ActionCall::expecting`](crate::ActionCall::expecting).
463#[derive(Clone)]
464pub struct ActionDefaults {
465    /// Wait for target actionability; `try_*` calls always skip immediately.
466    pub wait_for_target: bool,
467    /// Total action deadline, including queueing (default 30s). It must be
468    /// between 1ms and 24h; a sub-millisecond remainder rounds up to a whole
469    /// millisecond.
470    pub timeout: Duration,
471    /// Optional durable intent hook, invoked before mutation.
472    pub observer: Option<Arc<dyn DispatchObserver>>,
473}
474
475impl Default for ActionDefaults {
476    fn default() -> Self {
477        let ActionOptions {
478            wait_for_target,
479            timeout_ms,
480            observer,
481            ..
482        } = ActionOptions::default();
483        Self {
484            wait_for_target,
485            timeout: Duration::from_millis(timeout_ms),
486            observer,
487        }
488    }
489}
490
491impl std::fmt::Debug for ActionDefaults {
492    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
493        f.debug_struct("ActionDefaults")
494            .field("wait_for_target", &self.wait_for_target)
495            .field("timeout", &self.timeout)
496            .finish_non_exhaustive()
497    }
498}
499
500impl ActionDefaults {
501    pub(crate) fn options(&self) -> ActionOptions {
502        ActionOptions {
503            destination: Destination::default(),
504            wait_for_target: self.wait_for_target,
505            timeout_ms: duration_to_ms(self.timeout),
506            expect: None,
507            observer: self.observer.clone(),
508        }
509    }
510}
511
512fn wait_for_target() -> bool {
513    true
514}
515
516/// Longest accepted action deadline: 24 hours, in the milliseconds of the
517/// serialized [`ActionOptions::timeout_ms`]. `Duration` timeouts are checked
518/// against it after rounding up to whole milliseconds.
519pub const MAX_ACTION_TIMEOUT_MS: u64 = 86_400_000;
520
521/// Whole milliseconds for an action deadline, rounding a sub-millisecond
522/// remainder up so that only a zero duration becomes zero, and saturating so
523/// that an oversized duration still fails the range check.
524pub(crate) fn duration_to_ms(duration: Duration) -> u64 {
525    let ms = duration.as_millis() + u128::from(duration.subsec_nanos() % 1_000_000 != 0);
526    u64::try_from(ms).unwrap_or(u64::MAX)
527}
528
529fn default_timeout() -> u64 {
530    30_000
531}
532
533impl Default for ActionOptions {
534    fn default() -> Self {
535        Self {
536            destination: Destination::default(),
537            wait_for_target: true,
538            timeout_ms: default_timeout(),
539            expect: None,
540            observer: None,
541        }
542    }
543}
544
545impl ActionOptions {
546    /// Create default options with an explicit completion condition.
547    pub fn expecting(expect: Expectation) -> Self {
548        Self {
549            expect: Some(expect),
550            ..Self::default()
551        }
552    }
553}
554
555#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
556#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
557#[serde(rename_all = "snake_case")]
558/// Whether completion is proven, uncertain, or undispatched.
559pub enum ActionOutcome {
560    /// No primary command was sent; preparation may have occurred.
561    NotDispatched,
562    /// A primary command may have run without verified completion.
563    OutcomeUnknown,
564    /// The requested completion condition was observed.
565    VerifiedComplete,
566}
567
568#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
569#[derive(Debug, Clone, Copy, Serialize, Deserialize, PartialEq, Eq)]
570#[serde(rename_all = "snake_case")]
571/// Transport evidence for the primary action commands.
572pub enum DispatchState {
573    /// No primary command reached transport dispatch.
574    NotSent,
575    /// Dispatch began but at least one acknowledgment is missing.
576    MayHaveBeenSent,
577    /// Every sent primary command was acknowledged by Chrome.
578    Acknowledged,
579}
580
581/// Evidence about an action, deliberately excluding input values and page text.
582#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
583#[derive(Debug, Clone, Serialize, Deserialize)]
584pub struct ActionReceipt {
585    /// Page that satisfied the completion expectation, if known.
586    #[serde(default)]
587    pub destination_target_id: Option<String>,
588    /// Unix time at admission, in milliseconds.
589    pub started_at_ms: u64,
590    /// Unix time when this receipt was produced, in milliseconds.
591    pub finished_at_ms: u64,
592    /// Native GUID observed for a download expectation.
593    pub download_guid: Option<String>,
594    /// Action kind, without submitted values.
595    pub action: String,
596    /// Chrome target identifier.
597    pub target_id: String,
598    /// Conservative classification of the result.
599    pub outcome: ActionOutcome,
600    /// Evidence about primary command dispatch.
601    pub dispatch: DispatchState,
602    /// Whether focus, scrolling, or other preparatory input may have run.
603    pub preparation_may_have_executed: bool,
604    /// Kind of completion evidence observed, without sensitive values.
605    pub verification: Option<String>,
606    /// Elapsed wall-clock time in milliseconds.
607    pub elapsed_ms: u64,
608    /// Whether the intrinsic result required no mutation.
609    pub already_satisfied: bool,
610    /// Whether input release is continuing after return.
611    pub cleanup_pending: bool,
612}
613
614impl std::fmt::Debug for ActionOptions {
615    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
616        f.debug_struct("ActionOptions")
617            .field("timeout_ms", &self.timeout_ms)
618            .field("expect", &self.expect.as_ref().map(Expectation::kind))
619            .finish_non_exhaustive()
620    }
621}
622
623#[cfg(test)]
624mod duration_tests {
625    use super::*;
626
627    #[test]
628    fn action_timeouts_round_sub_millisecond_up_and_saturate() {
629        assert_eq!(duration_to_ms(Duration::ZERO), 0);
630        assert_eq!(duration_to_ms(Duration::from_nanos(1)), 1);
631        assert_eq!(duration_to_ms(Duration::from_millis(1)), 1);
632        assert_eq!(duration_to_ms(Duration::from_micros(1_500)), 2);
633        assert_eq!(duration_to_ms(Duration::from_secs(86_400)), 86_400_000);
634        assert_eq!(
635            duration_to_ms(Duration::from_secs(86_400) + Duration::from_nanos(1)),
636            86_400_001
637        );
638        assert_eq!(duration_to_ms(Duration::MAX), u64::MAX);
639        let defaults = ActionDefaults {
640            timeout: Duration::from_nanos(1),
641            ..ActionDefaults::default()
642        };
643        assert_eq!(defaults.options().timeout_ms, 1);
644        assert_eq!(ActionDefaults::default().timeout, Duration::from_secs(30));
645    }
646}