marver 0.0.28

A TUI workspace for AI agent sessions: tmux orchestration, git worktree management, and repo control in one place.
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
//! Terminal emulation for tmux panes.

pub mod keys;

use std::collections::HashMap;

use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
use tui_term::widget::PseudoTerminal;

use crate::tmux;

pub use keys::{encode as encode_key, send_keys_command};

/// Lines of scrollback kept per pane.
pub const DEFAULT_SCROLLBACK: usize = 10_000;

/// Out-of-band state a program sets, which `vt100` reports through callbacks
/// rather than storing on the screen.
#[derive(Debug, Default, Clone)]
pub struct PaneState {
    title: Option<String>,
    bell: bool,
}

impl vt100::Callbacks for PaneState {
    fn set_window_title(&mut self, _: &mut vt100::Screen, title: &[u8]) {
        self.title = Some(String::from_utf8_lossy(title).into_owned());
    }

    fn audible_bell(&mut self, _: &mut vt100::Screen) {
        self.bell = true;
    }
}

/// One emulated pane.
pub struct PaneTerminal {
    parser: vt100::Parser<PaneState>,
}

impl PaneTerminal {
    /// `size` is `(cols, rows)`.
    pub fn new(size: (u16, u16), scrollback: usize) -> Self {
        let (cols, rows) = size;
        Self {
            parser: vt100::Parser::new_with_callbacks(rows, cols, scrollback, PaneState::default()),
        }
    }

    /// Feed raw bytes from a `%output` notification.
    pub fn feed(&mut self, bytes: &[u8]) {
        self.parser.process(bytes);
    }

    /// Resize the emulated screen. `size` is `(cols, rows)`.
    pub fn resize(&mut self, size: (u16, u16)) {
        let (cols, rows) = size;
        self.parser.screen_mut().set_size(rows, cols);
    }

    /// `(cols, rows)`.
    pub fn size(&self) -> (u16, u16) {
        let (rows, cols) = self.parser.screen().size();
        (cols, rows)
    }

    pub fn screen(&self) -> &vt100::Screen {
        self.parser.screen()
    }

    /// How far back from the live screen this pane is showing, in lines.
    pub fn scrollback(&self) -> usize {
        self.parser.screen().scrollback()
    }

    /// Move the view `delta` lines back through what the agent printed;
    /// negative comes forward again. Returns whether it actually moved, so a
    /// wheel notch at the end of the scrollback costs no redraw.
    pub fn scroll_by(&mut self, delta: isize) -> bool {
        let was = self.scrollback();
        let want = was.saturating_add_signed(delta);
        self.parser.screen_mut().set_scrollback(want);
        // Clamped by vt100 to what there is, so ask rather than assume.
        self.scrollback() != was
    }

    /// Jump back to the live screen.
    pub fn scroll_to_bottom(&mut self) {
        self.parser.screen_mut().set_scrollback(0);
    }

    /// Visible text, without styling. Primarily for assertions.
    pub fn contents(&self) -> String {
        self.parser.screen().contents()
    }

    /// Cursor as `(col, row)`.
    pub fn cursor(&self) -> (u16, u16) {
        let (row, col) = self.parser.screen().cursor_position();
        (col, row)
    }

    /// The title the program set, if it set one.
    pub fn title(&self) -> Option<&str> {
        self.parser.callbacks().title.as_deref()
    }

    /// Whether the pane rang the bell since this was last cleared.
    pub fn bell(&self) -> bool {
        self.parser.callbacks().bell
    }

    /// Consume a pending bell, returning whether there was one.
    pub fn take_bell(&mut self) -> bool {
        std::mem::replace(&mut self.parser.callbacks_mut().bell, false)
    }

    /// A ratatui widget rendering this pane's current screen.
    pub fn widget(&self) -> PseudoTerminal<'_, vt100::Screen> {
        PseudoTerminal::new(self.parser.screen())
    }
}

impl Widget for &PaneTerminal {
    fn render(self, area: Rect, buf: &mut Buffer) {
        self.widget().render(area, buf);
    }
}

/// Every pane marver is emulating, keyed by tmux pane id (`%0`, `%1`, ...).
pub struct Panes {
    panes: HashMap<String, PaneTerminal>,
    size: (u16, u16),
    scrollback: usize,
}

impl Panes {
    /// `size` is `(cols, rows)`, applied to panes as they appear.
    pub fn new(size: (u16, u16), scrollback: usize) -> Self {
        Self {
            panes: HashMap::new(),
            size,
            scrollback,
        }
    }

    /// Route a control-mode event to the pane it concerns.
    pub fn apply(&mut self, event: &tmux::Event) -> bool {
        match event {
            tmux::Event::Output { pane, data } => {
                let size = self.size;
                let scrollback = self.scrollback;
                self.panes
                    .entry(pane.clone())
                    .or_insert_with(|| PaneTerminal::new(size, scrollback))
                    .feed(data);
                true
            }
            _ => false,
        }
    }

    pub fn get(&self, pane: &str) -> Option<&PaneTerminal> {
        self.panes.get(pane)
    }

    pub fn get_mut(&mut self, pane: &str) -> Option<&mut PaneTerminal> {
        self.panes.get_mut(pane)
    }

    /// Start emulating a pane before it has produced output.
    pub fn ensure(&mut self, pane: &str) -> &mut PaneTerminal {
        let size = self.size;
        let scrollback = self.scrollback;
        self.panes
            .entry(pane.to_string())
            .or_insert_with(|| PaneTerminal::new(size, scrollback))
    }

    pub fn remove(&mut self, pane: &str) -> Option<PaneTerminal> {
        self.panes.remove(pane)
    }

    /// Pane ids, sorted so iteration order is stable between frames.
    pub fn ids(&self) -> Vec<&str> {
        let mut ids: Vec<&str> = self.panes.keys().map(String::as_str).collect();
        ids.sort();
        ids
    }

    pub fn len(&self) -> usize {
        self.panes.len()
    }

    pub fn is_empty(&self) -> bool {
        self.panes.is_empty()
    }

    /// Resize every pane, and any created later. `size` is `(cols, rows)`.
    pub fn resize(&mut self, size: (u16, u16)) {
        self.size = size;
        for pane in self.panes.values_mut() {
            pane.resize(size);
        }
    }

    /// `(cols, rows)` new panes are created at.
    pub fn size(&self) -> (u16, u16) {
        self.size
    }
}

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

    fn output(pane: &str, data: &[u8]) -> tmux::Event {
        tmux::Event::Output {
            pane: pane.to_string(),
            data: data.to_vec(),
        }
    }

    fn term() -> PaneTerminal {
        PaneTerminal::new((20, 5), 100)
    }

    /// A pane holding `count` numbered lines, more than fit on screen.
    fn scrolled(count: usize) -> PaneTerminal {
        let mut pane = term();
        for n in 0..count {
            pane.feed(format!("line {n}\r\n").as_bytes());
        }
        pane
    }

    #[test]
    fn a_pane_can_be_scrolled_back_through_what_it_printed() {
        // 10k lines were being kept and none of them could be reached.
        let mut pane = scrolled(30);
        assert_eq!(pane.scrollback(), 0, "starts on the live screen");
        assert!(pane.contents().contains("line 29"));

        assert!(pane.scroll_by(10));

        assert_eq!(pane.scrollback(), 10);
        assert!(pane.contents().contains("line 19"), "{}", pane.contents());
        assert!(!pane.contents().contains("line 29"));
    }

    #[test]
    fn scrolling_past_the_ends_stops_rather_than_wrapping() {
        let mut pane = scrolled(30);

        // Further back than there is history.
        pane.scroll_by(10_000);
        let all_the_way = pane.scrollback();
        assert!(all_the_way > 0);
        assert!(
            !pane.scroll_by(10),
            "already at the top, so nothing moved and no redraw is owed"
        );

        // And forward again past the live screen.
        pane.scroll_by(-10_000);
        assert_eq!(pane.scrollback(), 0);
        assert!(!pane.scroll_by(-10));
    }

    #[test]
    fn a_pane_can_be_brought_back_to_what_is_happening_now() {
        let mut pane = scrolled(30);
        pane.scroll_by(15);

        pane.scroll_to_bottom();

        assert_eq!(pane.scrollback(), 0);
        assert!(pane.contents().contains("line 29"));
    }

    /// The rendered text of a widget, one string per row.
    fn render(term: &PaneTerminal, cols: u16, rows: u16) -> Vec<String> {
        let area = Rect::new(0, 0, cols, rows);
        let mut buf = Buffer::empty(area);
        term.render(area, &mut buf);
        (0..rows)
            .map(|y| {
                (0..cols)
                    .map(|x| buf[(x, y)].symbol().to_string())
                    .collect::<String>()
                    .trim_end()
                    .to_string()
            })
            .collect()
    }

    #[test]
    fn plain_text_lands_on_the_screen() {
        let mut term = term();
        term.feed(b"hello");
        assert!(term.contents().contains("hello"));
    }

    #[test]
    fn dimensions_are_cols_by_rows_not_transposed() {
        // A non-square size is the only way this bug shows up.
        let term = PaneTerminal::new((80, 24), 0);
        assert_eq!(term.size(), (80, 24));
        let (rows, cols) = term.screen().size();
        assert_eq!((rows, cols), (24, 80), "vt100 takes rows first");
    }

    #[test]
    fn resizing_keeps_the_cols_rows_order() {
        let mut term = term();
        term.resize((100, 30));
        assert_eq!(term.size(), (100, 30));
    }

    #[test]
    fn escape_sequences_are_interpreted_not_printed() {
        let mut term = term();
        term.feed(b"\x1b[31mred\x1b[0m");
        let contents = term.contents();
        assert!(contents.contains("red"));
        assert!(
            !contents.contains('\x1b'),
            "the escape must be consumed, got {contents:?}"
        );
    }

    #[test]
    fn cursor_movement_is_tracked_as_col_row() {
        let mut term = term();
        // CUP is row;col, one-based.
        term.feed(b"\x1b[3;7H");
        assert_eq!(term.cursor(), (6, 2), "reported as (col, row), zero-based");
    }

    #[test]
    fn carriage_return_overwrites_rather_than_appends() {
        let mut term = term();
        term.feed(b"first\rsecond");
        let first_line = term.contents().lines().next().unwrap().to_string();
        assert_eq!(first_line, "second");
    }

    #[test]
    fn clearing_the_screen_works() {
        let mut term = term();
        term.feed(b"junk");
        term.feed(b"\x1b[2J\x1b[H");
        assert_eq!(term.contents().trim(), "");
    }

    #[test]
    fn bytes_split_across_feeds_still_parse() {
        // tmux delivers output in whatever chunks it likes, including one that
        // ends mid-escape-sequence.
        let mut term = term();
        term.feed(b"\x1b[");
        term.feed(b"31m");
        term.feed(b"split");
        assert!(term.contents().contains("split"));
        assert!(!term.contents().contains('['));
    }

    #[test]
    fn a_title_is_captured_when_set() {
        let mut term = term();
        assert_eq!(term.title(), None);
        term.feed(b"\x1b]2;my title\x07");
        assert_eq!(term.title(), Some("my title"));
    }

    #[test]
    fn renders_into_a_ratatui_buffer() {
        let mut term = PaneTerminal::new((10, 3), 0);
        term.feed(b"ab\r\ncd");
        // The cursor is painted as a block at its position, which is why row 1
        // is "cdâ–ˆ" and not "cd".
        assert_eq!(render(&term, 10, 3), ["ab", "cdâ–ˆ", ""]);
    }

    #[test]
    fn rendering_preserves_colour() {
        let mut term = PaneTerminal::new((10, 1), 0);
        term.feed(b"\x1b[31mR\x1b[0m");
        let area = Rect::new(0, 0, 10, 1);
        let mut buf = Buffer::empty(area);
        (&term).render(area, &mut buf);
        // SGR 31 arrives as palette entry 1, not the named Color::Red.
        assert_eq!(
            buf[(0, 0)].fg,
            ratatui::style::Color::Indexed(1),
            "styling must survive the widget"
        );
    }

    #[test]
    fn a_bell_is_recorded_and_consumable() {
        let mut term = term();
        assert!(!term.bell());
        term.feed(b"before\x07after");
        assert!(term.bell(), "BEL should be noticed");
        assert!(term.take_bell());
        assert!(!term.bell(), "taking the bell clears it");
        assert!(
            term.contents().contains("beforeafter"),
            "BEL must not print"
        );
    }

    #[test]
    fn output_events_reach_the_right_pane() {
        let mut panes = Panes::new((20, 5), 100);
        panes.apply(&output("%0", b"zero"));
        panes.apply(&output("%1", b"one"));

        assert!(panes.get("%0").unwrap().contents().contains("zero"));
        assert!(panes.get("%1").unwrap().contents().contains("one"));
        assert!(
            !panes.get("%0").unwrap().contents().contains("one"),
            "panes must not bleed into each other"
        );
    }

    #[test]
    fn a_pane_appears_on_its_first_output() {
        let mut panes = Panes::new((20, 5), 100);
        assert!(panes.is_empty());
        // Waiting for an introduction would drop a shell's opening prompt.
        assert!(panes.apply(&output("%7", b"hi")));
        assert_eq!(panes.len(), 1);
        assert!(panes.get("%7").unwrap().contents().contains("hi"));
    }

    #[test]
    fn non_output_events_change_nothing() {
        let mut panes = Panes::new((20, 5), 100);
        assert!(!panes.apply(&tmux::Event::SessionsChanged));
        assert!(!panes.apply(&tmux::Event::Exit { reason: None }));
        assert!(panes.is_empty());
    }

    #[test]
    fn successive_output_accumulates_in_one_pane() {
        let mut panes = Panes::new((20, 5), 100);
        for byte in b"abc" {
            panes.apply(&output("%0", &[*byte]));
        }
        assert_eq!(panes.len(), 1);
        assert!(panes.get("%0").unwrap().contents().contains("abc"));
    }

    #[test]
    fn resize_applies_to_existing_and_future_panes() {
        let mut panes = Panes::new((20, 5), 100);
        panes.apply(&output("%0", b"x"));
        panes.resize((80, 24));

        assert_eq!(panes.get("%0").unwrap().size(), (80, 24));
        panes.apply(&output("%1", b"y"));
        assert_eq!(
            panes.get("%1").unwrap().size(),
            (80, 24),
            "a pane created after the resize must use the new size"
        );
    }

    #[test]
    fn panes_can_be_created_early_and_removed() {
        let mut panes = Panes::new((20, 5), 100);
        panes.ensure("%2").feed(b"early");
        assert!(panes.get("%2").unwrap().contents().contains("early"));
        assert!(panes.remove("%2").is_some());
        assert!(panes.get("%2").is_none());
        assert!(panes.remove("%2").is_none());
    }

    /// The whole pipeline against a real tmux server: a program writes to a
    /// pane, tmux reports it over control mode, the decoder unescapes it, the
    /// emulator interprets it, and the widget renders it.
    #[test]
    fn output_reaches_the_rendered_screen_end_to_end() {
        use crate::tmux::testing::TestServer;
        use crate::tmux::{ControlClient, DEFAULT_SIZE};
        use std::time::Duration;

        let server = TestServer::new();
        let dir = tempfile::TempDir::new().unwrap();
        server
            .tmux
            .new_session("e2e", dir.path(), DEFAULT_SIZE)
            .unwrap();
        let pane = server.tmux.list_panes("e2e").unwrap().remove(0);

        let mut client = ControlClient::attach(&server.tmux, "e2e", DEFAULT_SIZE).unwrap();
        let _ = client.wait_for(Duration::from_secs(10), |e| {
            matches!(e, tmux::Event::SessionChanged { .. })
        });

        client
            .send_command(&format!("send-keys -t {pane} -l 'printf MARVERPIPE'"))
            .unwrap();
        client
            .send_command(&format!("send-keys -t {pane} Enter"))
            .unwrap();

        let mut panes = Panes::new(DEFAULT_SIZE, 100);
        let deadline = std::time::Instant::now() + Duration::from_secs(10);
        let mut rendered = String::new();
        while std::time::Instant::now() < deadline {
            let Ok(event) = client.next_event(Duration::from_millis(500)) else {
                continue;
            };
            panes.apply(&event);
            if let Some(term) = panes.get(&pane) {
                rendered = term.contents();
                if rendered.contains("MARVERPIPE") {
                    break;
                }
            }
        }

        assert!(
            rendered.contains("MARVERPIPE"),
            "screen never showed the output; got {rendered:?}"
        );
        // The load-bearing assertion.
        assert!(
            !rendered.contains("\\033") && !rendered.contains("\\015"),
            "octal escapes were never decoded; got {rendered:?}"
        );
        assert!(
            !rendered.contains('\x1b'),
            "decoded escapes must be interpreted by the emulator, not displayed"
        );
    }

    #[test]
    fn pane_ids_come_back_in_a_stable_order() {
        let mut panes = Panes::new((20, 5), 100);
        for id in ["%2", "%0", "%10", "%1"] {
            panes.apply(&output(id, b"x"));
        }
        assert_eq!(panes.ids(), ["%0", "%1", "%10", "%2"]);
    }
}