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
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
//! The generic overlay picker behind the direct-key panels (`^L` models, `^D` modes, `^S` skills,
//! `^G` git, `^K` context, `^B` tabs).
//!
//! One widget, one key handler, one look — a new panel is a list of [`PickRow`]s plus a title. The
//! key handling here is pure so it can be unit-tested; the runtime only executes the [`PickAction`]
//! that comes back out.

use ratatui::Frame;
use ratatui::layout::Rect;
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, Clear, Padding, Paragraph};

use super::theme::{Theme, blend};

/// What choosing a row does. The runtime performs the side effect.
#[derive(Clone, PartialEq, Debug)]
pub enum PickAction {
    /// Hot-swap to this model.
    Model(String),
    /// Switch to `modes[i]`.
    Mode(usize),
    /// Run a git subcommand line (e.g. `log --oneline -20`) and show its output.
    Git(String),
    /// Run a slash command.
    Command(String),
    /// Focus the tab at this index.
    Tab(usize),
    /// Insert text at the composer cursor.
    Insert(String),
    /// Switch the picker into text-entry mode with this label; Enter then yields
    /// [`PickerEvent::Submit`] carrying the typed text and this key.
    Prompt(String),
    /// A read-only row (context inspector, model events).
    None,
}

/// One row of a picker.
#[derive(Clone, Debug)]
pub struct PickRow {
    pub label: String,
    /// Secondary text shown after the label.
    pub hint: String,
    /// Short right-aligned tag (`★`, `4h ago`, `128k`).
    pub badge: String,
    pub action: PickAction,
}

impl PickRow {
    pub fn new(label: impl Into<String>, hint: impl Into<String>, action: PickAction) -> Self {
        PickRow {
            label: label.into(),
            hint: hint.into(),
            badge: String::new(),
            action,
        }
    }

    pub fn badge(mut self, b: impl Into<String>) -> Self {
        self.badge = b.into();
        self
    }

    /// A non-selectable section header.
    pub fn header(label: impl Into<String>) -> Self {
        PickRow {
            label: label.into(),
            hint: String::new(),
            badge: String::new(),
            action: PickAction::None,
        }
    }
}

/// Which panel is open — the runtime uses this to decide how to handle extra keys.
#[derive(Clone, Copy, PartialEq, Eq, Debug)]
pub enum PickerKind {
    Model,
    Mode,
    Skills,
    Git,
    Tabs,
    Context,
    Events,
}

/// An open overlay panel.
#[derive(Clone, Debug)]
pub struct Picker {
    pub kind: PickerKind,
    pub title: String,
    pub rows: Vec<PickRow>,
    pub sel: usize,
    pub query: String,
    /// Whether typing filters the rows (off for menus, where letters are shortcuts).
    pub searchable: bool,
    pub footer: String,
    /// Active text prompt: `(key, label, buffer)`. Set by choosing a [`PickAction::Prompt`] row.
    pub prompt: Option<(String, String, String)>,
}

/// What a keypress did to the picker.
#[derive(Clone, PartialEq, Debug)]
pub enum PickerEvent {
    /// Nothing the runtime needs to act on.
    None,
    /// The picker closed (Esc, or a chosen action).
    Closed,
    /// Run this action, then close.
    Chose(PickAction),
    /// A text prompt was submitted: `(key, text)`.
    Submit(String, String),
}

impl Picker {
    pub fn new(kind: PickerKind, title: impl Into<String>, rows: Vec<PickRow>) -> Self {
        // Open on the first selectable row so a leading section header isn't highlighted.
        let sel = rows
            .iter()
            .position(|r| r.action != PickAction::None)
            .unwrap_or(0);
        Picker {
            kind,
            title: title.into(),
            rows,
            sel,
            query: String::new(),
            searchable: true,
            footer: String::new(),
            prompt: None,
        }
    }

    pub fn menu(mut self) -> Self {
        self.searchable = false;
        self
    }

    pub fn footer(mut self, f: impl Into<String>) -> Self {
        self.footer = f.into();
        self
    }

    /// Row indices matching the query (case-insensitive substring over label + hint). Section
    /// headers survive only while they still have a visible row under them.
    pub fn filtered(&self) -> Vec<usize> {
        if self.query.is_empty() {
            return (0..self.rows.len()).collect();
        }
        let q = self.query.to_lowercase();
        let mut out: Vec<usize> = Vec::new();
        for (i, r) in self.rows.iter().enumerate() {
            if r.action == PickAction::None {
                continue; // headers are dropped while filtering
            }
            if r.label.to_lowercase().contains(&q) || r.hint.to_lowercase().contains(&q) {
                out.push(i);
            }
        }
        out
    }

    /// The currently highlighted row, if it is selectable.
    pub fn selected(&self) -> Option<&PickRow> {
        self.rows
            .get(self.sel)
            .filter(|r| r.action != PickAction::None)
    }

    /// Move the highlight by `d` visible rows, skipping section headers and clamping at the ends.
    pub fn move_sel(&mut self, d: i32) {
        let vis = self.filtered();
        if vis.is_empty() {
            return;
        }
        let cur = vis.iter().position(|i| *i == self.sel).unwrap_or(0) as i32;
        let mut next = (cur + d).clamp(0, vis.len() as i32 - 1);
        // Step over headers in the direction of travel; fall back if we run out.
        let step = if d >= 0 { 1 } else { -1 };
        while self.rows[vis[next as usize]].action == PickAction::None {
            let probe = next + step;
            if probe < 0 || probe >= vis.len() as i32 {
                break;
            }
            next = probe;
        }
        self.sel = vis[next as usize];
    }

    /// Re-anchor the selection after the query changed.
    fn resync(&mut self) {
        let vis = self.filtered();
        if !vis.contains(&self.sel) {
            self.sel = vis
                .iter()
                .copied()
                .find(|i| self.rows[*i].action != PickAction::None)
                .unwrap_or(0);
        }
    }
}

/// Feed a keypress to the open picker.
pub fn handle_key(p: &mut Picker, code: ratatui::crossterm::event::KeyCode) -> PickerEvent {
    use ratatui::crossterm::event::KeyCode::*;

    // Text-entry mode (commit message, branch name, …) captures everything.
    if let Some((key, _label, buf)) = &mut p.prompt {
        match code {
            Esc => {
                p.prompt = None;
                return PickerEvent::None;
            }
            Enter => {
                let (key, text) = (key.clone(), buf.clone());
                p.prompt = None;
                return PickerEvent::Submit(key, text);
            }
            Backspace => {
                buf.pop();
                return PickerEvent::None;
            }
            Char(c) => {
                buf.push(c);
                return PickerEvent::None;
            }
            _ => return PickerEvent::None,
        }
    }

    match code {
        Esc => PickerEvent::Closed,
        Up => {
            p.move_sel(-1);
            PickerEvent::None
        }
        Down => {
            p.move_sel(1);
            PickerEvent::None
        }
        PageUp => {
            p.move_sel(-8);
            PickerEvent::None
        }
        PageDown => {
            p.move_sel(8);
            PickerEvent::None
        }
        Home => {
            p.sel = 0;
            p.move_sel(0);
            PickerEvent::None
        }
        End => {
            p.sel = p.rows.len().saturating_sub(1);
            p.move_sel(0);
            PickerEvent::None
        }
        Enter => match p.selected().map(|r| r.action.clone()) {
            Some(PickAction::Prompt(label)) => {
                let key = p
                    .selected()
                    .map(|r| r.label.clone())
                    .unwrap_or_else(|| label.clone());
                p.prompt = Some((key, label, String::new()));
                PickerEvent::None
            }
            Some(a) => PickerEvent::Chose(a),
            None => PickerEvent::None,
        },
        Backspace if p.searchable => {
            p.query.pop();
            p.resync();
            PickerEvent::None
        }
        Char(c) if p.searchable => {
            p.query.push(c);
            p.resync();
            PickerEvent::None
        }
        // In menu mode a letter jumps to (and runs) the row it prefixes — `l` for log, `p` for push.
        Char(c) => {
            let c = c.to_ascii_lowercase();
            match p
                .rows
                .iter()
                .position(|r| r.action != PickAction::None && r.label.to_lowercase().starts_with(c))
            {
                Some(i) => {
                    p.sel = i;
                    match p.rows[i].action.clone() {
                        PickAction::Prompt(label) => {
                            let key = p.rows[i].label.clone();
                            p.prompt = Some((key, label, String::new()));
                            PickerEvent::None
                        }
                        a => PickerEvent::Chose(a),
                    }
                }
                None => PickerEvent::None,
            }
        }
        _ => PickerEvent::None,
    }
}

/// Draw the picker: a centered panel with a title bar, an optional query line, the rows, and a
/// footer hint strip. Returns the clickable regions it drew, so every row is a button.
pub fn render(
    f: &mut Frame,
    area: Rect,
    p: &Picker,
    theme: &Theme,
) -> Vec<(u16, u16, u16, u16, super::Hit)> {
    let mut hits: Vec<(u16, u16, u16, u16, super::Hit)> = Vec::new();
    let vis = p.filtered();
    // Size to the content, but never past the terminal — on a small window the preferred minimum
    // has to give way, so the ceiling is computed first and the floor is clamped under it.
    let max_h = (area.height * 8 / 10).clamp(1, area.height.max(1));
    let h = (vis.len() as u16 + 6).max(9).min(max_h);
    let max_w = area.width.saturating_sub(4).max(1);
    let w = (area.width * 6 / 10).max(46).min(max_w);
    let rect = Rect {
        x: area.x + area.width.saturating_sub(w) / 2,
        y: area.y + area.height.saturating_sub(h) / 3,
        width: w,
        height: h,
    };
    f.render_widget(Clear, rect);
    // Clicks inside the panel must not fall through and close it.
    hits.push((rect.x, rect.y, rect.width, rect.height, super::Hit::Panel));
    let panel = Block::default()
        .style(Style::default().bg(theme.surface))
        .padding(Padding::new(1, 1, 0, 0));
    let inner = panel.inner(rect);
    f.render_widget(panel, rect);
    let iw = inner.width as usize;
    let surf = theme.surface;

    let mut lines: Vec<Line> = Vec::new();
    // Title bar: an accent rule, the title, then the row count.
    let count = format!(
        "{} ",
        vis.iter()
            .filter(|i| p.rows[**i].action != PickAction::None)
            .count()
    );
    let title_pad = iw.saturating_sub(p.title.chars().count() + count.chars().count() + 3);
    lines.push(Line::from(vec![
        Span::styled("", Style::default().fg(theme.accent).bg(surf)),
        Span::styled(
            format!(" {} ", p.title),
            Style::default()
                .fg(theme.user)
                .bg(surf)
                .add_modifier(Modifier::BOLD),
        ),
        Span::styled(" ".repeat(title_pad), Style::default().bg(surf)),
        Span::styled(count, Style::default().fg(theme.border).bg(surf)),
    ]));
    // Query / prompt line.
    if let Some((_key, label, buf)) = &p.prompt {
        lines.push(Line::from(vec![
            Span::styled(
                format!(" {label} "),
                Style::default().fg(theme.on_accent).bg(theme.accent),
            ),
            Span::styled(format!(" {buf}"), Style::default().fg(theme.user).bg(surf)),
        ]));
    } else if p.searchable {
        lines.push(Line::from(vec![
            Span::styled("  ", Style::default().bg(surf)),
            Span::styled(
                if p.query.is_empty() {
                    "type to filter".to_string()
                } else {
                    p.query.clone()
                },
                Style::default()
                    .fg(if p.query.is_empty() {
                        theme.border
                    } else {
                        theme.user
                    })
                    .bg(surf),
            ),
        ]));
    } else {
        lines.push(Line::from(Span::styled(" ", Style::default().bg(surf))));
    }
    lines.push(Line::from(Span::styled(
        "".repeat(iw),
        Style::default().fg(theme.border).bg(surf),
    )));

    // Hints line up in a column instead of trailing each label at a different offset.
    let label_col = vis
        .iter()
        .filter(|i| p.rows[**i].action != PickAction::None && !p.rows[**i].hint.is_empty())
        .map(|i| p.rows[*i].label.chars().count())
        .max()
        .unwrap_or(0)
        .min(iw / 3);

    // Rows, scrolled to keep the selection visible.
    let body_h = (h as usize).saturating_sub(5);
    let sel_pos = vis.iter().position(|i| *i == p.sel).unwrap_or(0);
    let scroll = sel_pos.saturating_sub(body_h.saturating_sub(1));
    for (n, &i) in vis.iter().skip(scroll).take(body_h).enumerate() {
        let r = &p.rows[i];
        if r.action != PickAction::None {
            // Row `n` of the body, which starts three lines into the panel.
            hits.push((
                inner.x,
                inner.y + 3 + n as u16,
                inner.width,
                1,
                super::Hit::Row(i),
            ));
        }
        if r.action == PickAction::None && r.hint.is_empty() && r.badge.is_empty() {
            // Section header.
            lines.push(Line::from(Span::styled(
                format!(" {}", r.label.to_uppercase()),
                Style::default()
                    .fg(theme.accent2)
                    .bg(surf)
                    .add_modifier(Modifier::BOLD),
            )));
            continue;
        }
        let selected = i == p.sel;
        let bg = if selected {
            blend(surf, theme.accent, 0.28)
        } else {
            surf
        };
        let fg = if selected {
            theme.user
        } else {
            theme.assistant
        };
        let mark = if selected { "" } else { " " };
        let mut spans = vec![
            Span::styled(mark.to_string(), Style::default().fg(theme.accent).bg(bg)),
            Span::styled(
                format!(" {}", r.label),
                Style::default().fg(fg).bg(bg).add_modifier(if selected {
                    Modifier::BOLD
                } else {
                    Modifier::empty()
                }),
            ),
        ];
        let mut used = 1 + 1 + r.label.chars().count();
        let badge_w = r.badge.chars().count();
        if !r.hint.is_empty() {
            // Pad the label out to the shared column so every hint starts at the same x.
            let pad = label_col.saturating_sub(r.label.chars().count());
            let room = iw.saturating_sub(used + pad + badge_w + 4);
            let hint: String = r.hint.chars().take(room).collect();
            used += pad + hint.chars().count() + 2;
            spans.push(Span::styled(
                format!("{}  {hint}", " ".repeat(pad)),
                Style::default().fg(theme.dim).bg(bg),
            ));
        }
        spans.push(Span::styled(
            " ".repeat(iw.saturating_sub(used + badge_w)),
            Style::default().bg(bg),
        ));
        if !r.badge.is_empty() {
            spans.push(Span::styled(
                r.badge.clone(),
                Style::default().fg(theme.accent2).bg(bg),
            ));
        }
        lines.push(Line::from(spans));
    }
    // Pad so the footer sits at the bottom edge.
    while lines.len() + 1 < h as usize {
        lines.push(Line::from(Span::styled(
            " ".repeat(iw),
            Style::default().bg(surf),
        )));
    }
    let footer = if p.footer.is_empty() {
        "↑↓ move · enter select · esc close".to_string()
    } else {
        p.footer.clone()
    };
    lines.push(Line::from(Span::styled(
        format!(" {footer}"),
        Style::default().fg(theme.border).bg(surf),
    )));
    f.render_widget(Paragraph::new(lines), inner);
    hits
}

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

    fn sample() -> Picker {
        Picker::new(
            PickerKind::Model,
            "Models",
            vec![
                PickRow::header("favorites"),
                PickRow::new("gpt-4o", "openai", PickAction::Model("gpt-4o".into())),
                PickRow::header("all"),
                PickRow::new(
                    "claude-opus-5",
                    "anthropic",
                    PickAction::Model("claude-opus-5".into()),
                ),
                PickRow::new("llama-3", "groq", PickAction::Model("llama-3".into())),
            ],
        )
    }

    #[test]
    fn opens_on_first_selectable_row_and_skips_headers() {
        let mut p = sample();
        assert_eq!(p.sel, 1);
        p.move_sel(1); // would land on the "all" header
        assert_eq!(p.sel, 3, "header must be skipped");
        p.move_sel(-1);
        assert_eq!(p.sel, 1);
    }

    #[test]
    fn filtering_drops_headers_and_resyncs_selection() {
        let mut p = sample();
        for c in "opus".chars() {
            handle_key(&mut p, KeyCode::Char(c));
        }
        let vis = p.filtered();
        assert_eq!(vis.len(), 1);
        assert_eq!(p.rows[vis[0]].label, "claude-opus-5");
        assert_eq!(p.sel, vis[0], "selection follows the filter");
        // Backspacing back to empty restores every row.
        for _ in 0..4 {
            handle_key(&mut p, KeyCode::Backspace);
        }
        assert_eq!(p.filtered().len(), 5);
    }

    #[test]
    fn enter_yields_the_chosen_action() {
        let mut p = sample();
        p.move_sel(1);
        assert_eq!(
            handle_key(&mut p, KeyCode::Enter),
            PickerEvent::Chose(PickAction::Model("claude-opus-5".into()))
        );
        assert_eq!(handle_key(&mut p, KeyCode::Esc), PickerEvent::Closed);
    }

    #[test]
    fn menu_mode_letters_run_the_matching_row() {
        let mut p = Picker::new(
            PickerKind::Git,
            "Git",
            vec![
                PickRow::new("log", "recent commits", PickAction::Git("log".into())),
                PickRow::new("push", "push HEAD", PickAction::Git("push".into())),
            ],
        )
        .menu();
        assert_eq!(
            handle_key(&mut p, KeyCode::Char('p')),
            PickerEvent::Chose(PickAction::Git("push".into()))
        );
        // Letters are shortcuts, not a filter, in menu mode.
        assert!(p.query.is_empty());
    }

    #[test]
    fn prompt_rows_capture_text_until_enter() {
        let mut p = Picker::new(
            PickerKind::Git,
            "Git",
            vec![PickRow::new(
                "commit",
                "commit staged changes",
                PickAction::Prompt("message".into()),
            )],
        )
        .menu();
        assert_eq!(handle_key(&mut p, KeyCode::Enter), PickerEvent::None);
        assert!(p.prompt.is_some());
        for c in "fix it".chars() {
            handle_key(&mut p, KeyCode::Char(c));
        }
        assert_eq!(
            handle_key(&mut p, KeyCode::Enter),
            PickerEvent::Submit("commit".into(), "fix it".into())
        );
        assert!(p.prompt.is_none());
    }
}