automata-windows 0.1.0

Declarative Workflow Engine for Windows UI Automation
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
/// Notepad smoke test — exercises the ui-automata executor end-to-end.
///
/// Windows 10 only.
///
/// What it does:
///   1. Launches Notepad
///   2. Types "Hello World"
///   3. Opens Format > Font dialog (via menu clicks)
///   4. Reads the current font size, increments by 2, cycling back to 12 after 22
///      using the formula: (size + 2) % 12 + 12
///   5. Confirms with OK
///   6. Saves the file to the default location (triggers Save As dialog)
///   7. Confirms the filename and saves
///   8. Types more text ("Goodbye")
///   9. Closes the window — Notepad shows an unsaved-changes dialog
///  10. Clicks "Don't Save"
///
/// Run from the repo root:
///   cargo run -p automata-windows --example notepad

#[cfg(not(target_os = "windows"))]
fn main() {
    eprintln!("This example only runs on Windows.");
}

#[cfg(target_os = "windows")]
fn main() {
    use std::time::Duration;
    use ui_automata::*;

    automata_windows::init_logging(Some(std::path::Path::new("notepad.log")));
    automata_windows::init_com();
    let desktop = automata_windows::Desktop::new();

    let mut executor = Executor::new(desktop);
    let mut state = ui_automata::WorkflowState::new(false);

    let s = |text: &str| SelectorPath::parse(text).expect("bad selector");

    // ── Phase 1: launch Notepad ───────────────────────────────────────────────
    let notepad_pid = executor
        .desktop
        .open_application("notepad.exe")
        .expect("failed to launch Notepad");
    eprintln!("[notepad] launched with pid={notepad_pid}");

    let launch_steps = vec![Step {
        intent: "wait for Notepad window".into(),
        precondition: None,
        action: Action::NoOp,
        expect: Condition::WindowWithAttribute {
            pid: Some(notepad_pid),
            title: None,
            automation_id: None,
            process: None,
        },
        timeout: Some(Duration::from_secs(15)),
        fallback: None,
        retry: RetryPolicy::None,
        on_failure: OnFailure::Abort,
        on_success: OnSuccess::Continue,
    }];
    executor
        .run(
            &Plan {
                name: "launch_notepad",
                steps: &launch_steps,
                recovery_handlers: vec![],
                max_recoveries: 0,
                unmount: &[],
                default_timeout: DEFAULT_TIMEOUT,
                default_retry: RetryPolicy::None,
            },
            &mut state,
        )
        .expect("Notepad window did not appear");

    executor
        .mount(vec![
            AnchorDef::session("notepad", s("[name~=Notepad]")).with_pid(notepad_pid),
            AnchorDef::stable(
                "editor",
                "notepad",
                s("[name~=Notepad] >> [role=edit][name='Text Editor']"),
            ),
            AnchorDef::stable(
                "menubar",
                "notepad",
                s("[name~=Notepad] >> [role='menu bar'][name=Application]"),
            ),
        ])
        .expect("failed to mount anchors");

    // ── Phase 2: type text ────────────────────────────────────────────────────
    let type_steps = vec![Step {
        intent: "type Hello World".into(),
        precondition: None,
        action: Action::TypeText {
            scope: "editor".into(),
            selector: s("[role=edit][name='Text Editor']"),
            text: "Hello World".into(),
        },
        expect: Condition::ElementHasText {
            scope: "editor".into(),
            selector: s("[role=edit][name='Text Editor']"),
            pattern: TextMatch::contains("Hello World"),
        },
        timeout: Some(Duration::from_secs(5)),
        fallback: None,
        retry: RetryPolicy::None,
        on_failure: OnFailure::Abort,
        on_success: OnSuccess::Continue,
    }];
    executor
        .run(
            &Plan {
                name: "type_hello_world",
                steps: &type_steps,
                recovery_handlers: vec![],
                max_recoveries: 0,
                unmount: &[],
                default_timeout: DEFAULT_TIMEOUT,
                default_retry: RetryPolicy::None,
            },
            &mut state,
        )
        .expect("typing failed");

    // ── Phase 3: open Format > Font dialog ───────────────────────────────────
    let font_sel = s("[name~=Notepad] >> [role='menu item'][name~=Font]");

    let font_dialog_steps = vec![
        Step {
            intent: "click Format menu and wait for popup".into(),
            precondition: None,
            action: Action::Click {
                scope: "menubar".into(),
                selector: s("[role='menu bar'] > [role='menu item'][name=Format]"),
            },
            expect: Condition::ElementFound {
                scope: "notepad".into(),
                selector: font_sel.clone(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "click Font menu item in popup".into(),
            precondition: None,
            action: Action::Click {
                scope: "notepad".into(),
                selector: font_sel,
            },
            expect: Condition::DialogPresent {
                scope: "notepad".into(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::Fixed {
                count: 1,
                delay: Duration::from_millis(300),
            },
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
    ];
    executor
        .run(
            &Plan {
                name: "open_font_dialog",
                steps: &font_dialog_steps,
                recovery_handlers: vec![],
                max_recoveries: 0,
                unmount: &[],
                default_timeout: DEFAULT_TIMEOUT,
                default_retry: RetryPolicy::None,
            },
            &mut state,
        )
        .expect("Font dialog did not open");

    // ── Phase 4: increment font size by 2 (cycling back to 12 after 22) ────────
    executor
        .mount(vec![AnchorDef::ephemeral(
            "font_dialog",
            "notepad",
            s("[name~=Notepad] >> [role=dialog][name=Font]"),
        )])
        .expect("failed to mount font_dialog anchor");

    let size_sel = s(
        "[role=dialog][name=Font] >> [role='combo box'][name='Size:'] > [role=edit][name='Size:']",
    );
    let set_size_steps = vec![
        Step {
            intent: "read current font size".into(),
            precondition: None,
            action: Action::Extract {
                key: "size".into(),
                scope: "font_dialog".into(),
                selector: size_sel.clone(),
                attribute: ExtractAttribute::Text,
                multiple: false,
                local: true,
            },
            expect: Condition::Always,
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "compute next font size".into(),
            precondition: None,
            action: Action::Eval {
                key: "new_size".into(),
                expr: "(size + 2) % 12 + 12".into(),
                output: None,
            },
            expect: Condition::Always,
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "set font size to computed value".into(),
            precondition: None,
            action: Action::SetValue {
                scope: "font_dialog".into(),
                selector: size_sel.clone(),
                value: "{output.new_size}".into(),
            },
            expect: Condition::ElementHasText {
                scope: "font_dialog".into(),
                selector: size_sel.clone(),
                pattern: TextMatch::non_empty(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "click OK to confirm font".into(),
            precondition: None,
            action: Action::Click {
                scope: "font_dialog".into(),
                selector: s("[role=dialog][name=Font] > [role=button][name=OK]"),
            },
            expect: Condition::DialogAbsent {
                scope: "notepad".into(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
    ];
    let set_size_unmount = vec!["font_dialog".to_owned()];
    executor
        .run(
            &Plan {
                name: "set_font_size",
                steps: &set_size_steps,
                recovery_handlers: vec![],
                max_recoveries: 0,
                unmount: &set_size_unmount,
                default_timeout: DEFAULT_TIMEOUT,
                default_retry: RetryPolicy::None,
            },
            &mut state,
        )
        .expect("failed to set font size");

    // ── Phase 5: save via File > Save ─────────────────────────────────────────
    executor
        .mount(vec![AnchorDef::ephemeral(
            "saveas_dialog",
            "notepad",
            s("[name~=Notepad] >> [role=dialog][name='Save As']"),
        )])
        .expect("failed to register saveas anchor");

    let save_steps = vec![
        Step {
            intent: "click File menu and wait for popup".into(),
            precondition: None,
            action: Action::Click {
                scope: "menubar".into(),
                selector: s("[role='menu bar'] > [role='menu item'][name=File]"),
            },
            expect: Condition::ElementFound {
                scope: "notepad".into(),
                selector: s("[name~=Notepad] >> [role='menu item'][name^=Save]"),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "click Save in File menu".into(),
            precondition: None,
            action: Action::Click {
                scope: "notepad".into(),
                selector: s("[name~=Notepad] >> [role='menu item'][name^=Save]"),
            },
            expect: Condition::DialogPresent {
                scope: "notepad".into(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::Fixed {
                count: 1,
                delay: Duration::from_millis(300),
            },
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "type filename in Save As dialog".into(),
            precondition: None,
            action: Action::SetValue {
                scope: "saveas_dialog".into(),
                selector: s(">> [role=combo box][name='File name:'] >> [role=edit]"),
                value: "hello-world.txt".into(),
            },
            expect: Condition::ElementHasText {
                scope: "saveas_dialog".into(),
                selector: s(">> [role=combo box][name='File name:'] >> [role=edit]"),
                pattern: TextMatch::contains("hello-world.txt"),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "click Save button".into(),
            precondition: None,
            action: Action::Invoke {
                scope: "saveas_dialog".into(),
                selector: s(">> [role=button][name=Save]"),
            },
            expect: Condition::DialogAbsent {
                scope: "notepad".into(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
    ];
    let save_handlers = vec![RecoveryHandler {
        name: "confirm_overwrite".into(),
        trigger: Condition::ElementFound {
            scope: "notepad".into(),
            selector: s(">> [role=dialog][name='Confirm Save As']"),
        },
        actions: vec![Action::Click {
            scope: "notepad".into(),
            selector: s(">> [role=dialog][name='Confirm Save As'] >> [role=button][name=Yes]"),
        }],
        resume: ResumeStrategy::RetryStep,
    }];
    let save_unmount = vec!["saveas_dialog".to_owned()];
    executor
        .run(
            &Plan {
                name: "save_file",
                steps: &save_steps,
                recovery_handlers: save_handlers,
                max_recoveries: 1,
                unmount: &save_unmount,
                default_timeout: DEFAULT_TIMEOUT,
                default_retry: RetryPolicy::None,
            },
            &mut state,
        )
        .expect("save failed");

    // ── Phase 6: edit more text ───────────────────────────────────────────────
    let edit_steps = vec![Step {
        intent: "append Goodbye".into(),
        precondition: None,
        action: Action::TypeText {
            scope: "editor".into(),
            selector: s("[role=edit][name='Text Editor']"),
            text: "\nGoodbye".into(),
        },
        expect: Condition::ElementHasText {
            scope: "editor".into(),
            selector: s("[role=edit][name='Text Editor']"),
            pattern: TextMatch::contains("Goodbye"),
        },
        timeout: Some(Duration::from_secs(5)),
        fallback: None,
        retry: RetryPolicy::None,
        on_failure: OnFailure::Abort,
        on_success: OnSuccess::Continue,
    }];
    executor
        .run(
            &Plan {
                name: "edit_more_text",
                steps: &edit_steps,
                recovery_handlers: vec![],
                max_recoveries: 0,
                unmount: &[],
                default_timeout: DEFAULT_TIMEOUT,
                default_retry: RetryPolicy::None,
            },
            &mut state,
        )
        .expect("editing failed");

    // ── Phase 7: close and dismiss unsaved-changes dialog ────────────────────
    let close_steps = vec![
        Step {
            intent: "click title bar Close button".into(),
            precondition: None,
            action: Action::Click {
                scope: "notepad".into(),
                selector: s("[name~=Notepad] >> [role='title bar'] > [role=button][name=Close]"),
            },
            expect: Condition::DialogPresent {
                scope: "notepad".into(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
        Step {
            intent: "click Don't Save".into(),
            precondition: None,
            action: Action::Click {
                scope: "notepad".into(),
                selector: s(">> [role=button][name^=Don][name$=Save]"),
            },
            expect: Condition::WindowClosed {
                anchor: "notepad".into(),
            },
            timeout: Some(Duration::from_secs(5)),
            fallback: None,
            retry: RetryPolicy::None,
            on_failure: OnFailure::Abort,
            on_success: OnSuccess::Continue,
        },
    ];
    executor
        .run(
            &Plan {
                name: "close_notepad",
                steps: &close_steps,
                recovery_handlers: vec![],
                max_recoveries: 0,
                unmount: &[],
                default_timeout: DEFAULT_TIMEOUT,
                default_retry: RetryPolicy::None,
            },
            &mut state,
        )
        .expect("close/dismiss failed");

    eprintln!("Notepad smoke test completed successfully.");
}