rmux-sdk 0.2.0

Public, daemon-backed Rust SDK for the RMUX terminal multiplexer (facade, ensure-session, snapshots, events, detach helpers).
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
//! Playwright-style visible text waits built on pane snapshots.

use std::error::Error;
use std::fmt;
use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::time::Duration;

use rmux_proto::RmuxError as ProtoError;
use tokio::time::Instant;

use crate::{Pane, PaneSnapshot, Result, RmuxError};

use super::{resolved_wait_timeout, TEXT_POLL_INTERVAL};

#[cfg(feature = "regex")]
const REGEX_SIZE_LIMIT: usize = 1_000_000;

/// Entry point for visible text assertions on one pane.
#[derive(Debug, Clone, Copy)]
pub struct VisibleTextExpectation<'a> {
    pane: &'a Pane,
}

impl<'a> VisibleTextExpectation<'a> {
    pub(crate) const fn new(pane: &'a Pane) -> Self {
        Self { pane }
    }

    /// Waits until the visible screen text contains `needle`.
    pub fn to_contain(self, needle: impl Into<String>) -> VisibleTextWait<'a> {
        VisibleTextWait::new(self.pane, VisibleTextMatcherSpec::Contains(needle.into()))
    }

    /// Waits until the visible screen text does not contain `needle`.
    ///
    /// Negative waits can pass before a process has printed anything. Prefer
    /// anchoring the workflow with a positive wait first when testing a TUI
    /// transition.
    pub fn not_to_contain(self, needle: impl Into<String>) -> VisibleTextWait<'a> {
        VisibleTextWait::new(
            self.pane,
            VisibleTextMatcherSpec::NotContains(needle.into()),
        )
    }

    /// Waits until any supplied literal is present in the visible screen text.
    pub fn to_match_any<I, S>(self, needles: I) -> VisibleTextWait<'a>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        VisibleTextWait::new(
            self.pane,
            VisibleTextMatcherSpec::Any(needles.into_iter().map(Into::into).collect()),
        )
    }

    /// Waits until all supplied literals are present in the visible screen
    /// text.
    pub fn to_match_all<I, S>(self, needles: I) -> VisibleTextWait<'a>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        VisibleTextWait::new(
            self.pane,
            VisibleTextMatcherSpec::All(needles.into_iter().map(Into::into).collect()),
        )
    }

    /// Waits until the visible screen text matches a regular expression.
    ///
    /// Available with `rmux-sdk` feature `regex`.
    #[cfg(feature = "regex")]
    pub fn to_match(self, pattern: impl Into<String>) -> VisibleTextWait<'a> {
        self.to_match_regex(pattern)
    }

    /// Waits until the visible screen text matches a regular expression.
    ///
    /// Available with `rmux-sdk` feature `regex`.
    #[cfg(feature = "regex")]
    pub fn to_match_regex(self, pattern: impl Into<String>) -> VisibleTextWait<'a> {
        VisibleTextWait::new(self.pane, VisibleTextMatcherSpec::Regex(pattern.into()))
    }

    /// Waits until the visible screen text does not match a regular
    /// expression.
    ///
    /// Available with `rmux-sdk` feature `regex`. Like other negative waits,
    /// this can pass before the process has printed anything; use a preceding
    /// positive wait when absence must be checked after a known state change.
    #[cfg(feature = "regex")]
    pub fn not_to_match_regex(self, pattern: impl Into<String>) -> VisibleTextWait<'a> {
        VisibleTextWait::new(self.pane, VisibleTextMatcherSpec::NotRegex(pattern.into()))
    }

    /// Waits until any supplied regular expression matches the visible screen.
    ///
    /// Available with `rmux-sdk` feature `regex`.
    #[cfg(feature = "regex")]
    pub fn to_match_any_regex<I, S>(self, patterns: I) -> VisibleTextWait<'a>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        VisibleTextWait::new(
            self.pane,
            VisibleTextMatcherSpec::RegexAny(patterns.into_iter().map(Into::into).collect()),
        )
    }

    /// Waits until all supplied regular expressions match the visible screen.
    ///
    /// Available with `rmux-sdk` feature `regex`.
    #[cfg(feature = "regex")]
    pub fn to_match_all_regex<I, S>(self, patterns: I) -> VisibleTextWait<'a>
    where
        I: IntoIterator<Item = S>,
        S: Into<String>,
    {
        VisibleTextWait::new(
            self.pane,
            VisibleTextMatcherSpec::RegexAll(patterns.into_iter().map(Into::into).collect()),
        )
    }
}

/// Awaitable visible text wait builder.
#[derive(Debug)]
#[must_use = "visible text waits do nothing unless awaited"]
pub struct VisibleTextWait<'a> {
    pane: &'a Pane,
    matcher: VisibleTextMatcherSpec,
    timeout: Option<Duration>,
    poll_interval: Duration,
}

impl<'a> VisibleTextWait<'a> {
    fn new(pane: &'a Pane, matcher: VisibleTextMatcherSpec) -> Self {
        Self {
            pane,
            matcher,
            timeout: None,
            poll_interval: TEXT_POLL_INTERVAL,
        }
    }

    /// Overrides the timeout for this wait.
    pub const fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

    /// Overrides the snapshot polling interval for this wait.
    pub const fn poll_interval(mut self, interval: Duration) -> Self {
        self.poll_interval = interval;
        self
    }

    async fn run(self) -> Result<PaneSnapshot> {
        let matcher = self.matcher.compile()?;
        let timeout = self
            .timeout
            .or_else(|| resolved_wait_timeout(self.pane.configured_default_timeout()));
        let deadline = timeout.map(|timeout| Instant::now() + timeout);
        loop {
            let snapshot = self.pane.snapshot().await?;
            if matcher.matches(&snapshot.visible_text()) {
                return Ok(snapshot);
            }

            if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
                return Err(RmuxError::wait_timeout(WaitTimeoutError::new(
                    matcher.describe(),
                    timeout.expect("deadline implies timeout"),
                    snapshot,
                )));
            }

            sleep_until_next_poll(deadline, self.poll_interval).await;

            if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
                return Err(RmuxError::wait_timeout(WaitTimeoutError::new(
                    matcher.describe(),
                    timeout.expect("deadline implies timeout"),
                    snapshot,
                )));
            }
        }
    }
}

impl<'a> IntoFuture for VisibleTextWait<'a> {
    type Output = Result<PaneSnapshot>;
    type IntoFuture = Pin<Box<dyn Future<Output = Self::Output> + Send + 'a>>;

    fn into_future(self) -> Self::IntoFuture {
        Box::pin(self.run())
    }
}

#[derive(Debug)]
enum VisibleTextMatcherSpec {
    Contains(String),
    NotContains(String),
    Any(Vec<String>),
    All(Vec<String>),
    #[cfg(feature = "regex")]
    Regex(String),
    #[cfg(feature = "regex")]
    NotRegex(String),
    #[cfg(feature = "regex")]
    RegexAny(Vec<String>),
    #[cfg(feature = "regex")]
    RegexAll(Vec<String>),
}

impl VisibleTextMatcherSpec {
    fn compile(self) -> Result<VisibleTextMatcher> {
        let invalid = match self {
            Self::Contains(ref value) | Self::NotContains(ref value) => value.is_empty(),
            Self::Any(ref values) | Self::All(ref values) => {
                values.is_empty() || values.iter().any(String::is_empty)
            }
            #[cfg(feature = "regex")]
            Self::Regex(ref value) | Self::NotRegex(ref value) => value.is_empty(),
            #[cfg(feature = "regex")]
            Self::RegexAny(ref values) | Self::RegexAll(ref values) => {
                values.is_empty() || values.iter().any(String::is_empty)
            }
        };
        if invalid {
            return Err(RmuxError::protocol(ProtoError::Server(
                "visible text wait patterns must not be empty".to_owned(),
            )));
        }

        match self {
            Self::Contains(value) => Ok(VisibleTextMatcher::Contains(value)),
            Self::NotContains(value) => Ok(VisibleTextMatcher::NotContains(value)),
            Self::Any(values) => Ok(VisibleTextMatcher::Any(values)),
            Self::All(values) => Ok(VisibleTextMatcher::All(values)),
            #[cfg(feature = "regex")]
            Self::Regex(pattern) => Ok(VisibleTextMatcher::Regex(compile_regex(pattern)?)),
            #[cfg(feature = "regex")]
            Self::NotRegex(pattern) => Ok(VisibleTextMatcher::NotRegex(compile_regex(pattern)?)),
            #[cfg(feature = "regex")]
            Self::RegexAny(patterns) => compile_regexes(patterns).map(VisibleTextMatcher::RegexAny),
            #[cfg(feature = "regex")]
            Self::RegexAll(patterns) => compile_regexes(patterns).map(VisibleTextMatcher::RegexAll),
        }
    }
}

#[derive(Debug)]
enum VisibleTextMatcher {
    Contains(String),
    NotContains(String),
    Any(Vec<String>),
    All(Vec<String>),
    #[cfg(feature = "regex")]
    Regex(regex::Regex),
    #[cfg(feature = "regex")]
    NotRegex(regex::Regex),
    #[cfg(feature = "regex")]
    RegexAny(Vec<regex::Regex>),
    #[cfg(feature = "regex")]
    RegexAll(Vec<regex::Regex>),
}

impl VisibleTextMatcher {
    fn matches(&self, visible_text: &str) -> bool {
        match self {
            Self::Contains(value) => visible_text.contains(value),
            Self::NotContains(value) => !visible_text.contains(value),
            Self::Any(values) => values.iter().any(|value| visible_text.contains(value)),
            Self::All(values) => values.iter().all(|value| visible_text.contains(value)),
            #[cfg(feature = "regex")]
            Self::Regex(pattern) => pattern.is_match(visible_text),
            #[cfg(feature = "regex")]
            Self::NotRegex(pattern) => !pattern.is_match(visible_text),
            #[cfg(feature = "regex")]
            Self::RegexAny(patterns) => patterns
                .iter()
                .any(|pattern| pattern.is_match(visible_text)),
            #[cfg(feature = "regex")]
            Self::RegexAll(patterns) => patterns
                .iter()
                .all(|pattern| pattern.is_match(visible_text)),
        }
    }

    fn describe(&self) -> String {
        match self {
            Self::Contains(value) => format!("contain `{value}`"),
            Self::NotContains(value) => format!("not contain `{value}`"),
            Self::Any(values) => format!("match any of {}", render_patterns(values)),
            Self::All(values) => format!("match all of {}", render_patterns(values)),
            #[cfg(feature = "regex")]
            Self::Regex(pattern) => format!("match regex `{}`", pattern.as_str()),
            #[cfg(feature = "regex")]
            Self::NotRegex(pattern) => format!("not match regex `{}`", pattern.as_str()),
            #[cfg(feature = "regex")]
            Self::RegexAny(patterns) => {
                format!("match any regex of {}", render_regex_patterns(patterns))
            }
            #[cfg(feature = "regex")]
            Self::RegexAll(patterns) => {
                format!("match all regex of {}", render_regex_patterns(patterns))
            }
        }
    }
}

/// Timeout details for a visible text wait.
#[derive(Debug)]
pub struct WaitTimeoutError {
    matcher: String,
    timeout: Duration,
    last_snapshot: PaneSnapshot,
}

impl WaitTimeoutError {
    pub(crate) fn new(matcher: String, timeout: Duration, last_snapshot: PaneSnapshot) -> Self {
        Self {
            matcher,
            timeout,
            last_snapshot,
        }
    }

    /// Returns the matcher description that did not become true.
    #[must_use]
    pub fn matcher(&self) -> &str {
        &self.matcher
    }

    /// Returns the timeout duration that elapsed.
    #[must_use]
    pub const fn timeout(&self) -> Duration {
        self.timeout
    }

    /// Returns the last visible snapshot captured before timeout.
    #[must_use]
    pub const fn last_snapshot(&self) -> &PaneSnapshot {
        &self.last_snapshot
    }

    /// Returns the last visible screen text captured before timeout.
    #[must_use]
    pub fn last_visible_text(&self) -> String {
        self.last_snapshot.visible_text()
    }
}

impl fmt::Display for WaitTimeoutError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "timed out after {}s waiting for visible text to {}; last visible screen:\n{}",
            self.timeout.as_secs_f32(),
            self.matcher,
            self.last_snapshot.visible_text()
        )
    }
}

impl Error for WaitTimeoutError {}

async fn sleep_until_next_poll(deadline: Option<Instant>, poll_interval: Duration) {
    let Some(deadline) = deadline else {
        tokio::time::sleep(poll_interval).await;
        return;
    };

    let now = Instant::now();
    if now >= deadline {
        return;
    }
    tokio::time::sleep(poll_interval.min(deadline - now)).await;
}

fn render_patterns(patterns: &[String]) -> String {
    patterns
        .iter()
        .map(|pattern| format!("`{pattern}`"))
        .collect::<Vec<_>>()
        .join(", ")
}

#[cfg(feature = "regex")]
fn compile_regex(pattern: String) -> Result<regex::Regex> {
    regex::RegexBuilder::new(&pattern)
        .size_limit(REGEX_SIZE_LIMIT)
        .dfa_size_limit(REGEX_SIZE_LIMIT)
        .build()
        .map_err(|error| RmuxError::invalid_regex(pattern, error.to_string()))
}

#[cfg(feature = "regex")]
fn compile_regexes(patterns: Vec<String>) -> Result<Vec<regex::Regex>> {
    patterns.into_iter().map(compile_regex).collect()
}

#[cfg(feature = "regex")]
fn render_regex_patterns(patterns: &[regex::Regex]) -> String {
    patterns
        .iter()
        .map(|pattern| format!("`{}`", pattern.as_str()))
        .collect::<Vec<_>>()
        .join(", ")
}