bohay 0.6.1

Next-Gen Agents multiplexer
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
//! `alacritty_terminal` implementation of `VtEngine`. Pure Rust — no Zig, no FFI.

use std::sync::mpsc::Sender;
use std::sync::{Arc, Mutex};

use alacritty_terminal::event::{Event, EventListener};
use alacritty_terminal::grid::{Dimensions, Scroll};
use alacritty_terminal::term::cell::Flags;
use alacritty_terminal::term::{Config, Term, TermMode};
use alacritty_terminal::vte::ansi::{Color as VtColor, Processor};

use ratatui::style::{Color, Modifier};

use super::{Cursor, RenderCell, VtEngine};

type TitleSlot = Arc<Mutex<Option<String>>>;

/// Receives terminal-generated responses (cursor reports, device attributes,
/// etc.) and forwards them back to the child via the shared write channel.
/// Also captures the window title (OSC 0/2) for agent detection.
#[derive(Clone)]
pub struct EventProxy {
    tx: Sender<Vec<u8>>,
    title: TitleSlot,
}

impl EventListener for EventProxy {
    fn send_event(&self, event: Event) {
        match event {
            Event::PtyWrite(text) => {
                let _ = self.tx.send(text.into_bytes());
            }
            Event::Title(t) => {
                if let Ok(mut g) = self.title.lock() {
                    *g = Some(t);
                }
            }
            Event::ResetTitle => {
                if let Ok(mut g) = self.title.lock() {
                    *g = None;
                }
            }
            _ => {}
        }
    }
}

/// A size descriptor for `Term::new` / `Term::resize`.
#[derive(Clone, Copy)]
struct Dims {
    cols: usize,
    rows: usize,
}

impl Dimensions for Dims {
    fn total_lines(&self) -> usize {
        self.rows
    }
    fn screen_lines(&self) -> usize {
        self.rows
    }
    fn columns(&self) -> usize {
        self.cols
    }
}

pub struct AlacrittyEngine {
    term: Term<EventProxy>,
    parser: Processor,
    title: TitleSlot,
}

impl AlacrittyEngine {
    pub fn new(cols: u16, rows: u16, resp_tx: Sender<Vec<u8>>) -> Self {
        let dims = Dims {
            cols: cols.max(1) as usize,
            rows: rows.max(1) as usize,
        };
        let title: TitleSlot = Arc::new(Mutex::new(None));
        let proxy = EventProxy {
            tx: resp_tx,
            title: title.clone(),
        };
        let term = Term::new(Config::default(), &dims, proxy);
        AlacrittyEngine {
            term,
            parser: Processor::new(),
            title,
        }
    }
}

impl VtEngine for AlacrittyEngine {
    fn advance(&mut self, bytes: &[u8]) {
        self.parser.advance(&mut self.term, bytes);
    }

    fn resize(&mut self, cols: u16, rows: u16) {
        self.term.resize(Dims {
            cols: cols.max(1) as usize,
            rows: rows.max(1) as usize,
        });
    }

    fn cursor(&self) -> Cursor {
        let p = self.term.grid().cursor.point;
        Cursor {
            x: p.column.0 as u16,
            y: p.line.0.max(0) as u16,
            // Scrolled into history: the live cursor isn't in view, so hide it
            // rather than draw it over an old line.
            visible: self.term.mode().contains(TermMode::SHOW_CURSOR)
                && self.term.grid().display_offset() == 0,
        }
    }

    fn for_each_cell(&self, f: &mut dyn FnMut(u16, u16, RenderCell)) {
        for indexed in self.term.grid().display_iter() {
            let row = indexed.point.line.0;
            if row < 0 {
                continue;
            }
            let cell = indexed.cell;
            if cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
                continue;
            }
            f(
                row as u16,
                indexed.point.column.0 as u16,
                RenderCell {
                    c: cell.c,
                    fg: map_color(cell.fg),
                    bg: map_color(cell.bg),
                    mods: map_flags(cell.flags),
                },
            );
        }
    }

    fn detection_text(&self, n: u16) -> String {
        let grid = self.term.grid();
        let rows = grid.screen_lines();
        let mut lines = vec![String::new(); rows];
        for indexed in grid.display_iter() {
            let r = indexed.point.line.0;
            if r < 0 || r as usize >= rows {
                continue;
            }
            if indexed.cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
                continue;
            }
            let c = indexed.cell.c;
            lines[r as usize].push(if c == '\0' { ' ' } else { c });
        }
        let start = rows.saturating_sub(n as usize);
        lines[start..]
            .iter()
            .map(|l| l.trim_end())
            .collect::<Vec<_>>()
            .join("\n")
    }

    fn visible_rows(&self) -> Vec<String> {
        let grid = self.term.grid();
        let rows = grid.screen_lines();
        let mut lines = vec![String::new(); rows];
        for indexed in grid.display_iter() {
            let r = indexed.point.line.0;
            if r < 0 || r as usize >= rows {
                continue;
            }
            if indexed.cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
                continue;
            }
            let c = indexed.cell.c;
            lines[r as usize].push(if c == '\0' { ' ' } else { c });
        }
        lines
    }

    fn title(&self) -> Option<String> {
        self.title.lock().ok().and_then(|g| g.clone())
    }

    fn scroll(&mut self, delta: i32) {
        if !self.term.mode().contains(TermMode::ALT_SCREEN) {
            self.term.scroll_display(Scroll::Delta(delta));
        }
    }

    fn scroll_to_top(&mut self) {
        if !self.term.mode().contains(TermMode::ALT_SCREEN) {
            self.term.scroll_display(Scroll::Top);
        }
    }

    fn scroll_to_bottom(&mut self) {
        self.term.scroll_display(Scroll::Bottom);
    }

    fn scroll_offset(&self) -> usize {
        self.term.grid().display_offset()
    }

    fn history_len(&self) -> usize {
        // `Dimensions::history_size` = total_lines − screen_lines (the scrollback).
        self.term.grid().history_size()
    }

    fn alt_screen(&self) -> bool {
        self.term.mode().contains(TermMode::ALT_SCREEN)
    }

    fn mouse_report(&self) -> bool {
        // MOUSE_MODE = REPORT_CLICK | MOUSE_MOTION | MOUSE_DRAG.
        self.term.mode().intersects(TermMode::MOUSE_MODE)
    }

    fn sgr_mouse(&self) -> bool {
        self.term.mode().contains(TermMode::SGR_MOUSE)
    }

    fn snapshot_ansi(&self) -> String {
        let grid = self.term.grid();
        let rows = grid.screen_lines();
        let cols = grid.columns();
        if rows == 0 || cols == 0 {
            return String::new();
        }
        let default = (' ', Color::Reset, Color::Reset, Modifier::empty());
        let mut cells = vec![vec![default; cols]; rows];
        for indexed in grid.display_iter() {
            let r = indexed.point.line.0;
            let c = indexed.point.column.0;
            if r < 0 || r as usize >= rows || c >= cols {
                continue;
            }
            let cell = indexed.cell;
            if cell.flags.contains(Flags::WIDE_CHAR_SPACER) {
                continue;
            }
            let ch = if cell.c == '\0' { ' ' } else { cell.c };
            cells[r as usize][c] = (
                ch,
                map_color(cell.fg),
                map_color(cell.bg),
                map_flags(cell.flags),
            );
        }

        // Trim trailing blank rows so replaying into any-size engine doesn't
        // scroll the content off-screen.
        let last_row = match cells
            .iter()
            .rposition(|row| row.iter().any(|c| *c != default))
        {
            Some(r) => r,
            None => return String::from("\x1b[2J\x1b[H"),
        };
        let mut out = String::from("\x1b[2J\x1b[H");
        for (ri, row) in cells.iter().take(last_row + 1).enumerate() {
            let last = row.iter().rposition(|c| *c != default).map_or(0, |i| i + 1);
            let mut cur = (Color::Reset, Color::Reset, Modifier::empty());
            for (ch, fg, bg, m) in &row[..last] {
                if (*fg, *bg, *m) != cur {
                    out.push_str(&sgr(*fg, *bg, *m));
                    cur = (*fg, *bg, *m);
                }
                out.push(*ch);
            }
            out.push_str("\x1b[0m");
            if ri < last_row {
                out.push_str("\r\n");
            }
        }
        out
    }
}

fn sgr(fg: Color, bg: Color, m: Modifier) -> String {
    let mut s = String::from("\x1b[0");
    if m.contains(Modifier::BOLD) {
        s.push_str(";1");
    }
    if m.contains(Modifier::DIM) {
        s.push_str(";2");
    }
    if m.contains(Modifier::ITALIC) {
        s.push_str(";3");
    }
    if m.contains(Modifier::UNDERLINED) {
        s.push_str(";4");
    }
    if m.contains(Modifier::REVERSED) {
        s.push_str(";7");
    }
    push_color(&mut s, fg, 38);
    push_color(&mut s, bg, 48);
    s.push('m');
    s
}

fn push_color(s: &mut String, c: Color, base: u8) {
    match c {
        Color::Indexed(i) => s.push_str(&format!(";{base};5;{i}")),
        Color::Rgb(r, g, b) => s.push_str(&format!(";{base};2;{r};{g};{b}")),
        _ => {}
    }
}

fn map_color(c: VtColor) -> Color {
    match c {
        VtColor::Spec(rgb) => Color::Rgb(rgb.r, rgb.g, rgb.b),
        VtColor::Indexed(i) => Color::Indexed(i),
        VtColor::Named(n) => {
            // The first 16 named colors map to the ANSI palette; everything
            // else (Foreground/Background/Cursor/Dim*) resolves to the host
            // terminal's default so its real background shows through.
            let idx = n as usize;
            if idx < 16 {
                Color::Indexed(idx as u8)
            } else {
                Color::Reset
            }
        }
    }
}

fn map_flags(fl: Flags) -> Modifier {
    let mut m = Modifier::empty();
    if fl.contains(Flags::BOLD) {
        m |= Modifier::BOLD;
    }
    if fl.contains(Flags::ITALIC) {
        m |= Modifier::ITALIC;
    }
    if fl.contains(Flags::UNDERLINE) {
        m |= Modifier::UNDERLINED;
    }
    if fl.contains(Flags::DIM) {
        m |= Modifier::DIM;
    }
    if fl.contains(Flags::INVERSE) {
        m |= Modifier::REVERSED;
    }
    if fl.contains(Flags::HIDDEN) {
        m |= Modifier::HIDDEN;
    }
    if fl.contains(Flags::STRIKEOUT) {
        m |= Modifier::CROSSED_OUT;
    }
    m
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::mpsc::channel;

    fn feed_lines(e: &mut AlacrittyEngine, n: usize) {
        for i in 0..n {
            e.advance(format!("line{i}\r\n").as_bytes());
        }
    }

    #[test]
    fn scrollback_offset_moves_clamps_and_resets() {
        let (tx, _rx) = channel();
        let mut e = AlacrittyEngine::new(20, 5, tx); // 5 visible rows
        feed_lines(&mut e, 50); // 50 lines → ~45 in scrollback

        assert_eq!(e.scroll_offset(), 0, "starts live at the bottom");

        e.scroll(10);
        assert_eq!(e.scroll_offset(), 10, "scrolls up 10 lines into history");
        assert!(!e.cursor().visible, "cursor hidden while scrolled back");

        e.scroll_to_top();
        let top = e.scroll_offset();
        assert!(top > 10, "top of history is well above the live bottom");
        e.scroll(1000);
        assert_eq!(
            e.scroll_offset(),
            top,
            "cannot scroll past the top of history"
        );

        e.scroll(-1000);
        assert_eq!(e.scroll_offset(), 0, "cannot scroll below the live bottom");
        e.scroll(5);
        e.scroll_to_bottom();
        assert_eq!(e.scroll_offset(), 0, "snaps back to live");
        assert!(e.cursor().visible, "cursor returns once live");
    }

    #[test]
    fn alt_screen_has_no_scrollback() {
        let (tx, _rx) = channel();
        let mut e = AlacrittyEngine::new(20, 5, tx);
        feed_lines(&mut e, 20);
        e.advance(b"\x1b[?1049h"); // enter the alternate screen
        assert!(e.alt_screen());
        e.scroll(5);
        assert_eq!(e.scroll_offset(), 0, "the alt screen ignores scrollback");
    }

    #[test]
    fn mouse_tracking_modes_are_detected() {
        let (tx, _rx) = channel();
        let mut e = AlacrittyEngine::new(20, 5, tx);
        assert!(!e.mouse_report(), "no tracking by default");
        assert!(!e.sgr_mouse());
        // A TUI agent enabling normal + SGR mouse reporting (DECSET 1000, 1006).
        e.advance(b"\x1b[?1000h\x1b[?1006h");
        assert!(e.mouse_report(), "wheel should be forwarded to the app");
        assert!(e.sgr_mouse(), "reports use the SGR encoding");
        // Disabling it hands the wheel back to bohay's scrollback.
        e.advance(b"\x1b[?1000l");
        assert!(!e.mouse_report());
    }
}