retach 0.10.0

Persistent terminal sessions with native scrollback passthrough
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
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
//! VTE-based terminal screen emulator with scrollback history.
//! Processes escape sequences and maintains a grid of styled cells.

pub(crate) mod cell;
pub(crate) mod grid;
pub(crate) mod performer;
pub(crate) mod render;
pub(crate) mod style;
pub mod traits;

use std::collections::VecDeque;
use vte::Parser;

pub use cell::{Cell, Grapheme, Row};
use grid::Grid;
pub use grid::{sanitize_dimensions, CursorShape, TerminalSize, MAX_DIMENSION};
pub use grid::{ActiveCharset, Charset, MouseEncoding, MouseModes, TerminalModes};
use performer::ScreenPerformer;
pub use render::{AnsiRenderer, DirtyTracker};
pub use style::{Color, Style, StyleId, UnderlineStyle};
pub use traits::TerminalEmulator;

/// Full cursor state saved by DECSC (ESC 7) / CSI s / mode 1048.
#[derive(Copy, Clone)]
pub(super) struct SavedCursor {
    pub(super) x: u16,
    pub(super) y: u16,
    pub(super) style: Style,
    pub(super) g0_charset: grid::Charset,
    pub(super) g1_charset: grid::Charset,
    pub(super) active_charset: grid::ActiveCharset,
    pub(super) autowrap_mode: bool,
    pub(super) origin_mode: bool,
    /// VT220 "last column flag": deferred autowrap is pending.
    pub(super) wrap_pending: bool,
}

/// Maximum responses/passthrough entries buffered per process() call.
/// 1024 is a safety cap — normal output produces 0-2 responses (DA, DSR).
/// Pathological PTY output (e.g. 1000 DSR queries in one write) is truncated.
const MAX_PENDING: usize = 1024;

/// Notifications (OSC 9/777) queued for replay on reconnect. 50 prevents
/// a disconnected session from accumulating megabytes of stale notifications
/// while still preserving recent ones for the reconnecting client.
const MAX_QUEUED_NOTIFICATIONS: usize = 50;

/// Non-grid state that the performer needs mutable access to.
/// Grouped to reduce borrow count in ScreenPerformer.
pub(super) struct ScreenState {
    pub(super) current_style: Style,
    pub(super) in_alt_screen: bool,
    pub(super) saved_grid: Option<grid::SavedGrid>,
    pub(super) saved_cursor_state: Option<SavedCursor>,
    pub(super) saved_modes: Option<grid::TerminalModes>,
    /// Scroll region saved when entering alt screen; restored on exit.
    pub(super) saved_scroll_region: Option<(u16, u16)>,
    pub(super) pending_responses: Vec<Vec<u8>>,
    pub(super) pending_passthrough: Vec<Vec<u8>>,
    pub(super) queued_notifications: VecDeque<Vec<u8>>,
    pub(super) title: String,
    pub(super) title_stack: Vec<String>,
    pub(super) last_printed_char: char,
}

impl ScreenState {
    /// Push a PTY response (DA, DSR) with bounded growth.
    pub fn push_response(&mut self, data: Vec<u8>) {
        if self.pending_responses.len() < MAX_PENDING {
            self.pending_responses.push(data);
        } else {
            #[cfg(feature = "tracing")]
            tracing::debug!("pending_responses full, dropping response");
        }
    }

    /// Push a passthrough sequence (bell, OSC, etc.) with bounded growth.
    pub fn push_passthrough(&mut self, data: Vec<u8>) {
        if self.pending_passthrough.len() < MAX_PENDING {
            self.pending_passthrough.push(data);
        }
    }

    /// Queue a text notification (OSC 9/777/99) for delivery or replay.
    /// Always enqueues; the consumer (relay or reconnect handler) drains.
    /// Oldest notifications are dropped when the queue is full.
    pub fn push_notification(&mut self, data: Vec<u8>) {
        if self.queued_notifications.len() >= MAX_QUEUED_NOTIFICATIONS {
            self.queued_notifications.pop_front();
        }
        self.queued_notifications.push_back(data);
    }
}

impl Default for ScreenState {
    fn default() -> Self {
        Self {
            current_style: Style::default(),
            in_alt_screen: false,
            saved_grid: None,
            saved_cursor_state: None,
            saved_modes: None,
            saved_scroll_region: None,
            pending_responses: Vec::new(),
            pending_passthrough: Vec::new(),
            queued_notifications: VecDeque::new(),
            title: String::new(),
            title_stack: Vec::new(),
            last_printed_char: ' ',
        }
    }
}

/// Terminal screen emulator that processes VTE escape sequences into a cell grid.
///
/// `Screen` is `Send + Sync`. The intended multi-thread sharing model is
/// `Arc<Mutex<Screen>>`: one writer feeds PTY bytes via
/// [`process`](Screen::process) while other threads lock to render or
/// inspect state.
pub struct Screen {
    pub(super) grid: Grid,
    pub(super) state: ScreenState,
    parser: Parser,
}

impl Screen {
    /// Create a screen with the given dimensions and scrollback line limit.
    pub fn new(cols: u16, rows: u16, scrollback_limit: usize) -> Self {
        Self {
            grid: Grid::new(cols, rows, scrollback_limit),
            state: ScreenState::default(),
            parser: Parser::new(),
        }
    }

    /// Borrow the underlying grid (read-only).
    #[cfg(test)]
    pub(crate) fn grid(&self) -> &Grid {
        &self.grid
    }

    /// Current SGR style.
    #[cfg(test)]
    pub(crate) fn current_style(&self) -> style::Style {
        self.state.current_style
    }

    /// Number of visible rows in the grid.
    pub fn rows(&self) -> u16 {
        self.grid.rows()
    }

    /// Whether the screen is currently in alternate screen mode.
    pub fn in_alt_screen(&self) -> bool {
        self.state.in_alt_screen
    }

    /// Feed raw bytes through the VTE parser, updating the grid and state.
    pub fn process(&mut self, bytes: &[u8]) {
        let mut performer = ScreenPerformer {
            grid: &mut self.grid,
            state: &mut self.state,
        };
        for &byte in bytes {
            self.parser.advance(&mut performer, byte);
        }
    }

    /// Take pending responses that need to be written back to PTY stdin
    pub fn take_responses(&mut self) -> Vec<Vec<u8>> {
        std::mem::take(&mut self.state.pending_responses)
    }

    /// Take pending OSC passthrough sequences to forward to the outer terminal.
    pub fn take_passthrough(&mut self) -> Vec<Vec<u8>> {
        std::mem::take(&mut self.state.pending_passthrough)
    }

    /// Drain queued desktop notifications (OSC 9/777/99).
    pub fn take_queued_notifications(&mut self) -> Vec<Vec<u8>> {
        self.state.queued_notifications.drain(..).collect()
    }

    /// Drain and return scrollback rows added since the last call (advances
    /// the pending cursor).
    pub fn take_pending_scrollback(&mut self) -> Vec<Row> {
        let start = self.grid.pending_start();
        let count = self.grid.pending_scrollback_count();
        self.grid.set_pending_start(self.grid.scrollback_len());
        self.grid
            .scrollback_rows()
            .skip(start)
            .take(count)
            .cloned()
            .collect()
    }

    /// Advance the pending-scrollback cursor to the end without materializing
    /// rows. Equivalent to discarding `take_pending_scrollback()`'s result.
    pub fn discard_pending_scrollback(&mut self) {
        self.grid.set_pending_start(self.grid.scrollback_len());
    }

    /// Return all accumulated scrollback lines as rendered ANSI bytes.
    pub fn get_history(&self) -> Vec<Vec<u8>> {
        self.grid
            .scrollback_rows()
            .map(|row| render::render_line(row, self.grid.style_table()))
            .collect()
    }

    /// Look up the resolved style for a visible cell. Test convenience.
    #[cfg(test)]
    pub(crate) fn cell_style(&self, row: usize, col: usize) -> style::Style {
        self.grid
            .style_table()
            .get(self.grid.visible_row(row)[col].style_id)
    }

    /// Character in a visible cell. Test convenience.
    #[cfg(test)]
    pub(crate) fn cell_char(&self, row: usize, col: usize) -> char {
        self.grid.visible_row(row)[col].c
    }

    /// Display width of a visible cell. Test convenience.
    #[cfg(test)]
    pub(crate) fn cell_width(&self, row: usize, col: usize) -> u8 {
        self.grid.visible_row(row)[col].width
    }

    /// Compact the style table by scanning all cells for live style IDs
    /// and reclaiming unused slots.
    #[cfg(test)]
    pub fn compact_styles(&mut self) {
        compact_styles(&mut self.grid, self.state.saved_grid.as_ref());
    }

    /// Resize the grid to new dimensions, restoring scrollback lines on vertical expand.
    ///
    /// Dimensions are clamped to `1..=MAX_DIMENSION` (4096) on both axes;
    /// see [`sanitize_dimensions`].
    pub fn resize(&mut self, cols: u16, rows: u16) {
        let old_rows = self.grid.rows();

        // Restore scrollback lines when growing vertically (not in alt screen).
        // With unified buffer, scrollback rows are already in cells — just move the boundary.
        if !self.state.in_alt_screen && rows > old_rows {
            let grow = (rows - old_rows) as usize;
            let restore_count = grow.min(self.grid.scrollback_len());
            self.grid.restore_scrollback(restore_count);
            self.grid.set_cursor_y_unclamped(
                self.grid
                    .cursor_y()
                    .saturating_add(u16::try_from(restore_count).unwrap_or(u16::MAX)),
            );
        }

        self.grid.resize(cols, rows);
    }

    /// Number of columns in the terminal grid.
    pub fn cols(&self) -> u16 {
        self.grid.cols()
    }

    /// The visible row at `y` (0-based).
    ///
    /// # Panics
    ///
    /// Panics if `y >= rows()`.
    pub fn visible_row(&self, y: u16) -> &cell::Row {
        self.grid.visible_row(y as usize)
    }

    /// Iterate over visible rows (the current screen content).
    ///
    /// Unboxed, allocation-free counterpart of
    /// [`traits::TerminalEmulator::visible_rows`].
    pub fn visible_rows(&self) -> impl Iterator<Item = &cell::Row> {
        self.grid.visible_rows()
    }

    /// The scrollback row at `i` (0-based, oldest first).
    ///
    /// # Panics
    ///
    /// Panics if `i >= scrollback_len()`.
    pub fn scrollback_row(&self, i: usize) -> &cell::Row {
        self.grid.scrollback_row(i)
    }

    /// Iterate over scrollback rows, oldest first (allocation-free).
    pub fn scrollback_rows(&self) -> impl Iterator<Item = &cell::Row> {
        self.grid.scrollback_rows()
    }

    /// Number of scrollback rows currently stored.
    pub fn scrollback_len(&self) -> usize {
        self.grid.scrollback_len()
    }

    /// Current cursor position as `(x, y)`, both 0-based.
    pub fn cursor_position(&self) -> (u16, u16) {
        self.grid.cursor_pos()
    }

    /// Whether the cursor is currently visible (DECTCEM).
    pub fn cursor_visible(&self) -> bool {
        self.grid.cursor_visible()
    }

    /// DECSCUSR cursor shape.
    pub fn cursor_shape(&self) -> grid::CursorShape {
        self.grid.modes().cursor_shape
    }

    /// Resolve a cell's interned style ID to a full [`style::Style`].
    pub fn resolve_style(&self, id: style::StyleId) -> style::Style {
        self.grid.style_table().get(id)
    }

    /// Current scroll region as `(top, bottom)`, both 0-based.
    pub fn scroll_region(&self) -> (u16, u16) {
        self.grid.scroll_region()
    }

    /// Terminal mode flags (autowrap, mouse, charset, etc.).
    pub fn modes(&self) -> &grid::TerminalModes {
        self.grid.modes()
    }

    /// Current window title (set by OSC 0/2).
    pub fn title(&self) -> &str {
        &self.state.title
    }
}

impl traits::TerminalEmulator for Screen {
    fn process(&mut self, bytes: &[u8]) {
        self.process(bytes);
    }

    fn resize(&mut self, cols: u16, rows: u16) {
        self.resize(cols, rows);
    }

    fn cols(&self) -> u16 {
        Screen::cols(self)
    }

    fn rows(&self) -> u16 {
        self.grid.rows()
    }

    fn visible_row(&self, y: u16) -> &cell::Row {
        Screen::visible_row(self, y)
    }

    fn scrollback_row(&self, i: usize) -> &cell::Row {
        Screen::scrollback_row(self, i)
    }

    fn scrollback_len(&self) -> usize {
        Screen::scrollback_len(self)
    }

    fn cursor_position(&self) -> (u16, u16) {
        Screen::cursor_position(self)
    }

    fn cursor_visible(&self) -> bool {
        Screen::cursor_visible(self)
    }

    fn resolve_style(&self, id: style::StyleId) -> style::Style {
        Screen::resolve_style(self, id)
    }

    fn in_alt_screen(&self) -> bool {
        Screen::in_alt_screen(self)
    }

    fn take_responses(&mut self) -> Vec<Vec<u8>> {
        Screen::take_responses(self)
    }

    fn title(&self) -> &str {
        Screen::title(self)
    }

    fn cursor_shape(&self) -> grid::CursorShape {
        Screen::cursor_shape(self)
    }

    fn scroll_region(&self) -> (u16, u16) {
        Screen::scroll_region(self)
    }

    fn modes(&self) -> &grid::TerminalModes {
        Screen::modes(self)
    }

    fn take_passthrough(&mut self) -> Vec<Vec<u8>> {
        Screen::take_passthrough(self)
    }

    fn take_queued_notifications(&mut self) -> Vec<Vec<u8>> {
        Screen::take_queued_notifications(self)
    }

    fn take_pending_scrollback(&mut self) -> Vec<cell::Row> {
        Screen::take_pending_scrollback(self)
    }
}

/// Scan all cells in the grid (scrollback + visible) and saved_grid,
/// then reclaim style table slots not referenced by any cell.
pub(crate) fn compact_styles(grid: &mut Grid, saved_grid: Option<&grid::SavedGrid>) {
    let cap = grid.style_table().capacity();
    if cap <= 1 {
        return;
    }

    let mut live = vec![false; cap];
    live[0] = true; // default style is always live

    for row in grid.scrollback_rows().chain(grid.visible_rows()) {
        for cell in row.iter() {
            let id = cell.style_id.index();
            if id < cap {
                live[id] = true;
            }
        }
    }

    if let Some(saved) = saved_grid {
        for row in saved.visible_rows() {
            for cell in row.iter() {
                let id = cell.style_id.index();
                if id < cap {
                    live[id] = true;
                }
            }
        }
    }

    grid.style_table_mut().reclaim(&live);
}

#[cfg(test)]
mod tests_traits {
    use super::traits::TerminalEmulator;
    use super::*;

    #[test]
    fn screen_implements_terminal_emulator() {
        let mut screen = Screen::new(80, 24, 100);

        // Test process + visible_rows
        TerminalEmulator::process(&mut screen, b"Hello");
        let rows: Vec<&cell::Row> = TerminalEmulator::visible_rows(&screen).collect();
        assert_eq!(rows.len(), 24);
        assert_eq!(rows[0][0].c, 'H');
        assert_eq!(rows[0][4].c, 'o');

        // Test dimensions
        assert_eq!(TerminalEmulator::cols(&screen), 80);
        assert_eq!(TerminalEmulator::rows(&screen), 24);

        // Test cursor
        assert_eq!(TerminalEmulator::cursor_position(&screen), (5, 0));
        assert!(TerminalEmulator::cursor_visible(&screen));

        // Test resolve_style
        let style = TerminalEmulator::resolve_style(&screen, rows[0][0].style_id);
        assert!(style.is_default());

        // Test alt screen
        assert!(!TerminalEmulator::in_alt_screen(&screen));

        // Test title
        assert_eq!(TerminalEmulator::title(&screen), "");

        // Test scrollback
        assert_eq!(TerminalEmulator::scrollback_len(&screen), 0);
        assert_eq!(TerminalEmulator::scrollback_rows(&screen).count(), 0);

        // Test take_responses
        assert!(TerminalEmulator::take_responses(&mut screen).is_empty());
    }

    #[test]
    fn screen_as_dyn_terminal_emulator() {
        let mut screen = Screen::new(40, 10, 50);
        let emu: &mut dyn TerminalEmulator = &mut screen;
        emu.process(b"test");
        assert_eq!(emu.cols(), 40);
        assert_eq!(emu.rows(), 10);
        let rows: Vec<_> = emu.visible_rows().collect();
        assert_eq!(rows[0][0].c, 't');
    }

    #[test]
    fn trait_index_access_matches_iterators() {
        let mut screen = Screen::new(10, 3, 100);
        screen.process(b"a\r\nb\r\nc\r\nd\r\ne"); // scrolls: "a","b" into scrollback
        let emu: &dyn TerminalEmulator = &screen;

        let via_iter: Vec<String> = emu.visible_rows().map(|r| r.text()).collect();
        let via_index: Vec<String> = (0..emu.rows())
            .map(|y| emu.visible_row(y).text())
            .collect();
        assert_eq!(via_iter, via_index);

        assert!(emu.scrollback_len() > 0);
        let sb_iter: Vec<String> = emu.scrollback_rows().map(|r| r.text()).collect();
        let sb_index: Vec<String> = (0..emu.scrollback_len())
            .map(|i| emu.scrollback_row(i).text())
            .collect();
        assert_eq!(sb_iter, sb_index);
        assert_eq!(sb_index[0], "a"); // oldest first
    }

    #[test]
    fn ansi_renderer_clears_title_when_empty() {
        // Bug 3: AnsiRenderer should emit a title-clearing OSC when the
        // title was previously set and is now empty.
        use super::render::AnsiRenderer;

        let mut screen = Screen::new(10, 3, 0);
        // Set a title
        screen.process(b"\x1b]2;Hello\x07");
        assert_eq!(screen.title(), "Hello");

        let mut renderer = AnsiRenderer::new();
        // First render — should contain the title
        let output = renderer.render(&screen, true);
        let text = String::from_utf8_lossy(&output);
        assert!(
            text.contains("\x1b]2;Hello\x07"),
            "first render should contain title OSC"
        );

        // Clear the title
        screen.process(b"\x1b]2;\x07");
        assert_eq!(screen.title(), "");

        // Second render — should emit an empty-title OSC to clear it
        let output = renderer.render(&screen, true);
        let text = String::from_utf8_lossy(&output);
        assert!(
            text.contains("\x1b]2;\x07"),
            "render should emit title-clearing OSC when title becomes empty, \
             got: {text}"
        );
    }
}

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

    /// Strip ANSI escape sequences, returning only printable text.
    pub fn strip_ansi(bytes: &[u8]) -> String {
        let s = String::from_utf8_lossy(bytes);
        let mut out = String::new();
        let mut in_esc = false;
        for ch in s.chars() {
            if in_esc {
                if ch.is_ascii_alphabetic() {
                    in_esc = false;
                }
                continue;
            }
            if ch == '\x1b' {
                in_esc = true;
                continue;
            }
            if ch >= ' ' {
                out.push(ch);
            }
        }
        out.trim_end().to_string()
    }

    /// Collect visible grid rows as trimmed strings.
    pub fn screen_lines(screen: &Screen) -> Vec<String> {
        screen
            .grid
            .visible_rows()
            .map(|row| {
                let s: String = row.iter().map(|c| c.c).collect();
                s.trim_end().to_string()
            })
            .collect()
    }

    /// Collect scrollback history as trimmed text strings (ANSI stripped).
    pub fn history_texts(screen: &Screen) -> Vec<String> {
        screen.get_history().iter().map(|b| strip_ansi(b)).collect()
    }
}

#[cfg(test)]
mod history_boundary_tests;
#[cfg(test)]
mod tests_large_updates;
#[cfg(test)]
mod tests_live_scrollback;
#[cfg(test)]
mod tests_progress_bar_scrollback;
#[cfg(test)]
mod tests_reattach;
#[cfg(test)]
mod tests_reconnect_scrollback;
#[cfg(test)]
mod tests_resize;
#[cfg(test)]
mod tests_screen;