rmux-sdk 0.6.1

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
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
//! Terminal-native locators over visible pane snapshots.
//!
//! A locator is a retryable query against rendered terminal text. It does not
//! model a DOM tree and does not infer hidden input fields; every match comes
//! from the latest [`PaneSnapshot`] visible grid.

use std::future::{Future, IntoFuture};
use std::pin::Pin;
use std::time::{Duration, Instant};

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

mod query;

/// State awaited by [`Locator::wait_for_state`].
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LocatorState {
    /// At least one visible text match exists.
    Visible,
    /// No visible text match exists.
    Hidden,
}

/// Text query accepted by [`Pane::get_by_text`](crate::Pane::get_by_text).
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LocatorText {
    /// Literal text searched line-by-line in the rendered snapshot.
    Literal(String),
    /// Regular expression searched line-by-line in the rendered snapshot.
    #[cfg(feature = "regex")]
    Regex(String),
}

impl From<&str> for LocatorText {
    fn from(value: &str) -> Self {
        Self::Literal(value.to_owned())
    }
}

impl From<String> for LocatorText {
    fn from(value: String) -> Self {
        Self::Literal(value)
    }
}

#[cfg(feature = "regex")]
impl From<regex::Regex> for LocatorText {
    fn from(value: regex::Regex) -> Self {
        Self::Regex(value.as_str().to_owned())
    }
}

/// Additional constraints applied after the base locator query.
#[derive(Debug, Default, Clone, PartialEq, Eq, Hash)]
pub struct LocatorFilter {
    /// Keep matches whose matched text contains this literal.
    pub has_text: Option<String>,
    /// Drop matches whose matched text contains this literal.
    pub has_not_text: Option<String>,
    /// `Some(true)` keeps visible matches.
    ///
    /// `Some(false)` is rejected because terminal snapshots cannot prove that
    /// a matched string is hidden; use [`LocatorState::Hidden`] or
    /// [`LocatorExpectation::to_be_hidden`] to wait for absence instead.
    pub visible: Option<bool>,
}

/// One resolved terminal locator match.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct LocatorMatch {
    /// Text coordinates reported by the snapshot search.
    pub text_match: PaneTextMatch,
}

/// Terminal text locator bound to one pane.
#[derive(Debug, Clone)]
#[must_use = "locators do nothing unless an action, assertion, or wait is awaited"]
pub struct Locator {
    pane: Pane,
    query: LocatorQuery,
    selection: LocatorSelection,
    filters: LocatorFilter,
    timeout: Option<Duration>,
    poll_interval: Duration,
    invalid_reason: Option<String>,
}

#[derive(Debug, Clone, PartialEq, Eq, Hash)]
enum LocatorQuery {
    Text(LocatorText),
    Or(Box<LocatorQuery>, Box<LocatorQuery>),
    And(Box<LocatorQuery>, Box<LocatorQuery>),
}

#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
enum LocatorSelection {
    #[default]
    Strict,
    First,
    Last,
    Nth(usize),
}

impl Locator {
    pub(crate) fn get_by_text(pane: Pane, text: impl Into<LocatorText>) -> Self {
        Self::new(pane, LocatorQuery::Text(text.into()))
    }

    pub(crate) fn parse(pane: Pane, selector: impl AsRef<str>) -> Self {
        let selector = selector.as_ref();
        let text = selector.strip_prefix("text=").unwrap_or(selector);
        Self::get_by_text(pane, text)
    }

    fn new(pane: Pane, query: LocatorQuery) -> Self {
        Self {
            pane,
            query,
            selection: LocatorSelection::Strict,
            filters: LocatorFilter::default(),
            timeout: None,
            poll_interval: crate::wait::TEXT_POLL_INTERVAL,
            invalid_reason: None,
        }
    }

    /// Selects the first current match before applying strict actions.
    pub const fn first(mut self) -> Self {
        self.selection = LocatorSelection::First;
        self
    }

    /// Selects the last current match before applying strict actions.
    pub const fn last(mut self) -> Self {
        self.selection = LocatorSelection::Last;
        self
    }

    /// Selects the zero-based `index` match before applying strict actions.
    pub const fn nth(mut self, index: usize) -> Self {
        self.selection = LocatorSelection::Nth(index);
        self
    }

    /// Adds terminal-native text filters to this locator.
    pub fn filter(mut self, filter: LocatorFilter) -> Self {
        self.filters = filter;
        self
    }

    /// Creates a locator that matches either locator's text query.
    ///
    /// Both locators must target the same pane. If they do not, the mismatch
    /// is reported when the resulting locator is awaited. Composition accepts
    /// plain locators only; apply filters, selections, and timeout overrides to
    /// the combined locator.
    pub fn or(self, other: Self) -> Self {
        self.combine(other, LocatorCombiner::Or)
    }

    /// Creates a locator that keeps matches present in both text queries.
    ///
    /// Intersections are based on exact visible coordinates. Composition
    /// accepts plain locators only; apply filters, selections, and timeout
    /// overrides to the combined locator.
    pub fn and(self, other: Self) -> Self {
        self.combine(other, LocatorCombiner::And)
    }

    /// Overrides the timeout for waits and assertions derived from this locator.
    pub const fn timeout(mut self, timeout: Duration) -> Self {
        self.timeout = Some(timeout);
        self
    }

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

    /// Waits until this locator is visible.
    pub fn wait_for(self) -> LocatorWait {
        self.wait_for_state(LocatorState::Visible)
    }

    /// Waits until this locator reaches `state`.
    pub fn wait_for_state(self, state: LocatorState) -> LocatorWait {
        LocatorWait {
            locator: self,
            state,
        }
    }

    /// Starts locator assertions.
    pub fn expect(self) -> LocatorExpectation {
        LocatorExpectation { locator: self }
    }

    pub(crate) async fn resolve(&self, snapshot: &PaneSnapshot) -> Result<Vec<LocatorMatch>> {
        if let Some(reason) = &self.invalid_reason {
            return Err(RmuxError::protocol(rmux_proto::RmuxError::Server(
                reason.clone(),
            )));
        }
        let mut matches = query::evaluate_query(&self.query, snapshot)?;
        query::apply_filter(&mut matches, &self.filters)?;
        Ok(query::apply_selection(matches, self.selection))
    }

    pub(crate) async fn resolve_strict_with_wait(&self) -> Result<(PaneSnapshot, LocatorMatch)> {
        let timeout = self
            .timeout
            .or_else(|| crate::wait::resolved_wait_timeout(self.pane.configured_default_timeout()));
        let deadline = timeout.map(|timeout| Instant::now() + timeout);
        loop {
            let snapshot = self.pane.snapshot().await?;
            let matches = self.resolve(&snapshot).await?;
            match matches.len() {
                1 => {
                    let item = matches
                        .into_iter()
                        .next()
                        .expect("single match length guarantees one entry");
                    return Ok((snapshot, item));
                }
                0 => {}
                count => return Err(strict_locator_error(count, self.describe(), &snapshot)),
            }
            if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
                return Err(RmuxError::wait_timeout(WaitTimeoutError::new(
                    format!("strict locator {}", self.describe()),
                    timeout.expect("deadline implies timeout"),
                    snapshot,
                )));
            }
            sleep_until_next_poll(deadline, self.poll_interval).await;
        }
    }

    pub(crate) fn pane(&self) -> &Pane {
        &self.pane
    }

    fn combine(self, other: Self, combiner: LocatorCombiner) -> Self {
        let invalid_reason = if self.pane.target() != other.pane.target()
            || self.pane.endpoint() != other.pane.endpoint()
        {
            Some(format!(
                "locator combination requires the same pane endpoint and target, got {} and {}",
                self.pane.target().to_proto(),
                other.pane.target().to_proto()
            ))
        } else if let Some(reason) = self.invalid_reason.clone() {
            Some(reason)
        } else if let Some(reason) = other.invalid_reason.clone() {
            Some(reason)
        } else if !self.is_plain_combinable() || !other.is_plain_combinable() {
            Some(format!(
                "locator.{} only supports plain locators; apply first/last/nth, filters, timeout, or poll_interval after combining",
                combiner.name()
            ))
        } else {
            None
        };
        let query = match combiner {
            LocatorCombiner::Or => LocatorQuery::Or(Box::new(self.query), Box::new(other.query)),
            LocatorCombiner::And => LocatorQuery::And(Box::new(self.query), Box::new(other.query)),
        };
        Self {
            pane: self.pane,
            query,
            selection: LocatorSelection::Strict,
            filters: LocatorFilter::default(),
            timeout: None,
            poll_interval: crate::wait::TEXT_POLL_INTERVAL,
            invalid_reason,
        }
    }

    fn describe(&self) -> String {
        query::describe_query(&self.query)
    }

    fn is_plain_combinable(&self) -> bool {
        self.selection == LocatorSelection::Strict
            && self.filters == LocatorFilter::default()
            && self.timeout.is_none()
            && self.poll_interval == crate::wait::TEXT_POLL_INTERVAL
            && self.invalid_reason.is_none()
    }
}

#[derive(Debug, Clone, Copy)]
enum LocatorCombiner {
    Or,
    And,
}

impl LocatorCombiner {
    const fn name(self) -> &'static str {
        match self {
            Self::Or => "or",
            Self::And => "and",
        }
    }
}

impl Pane {
    /// Creates a terminal-native locator for visible literal or regex text.
    ///
    /// The locator evaluates against rendered pane snapshots; it does not
    /// model hidden controls or a DOM.
    pub fn get_by_text(&self, text: impl Into<LocatorText>) -> Locator {
        Locator::get_by_text(self.clone(), text)
    }

    /// Parses a small terminal locator selector.
    ///
    /// P3 supports `text=...`; other selectors are treated as literal text so
    /// callers do not accidentally opt into a fake CSS/DOM language.
    pub fn locator(&self, selector: impl AsRef<str>) -> Locator {
        Locator::parse(self.clone(), selector)
    }
}

/// Awaitable locator wait.
#[derive(Debug)]
#[must_use = "locator waits do nothing unless awaited"]
pub struct LocatorWait {
    locator: Locator,
    state: LocatorState,
}

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

    async fn run(self) -> Result<PaneSnapshot> {
        wait_for_locator_state(self.locator, self.state).await
    }
}

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

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

/// Assertion builder for one locator.
#[derive(Debug)]
#[must_use = "locator assertions do nothing unless awaited"]
pub struct LocatorExpectation {
    locator: Locator,
}

impl LocatorExpectation {
    /// Asserts that exactly one match is visible.
    pub fn to_be_visible(self) -> LocatorAssertion {
        LocatorAssertion::new(self.locator, LocatorAssertionKind::Visible)
    }

    /// Asserts that no match is visible.
    pub fn to_be_hidden(self) -> LocatorAssertion {
        LocatorAssertion::new(self.locator, LocatorAssertionKind::Hidden)
    }

    /// Asserts that one strict match contains `text`.
    pub fn to_contain_text(self, text: impl Into<String>) -> LocatorAssertion {
        LocatorAssertion::new(
            self.locator,
            LocatorAssertionKind::ContainsText(text.into()),
        )
    }

    /// Asserts that one strict match has exactly `text`.
    pub fn to_have_text(self, text: impl Into<String>) -> LocatorAssertion {
        LocatorAssertion::new(self.locator, LocatorAssertionKind::HasText(text.into()))
    }

    /// Asserts the current match count.
    pub fn to_have_count(self, count: usize) -> LocatorAssertion {
        LocatorAssertion::new(self.locator, LocatorAssertionKind::Count(count))
    }
}

/// Awaitable locator assertion.
#[derive(Debug)]
#[must_use = "locator assertions do nothing unless awaited"]
pub struct LocatorAssertion {
    locator: Locator,
    kind: LocatorAssertionKind,
}

#[derive(Debug)]
enum LocatorAssertionKind {
    Visible,
    Hidden,
    ContainsText(String),
    HasText(String),
    Count(usize),
}

impl LocatorAssertion {
    fn new(locator: Locator, kind: LocatorAssertionKind) -> Self {
        Self { locator, kind }
    }

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

    async fn run(self) -> Result<PaneSnapshot> {
        wait_for_assertion(self.locator, self.kind).await
    }
}

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

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

async fn wait_for_locator_state(locator: Locator, state: LocatorState) -> Result<PaneSnapshot> {
    wait_until(
        locator,
        move |matches, _snapshot| match state {
            LocatorState::Visible => !matches.is_empty(),
            LocatorState::Hidden => matches.is_empty(),
        },
        format!("locator to be {state:?}"),
    )
    .await
}

async fn wait_for_assertion(locator: Locator, kind: LocatorAssertionKind) -> Result<PaneSnapshot> {
    let description = assertion_description(&kind);
    let timeout = locator
        .timeout
        .or_else(|| crate::wait::resolved_wait_timeout(locator.pane.configured_default_timeout()));
    let deadline = timeout.map(|timeout| Instant::now() + timeout);
    loop {
        let snapshot = locator.pane.snapshot().await?;
        let matches = locator.resolve(&snapshot).await?;
        match assertion_outcome(&matches, &kind) {
            AssertionOutcome::Matched => return Ok(snapshot),
            AssertionOutcome::Continue => {}
            AssertionOutcome::StrictViolation => {
                return Err(strict_locator_error(
                    matches.len(),
                    locator.describe(),
                    &snapshot,
                ));
            }
        }
        if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
            return Err(RmuxError::wait_timeout(WaitTimeoutError::new(
                description,
                timeout.expect("deadline implies timeout"),
                snapshot,
            )));
        }
        sleep_until_next_poll(deadline, locator.poll_interval).await;
    }
}

async fn wait_until(
    locator: Locator,
    predicate: impl Fn(&[LocatorMatch], &PaneSnapshot) -> bool,
    description: String,
) -> Result<PaneSnapshot> {
    let timeout = locator
        .timeout
        .or_else(|| crate::wait::resolved_wait_timeout(locator.pane.configured_default_timeout()));
    let deadline = timeout.map(|timeout| Instant::now() + timeout);
    loop {
        let snapshot = locator.pane.snapshot().await?;
        let matches = locator.resolve(&snapshot).await?;
        if predicate(&matches, &snapshot) {
            return Ok(snapshot);
        }
        if deadline.is_some_and(|deadline| Instant::now() >= deadline) {
            return Err(RmuxError::wait_timeout(WaitTimeoutError::new(
                description,
                timeout.expect("deadline implies timeout"),
                snapshot,
            )));
        }
        sleep_until_next_poll(deadline, locator.poll_interval).await;
    }
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum AssertionOutcome {
    Matched,
    Continue,
    StrictViolation,
}

fn assertion_outcome(matches: &[LocatorMatch], kind: &LocatorAssertionKind) -> AssertionOutcome {
    match kind {
        LocatorAssertionKind::Visible => strict_unary_outcome(matches, |_| true),
        LocatorAssertionKind::Hidden => {
            if matches.is_empty() {
                AssertionOutcome::Matched
            } else {
                AssertionOutcome::Continue
            }
        }
        LocatorAssertionKind::ContainsText(text) => {
            strict_unary_outcome(matches, |item| item.text_match.text.contains(text))
        }
        LocatorAssertionKind::HasText(text) => {
            strict_unary_outcome(matches, |item| item.text_match.text == *text)
        }
        LocatorAssertionKind::Count(count) => {
            if matches.len() == *count {
                AssertionOutcome::Matched
            } else {
                AssertionOutcome::Continue
            }
        }
    }
}

fn strict_unary_outcome(
    matches: &[LocatorMatch],
    predicate: impl FnOnce(&LocatorMatch) -> bool,
) -> AssertionOutcome {
    match matches {
        [] => AssertionOutcome::Continue,
        [item] if predicate(item) => AssertionOutcome::Matched,
        [_] => AssertionOutcome::Continue,
        _ => AssertionOutcome::StrictViolation,
    }
}

fn assertion_description(kind: &LocatorAssertionKind) -> String {
    match kind {
        LocatorAssertionKind::Visible => "locator to be visible".to_owned(),
        LocatorAssertionKind::Hidden => "locator to be hidden".to_owned(),
        LocatorAssertionKind::ContainsText(text) => format!("locator to contain text `{text}`"),
        LocatorAssertionKind::HasText(text) => format!("locator to have text `{text}`"),
        LocatorAssertionKind::Count(count) => format!("locator to have count {count}"),
    }
}

fn strict_locator_error(count: usize, query: String, snapshot: &PaneSnapshot) -> RmuxError {
    RmuxError::protocol(rmux_proto::RmuxError::Server(format!(
        "strict locator violation: expected 1 match, found {count}; locator: {query}; last visible screen:\n{}",
        snapshot.visible_text()
    )))
}

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 {
        tokio::time::sleep(poll_interval.min(deadline - now)).await;
    }
}