tastty-driver 0.1.0

Terminal automation driver built on tastty
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
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::time::{Duration, Instant};

use regex::Regex;
use tastty::{AbsolutePosition, Position, Screen, Terminal};

use crate::snapshot::{scrollback_snapshot_from_screen, snapshot_from_screen};
use crate::wait::condition::{WaitCondition, WaitConditionKind};
use crate::wait::error::WaitError;
use crate::wait::outcome::WaitMatch;

/// Hard floor on the ratio of [`StableCondition`](crate::StableCondition) settle
/// to its poll cadence. With fewer than this many poll rounds inside the settle
/// window, the wait engine cannot credibly assert stability: a quiet
/// inter-tick gap on a periodically-redrawing program (htop, btop,
/// glances) is indistinguishable from a settled screen.
const MIN_SETTLE_VS_POLL: u32 = 4;

/// Soft floor below which a stability wait is unlikely to outlast a
/// typical monitor-TUI tick. Settles below this value pass the hard
/// floor but emit a `tracing::warn!` advising the caller, since the
/// inter-tick gap on common monitor TUIs (1-2 s) is wider than the
/// settle window and the wait will land in that gap.
const STABLE_SETTLE_WARN_BELOW: Duration = Duration::from_secs(1);

fn validate_stable_floor(settle: Duration, poll: Duration) -> Result<(), WaitError> {
    let floor = poll.saturating_mul(MIN_SETTLE_VS_POLL);
    if settle < floor {
        return Err(WaitError::SettleBelowPollFloor {
            settle,
            poll,
            floor,
        });
    }
    if settle < STABLE_SETTLE_WARN_BELOW {
        tracing::warn!(
            settle_ms = settle.as_millis() as u64,
            poll_ms = poll.as_millis() as u64,
            "stable wait settle below {}ms; monitor TUIs typically tick every 1-2 s, consider settle >= 1500 ms",
            STABLE_SETTLE_WARN_BELOW.as_millis()
        );
    }
    Ok(())
}

// Two regexes with the same source string match the same inputs, so
// equality on `pattern` is sufficient and avoids a manual structural
// compare on the regex automaton.
#[derive(Clone, Debug)]
struct CompiledPattern {
    pattern: String,
    regex: Regex,
}

impl PartialEq for CompiledPattern {
    fn eq(&self, other: &Self) -> bool {
        self.pattern == other.pattern
    }
}

impl Eq for CompiledPattern {}

pub(crate) enum CompiledCondition {
    Flat(FlatCondition),
    AnyOf(Vec<FlatCondition>),
}

impl CompiledCondition {
    pub(crate) fn compile(condition: &WaitCondition) -> Result<Self, WaitError> {
        let poll = condition.poll;
        match &condition.kind {
            WaitConditionKind::AnyOf(subs) => {
                let mut compiled = Vec::with_capacity(subs.len());
                for sub in subs {
                    compiled.push(FlatCondition::compile(sub, poll)?);
                }
                Ok(Self::AnyOf(compiled))
            }
            other => Ok(Self::Flat(FlatCondition::compile(other, poll)?)),
        }
    }

    pub(crate) fn is_exit_or_stable(&self) -> bool {
        match self {
            Self::Flat(flat) => flat.is_exit_or_stable(),
            // An any_of survives a process exit only if at least one
            // sub-condition is passively-satisfiable from a dead child.
            // Otherwise the dead-process branch should fail the wait so the
            // caller learns the child exited without a match.
            Self::AnyOf(subs) => subs.iter().any(FlatCondition::is_exit_or_stable),
        }
    }

    /// Earliest instant at which a Stable sub-condition would settle, if
    /// any are currently tracking a candidate signature. Returned to the
    /// async wait future so it can include the settle deadline alongside
    /// its overall timeout when registering with the timer thread; without
    /// this, a Stable condition with no further output would never wake.
    #[cfg(feature = "async")]
    pub(crate) fn next_stable_deadline(&self) -> Option<Instant> {
        match self {
            Self::Flat(flat) => flat.next_stable_deadline(),
            Self::AnyOf(subs) => subs
                .iter()
                .filter_map(FlatCondition::next_stable_deadline)
                .min(),
        }
    }
}

pub(crate) struct FlatCondition {
    kind: WaitConditionKind<CompiledPattern>,
    stable: StableState,
}

impl FlatCondition {
    fn compile(kind: &WaitConditionKind<String>, poll: Duration) -> Result<Self, WaitError> {
        let compile_pattern = |pattern: &String| -> Result<CompiledPattern, WaitError> {
            let regex = Regex::new(pattern).map_err(|source| WaitError::InvalidRegex {
                pattern: pattern.clone(),
                source: source.into(),
            })?;
            Ok(CompiledPattern {
                pattern: pattern.clone(),
                regex,
            })
        };
        let kind = match kind {
            WaitConditionKind::Text(text) => WaitConditionKind::Text(text.clone()),
            WaitConditionKind::Regex {
                pattern,
                include_scrollback,
            } => WaitConditionKind::Regex {
                pattern: compile_pattern(pattern)?,
                include_scrollback: *include_scrollback,
            },
            WaitConditionKind::RowRegex { row, pattern } => WaitConditionKind::RowRegex {
                row: *row,
                pattern: compile_pattern(pattern)?,
            },
            WaitConditionKind::CellText { position, text } => WaitConditionKind::CellText {
                position: *position,
                text: text.clone(),
            },
            WaitConditionKind::Cursor(position) => WaitConditionKind::Cursor(*position),
            WaitConditionKind::Exit => WaitConditionKind::Exit,
            WaitConditionKind::Stable {
                settle,
                ignore_cursor,
                ignore_style,
            } => {
                validate_stable_floor(*settle, poll)?;
                WaitConditionKind::Stable {
                    settle: *settle,
                    ignore_cursor: *ignore_cursor,
                    ignore_style: *ignore_style,
                }
            }
            // Nested any_of is rejected at compile time. The outer compile
            // path handles top-level AnyOf; this arm only fires when an
            // any_of appears inside another any_of's sub-list.
            WaitConditionKind::AnyOf(_) => return Err(WaitError::NestedAnyOf),
        };
        Ok(Self {
            kind,
            stable: StableState::default(),
        })
    }

    fn is_exit_or_stable(&self) -> bool {
        matches!(
            self.kind,
            WaitConditionKind::Exit | WaitConditionKind::Stable { .. }
        )
    }

    #[cfg(feature = "async")]
    fn next_stable_deadline(&self) -> Option<Instant> {
        match (&self.kind, self.stable.stable_since) {
            (WaitConditionKind::Stable { settle, .. }, Some(since)) => Some(since + *settle),
            _ => None,
        }
    }
}

#[derive(Default)]
struct StableState {
    last: Option<StableSignature>,
    stable_since: Option<Instant>,
}

/// 64-bit content fingerprint of a single [`Screen`] view, paired with
/// the cursor position when the caller is tracking it.
///
/// The signature is only ever compared between two captures from the
/// same process, so any [`Hasher`] suffices: a 64-bit collision between
/// unrelated frames would settle one tick early but never falsely
/// under-settle a screen that is still changing.
#[derive(Eq, PartialEq)]
struct StableSignature {
    screen: u64,
    cursor: Option<Position>,
}

impl StableSignature {
    fn capture(screen: &Screen, ignore_cursor: bool, ignore_style: bool) -> Self {
        let mut hasher = DefaultHasher::new();
        screen.size().hash(&mut hasher);
        if ignore_style {
            for row in 0..screen.size().rows {
                if let Some(text) = screen.row_text(row) {
                    text.hash(&mut hasher);
                }
            }
        } else {
            for (pos, cell) in screen.cells() {
                pos.hash(&mut hasher);
                cell.contents().hash(&mut hasher);
                cell.attrs().hash(&mut hasher);
                cell.is_wide().hash(&mut hasher);
                cell.is_wide_continuation().hash(&mut hasher);
                cell.hyperlink().hash(&mut hasher);
            }
        }
        let cursor = if ignore_cursor {
            None
        } else {
            Some(screen.cursor())
        };
        Self {
            screen: hasher.finish(),
            cursor,
        }
    }
}

pub(crate) enum Probe {
    NotYet,
    Matched(Option<WaitMatch>),
}

/// Evaluate a compiled wait condition against the current screen.
///
/// The `terminal` handle is unused by every arm except
/// [`WaitConditionKind::Exit`], which polls [`Terminal::try_wait`]
/// independently of the parser read guard the caller already holds for
/// `screen`.
pub(crate) fn probe(
    terminal: &Terminal,
    screen: &Screen,
    condition: &mut CompiledCondition,
) -> Result<Probe, WaitError> {
    match condition {
        CompiledCondition::Flat(flat) => probe_flat(terminal, screen, flat, None),
        CompiledCondition::AnyOf(subs) => {
            for (i, sub) in subs.iter_mut().enumerate() {
                match probe_flat(terminal, screen, sub, Some(i))? {
                    Probe::NotYet => {}
                    Probe::Matched(wait_match) => return Ok(Probe::Matched(wait_match)),
                }
            }
            Ok(Probe::NotYet)
        }
    }
}

fn probe_flat(
    terminal: &Terminal,
    screen: &Screen,
    condition: &mut FlatCondition,
    condition_index: Option<usize>,
) -> Result<Probe, WaitError> {
    let make_match = |position: Option<AbsolutePosition>,
                      captures: Vec<Option<String>>,
                      matched_line: Option<String>,
                      preceding_lines: Vec<String>|
     -> WaitMatch {
        WaitMatch {
            position,
            captures,
            condition_index,
            matched_line,
            preceding_lines,
        }
    };
    // Cursor/exit/stable matches are not line-bound; they only carry a
    // WaitMatch at all when they participate in an any_of so the caller
    // can identify which sub-condition won.
    let bare_match = || -> Option<WaitMatch> {
        condition_index.map(|_| make_match(None, Vec::new(), None, Vec::new()))
    };

    match &condition.kind {
        WaitConditionKind::Text(text) => {
            // Per-line scan rather than `screen.visible_text_rows().join("\n").contains(text)`:
            // the matched-line context is only well-defined per line, and
            // a cross-line substring would not resolve to a single
            // matched_line anyway.
            let lines = screen.visible_text_rows();
            for (line_idx, line) in lines.iter().enumerate() {
                if let Some(byte_off) = line.find(text.as_str()) {
                    let col = line[..byte_off].chars().count() as u16;
                    let position = screen.visible_to_absolute(Position {
                        row: line_idx as u16,
                        col,
                    });
                    let preceding = lines[..line_idx].to_vec();
                    return Ok(Probe::Matched(Some(make_match(
                        position,
                        Vec::new(),
                        Some(line.clone()),
                        preceding,
                    ))));
                }
            }
            Ok(Probe::NotYet)
        }
        WaitConditionKind::Regex {
            pattern,
            include_scrollback,
        } => {
            let (lines, scrollback_lines): (Vec<String>, usize) = if *include_scrollback {
                let s = scrollback_snapshot_from_screen(screen, None);
                (s.lines, s.scrollback_lines)
            } else {
                (screen.visible_text_rows(), 0)
            };
            let text = lines.join("\n");
            if let Some(captures) = pattern.regex.captures(&text) {
                let located = locate_match_in_lines(&lines, captures.get(0));
                let (position, matched_line, preceding_lines) = match located {
                    Some((local_row, col, line, preceding)) => {
                        let position =
                            local_row_to_absolute(screen, scrollback_lines, local_row, col);
                        (position, Some(line), preceding)
                    }
                    None => (None, None, Vec::new()),
                };
                Ok(Probe::Matched(Some(make_match(
                    position,
                    captures_to_strings(&captures),
                    matched_line,
                    preceding_lines,
                ))))
            } else {
                Ok(Probe::NotYet)
            }
        }
        WaitConditionKind::RowRegex { row, pattern } => {
            let Some(line) = screen.row_text(*row) else {
                return Ok(Probe::NotYet);
            };
            if let Some(captures) = pattern.regex.captures(&line) {
                let col = captures
                    .get(0)
                    .map(|m| line[..m.start()].chars().count() as u16)
                    .unwrap_or(0);
                let preceding: Vec<String> = (0..*row)
                    .map(|r| screen.row_text(r).unwrap_or_default())
                    .collect();
                let position = screen.visible_to_absolute(Position { row: *row, col });
                Ok(Probe::Matched(Some(make_match(
                    position,
                    captures_to_strings(&captures),
                    Some(line),
                    preceding,
                ))))
            } else {
                Ok(Probe::NotYet)
            }
        }
        WaitConditionKind::CellText { position, text } => {
            let matched = screen
                .cell(position.row, position.col)
                .is_some_and(|cell| cell.contents() == text.as_str());
            if matched {
                let row_idx = position.row;
                let matched_line = screen.row_text(row_idx);
                let preceding: Vec<String> = (0..row_idx)
                    .map(|r| screen.row_text(r).unwrap_or_default())
                    .collect();
                let absolute = screen.visible_to_absolute(*position);
                Ok(Probe::Matched(Some(make_match(
                    absolute,
                    Vec::new(),
                    matched_line,
                    preceding,
                ))))
            } else {
                Ok(Probe::NotYet)
            }
        }
        WaitConditionKind::Cursor(position) => {
            if screen.cursor() == *position {
                Ok(Probe::Matched(bare_match()))
            } else {
                Ok(Probe::NotYet)
            }
        }
        WaitConditionKind::Exit => match terminal.try_wait() {
            Ok(Some(_)) => Ok(Probe::Matched(bare_match())),
            Ok(None) => Ok(Probe::NotYet),
            Err(source) => Err(WaitError::ExitStatus {
                snapshot: Box::new(snapshot_from_screen(screen)),
                source,
            }),
        },
        WaitConditionKind::Stable {
            settle,
            ignore_cursor,
            ignore_style,
        } => {
            let now = Instant::now();
            let signature = StableSignature::capture(screen, *ignore_cursor, *ignore_style);
            match &condition.stable.last {
                Some(prev) if *prev == signature => {}
                _ => {
                    condition.stable.last = Some(signature);
                    condition.stable.stable_since = Some(now);
                }
            }
            let settled = condition
                .stable
                .stable_since
                .is_some_and(|stable_since| now.duration_since(stable_since) >= *settle);
            if settled {
                Ok(Probe::Matched(bare_match()))
            } else {
                Ok(Probe::NotYet)
            }
        }
        // FlatCondition::compile rejects AnyOf with WaitError::NestedAnyOf,
        // so a compiled flat kind never carries this variant.
        WaitConditionKind::AnyOf(_) => unreachable!("FlatCondition cannot wrap AnyOf"),
    }
}

fn captures_to_strings(captures: &regex::Captures<'_>) -> Vec<Option<String>> {
    captures
        .iter()
        .map(|opt| opt.map(|m| m.as_str().to_string()))
        .collect()
}

/// Resolve a regex match position back to a row, column, matched line,
/// and preceding-line slice within `lines` (joined by `\n` when the
/// regex was applied).
///
/// The returned row index is local to `lines` and the caller's
/// responsibility to map onto an [`AbsolutePosition`]; see
/// [`local_row_to_absolute`].
fn locate_match_in_lines(
    lines: &[String],
    full_match: Option<regex::Match<'_>>,
) -> Option<(usize, u16, String, Vec<String>)> {
    let m = full_match?;
    let target = m.start();
    let mut consumed = 0usize;
    for (row_idx, line) in lines.iter().enumerate() {
        let line_end = consumed + line.len();
        if target <= line_end {
            let col_bytes = target.saturating_sub(consumed);
            let col = line
                .get(..col_bytes)
                .map(|s| s.chars().count())
                .unwrap_or(0) as u16;
            return Some((row_idx, col, line.clone(), lines[..row_idx].to_vec()));
        }
        consumed = line_end + 1;
    }
    None
}

/// Map a row index local to a regex-scan buffer onto its
/// [`AbsolutePosition`]. The buffer is the joined-text slice the regex
/// was applied to: `scrollback_lines` retained scrollback rows
/// (oldest first) followed by the visible rows. `0` for `scrollback_lines`
/// indicates a visible-only scan.
fn local_row_to_absolute(
    screen: &Screen,
    scrollback_lines: usize,
    local_row: usize,
    col: u16,
) -> Option<AbsolutePosition> {
    if local_row < scrollback_lines {
        let row = screen
            .scrollback_origin_row()
            .saturating_add(local_row as u64);
        Some(AbsolutePosition { row, col })
    } else {
        let viewport_row = (local_row - scrollback_lines) as u16;
        screen.visible_to_absolute(Position {
            row: viewport_row,
            col,
        })
    }
}

#[cfg(test)]
mod stable_floor_tests {
    use super::*;

    fn compile_err(condition: WaitCondition) -> WaitError {
        match CompiledCondition::compile(&condition) {
            Ok(_) => panic!("expected compile to reject {condition}"),
            Err(err) => err,
        }
    }

    fn compile_ok(condition: WaitCondition) {
        if let Err(err) = CompiledCondition::compile(&condition) {
            panic!("expected compile to accept {condition}, got {err:?}");
        }
    }

    #[test]
    fn below_floor_rejected_with_details() {
        let poll = Duration::from_millis(50);
        let settle = Duration::from_millis(100);
        let err = compile_err(WaitCondition::stable(settle).poll(poll).into());
        let WaitError::SettleBelowPollFloor {
            settle: e_settle,
            poll: e_poll,
            floor,
        } = err
        else {
            panic!("expected SettleBelowPollFloor, got {err:?}");
        };
        assert_eq!(e_settle, settle);
        assert_eq!(e_poll, poll);
        assert_eq!(floor, Duration::from_millis(200));
    }

    #[test]
    fn at_floor_accepted() {
        compile_ok(
            WaitCondition::stable(Duration::from_millis(200))
                .poll(Duration::from_millis(50))
                .into(),
        );
    }

    #[test]
    fn above_floor_below_warn_accepted() {
        compile_ok(
            WaitCondition::stable(Duration::from_millis(800))
                .poll(Duration::from_millis(50))
                .into(),
        );
    }

    #[test]
    fn floor_applied_inside_any_of_with_outer_poll() {
        let subs: [WaitCondition; 2] = [
            WaitCondition::regex("ready").into(),
            WaitCondition::stable(Duration::from_millis(300)).into(),
        ];
        let condition = WaitCondition::any_of(subs).poll(Duration::from_millis(100));
        let err = compile_err(condition);
        assert!(
            matches!(err, WaitError::SettleBelowPollFloor { .. }),
            "expected SettleBelowPollFloor, got {err:?}"
        );
    }

    #[test]
    fn invalid_regex_display_preserves_underlying_message() {
        let err = compile_err(WaitCondition::regex("(unclosed").into());
        let WaitError::InvalidRegex { pattern, source } = &err else {
            panic!("expected InvalidRegex, got {err:?}");
        };
        assert_eq!(pattern, "(unclosed");
        let source_message = source.to_string();
        assert!(
            !source_message.is_empty(),
            "wrapper must surface a non-empty regex diagnostic"
        );
        let display = err.to_string();
        assert!(
            display.contains("(unclosed"),
            "Display must include the offending pattern, got {display:?}",
        );
        assert!(
            display.contains(&source_message),
            "Display must include the wrapped diagnostic, got {display:?}",
        );
    }
}