cordy 0.2.0

A cross-platform TUI coding agent in Rust — workspace tabs, PTY terminals, direct-key panels, hot-swap any model/provider mid-conversation, MCP, skills, sub-agents and background jobs.
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
//! Floating PTY terminals and the editor panel.
//!
//! Each panel owns a real pseudo-terminal: a child process on one end, a [`vt100`] screen on the
//! other. A reader thread pumps bytes into the parser, the render pass copies the parsed screen
//! into ratatui cells, and keystrokes are encoded back into the PTY. That is enough to host a
//! shell, a test watcher, or a full-screen editor like Neovim next to the chat.

use std::io::{Read, Write};
use std::path::Path;
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::{Arc, Mutex};

use portable_pty::{Child, CommandBuilder, MasterPty, PtySize, native_pty_system};
use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Paragraph};

use super::theme::Theme;

/// One terminal panel.
pub struct TermPanel {
    pub title: String,
    pub rows: u16,
    pub cols: u16,
    /// The child exited; the panel stays until closed so its output is still readable.
    pub exited: Arc<AtomicBool>,
    /// Set by the reader thread whenever new output lands, cleared by the render loop.
    dirty: Arc<AtomicBool>,
    parser: Arc<Mutex<vt100::Parser>>,
    writer: Box<dyn Write + Send>,
    master: Box<dyn MasterPty + Send>,
    child: Box<dyn Child + Send + Sync>,
}

impl TermPanel {
    /// Start `program` (or the user's default shell) in a new PTY of `rows`×`cols`.
    pub fn spawn(
        title: &str,
        program: Option<&str>,
        args: &[String],
        cwd: &Path,
        rows: u16,
        cols: u16,
    ) -> anyhow::Result<TermPanel> {
        let pty = native_pty_system();
        let pair = pty.openpty(PtySize {
            rows,
            cols,
            pixel_width: 0,
            pixel_height: 0,
        })?;
        let mut cmd = match program {
            Some(p) => CommandBuilder::new(p),
            None => CommandBuilder::new_default_prog(),
        };
        for a in args {
            cmd.arg(a);
        }
        cmd.cwd(cwd);
        // Child processes should not try to talk to Cordy's own alternate screen.
        cmd.env("TERM", "xterm-256color");
        let child = pair.slave.spawn_command(cmd)?;
        drop(pair.slave);

        let parser = Arc::new(Mutex::new(vt100::Parser::new(rows, cols, 5_000)));
        let exited = Arc::new(AtomicBool::new(false));
        let dirty = Arc::new(AtomicBool::new(true));
        let mut reader = pair.master.try_clone_reader()?;
        let writer = pair.master.take_writer()?;
        {
            let parser = parser.clone();
            let exited = exited.clone();
            let dirty = dirty.clone();
            std::thread::spawn(move || {
                let mut buf = [0u8; 8192];
                loop {
                    match reader.read(&mut buf) {
                        Ok(0) | Err(_) => break,
                        Ok(n) => {
                            if let Ok(mut p) = parser.lock() {
                                p.process(&buf[..n]);
                            }
                            dirty.store(true, Ordering::Relaxed);
                        }
                    }
                }
                exited.store(true, Ordering::Relaxed);
                dirty.store(true, Ordering::Relaxed);
            });
        }
        Ok(TermPanel {
            title: title.to_string(),
            rows,
            cols,
            exited,
            dirty,
            parser,
            writer,
            master: pair.master,
            child,
        })
    }

    /// Whether new output arrived since the last render (and clear the flag).
    pub fn take_dirty(&self) -> bool {
        self.dirty.swap(false, Ordering::Relaxed)
    }

    pub fn has_exited(&self) -> bool {
        self.exited.load(Ordering::Relaxed)
    }

    /// Tell the child its window changed. No-op when the size is unchanged.
    pub fn resize(&mut self, rows: u16, cols: u16) {
        if (rows, cols) == (self.rows, self.cols) || rows == 0 || cols == 0 {
            return;
        }
        self.rows = rows;
        self.cols = cols;
        let _ = self.master.resize(PtySize {
            rows,
            cols,
            pixel_width: 0,
            pixel_height: 0,
        });
        if let Ok(mut p) = self.parser.lock() {
            p.screen_mut().set_size(rows, cols);
        }
        self.dirty.store(true, Ordering::Relaxed);
    }

    /// Send raw bytes to the child.
    pub fn write(&mut self, bytes: &[u8]) {
        let _ = self.writer.write_all(bytes);
        let _ = self.writer.flush();
    }

    /// Whether the child asked for application cursor keys (`\x1bOA` rather than `\x1b[A`) — vim
    /// and readline both care.
    fn application_cursor(&self) -> bool {
        self.parser
            .lock()
            .map(|p| p.screen().application_cursor())
            .unwrap_or(false)
    }

    /// Kill the child process.
    pub fn kill(&mut self) {
        let _ = self.child.kill();
    }
}

/// Encode a crossterm key for a PTY.
pub fn encode_key(panel: &TermPanel, k: ratatui::crossterm::event::KeyEvent) -> Vec<u8> {
    use ratatui::crossterm::event::{KeyCode::*, KeyModifiers};
    let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
    let alt = k.modifiers.contains(KeyModifiers::ALT);
    let app = panel.application_cursor();
    let arrow = |c: char| {
        if app {
            format!("\x1bO{c}").into_bytes()
        } else {
            format!("\x1b[{c}").into_bytes()
        }
    };
    let mut out = match k.code {
        Char(c) if ctrl => {
            // ctrl+a..z / ctrl+[\]^_ map onto the C0 control codes.
            let b = c.to_ascii_lowercase() as u8;
            match b {
                b'a'..=b'z' => vec![b - b'a' + 1],
                b'[' => vec![0x1b],
                b'\\' => vec![0x1c],
                b']' => vec![0x1d],
                b'^' => vec![0x1e],
                b'_' | b'/' => vec![0x1f],
                b' ' | b'@' => vec![0x00],
                _ => c.to_string().into_bytes(),
            }
        }
        Char(c) => c.to_string().into_bytes(),
        Enter => vec![b'\r'],
        Backspace => vec![0x7f],
        Tab => vec![b'\t'],
        BackTab => b"\x1b[Z".to_vec(),
        Esc => vec![0x1b],
        Up => arrow('A'),
        Down => arrow('B'),
        Right => arrow('C'),
        Left => arrow('D'),
        Home => b"\x1b[H".to_vec(),
        End => b"\x1b[F".to_vec(),
        PageUp => b"\x1b[5~".to_vec(),
        PageDown => b"\x1b[6~".to_vec(),
        Delete => b"\x1b[3~".to_vec(),
        Insert => b"\x1b[2~".to_vec(),
        F(n) => match n {
            1 => b"\x1bOP".to_vec(),
            2 => b"\x1bOQ".to_vec(),
            3 => b"\x1bOR".to_vec(),
            4 => b"\x1bOS".to_vec(),
            5..=15 => {
                // \x1b[15~ .. \x1b[24~ with the usual gaps in the numbering.
                const CODES: [u8; 11] = [15, 17, 18, 19, 20, 21, 23, 24, 25, 26, 28];
                format!("\x1b[{}~", CODES[(n - 5) as usize]).into_bytes()
            }
            _ => Vec::new(),
        },
        _ => Vec::new(),
    };
    // Alt is the ESC prefix.
    if alt && !out.is_empty() && out[0] != 0x1b {
        let mut esc = vec![0x1b];
        esc.append(&mut out);
        return esc;
    }
    out
}

/// Map a vt100 color onto ratatui, falling back to the theme for "default".
fn conv(c: vt100::Color, fallback: Color) -> Color {
    match c {
        vt100::Color::Default => fallback,
        vt100::Color::Idx(i) => Color::Indexed(i),
        vt100::Color::Rgb(r, g, b) => Color::Rgb(r, g, b),
    }
}

/// Draw a terminal panel into `area`, resizing the PTY to match.
pub fn render(f: &mut Frame, area: Rect, panel: &mut TermPanel, theme: &Theme, focused: bool) {
    // Header strip: title, exit state, and how to get back to the chat.
    let head_style = Style::default()
        .fg(if focused { theme.on_accent } else { theme.dim })
        .bg(if focused {
            theme.accent
        } else {
            theme.elevated
        });
    let status = if panel.has_exited() { " (exited)" } else { "" };
    let hint = if focused {
        "^Alt+T back to chat · ^Alt+W close"
    } else {
        "^Alt+T focus"
    };
    let title = format!("{}{}", panel.title, status);
    let pad =
        (area.width as usize).saturating_sub(title.chars().count() + hint.chars().count() + 2);
    f.render_widget(
        Paragraph::new(Line::from(vec![
            Span::styled(title, head_style.add_modifier(Modifier::BOLD)),
            Span::styled(" ".repeat(pad), head_style),
            Span::styled(format!("{hint} "), head_style),
        ])),
        Rect { height: 1, ..area },
    );

    let body = Rect {
        y: area.y + 1,
        height: area.height.saturating_sub(1),
        ..area
    };
    if body.height == 0 || body.width == 0 {
        return;
    }
    panel.resize(body.height, body.width);

    f.render_widget(
        Block::default().style(Style::default().bg(theme.base)),
        body,
    );
    let Ok(parser) = panel.parser.lock() else {
        return;
    };
    let screen = parser.screen();
    let mut lines: Vec<Line> = Vec::with_capacity(body.height as usize);
    for row in 0..body.height {
        let mut spans: Vec<Span> = Vec::new();
        // Coalesce runs of identical style so a full screen isn't one span per cell.
        let mut run = String::new();
        let mut run_style: Option<Style> = None;
        for col in 0..body.width {
            let (text, style) = match screen.cell(row, col) {
                Some(cell) => {
                    let mut st = Style::default()
                        .fg(conv(cell.fgcolor(), theme.assistant))
                        .bg(conv(cell.bgcolor(), theme.base));
                    if cell.bold() {
                        st = st.add_modifier(Modifier::BOLD);
                    }
                    if cell.italic() {
                        st = st.add_modifier(Modifier::ITALIC);
                    }
                    if cell.underline() {
                        st = st.add_modifier(Modifier::UNDERLINED);
                    }
                    if cell.inverse() {
                        st = st.add_modifier(Modifier::REVERSED);
                    }
                    let t = if cell.has_contents() {
                        cell.contents().to_string()
                    } else {
                        " ".to_string()
                    };
                    (t, st)
                }
                None => (" ".to_string(), Style::default().bg(theme.base)),
            };
            match run_style {
                Some(s) if s == style => run.push_str(&text),
                Some(s) => {
                    spans.push(Span::styled(std::mem::take(&mut run), s));
                    run.push_str(&text);
                    run_style = Some(style);
                }
                None => {
                    run.push_str(&text);
                    run_style = Some(style);
                }
            }
        }
        if let Some(s) = run_style {
            spans.push(Span::styled(run, s));
        }
        lines.push(Line::from(spans));
    }
    f.render_widget(Paragraph::new(lines), body);

    // Put the real cursor where the child put it, so editors feel native.
    if focused && !screen.hide_cursor() {
        let (cy, cx) = screen.cursor_position();
        if cy < body.height && cx < body.width {
            f.set_cursor_position((body.x + cx, body.y + cy));
        }
    }
}

/// The set of open terminal panels for a session.
#[derive(Default)]
pub struct Terminals {
    pub panels: Vec<TermPanel>,
    /// Index of the panel shown/receiving keys.
    pub active: usize,
    /// Whether the panel area is shown at all.
    pub visible: bool,
    /// Whether keystrokes go to the terminal instead of the composer.
    pub focused: bool,
    /// Share of the chat area the panel takes, in percent.
    pub height_pct: u16,
}

impl Terminals {
    /// Open a panel and focus it. Returns the error message on failure.
    pub fn open(
        &mut self,
        title: &str,
        program: Option<&str>,
        args: &[String],
        cwd: &Path,
    ) -> Result<(), String> {
        if self.panels.len() >= 4 {
            return Err("terminal limit reached (4) — close one with ^Alt+W".into());
        }
        // Real dimensions arrive on the first render; start with something sane.
        match TermPanel::spawn(title, program, args, cwd, 24, 80) {
            Ok(p) => {
                self.panels.push(p);
                self.active = self.panels.len() - 1;
                self.visible = true;
                self.focused = true;
                if self.height_pct == 0 {
                    self.height_pct = 45;
                }
                Ok(())
            }
            Err(e) => Err(format!("could not start terminal: {e}")),
        }
    }

    /// Close the active panel, killing its child.
    pub fn close_active(&mut self) {
        if self.panels.is_empty() {
            return;
        }
        let i = self.active.min(self.panels.len() - 1);
        self.panels[i].kill();
        self.panels.remove(i);
        self.active = self.active.min(self.panels.len().saturating_sub(1));
        if self.panels.is_empty() {
            self.visible = false;
            self.focused = false;
        }
    }

    pub fn active_panel(&mut self) -> Option<&mut TermPanel> {
        let i = self.active;
        self.panels.get_mut(i)
    }

    /// Cycle to the next panel.
    pub fn next(&mut self) {
        if !self.panels.is_empty() {
            self.active = (self.active + 1) % self.panels.len();
        }
    }

    /// Whether any panel produced output since the last frame.
    pub fn any_dirty(&self) -> bool {
        self.panels.iter().any(|p| p.take_dirty())
    }

    /// Grow or shrink the panel, clamped to something usable on both sides.
    pub fn grow(&mut self, delta: i16) {
        let next = self.height_pct as i16 + delta;
        self.height_pct = next.clamp(15, 80) as u16;
    }

    pub fn kill_all(&mut self) {
        for p in &mut self.panels {
            p.kill();
        }
        self.panels.clear();
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use ratatui::crossterm::event::{KeyCode, KeyEvent, KeyModifiers};

    fn panel() -> TermPanel {
        // A trivial child that exits immediately — enough to exercise encoding and resize.
        let prog = if cfg!(windows) { "cmd.exe" } else { "sh" };
        let args = if cfg!(windows) {
            vec!["/C".to_string(), "exit".to_string()]
        } else {
            vec!["-c".to_string(), "exit".to_string()]
        };
        TermPanel::spawn("test", Some(prog), &args, Path::new("."), 10, 40).unwrap()
    }

    #[test]
    fn spawns_a_pty_and_reports_its_size() {
        let p = panel();
        assert_eq!((p.rows, p.cols), (10, 40));
    }

    #[test]
    fn encodes_control_and_arrow_keys() {
        let p = panel();
        let key = |code, m| KeyEvent::new(code, m);
        assert_eq!(
            encode_key(&p, key(KeyCode::Char('c'), KeyModifiers::CONTROL)),
            vec![3]
        );
        assert_eq!(
            encode_key(&p, key(KeyCode::Char('a'), KeyModifiers::NONE)),
            b"a".to_vec()
        );
        assert_eq!(
            encode_key(&p, key(KeyCode::Enter, KeyModifiers::NONE)),
            b"\r".to_vec()
        );
        assert_eq!(
            encode_key(&p, key(KeyCode::Backspace, KeyModifiers::NONE)),
            vec![0x7f]
        );
        // Default (non-application) cursor mode.
        assert_eq!(
            encode_key(&p, key(KeyCode::Up, KeyModifiers::NONE)),
            b"\x1b[A".to_vec()
        );
        // Alt prefixes with ESC.
        assert_eq!(
            encode_key(&p, key(KeyCode::Char('b'), KeyModifiers::ALT)),
            vec![0x1b, b'b']
        );
    }

    #[test]
    fn terminals_open_close_and_clamp_height() {
        let mut t = Terminals {
            height_pct: 45,
            ..Default::default()
        };
        t.grow(100);
        assert_eq!(t.height_pct, 80);
        t.grow(-200);
        assert_eq!(t.height_pct, 15);
        assert!(t.panels.is_empty());
        t.close_active(); // no panic on empty
        assert!(!t.visible);
    }
}