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
//! The window chrome: the header bar (brand, tab strip, git, model) and the status bar — the
//! only two rows the app spends on itself.
//!
//! Everything here is pure rendering over [`Model`] plus one async helper ([`poll_git`]) that the
//! runtime ticks in the background — the render path never shells out.

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

use unicode_width::UnicodeWidthStr;

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

/// Display columns a string occupies. Several of the chrome glyphs are double-width, so counting
/// `chars()` would misplace both the padding and the click regions.
fn cols(s: &str) -> usize {
    UnicodeWidthStr::width(s)
}

/// Working-tree state for the header's git segment. An empty `branch` means "not a repo".
#[derive(Debug, Clone, Default, PartialEq)]
pub struct GitStatus {
    pub branch: String,
    pub staged: usize,
    pub unstaged: usize,
    pub untracked: usize,
    pub ahead: usize,
    pub behind: usize,
}

impl GitStatus {
    pub fn is_dirty(&self) -> bool {
        self.staged + self.unstaged + self.untracked > 0
    }
}

/// One entry in the tab strip. The heavy per-tab state lives in the runtime; this is only what the
/// header needs to draw.
#[derive(Debug, Clone, Default, PartialEq)]
pub struct TabMeta {
    /// Short label — the session title, or the tab's mode when it has no title yet.
    pub title: String,
    /// Active model on that tab (shown in the tab tooltip row / `/tabs` listing).
    pub model: String,
    pub mode: String,
    /// The tab is mid-turn.
    pub busy: bool,
    /// Assistant/tool entries added since the tab was last focused.
    pub unread: usize,
}

/// Read the working tree's git state. Returns `None` outside a repository or when `git` is absent.
pub async fn poll_git(cwd: &std::path::Path) -> Option<GitStatus> {
    let out = tokio::process::Command::new("git")
        .args(["status", "--porcelain=v1", "-b", "--untracked-files=normal"])
        .current_dir(cwd)
        .output()
        .await
        .ok()?;
    if !out.status.success() {
        return None;
    }
    Some(parse_status(&String::from_utf8_lossy(&out.stdout)))
}

/// Parse `git status --porcelain=v1 -b` output into a [`GitStatus`].
fn parse_status(text: &str) -> GitStatus {
    let mut st = GitStatus::default();
    for line in text.lines() {
        if let Some(head) = line.strip_prefix("## ") {
            // `main...origin/main [ahead 1, behind 2]` — or `HEAD (no branch)` when detached.
            let name = head.split([' ', '.']).next().unwrap_or("").to_string();
            st.branch = if name.is_empty() { "HEAD".into() } else { name };
            if let Some(bracket) = head.split_once('[').map(|(_, r)| r) {
                for part in bracket.trim_end_matches(']').split(',') {
                    let part = part.trim();
                    if let Some(n) = part.strip_prefix("ahead ") {
                        st.ahead = n.trim().parse().unwrap_or(0);
                    } else if let Some(n) = part.strip_prefix("behind ") {
                        st.behind = n.trim().parse().unwrap_or(0);
                    }
                }
            }
            continue;
        }
        let mut chars = line.chars();
        let (Some(x), Some(y)) = (chars.next(), chars.next()) else {
            continue;
        };
        if x == '?' {
            st.untracked += 1;
            continue;
        }
        if x != ' ' {
            st.staged += 1;
        }
        if y != ' ' {
            st.unstaged += 1;
        }
    }
    st
}

/// A horizontal meter with sub-cell resolution, e.g. `████▌░░░`.
pub fn meter(pct: u64, width: usize, fg: Color, track: Color) -> Vec<Span<'static>> {
    const PARTIALS: [char; 8] = ['', '', '', '', '', '', '', ''];
    if width == 0 {
        return Vec::new();
    }
    let eighths = (pct.min(100) as usize * width * 8) / 100;
    let full = eighths / 8;
    let rem = eighths % 8;
    let mut out = Vec::new();
    if full > 0 {
        out.push(Span::styled(
            "".repeat(full.min(width)),
            Style::default().fg(fg),
        ));
    }
    let mut used = full.min(width);
    if rem > 0 && used < width {
        out.push(Span::styled(
            PARTIALS[rem - 1].to_string(),
            Style::default().fg(fg),
        ));
        used += 1;
    }
    if used < width {
        out.push(Span::styled(
            "".repeat(width - used),
            Style::default().fg(track),
        ));
    }
    out
}

/// The brand mark: a diamond plus `cordy` washed across the accent gradient.
fn brand(theme: &Theme, bg: Color) -> Vec<Span<'static>> {
    let word = "cordy";
    let ramp = theme.ramp(word.chars().count());
    let mut spans = vec![Span::styled(
        "",
        Style::default()
            .fg(theme.accent)
            .bg(bg)
            .add_modifier(Modifier::BOLD),
    )];
    for (c, col) in word.chars().zip(ramp) {
        spans.push(Span::styled(
            c.to_string(),
            Style::default().fg(col).bg(bg).add_modifier(Modifier::BOLD),
        ));
    }
    spans
}

/// A run of spans plus the click target they belong to.
struct Seg {
    spans: Vec<Span<'static>>,
    hit: Option<super::Hit>,
}

impl Seg {
    fn new(spans: Vec<Span<'static>>, hit: Option<super::Hit>) -> Self {
        Seg { spans, hit }
    }
    fn width(&self) -> usize {
        self.spans.iter().map(|s| cols(&s.content)).sum()
    }
}

/// Lay segments out from `x`, registering each one's clickable region as it goes.
fn place(model: &mut Model, segs: Vec<Seg>, x: u16, y: u16, out: &mut Vec<Span<'static>>) -> u16 {
    let mut cx = x;
    for seg in segs {
        let w = seg.width() as u16;
        if let Some(hit) = seg.hit {
            model.push_hit(cx, y, w, 1, hit);
        }
        cx += w;
        out.extend(seg.spans);
    }
    cx
}

/// The header: brand and tabs on the left, then everything you want to be sure of before pressing
/// Enter — provider, model, branch, context, spend. Each segment is a click target for the panel
/// that owns it.
pub fn render_header(f: &mut Frame, area: Rect, model: &mut Model, theme: &Theme, tick: u64) {
    let bg = theme.elevated;
    f.render_widget(Block::default().style(Style::default().bg(bg)), area);
    let width = area.width as usize;
    let dim = Style::default().fg(theme.dim).bg(bg);
    let sep = || {
        Seg::new(
            vec![Span::styled(
                "  ·  ",
                Style::default().fg(theme.border).bg(bg),
            )],
            None,
        )
    };

    // --- right cluster, measured first so the tab strip knows its budget ---
    let mut right: Vec<Seg> = vec![Seg::new(
        vec![
            Span::styled(format!("{} ", model.provider_kind), dim),
            Span::styled("", Style::default().fg(theme.border).bg(bg)),
            Span::styled(
                short_model(&model.model_name),
                Style::default()
                    .fg(theme.accent)
                    .bg(bg)
                    .add_modifier(Modifier::BOLD),
            ),
        ],
        Some(super::Hit::ModelChip),
    )];
    if let Some(git) = &model.git
        && !git.branch.is_empty()
    {
        let mut spans = vec![
            Span::styled(
                "",
                Style::default()
                    .fg(blend(theme.dim, theme.accent, 0.5))
                    .bg(bg),
            ),
            Span::styled(git.branch.clone(), Style::default().fg(theme.user).bg(bg)),
        ];
        for (n, glyph, color) in [
            (git.staged, '', theme.success),
            (git.unstaged, '', theme.warning),
            (git.untracked, '?', theme.dim),
            (git.ahead, '', theme.info),
            (git.behind, '', theme.danger),
        ] {
            if n > 0 {
                spans.push(Span::styled(
                    format!(" {glyph}{n}"),
                    Style::default().fg(color).bg(bg),
                ));
            }
        }
        right.push(sep());
        right.push(Seg::new(spans, Some(super::Hit::Git)));
    }
    let pct = model.ctx_pct();
    if model.last_in > 0 {
        let mut spans = meter(pct, 8, theme.gauge(pct), theme.border);
        for sp in &mut spans {
            sp.style = sp.style.bg(bg);
        }
        spans.push(Span::styled(format!(" {pct}%"), dim));
        spans.push(Span::styled(
            format!(" {}", super::fmt_tokens(model.last_in)),
            Style::default().fg(theme.border).bg(bg),
        ));
        right.push(sep());
        right.push(Seg::new(spans, Some(super::Hit::Context)));
    }
    let cost = model.cost_str();
    if !cost.is_empty() {
        right.push(sep());
        right.push(Seg::new(
            vec![Span::styled(
                cost,
                Style::default().fg(theme.accent2).bg(bg),
            )],
            Some(super::Hit::Cost),
        ));
    }
    right.push(Seg::new(
        vec![Span::styled(" ", Style::default().bg(bg))],
        None,
    ));
    let right_w: usize = right.iter().map(Seg::width).sum();

    // --- left: brand + tabs ---
    let mut left: Vec<Seg> = vec![Seg::new(brand(theme, bg), None)];
    let budget = width.saturating_sub(right_w + 4);
    let mut used: usize = left.iter().map(Seg::width).sum();
    if model.tabs.len() > 1 {
        left.push(Seg::new(
            vec![Span::styled("  ", Style::default().bg(bg))],
            None,
        ));
        used += 2;
        for (i, tab) in model.tabs.iter().enumerate() {
            let active = i == model.tab;
            let mark = if tab.busy {
                super::spinner_frame(tick)
            } else if active {
                ''
            } else if tab.unread > 0 {
                ''
            } else {
                ' '
            };
            let label: String = tab.title.chars().take(14).collect();
            let text = format!("{mark} {} {label}  ", i + 1);
            if used + cols(&text) > budget {
                left.push(Seg::new(vec![Span::styled("", dim)], None));
                break;
            }
            used += cols(&text);
            let style = if active {
                Style::default()
                    .fg(theme.user)
                    .bg(theme.surface)
                    .add_modifier(Modifier::BOLD)
            } else if tab.unread > 0 {
                Style::default().fg(theme.accent2).bg(bg)
            } else {
                dim
            };
            left.push(Seg::new(
                vec![Span::styled(text, style)],
                Some(super::Hit::Tab(i)),
            ));
        }
    }

    let left_w: usize = left.iter().map(Seg::width).sum();
    let mut spans: Vec<Span> = Vec::new();
    let cx = place(model, left, area.x, area.y, &mut spans);
    let pad = width.saturating_sub(left_w + right_w);
    spans.push(Span::styled(" ".repeat(pad), Style::default().bg(bg)));
    place(model, right, cx + pad as u16, area.y, &mut spans);
    f.render_widget(Paragraph::new(Line::from(spans)), area);
}

/// One entry in the hint bar: key, glyph, label, and the panel clicking it opens.
const HINTS: [(&str, &str, &str, super::Hit); 8] = [
    ("^P", "", "palette", super::Hit::Palette),
    ("^L", "", "model", super::Hit::ModelChip),
    ("^D", "", "mode", super::Hit::Mode),
    ("^G", "", "git", super::Hit::Git),
    ("^S", "", "skills", super::Hit::Skills),
    ("^E", "", "editor", super::Hit::Editor),
    ("^T", "", "term", super::Hit::Term),
    ("^B", "", "tabs", super::Hit::Tabs),
];

/// `^P ⚡ palette`, lit up when the pointer is on it.
fn hint_seg(
    key: &str,
    glyph: &str,
    label: &str,
    hit: super::Hit,
    theme: &Theme,
    hovered: Option<super::Hit>,
) -> Seg {
    let on = hovered == Some(hit);
    Seg::new(
        vec![
            Span::styled(
                key.to_string(),
                Style::default()
                    .fg(if on { theme.accent2 } else { theme.accent })
                    .add_modifier(Modifier::BOLD),
            ),
            // An explicit space on both sides: the glyphs have different widths, and without it
            // the labels jitter relative to their keys.
            Span::styled(
                format!(" {glyph} "),
                Style::default().fg(if on { theme.accent2 } else { theme.border }),
            ),
            Span::styled(
                format!("{label}  "),
                Style::default()
                    .fg(if on { theme.user } else { theme.dim })
                    .add_modifier(if on {
                        Modifier::UNDERLINED
                    } else {
                        Modifier::empty()
                    }),
            ),
        ],
        Some(hit),
    )
}

/// The bottom bar: the active mode, everything reachable from here, and what is running. With the
/// mouse captured this row is a menu bar — each hint is a button, not just a reminder.
pub fn render_hints(f: &mut Frame, area: Rect, model: &mut Model, theme: &Theme, tick: u64) {
    let hovered = model.hover;
    let mut segs: Vec<Seg> = vec![Seg::new(
        vec![
            Span::styled(
                format!(" {} ", model.mode()),
                Style::default()
                    .fg(theme.on_accent)
                    .bg(if model.mode_flash > 0 {
                        theme.accent2
                    } else {
                        theme.accent
                    })
                    .add_modifier(Modifier::BOLD),
            ),
            Span::raw("  "),
        ],
        Some(super::Hit::Mode),
    )];
    // Stop only exists mid-turn, and takes the first slot when it does.
    if model.busy {
        segs.push(hint_seg(
            "^C",
            "",
            "stop",
            super::Hit::Stop,
            theme,
            hovered,
        ));
    }
    for (key, glyph, label, hit) in HINTS {
        segs.push(hint_seg(key, glyph, label, hit, theme, hovered));
    }

    // Build the right edge first — it is what the hints have to fit around.
    let mut right: Vec<Span> = Vec::new();
    if model.busy {
        right.push(Span::styled(
            format!("{} {}  ", super::spinner_frame(tick), model.status),
            Style::default().fg(theme.accent),
        ));
    } else if model.status.starts_with("error") {
        right.push(Span::styled(
            format!("{}  ", model.status),
            Style::default().fg(theme.danger),
        ));
    }
    for (n, glyph, color) in [
        (model.bg_count, '', theme.tool),
        (model.subagent_count, '', theme.accent2),
        (model.term_count, '', theme.dim),
    ] {
        if n > 0 {
            right.push(Span::styled(
                format!("{glyph}{n} "),
                Style::default().fg(color),
            ));
        }
    }
    if let Some(goal) = &model.goal_line {
        right.push(Span::styled(
            format!("{goal}  "),
            Style::default().fg(theme.warning),
        ));
    }
    // Whether the mouse belongs to Cordy or to the terminal — click it to swap.
    right.push(Span::styled(
        if model.mouse_on { "" } else { "" },
        Style::default().fg(if model.mouse_on {
            theme.accent
        } else {
            theme.border
        }),
    ));
    let rw: usize = right.iter().map(|s| cols(&s.content)).sum();

    // Drop hints from the right until the row fits; the mode chip always survives.
    let width = area.width as usize;
    while segs.len() > 1 && segs.iter().map(Seg::width).sum::<usize>() + rw > width {
        segs.pop();
    }

    let mut spans: Vec<Span> = Vec::new();
    place(model, segs, area.x, area.y, &mut spans);
    f.render_widget(Paragraph::new(Line::from(spans)), area);

    let rx = area.x + area.width.saturating_sub(rw as u16);
    model.push_hit(
        area.x + area.width.saturating_sub(2),
        area.y,
        2,
        1,
        super::Hit::Mouse,
    );
    f.render_widget(
        Paragraph::new(Line::from(right)).alignment(Alignment::Right),
        Rect {
            x: rx,
            width: rw as u16,
            ..area
        },
    );
}

/// Trim a provider-qualified model id down to something that fits a chip: `anthropic/claude-opus-5`
/// → `claude-opus-5`.
pub fn short_model(name: &str) -> String {
    let tail = name.rsplit('/').next().unwrap_or(name);
    if tail.chars().count() > 26 {
        format!(
            "{}",
            tail.chars()
                .skip(tail.chars().count() - 25)
                .collect::<String>()
        )
    } else {
        tail.to_string()
    }
}

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

    #[test]
    fn parses_branch_counts_and_divergence() {
        let out = "## main...origin/main [ahead 2, behind 1]\nM  src/a.rs\n M src/b.rs\nMM src/c.rs\n?? new.txt\n";
        let st = parse_status(out);
        assert_eq!(st.branch, "main");
        assert_eq!(st.ahead, 2);
        assert_eq!(st.behind, 1);
        assert_eq!(st.staged, 2); // "M " and "MM"
        assert_eq!(st.unstaged, 2); // " M" and "MM"
        assert_eq!(st.untracked, 1);
        assert!(st.is_dirty());
    }

    #[test]
    fn parses_clean_repo_without_upstream() {
        let st = parse_status("## feature/x\n");
        assert_eq!(st.branch, "feature/x");
        assert_eq!((st.ahead, st.behind), (0, 0));
        assert!(!st.is_dirty());
    }

    #[test]
    fn meter_fills_proportionally() {
        let full = meter(100, 4, Color::Red, Color::Blue);
        let text: String = full.iter().map(|s| s.content.to_string()).collect();
        assert_eq!(text, "████");
        let empty = meter(0, 4, Color::Red, Color::Blue);
        let text: String = empty.iter().map(|s| s.content.to_string()).collect();
        assert_eq!(text, "░░░░");
        // Every width is honored exactly, partial cell included.
        for pct in [1, 13, 37, 50, 66, 99] {
            let w: usize = meter(pct, 10, Color::Red, Color::Blue)
                .iter()
                .map(|s| s.content.chars().count())
                .sum();
            assert_eq!(w, 10, "pct={pct}");
        }
    }

    #[test]
    fn model_chip_trims_provider_prefix() {
        assert_eq!(short_model("anthropic/claude-opus-5"), "claude-opus-5");
        assert_eq!(short_model("gpt-4o-mini"), "gpt-4o-mini");
        assert!(short_model(&"x".repeat(80)).starts_with(''));
        assert_eq!(short_model(&"x".repeat(80)).chars().count(), 26);
    }
}