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
use std::thread;
use std::time::{Duration, Instant};
use std::collections::HashMap;
use crate::{
Action, AnchorDef, AutomataError, Desktop, OnFailure, Plan, RecoveryHandler, ResumeStrategy,
RetryPolicy, ShadowDom, Step, output::Output, step::OnSuccess,
};
const POLL_INTERVAL: Duration = Duration::from_millis(100);
#[derive(PartialEq, Eq)]
enum StepOutcome {
Continue,
ReturnPhase,
}
/// Workflow-level mutable state: output, locals, and per-run flags.
/// Separated from `Executor` so it can be created, passed around, and
/// returned independently (e.g. across subflow invocations).
#[derive(Debug)]
pub struct WorkflowState {
/// Resolved param values for this workflow invocation. Read-only during execution;
/// accessible in `Eval` expressions as `param.key`.
pub params: HashMap<String, String>,
/// Workflow-local values from `Extract { local: true }`. Not propagated to
/// parent workflows. Accessible via `{output.<key>}` within this workflow.
pub locals: HashMap<String, String>,
/// Accumulated output from `Extract` actions. Read after the workflow completes.
/// Propagated to parent workflows via output.merge. Accessible via `{output.<key>}`.
pub output: Output,
/// When `false`, the post-action DOM snapshot is skipped entirely.
/// Set via `defaults.action_snapshot: false` in the workflow YAML.
pub action_snapshot: bool,
}
impl WorkflowState {
pub fn new(action_snapshot: bool) -> Self {
Self {
locals: HashMap::new(),
output: Output::new(),
params: HashMap::new(),
action_snapshot,
}
}
}
/// Runs plans against a live UIA desktop.
///
/// Owns the `ShadowDom` (element handle cache) and the desktop. Global recovery
/// handlers fire for every plan; plan-local handlers fire only within their plan.
pub struct Executor<D: Desktop> {
pub dom: ShadowDom<D>,
pub desktop: D,
pub global_handlers: Vec<RecoveryHandler>,
}
impl<D: Desktop> Executor<D> {
pub fn new(desktop: D) -> Self {
Self {
dom: ShadowDom::new(),
desktop,
global_handlers: vec![],
}
}
/// Register anchor definitions.
pub fn mount(&mut self, anchors: Vec<AnchorDef>) -> Result<(), AutomataError> {
self.dom.mount(anchors, &self.desktop)
}
/// Unmount anchors by name.
pub fn unmount(&mut self, names: &[&str]) {
self.dom.unmount(names, &self.desktop);
}
/// Clean up DOM anchors at `depth`.
pub fn cleanup_depth(&mut self, depth: usize) {
self.dom.cleanup_depth(depth, &self.desktop);
}
/// Run all steps of a plan in order.
///
/// Anchors listed in `plan.unmount` are always removed after the plan
/// completes, whether it succeeds or fails (guaranteed cleanup).
pub fn run(&mut self, plan: &Plan<'_>, state: &mut WorkflowState) -> Result<(), AutomataError> {
self.log_info(&format!("plan: {}", plan.name));
let total = plan.steps.len();
let mut recovery_count: u32 = 0;
let result = (|| {
for (i, step) in plan.steps.iter().enumerate() {
let outcome = self.run_step(
step,
&plan.recovery_handlers,
plan.max_recoveries,
&mut recovery_count,
i + 1,
total,
plan.default_timeout,
&plan.default_retry,
state,
)?;
if outcome == StepOutcome::ReturnPhase {
break;
}
}
Ok(())
})();
if !plan.unmount.is_empty() {
let names: Vec<&str> = plan.unmount.iter().map(String::as_str).collect();
self.unmount(&names);
}
result
}
// ── Step execution ────────────────────────────────────────────────────────
fn run_step(
&mut self,
step: &Step,
local_handlers: &[RecoveryHandler],
max_recoveries: u32,
recovery_count: &mut u32,
step_num: usize,
total: usize,
default_timeout: Duration,
default_retry: &RetryPolicy,
state: &mut WorkflowState,
) -> Result<StepOutcome, AutomataError> {
let prefix = format!("step {step_num}/{total}");
let label = format!("{prefix} '{}'", step.intent);
self.log_info(&label);
let timeout = step.timeout.unwrap_or(default_timeout);
let retry = match &step.retry {
RetryPolicy::None => default_retry,
policy => policy,
};
if let Some(pre) = &step.precondition {
let pre_desc = pre.describe();
log::debug!("precondition: {pre_desc}");
if !self.eval(pre, state)? {
log::debug!("{prefix}: precondition not satisfied, skipping");
return Ok(StepOutcome::Continue);
}
}
let action = step.action.apply_output(&state.locals, &state.output);
let expect = step.expect.apply_output(&state.locals, &state.output);
let cond_desc = expect.describe();
let action_desc = action.describe();
let mut attempts: u32 = 0;
let mut last_action_error: Option<String>;
loop {
last_action_error = None; // reset each attempt; prior attempt's error must not bleed into this one
log::debug!("action: {action_desc}");
let action_result = self.exec(&action, state);
match &action_result {
Ok(()) => log::debug!("action → Ok"),
Err(e) => {
let msg = e.to_string();
// Downgrade to debug when on_failure=continue — the caller
// expects failure and the step-level outcome handles it.
match &step.on_failure {
OnFailure::Continue => {
log::debug!("{label}: action → Err: {msg}");
}
OnFailure::Abort => {
self.log_warn(&format!("{label}: action → Err: {msg}"));
}
}
last_action_error = Some(msg);
}
}
// Sync once after the action so the trace captures what changed.
// Skipped when action_snapshot is false (e.g. complex windows with deep trees).
if state.action_snapshot {
if let Some(scope) = expect.scope_name() {
self.dom.sync(scope, &self.desktop);
}
}
let deadline = Instant::now() + timeout;
let mut last_poll: Option<bool> = None;
loop {
let satisfied = self.eval(&expect, state)?;
if last_poll != Some(satisfied) {
log::debug!("poll: {cond_desc} → {satisfied}");
last_poll = Some(satisfied);
}
if satisfied {
// Action error prevents success — fall through to retry/recovery
// rather than returning immediately, so those mechanisms can fire.
// Exception: on_failure=continue explicitly opts out of this.
if let (Some(_), OnFailure::Abort) = (&last_action_error, &step.on_failure) {
break;
}
self.log_info(&format!("{prefix}: ok"));
return Ok(match step.on_success {
OnSuccess::Continue => StepOutcome::Continue,
OnSuccess::ReturnPhase => {
log::debug!("{prefix}: on_success=return_phase, stopping phase");
StepOutcome::ReturnPhase
}
});
}
if Instant::now() >= deadline {
break;
}
thread::sleep(POLL_INTERVAL);
}
let timeout_msg = format!(
"{label}: timed out (attempt {}), checking recovery",
attempts + 1
);
self.log_warn(&timeout_msg);
let all: Vec<(String, crate::Condition, Vec<Action>, ResumeStrategy)> = local_handlers
.iter()
.chain(self.global_handlers.iter())
.map(|h| {
(
h.name.clone(),
h.trigger.clone(),
h.actions.clone(),
h.resume,
)
})
.collect();
let mut fired: Option<(String, Vec<Action>, ResumeStrategy)> = None;
for (name, trigger, actions, resume) in all {
if self.eval(&trigger, state)? {
fired = Some((name, actions, resume));
break;
}
}
match fired {
Some((name, actions, resume)) if *recovery_count < max_recoveries => {
*recovery_count += 1;
self.log_info(&format!(
"{label}: recovery handler '{name}' fired ({recovery_count}/{max_recoveries})"
));
for action in &actions {
let rdesc = action.describe();
log::debug!("recovery action: {rdesc}");
if let Err(e) = self.exec(action, state) {
log::debug!("{label}: recovery action → Err: {e}");
} else {
log::debug!("recovery action → Ok");
}
}
match resume {
ResumeStrategy::RetryStep => {
attempts += 1;
continue;
}
ResumeStrategy::SkipStep => {
self.log_info(&format!("{label}: skipped by recovery"));
return Ok(StepOutcome::Continue);
}
ResumeStrategy::Fail => {
let msg = format!("{label}: recovery handler '{name}' instructed Fail");
log::debug!("{msg}");
return Err(AutomataError::Internal(msg));
}
}
}
Some((name, _, _)) => {
let msg = format!(
"{label}: recovery handler '{name}' would fire but max_recoveries ({max_recoveries}) reached"
);
self.log_warn(&msg);
return self
.apply_on_failure_policy(step, &label, &expect, timeout, msg, state);
}
None => match retry {
RetryPolicy::Fixed { count, delay } if attempts < *count => {
attempts += 1;
thread::sleep(*delay);
continue;
}
_ => {
let msg = match &last_action_error {
Some(e) => format!(
"{label}: timed out after {} attempt(s)\n action error: {e}\n expect: {cond_desc}",
attempts + 1
),
None => format!(
"{label}: timed out after {} attempt(s)\n expect: {cond_desc}",
attempts + 1
),
};
log::debug!("{msg}");
return self
.apply_on_failure_policy(step, &label, &expect, timeout, msg, state);
}
},
}
}
}
// ── Helpers ───────────────────────────────────────────────────────────────
/// Try `fallback` (if any), re-poll `expect`, then apply `on_failure` policy.
fn apply_on_failure_policy(
&mut self,
step: &Step,
label: &str,
expect: &crate::Condition,
timeout: Duration,
failure_msg: String,
state: &mut WorkflowState,
) -> Result<StepOutcome, AutomataError> {
if let Some(fallback) = &step.fallback {
self.log_info(&format!("{label}: trying fallback action"));
if let Err(e) = self.exec(fallback, state) {
log::debug!("{label}: fallback action → Err: {e}");
}
// Re-poll expect with a fresh timeout.
let deadline = Instant::now() + timeout;
loop {
if self.eval(expect, state)? {
self.log_info(&format!("{label}: fallback succeeded"));
return Ok(match step.on_success {
OnSuccess::Continue => StepOutcome::Continue,
OnSuccess::ReturnPhase => {
log::debug!("{label}: on_success=return_phase, stopping phase");
StepOutcome::ReturnPhase
}
});
}
if Instant::now() >= deadline {
break;
}
thread::sleep(POLL_INTERVAL);
}
self.log_warn(&format!("{label}: fallback did not satisfy expect"));
}
match &step.on_failure {
OnFailure::Abort => Err(AutomataError::Internal(failure_msg)),
OnFailure::Continue => {
self.log_warn(&format!("{label}: on_failure=continue, proceeding"));
Ok(StepOutcome::Continue)
}
}
}
fn exec(&mut self, action: &Action, state: &mut WorkflowState) -> Result<(), AutomataError> {
action.execute(
&mut self.dom,
&self.desktop,
&mut state.output,
&mut state.locals,
&state.params,
)
}
fn eval(
&mut self,
cond: &crate::Condition,
state: &WorkflowState,
) -> Result<bool, AutomataError> {
cond.evaluate(
&mut self.dom,
&self.desktop,
&state.locals,
&state.params,
&state.output,
)
}
/// Evaluate a condition against the current DOM state. Used by `WorkflowFile::run()`
/// for phase-level preconditions before mounting anchors.
pub fn eval_condition(
&mut self,
cond: &crate::Condition,
locals: &std::collections::HashMap<String, String>,
params: &std::collections::HashMap<String, String>,
output: &crate::output::Output,
) -> Result<bool, AutomataError> {
cond.evaluate(&mut self.dom, &self.desktop, locals, params, output)
}
fn log_info(&self, msg: &str) {
log::info!("{msg}");
}
fn log_warn(&self, msg: &str) {
log::warn!("{msg}");
}
}