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
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
//! Workflow engine: sequence execution, repeat, condition evaluation, and glob matching.
//!
//! These methods are all on `WindowState` and are used by the main action dispatch
//! in `mod.rs` and by each other for recursive workflow execution.
use crate::app::window_state::WindowState;
use crate::app::window_state::WorkflowContext;
use crate::config::snippets::{ConditionCheck, CustomActionConfig, SequenceStepBehavior};
use par_term_config::text::truncate_chars;
use std::collections::HashSet;
use std::sync::{Arc, Mutex};
/// Result of executing a single workflow step.
pub(crate) enum StepOutcome {
/// Step completed successfully.
Success,
/// Step "failed" (ShellCommand non-zero exit, or Condition false).
Failure,
/// Unrecoverable error: action not found, circular reference, or a
/// `capture_output` ShellCommand that timed out or could not be spawned.
///
/// Always halts the enclosing Sequence or Repeat *without* consulting
/// `on_failure` / `stop_on_failure`. Every arm that produces this variant
/// shows a toast first, so the halt is never silent.
Abort,
}
/// QA-002: Maximum total delay (ms) allowed for a single Repeat or Sequence before
/// rejecting the action. This caps the event-loop freeze caused by `thread::sleep`
/// in the sync event loop. The proper fix is dispatching to a background Tokio task,
/// but that requires extracting all `&mut self` mutations into a command queue.
/// See AUDIT.md QA-002 for the full plan.
pub(crate) const MAX_TOTAL_DELAY_MS: u64 = 5_000;
/// Deadline for the `git rev-parse` invocation backing a `GitBranch` condition.
/// Sub-millisecond for a healthy local repository.
const GIT_TIMEOUT: std::time::Duration = std::time::Duration::from_secs(2);
/// Cap on captured `ShellCommand` output stored in a [`WorkflowContext`].
pub(crate) const MAX_CAPTURED_OUTPUT_CHARS: usize = 65536;
impl WindowState {
/// Execute an action as a workflow step and return a typed outcome.
///
/// Returns:
/// - `StepOutcome::Success` for most action types (they don't "fail")
/// - `StepOutcome::Failure` if a `ShellCommand` with `capture_output` exits non-zero,
/// or if a `Condition` check evaluates to false
/// - `StepOutcome::Abort` if the action is not found, a circular reference is
/// detected, or a `capture_output` `ShellCommand` hits `timeout_secs` or
/// cannot be spawned
///
/// Every `Abort` path shows a toast before returning, so a halted workflow
/// always leaves the user something to read.
pub(crate) fn execute_action_as_step(
&mut self,
action_id: &str,
ctx: &Arc<Mutex<Option<WorkflowContext>>>,
visited: &mut HashSet<String>,
) -> StepOutcome {
if visited.contains(action_id) {
self.show_toast(format!(
"Workflow: circular reference detected ({})",
action_id
));
return StepOutcome::Abort;
}
let action = match self
.config
.load()
.actions
.iter()
.find(|a| a.id() == action_id)
{
Some(a) => a.clone(),
None => {
self.show_toast(format!("Workflow: action '{}' not found", action_id));
return StepOutcome::Abort;
}
};
visited.insert(action_id.to_string());
let outcome = match &action {
CustomActionConfig::ShellCommand {
capture_output,
command,
args,
notify_on_success,
timeout_secs,
title,
..
} => {
if *capture_output {
// Run synchronously: the exit code determines the step outcome, so
// this cannot be moved off-thread without the command queue that
// QA-002 tracks. Bound it instead — an unbounded `output()` here
// freezes the event loop for as long as the command runs.
let mut cmd = std::process::Command::new(command);
cmd.args(args);
let output_result = crate::process_timeout::output_with_timeout(
&mut cmd,
std::time::Duration::from_secs(*timeout_secs),
);
match output_result {
Ok(output) => {
let exit_code = output.status.code().unwrap_or(-1);
let mut combined = String::new();
combined.push_str(&output.stdout);
combined.push_str(&output.stderr);
// By characters, not bytes: `String::truncate` panics on a
// byte index that falls inside a multi-byte character.
if combined.chars().count() > MAX_CAPTURED_OUTPUT_CHARS {
combined = truncate_chars(&combined, MAX_CAPTURED_OUTPUT_CHARS)
.to_string();
}
let wf_ctx = WorkflowContext {
last_exit_code: Some(exit_code),
last_output: if combined.is_empty() {
None
} else {
Some(combined)
},
};
if let Ok(mut guard) = ctx.lock() {
*guard = Some(wf_ctx);
}
if output.status.success() {
log::info!("Step ShellCommand '{}' succeeded", title);
if *notify_on_success {
log::info!("Command '{}' output captured", title);
}
StepOutcome::Success
} else {
log::error!(
"Step ShellCommand '{}' failed with exit code {}",
title,
exit_code
);
StepOutcome::Failure
}
}
Err(e) => {
// Timeout or spawn failure. This halts the whole
// workflow, so it has to be visible: the log line
// alone left the user watching a sequence stop for
// no stated reason.
log::error!("Step command '{}' did not complete: {}", title, e);
self.show_toast(format!(
"Workflow: step '{}' did not complete: {}",
title, e
));
StepOutcome::Abort
}
}
} else {
// Fire-and-forget for non-capturing shell commands (always succeed from step perspective)
let id = action.id().to_string();
self.execute_custom_action(&id);
StepOutcome::Success
}
}
CustomActionConfig::Condition { check, .. } => {
if self.evaluate_condition_check(check, ctx) {
StepOutcome::Success
} else {
StepOutcome::Failure
}
}
CustomActionConfig::Sequence { steps, .. } => {
// Use the same visited set so that cross-sequence cycles are detected.
// action_id is already in visited (inserted above); any nested action that
// directly or indirectly references it will be caught when execute_action_as_step
// checks visited at entry.
let steps = steps.clone();
self.execute_sequence_steps(&steps, ctx, visited)
}
CustomActionConfig::Repeat {
action_id: rep_id,
count,
delay_ms: rep_delay,
stop_on_success,
stop_on_failure,
..
} => {
// Use the same visited set so that cross-repeat cycles are detected.
let rep_id = rep_id.clone();
// QA-004: Clamp repeat count to prevent config-based DoS.
// QA-002: Also cap total delay to MAX_TOTAL_DELAY_MS so the event loop
// is never frozen for more than a few seconds. The count cap alone
// doesn't bound delay time (100 iterations * 1s = 100s freeze).
const MAX_SAFE_REPEAT_COUNT: u32 = 100;
let count = (*count).min(MAX_SAFE_REPEAT_COUNT);
let rep_delay = *rep_delay;
let max_iterations_for_delay = MAX_TOTAL_DELAY_MS
.checked_div(rep_delay)
.map(|d| d.max(1) as u32)
.unwrap_or(count);
let count = count.min(max_iterations_for_delay);
let stop_on_success = *stop_on_success;
let stop_on_failure = *stop_on_failure;
let mut final_outcome = StepOutcome::Success;
for i in 0..count {
let outcome = self.execute_action_as_step(&rep_id, ctx, visited);
// Reset visited between repetitions: re-entering the same action
// in the next iteration is not a cycle.
visited.clear();
match outcome {
StepOutcome::Abort => {
// An aborted iteration breaks the loop regardless of
// `stop_on_failure` — the abort is not a failure the
// Repeat gets to override. The toast came from
// execute_action_as_step.
final_outcome = StepOutcome::Abort;
break;
}
StepOutcome::Success if stop_on_success => break,
StepOutcome::Failure if stop_on_failure => {
final_outcome = StepOutcome::Failure;
break;
}
_ => {}
}
if rep_delay > 0 && i < count - 1 {
std::thread::sleep(std::time::Duration::from_millis(rep_delay));
}
}
final_outcome
}
_ => {
// InsertText, KeySequence, NewTab, SplitPane always succeed
let id = action.id().to_string();
self.execute_custom_action(&id);
StepOutcome::Success
}
};
visited.remove(action_id);
outcome
}
/// Evaluate a `ConditionCheck` and return true if the check passes.
pub(crate) fn evaluate_condition_check(
&self,
check: &ConditionCheck,
ctx: &Arc<Mutex<Option<WorkflowContext>>>,
) -> bool {
match check {
ConditionCheck::ExitCode { value } => {
if let Ok(guard) = ctx.lock()
&& let Some(wf_ctx) = guard.as_ref()
{
return wf_ctx.last_exit_code == Some(*value);
}
false
}
ConditionCheck::OutputContains {
pattern,
case_sensitive,
} => {
if let Ok(guard) = ctx.lock()
&& let Some(wf_ctx) = guard.as_ref()
&& let Some(output) = &wf_ctx.last_output
{
return if *case_sensitive {
output.contains(pattern.as_str())
} else {
output.to_lowercase().contains(&pattern.to_lowercase())
};
}
false
}
ConditionCheck::EnvVar { name, value } => match std::env::var(name) {
Ok(env_val) => {
if let Some(expected) = value {
&env_val == expected
} else {
true // existence check
}
}
Err(_) => false,
},
ConditionCheck::DirMatches { pattern } => {
// Use the terminal's reported CWD (from shell integration / OSC 7) stored
// in session variables, rather than par-term's own process CWD.
let cwd = {
let vars = self.badge_state.variables.read();
vars.path.clone()
};
let cwd = if cwd.is_empty() {
// Fallback to process CWD if shell has not yet reported its path.
std::env::current_dir()
.ok()
.and_then(|p| p.to_str().map(|s| s.to_string()))
.unwrap_or_default()
} else {
cwd
};
glob_match(pattern, &cwd)
}
ConditionCheck::GitBranch { pattern } => {
// Run git in the terminal's CWD so the branch reflects the active shell's
// repository, not par-term's own process directory.
let cwd = {
let vars = self.badge_state.variables.read();
vars.path.clone()
};
let mut cmd = std::process::Command::new("git");
cmd.args(["rev-parse", "--abbrev-ref", "HEAD"]);
if !cwd.is_empty() {
cmd.current_dir(&cwd);
}
// Bounded: this runs on the event loop thread from a keybinding, and a
// network-mounted .git or a stale index.lock would otherwise freeze the UI.
let branch = crate::process_timeout::stdout_with_timeout(&mut cmd, GIT_TIMEOUT)
.unwrap_or_else(|e| {
log::warn!("git rev-parse for GitBranch condition failed: {e}");
String::new()
});
glob_match(pattern, &branch)
}
}
}
/// Execute sequence steps synchronously (called from event loop thread or background thread).
///
/// # Blocking note (QA-002)
///
/// This method is called from the event loop thread. Steps with `delay_ms > 0` will
/// block the event loop for the delay duration. Total delay is capped at
/// `MAX_TOTAL_DELAY_MS` to prevent extended UI freezes. The proper fix is to
/// dispatch to a background Tokio task communicating via mpsc, but that requires
/// extracting all `&mut self` mutations into a command queue (deferred).
pub(crate) fn execute_sequence_sync(
&mut self,
steps: Vec<par_term_config::snippets::SequenceStep>,
ctx: &Arc<Mutex<Option<WorkflowContext>>>,
) {
let mut visited: HashSet<String> = HashSet::new();
self.execute_sequence_steps(&steps, ctx, &mut visited);
}
/// Core sequence execution loop. Accepts an external `visited` set so that cycle
/// detection is shared across nested Sequence and Repeat actions within a single
/// workflow execution. The `visited` set grows as actions are entered and shrinks
/// as they return, allowing the same action to appear in separate (non-nested) steps.
///
/// Returns:
/// - `StepOutcome::Abort` -- a step aborted (missing action, circular ref, or a
/// captured `ShellCommand` that timed out or could not be spawned), or a step
/// failed with `on_failure = Abort`. A toast has been shown either way.
/// - `StepOutcome::Failure` -- a step failed with `on_failure = Stop` (silent early exit)
/// - `StepOutcome::Success` -- all steps completed (including any `Continue`-on-failure steps)
///
/// An abort is deliberately *not* a failure: it halts without reading
/// `step.on_failure`, so `continue` does not keep the sequence going past
/// one. See the "abort vs. failure" note in `docs/features/SNIPPETS.md`.
pub(crate) fn execute_sequence_steps(
&mut self,
steps: &[par_term_config::snippets::SequenceStep],
ctx: &Arc<Mutex<Option<WorkflowContext>>>,
visited: &mut HashSet<String>,
) -> StepOutcome {
// QA-002: Track cumulative delay to cap total event-loop freeze time.
let mut total_delay_ms: u64 = 0;
for step in steps {
if step.delay_ms > 0 {
// QA-002: Cap per-step delay so total never exceeds MAX_TOTAL_DELAY_MS.
let remaining = MAX_TOTAL_DELAY_MS.saturating_sub(total_delay_ms);
if remaining == 0 {
log::warn!(
"Sequence: total delay cap ({MAX_TOTAL_DELAY_MS}ms) reached, \
skipping remaining steps"
);
break;
}
let actual_delay = step.delay_ms.min(remaining);
total_delay_ms += actual_delay;
std::thread::sleep(std::time::Duration::from_millis(actual_delay));
}
let outcome = self.execute_action_as_step(&step.action_id, ctx, visited);
match outcome {
StepOutcome::Abort => {
// Halt without reading `step.on_failure` — an abort overrides
// even `continue`, by design (see the doc comment above).
// execute_action_as_step has already toasted the reason.
return StepOutcome::Abort;
}
StepOutcome::Success => {
// Continue to next step
}
StepOutcome::Failure => {
match step.on_failure {
SequenceStepBehavior::Abort => {
self.show_toast(format!(
"Workflow: step '{}' failed, aborting sequence",
step.action_id
));
return StepOutcome::Abort;
}
SequenceStepBehavior::Stop => {
return StepOutcome::Failure; // silent stop, propagate as failure
}
SequenceStepBehavior::Continue => {
// continue to next step
}
}
}
}
}
StepOutcome::Success
}
/// Execute a Condition action when triggered directly (not inside a Sequence).
pub(crate) fn execute_condition_standalone(
&mut self,
check: &ConditionCheck,
on_true_id: Option<&str>,
on_false_id: Option<&str>,
) {
let ctx = Arc::clone(&self.last_workflow_context);
let result = self.evaluate_condition_check(check, &ctx);
let target_id = if result { on_true_id } else { on_false_id };
if let Some(id) = target_id {
let id = id.to_string();
self.execute_custom_action(&id);
}
}
/// Execute a Repeat action: run action_id up to count times with optional delay.
///
/// # Blocking note (QA-002)
///
/// This method is called from the event loop thread. Iterations with `delay_ms > 0` will
/// block the event loop for the delay duration. Total delay is capped at
/// `MAX_TOTAL_DELAY_MS` to prevent extended UI freezes. The proper fix is to dispatch
/// to a background Tokio task communicating via mpsc, but that requires extracting all
/// `&mut self` mutations into a command queue (deferred).
pub(crate) fn execute_repeat(
&mut self,
action_id: &str,
count: u32,
delay_ms: u64,
stop_on_success: bool,
stop_on_failure: bool,
ctx: Arc<Mutex<Option<WorkflowContext>>>,
) {
// QA-002: Cap total delay to MAX_TOTAL_DELAY_MS.
let delay_cap = MAX_TOTAL_DELAY_MS
.checked_div(delay_ms)
.map(|d| d.max(1) as u32)
.unwrap_or(count);
let count = count.min(delay_cap);
let mut visited: HashSet<String> = HashSet::new();
for i in 0..count {
let outcome = self.execute_action_as_step(action_id, &ctx, &mut visited);
visited.clear(); // Reset visited between repetitions to allow re-entry
match outcome {
// Abort breaks the loop whatever `stop_on_failure` says; the
// toast came from execute_action_as_step.
StepOutcome::Abort => break,
StepOutcome::Success => {
if stop_on_success {
break;
}
}
StepOutcome::Failure => {
if stop_on_failure {
break;
}
}
}
// Sleep between iterations (not after the last one)
if delay_ms > 0 && i < count - 1 {
std::thread::sleep(std::time::Duration::from_millis(delay_ms));
}
}
}
}
/// Simple glob pattern matching (supports `*` as wildcard, no `?` or `[` brackets).
pub(crate) fn glob_match(pattern: &str, text: &str) -> bool {
// Fast path: no wildcard
if !pattern.contains('*') {
return pattern == text;
}
// Split pattern on '*' and check all parts are present in order
let parts: Vec<&str> = pattern.split('*').collect();
let mut remaining = text;
for (i, part) in parts.iter().enumerate() {
if part.is_empty() {
continue;
}
if i == 0 {
// First part must match the start
if !remaining.starts_with(part) {
return false;
}
remaining = &remaining[part.len()..];
} else if i == parts.len() - 1 {
// Last part must match the end
return remaining.ends_with(part);
} else {
// Middle parts must appear somewhere
if let Some(pos) = remaining.find(part) {
remaining = &remaining[pos + part.len()..];
} else {
return false;
}
}
}
true
}