rustimal 0.6.0

A minimal, GPU-rendered terminal for Windows that runs Git Bash, with animated split panes and a glass look
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
//! Drawing a conversation in a pane. The text is first laid out as lines of coloured
//! pieces ([`transcript`]), then the visible ones are drawn above the message box.

use super::{Chat, Item, StepKind, Turn};
use crate::config::{Palette, Rgba};
use crate::glyphs::STYLE_BOLD;
use crate::gpu::Quad;
use crate::layout::Rect;
use crate::render::{Ctx, mix, rounded, text, with_alpha};

/// While a turn runs, only this many of its latest small lines are shown.
const LIVE_LINES: usize = 6;
/// The message box grows to this many lines.
const INPUT_LINES: usize = 6;
const SPINNER: [char; 10] = [
    '\u{280b}', '\u{2819}', '\u{2839}', '\u{2838}', '\u{283c}', '\u{2834}', '\u{2826}', '\u{2827}', '\u{2807}',
    '\u{280f}',
];

#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Tone {
    Text,
    /// Small print: what happens between the question and the answer.
    Faint,
    Accent,
    Good,
    Bad,
    Warn,
    Code,
}

#[derive(Debug, PartialEq, Eq)]
struct Piece {
    text: String,
    tone: Tone,
    bold: bool,
}

#[derive(Default, Debug)]
struct Line {
    pieces: Vec<Piece>,
    /// Part of a code block, drawn on its own background.
    block: bool,
}

impl Line {
    fn new(text: impl Into<String>, tone: Tone) -> Self {
        Line { pieces: vec![Piece { text: text.into(), tone, bold: false }], block: false }
    }

    #[cfg(test)]
    fn plain(&self) -> String {
        self.pieces.iter().map(|p| p.text.as_str()).collect()
    }
}

fn clean(text: &str) -> String {
    text.replace('\t', "    ").chars().filter(|c| !c.is_control()).collect()
}

/// Cut `text` to `width` characters, marking that it was cut.
fn clip_to(text: &str, width: usize) -> String {
    if text.chars().count() <= width {
        return text.to_string();
    }
    text.chars().take(width.saturating_sub(1)).collect::<String>() + "\u{2026}"
}

/// Break styled characters into lines of at most `width`, at spaces where possible.
fn wrap_cells(cells: &[(char, Tone, bool)], width: usize) -> Vec<Vec<(char, Tone, bool)>> {
    let width = width.max(1);
    let mut lines = Vec::new();
    let mut start = 0;
    while cells.len() - start > width {
        let window = &cells[start..=start + width];
        // A space at the break is dropped; a word longer than a line is cut.
        match window.iter().rposition(|c| c.0 == ' ').filter(|&i| i > 0) {
            Some(i) => {
                lines.push(cells[start..start + i].to_vec());
                start += i + 1;
            }
            None => {
                lines.push(cells[start..start + width].to_vec());
                start += width;
            }
        }
    }
    lines.push(cells[start..].to_vec());
    lines
}

fn to_line(cells: &[(char, Tone, bool)]) -> Line {
    let mut line = Line::default();
    for &(c, tone, bold) in cells {
        match line.pieces.last_mut() {
            Some(p) if p.tone == tone && p.bold == bold => p.text.push(c),
            _ => line.pieces.push(Piece { text: c.to_string(), tone, bold }),
        }
    }
    line
}

/// Wrapped lines of `body`, with `first` before the first and the same room before the rest.
fn hanging(out: &mut Vec<Line>, first: (&str, Tone), body: &[(char, Tone, bool)], width: usize) {
    let indent = first.0.chars().count();
    for (i, cells) in wrap_cells(body, width.saturating_sub(indent)).into_iter().enumerate() {
        let mut line = to_line(&cells);
        let lead = if i == 0 { first.0.to_string() } else { " ".repeat(indent) };
        line.pieces.insert(0, Piece { text: lead, tone: first.1, bold: i == 0 });
        out.push(line);
    }
}

fn plain_cells(text: &str, tone: Tone) -> Vec<(char, Tone, bool)> {
    clean(text).chars().map(|c| (c, tone, false)).collect()
}

/// Inline Markdown: `code` and **bold**. The marks themselves are not shown.
fn inline_cells(text: &str, bold_all: bool) -> Vec<(char, Tone, bool)> {
    let chars: Vec<char> = clean(text).chars().collect();
    let (mut out, mut code, mut bold, mut i) = (Vec::new(), false, false, 0);
    while i < chars.len() {
        if chars[i] == '`' {
            code = !code;
            i += 1;
        } else if !code && chars[i] == '*' && chars.get(i + 1) == Some(&'*') {
            bold = !bold;
            i += 2;
        } else {
            out.push((chars[i], if code { Tone::Code } else { Tone::Text }, bold || bold_all));
            i += 1;
        }
    }
    out
}

/// An answer, with the Markdown that agents commonly use.
fn markdown(out: &mut Vec<Line>, source: &str, width: usize) {
    let mut fenced = false;
    for raw in source.lines() {
        let trimmed = raw.trim_start();
        if trimmed.starts_with("```") {
            fenced = !fenced;
            continue;
        }
        if fenced {
            // Code keeps its spacing; long lines continue on the next one.
            let cells = plain_cells(raw, Tone::Code);
            let chunks: Vec<_> = cells.chunks(width.saturating_sub(2).max(1)).collect();
            for chunk in if chunks.is_empty() { vec![&cells[..]] } else { chunks } {
                let mut line = to_line(chunk);
                line.pieces.insert(0, Piece { text: "  ".into(), tone: Tone::Code, bold: false });
                line.block = true;
                out.push(line);
            }
            continue;
        }
        if trimmed.is_empty() {
            out.push(Line::default());
            continue;
        }
        let indent = " ".repeat(raw.len() - trimmed.len());
        let heading = trimmed.trim_start_matches('#');
        if heading.len() < trimmed.len() && heading.starts_with(' ') {
            hanging(out, ("", Tone::Text), &inline_cells(heading.trim_start(), true), width);
        } else if let Some(item) = trimmed.strip_prefix("- ").or_else(|| trimmed.strip_prefix("* ")) {
            hanging(out, (&format!("{indent}\u{2022} "), Tone::Faint), &inline_cells(item, false), width);
        } else {
            hanging(out, (&indent, Tone::Text), &inline_cells(trimmed, false), width);
        }
    }
}

fn seconds(secs: f32) -> String {
    let s = secs.max(0.0) as u64;
    if s >= 60 { format!("{}m {:02}s", s / 60, s % 60) } else { format!("{s}s") }
}

fn count(n: usize, one: &str, many: &str) -> String {
    format!("{n} {}", if n == 1 { one } else { many })
}

/// One small line, cut to fit.
fn small(mark: &str, mark_tone: Tone, body: &str, width: usize) -> Line {
    let body = clip_to(&clean(body.lines().next().unwrap_or_default()), width.saturating_sub(4));
    let mut line = Line::new(format!("  {mark} "), mark_tone);
    line.pieces.push(Piece { text: body, tone: Tone::Faint, bold: false });
    line
}

/// While it runs: the latest of what the agent is doing.
fn live(out: &mut Vec<Line>, turn: &Turn, elapsed: f32, width: usize) {
    let from = turn.items.len().saturating_sub(LIVE_LINES);
    for item in &turn.items[from..] {
        out.push(match item {
            Item::Step(s) => {
                let (mark, tone) = match s.ok {
                    None => ("\u{203a}", Tone::Accent),
                    Some(true) => ("\u{2713}", Tone::Faint),
                    Some(false) => ("\u{2717}", Tone::Bad),
                };
                small(mark, tone, &s.label, width)
            }
            Item::Text(t) | Item::Note(t) => small("\u{00b7}", Tone::Faint, t, width),
        });
    }
    let spin = SPINNER[(elapsed * 10.0) as usize % SPINNER.len()];
    let mut line = Line::new(format!("  {spin} "), Tone::Accent);
    line.pieces.push(Piece { text: format!("Working \u{00b7} {}", seconds(elapsed)), tone: Tone::Faint, bold: false });
    out.push(line);
}

/// After it ends: one line saying what was done, then the answer.
fn finished(out: &mut Vec<Line>, turn: &Turn, width: usize) {
    let mut edits: Vec<&str> = Vec::new();
    for s in turn.steps().filter(|s| s.kind == StepKind::Edit && s.ok != Some(false)) {
        if !edits.contains(&s.label.as_str()) {
            edits.push(&s.label);
        }
    }
    let commands = turn.steps().filter(|s| s.kind == StepKind::Command && s.ok == Some(true)).count();
    let others = turn.steps().filter(|s| s.kind == StepKind::Other).count();
    let mut parts = Vec::new();
    if !edits.is_empty() {
        parts.push(count(edits.len(), "file changed", "files changed"));
    }
    if commands > 0 {
        parts.push(count(commands, "command run", "commands run"));
    }
    if others > 0 {
        parts.push(count(others, "other step", "other steps"));
    }
    parts.push(seconds(turn.took.unwrap_or_default()));
    out.push(small("\u{2713}", Tone::Good, &parts.join(" \u{00b7} "), width));
    // Changed files are always named.
    for label in edits {
        out.push(small(" ", Tone::Faint, label, width));
    }
    if let Some(answer) = turn.answer() {
        out.push(Line::default());
        markdown(out, answer, width);
    }
    if let Some(error) = &turn.error {
        out.push(Line::default());
        for part in error.lines() {
            hanging(out, ("", Tone::Bad), &plain_cells(part, Tone::Bad), width);
        }
    }
    // Last, next to the hint that offers to allow it, and never cut short: nothing should
    // be allowed that can't be read in full.
    if !turn.denied.is_empty() {
        out.push(Line::default());
    }
    for denied in &turn.denied {
        let note = if denied.rule.is_some() { "Blocked: " } else { "Blocked (can't be allowed here): " };
        let body = plain_cells(&format!("{note}{}", denied.label), Tone::Faint);
        hanging(out, ("  ! ", Tone::Warn), &body, width);
    }
}

fn transcript(chat: &Chat, width: usize) -> Vec<Line> {
    let mut out = Vec::new();
    for turn in &chat.turns {
        if !out.is_empty() {
            out.push(Line::default());
        }
        for (i, part) in turn.asked.lines().enumerate() {
            let mark = if i == 0 { "\u{276f} " } else { "  " };
            let cells: Vec<_> = clean(part).chars().map(|c| (c, Tone::Text, true)).collect();
            hanging(&mut out, (mark, Tone::Accent), &cells, width);
        }
        if turn.done() {
            finished(&mut out, turn, width);
        } else {
            live(&mut out, turn, chat.elapsed(), width);
        }
    }
    out
}

/// The message box's lines, and where the cursor is in them.
fn input_lines(input: &str, cursor: usize, width: usize) -> (Vec<String>, (usize, usize)) {
    let width = width.max(1);
    let mut lines = vec![String::new()];
    let (mut at, mut col) = ((0, 0), 0);
    for (i, c) in input.chars().enumerate() {
        if col == width && c != '\n' {
            lines.push(String::new());
            col = 0;
        }
        if i == cursor {
            at = (lines.len() - 1, col);
        }
        if c == '\n' {
            lines.push(String::new());
            col = 0;
        } else if let Some(line) = lines.last_mut() {
            line.push(c);
            col += 1;
        }
    }
    if cursor >= input.chars().count() {
        if col == width {
            lines.push(String::new());
            col = 0;
        }
        at = (lines.len() - 1, col);
    }
    (lines, at)
}

fn color(tone: Tone, pal: &Palette) -> Rgba {
    match tone {
        Tone::Text => pal.foreground,
        Tone::Faint => mix(pal.surface, pal.foreground, 0.55),
        Tone::Accent => pal.accent,
        Tone::Good => pal.ansi[2],
        Tone::Bad => pal.ansi[1],
        Tone::Warn => pal.ansi[3],
        Tone::Code => pal.ansi[6],
    }
}

/// Draw the conversation inside a pane's card.
pub fn draw(ctx: &mut Ctx, chat: &mut Chat, card: Rect, opacity: f32, out: &mut Vec<Quad>) {
    let (cw, ch, s) = (ctx.glyphs.cell_w, ctx.glyphs.cell_h, ctx.scale);
    let pal = ctx.palette;
    let pad = (ctx.config.padding * s).round().max(8.0 * s);
    let inner = Rect::new(card.x + pad, card.y + pad, card.w - 2.0 * pad, card.h - 2.0 * pad);
    if inner.w < cw * 12.0 || inner.h < ch * 6.0 {
        return;
    }
    let clip = [inner.x, inner.y, inner.right(), inner.bottom()];
    let fade = |c: Rgba| with_alpha(c, opacity);
    let faint = fade(color(Tone::Faint, pal));
    let cols = (inner.w / cw) as usize;

    // Header: who is answering, and where.
    let folder = chat.dir.file_name().map_or_else(|| chat.dir.to_string_lossy(), |n| n.to_string_lossy());
    let name = chat.agent.name();
    let used = text(ctx, out, inner.x, inner.y, name, fade(pal.accent), STYLE_BOLD, inner.w, clip);
    text(ctx, out, inner.x + used, inner.y, &format!("  {folder}"), faint, 0, inner.w - used, clip);
    let top = inner.y + (ch * 1.5).round();
    out.push(rounded(
        Rect::new(inner.x, top - (ch * 0.3).round(), inner.w, s.max(1.0)),
        fade(pal.border),
        0.0,
        0.0,
        [0.0; 4],
        clip,
    ));

    // The hint line and the message box are fixed at the bottom.
    let hint = if chat.running() {
        "ctrl+c stop \u{00b7} esc terminal".to_string()
    } else if !chat.grantable().is_empty() {
        "ctrl+y allow what was blocked and retry \u{00b7} esc terminal".to_string()
    } else {
        "enter send \u{00b7} ctrl+c copy answer \u{00b7} esc terminal".to_string()
    };
    let hint_y = inner.bottom() - ch;
    let hint_tone = if !chat.running() && !chat.grantable().is_empty() { fade(pal.ansi[3]) } else { faint };
    text(ctx, out, inner.x, hint_y, &hint, hint_tone, 0, inner.w, clip);

    let box_cols = cols.saturating_sub(4);
    let (typed, (row, col)) = input_lines(&chat.input, chat.cursor, box_cols);
    let shown = typed.len().min(INPUT_LINES);
    let first = (row + 1).saturating_sub(shown);
    let box_h = (shown as f32 * ch + ch * 0.7).round();
    let frame = Rect::new(inner.x, hint_y - box_h - (ch * 0.35).round(), inner.w, box_h);
    let edge = if ctx.focused { with_alpha(pal.accent, 0.8) } else { pal.border };
    out.push(rounded(
        frame,
        fade(with_alpha(mix(pal.surface, pal.foreground, 0.05), 0.9)),
        8.0 * s,
        s.max(1.0),
        fade(edge),
        clip,
    ));
    let tx = frame.x + 2.0 * cw;
    let ty = frame.y + (ch * 0.35).round();
    text(ctx, out, frame.x + (cw * 0.5).round(), ty, "\u{276f}", fade(pal.accent), STYLE_BOLD, cw, clip);
    if chat.input.is_empty() {
        let placeholder = if chat.turns.is_empty() { "What should it do?" } else { "Reply\u{2026}" };
        text(ctx, out, tx + cw, ty, placeholder, faint, 0, inner.w - 4.0 * cw, clip);
    }
    for (i, line) in typed.iter().skip(first).take(shown).enumerate() {
        text(ctx, out, tx, ty + i as f32 * ch, line, fade(pal.foreground), 0, (box_cols + 1) as f32 * cw, clip);
    }
    if ctx.focused {
        let caret = Rect::new(tx + col as f32 * cw, ty + (row - first) as f32 * ch, (2.0 * s).max(2.0), ch);
        out.push(rounded(caret, with_alpha(pal.cursor, ctx.cursor_alpha * opacity), 0.0, 0.0, [0.0; 4], clip));
    }

    // The conversation fills the rest, newest at the bottom.
    let bottom = frame.y - (ch * 0.5).round();
    let rows = ((bottom - top) / ch).floor().max(0.0) as usize;
    let lines = transcript(chat, cols.saturating_sub(1));
    let max_scroll = lines.len().saturating_sub(rows);
    chat.scroll = chat.scroll.min(max_scroll);
    let from = max_scroll - chat.scroll;
    if lines.is_empty() {
        let about = format!("{name} works in this folder. Its file edits are applied without asking.");
        text(ctx, out, inner.x, top, &about, faint, 0, inner.w, clip);
    }
    let body_clip = [inner.x, top, inner.right(), bottom];
    for (i, line) in lines.iter().skip(from).take(rows).enumerate() {
        let y = top + i as f32 * ch;
        if line.block {
            let back = Rect::new(inner.x, y, inner.w, ch);
            out.push(rounded(
                back,
                fade(with_alpha(mix(pal.surface, pal.foreground, 0.08), 0.85)),
                0.0,
                0.0,
                [0.0; 4],
                body_clip,
            ));
        }
        let mut x = inner.x;
        for piece in &line.pieces {
            let style = if piece.bold { STYLE_BOLD } else { 0 };
            x += text(ctx, out, x, y, &piece.text, fade(color(piece.tone, pal)), style, inner.right() - x, body_clip);
        }
    }
    if chat.scroll > 0 {
        let more = format!("\u{2193} {} more", chat.scroll);
        let w = more.chars().count() as f32 * cw;
        text(ctx, out, inner.right() - w, inner.y, &more, faint, 0, w, clip);
    }
}

#[cfg(test)]
mod tests {
    use std::path::PathBuf;

    use super::super::{Agent, Denied, Event};
    use super::*;

    fn shown(chat: &Chat) -> Vec<String> {
        transcript(chat, 60).iter().map(Line::plain).collect()
    }

    #[test]
    fn small_lines_while_working_then_a_summary_and_the_answer() {
        let mut chat = Chat::new(Agent::Claude, PathBuf::from("."));
        chat.begin("fix it".into());
        chat.apply(Event::Text("Looking first.\nMore.".into()));
        chat.apply(Event::Step { id: "1".into(), label: "Edited a.rs".into(), kind: StepKind::Edit });
        chat.apply(Event::StepDone { id: "1".into(), ok: true });
        chat.apply(Event::Step { id: "2".into(), label: "$ cargo test".into(), kind: StepKind::Command });
        let running = shown(&chat);
        assert_eq!(
            running[..4],
            ["\u{276f} fix it", "  \u{00b7} Looking first.", "  \u{2713} Edited a.rs", "  \u{203a} $ cargo test"]
        );
        assert!(running[4].contains("Working"));
        chat.apply(Event::StepDone { id: "2".into(), ok: false });
        let long = format!("$ cargo test {}--the-end", "--flag ".repeat(12));
        chat.apply(Event::Denied(Denied { label: long, rule: Some("Bash(x)".into()) }));
        chat.apply(Event::Text("**Fixed** `a.rs`.".into()));
        chat.apply(Event::Finished { error: None });
        let after = shown(&chat);
        assert_eq!(
            after[..6],
            ["\u{276f} fix it", "  \u{2713} 1 file changed \u{00b7} 0s", "    Edited a.rs", "", "Fixed a.rs.", ""]
        );
        assert!(after[6].starts_with("  ! Blocked: $ cargo test"));
        assert!(after.len() > 7 && after.last().is_some_and(|l| l.ends_with("--the-end")), "in full: {after:?}");
    }

    #[test]
    fn answers_wrap_and_keep_code_blocks() {
        let mut out = Vec::new();
        markdown(&mut out, "## Title\n- one two three four\n```rust\n    let x = 1;\n```", 12);
        let plain: Vec<_> = out.iter().map(Line::plain).collect();
        assert_eq!(plain, ["Title", "\u{2022} one two", "  three four", "      let x ", "  = 1;"]);
        assert!(out[3].block && !out[1].block);
        let long = wrap_cells(&plain_cells("abcdefgh ij", Tone::Text), 4);
        assert_eq!(long.iter().map(|l| to_line(l).plain()).collect::<Vec<_>>(), ["abcd", "efgh", "ij"]);
    }

    #[test]
    fn the_cursor_follows_the_wrapped_message() {
        assert_eq!(input_lines("", 0, 5), (vec![String::new()], (0, 0)));
        assert_eq!(input_lines("abcdefg", 6, 5), (vec!["abcde".into(), "fg".into()], (1, 1)));
        assert_eq!(input_lines("abcde", 5, 5).1, (1, 0), "after a full line");
        assert_eq!(input_lines("a\nb", 2, 5).1, (1, 0));
    }
}