use super::{Chat, Item, StepKind, Turn};
use crate::config::{Palette, Rgba};
use crate::render::glyphs::STYLE_BOLD;
use crate::render::gpu::Quad;
use crate::render::{Ctx, mix, rounded, text, with_alpha};
use crate::terminal::layout::Rect;
const LIVE_LINES: usize = 6;
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,
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>,
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()
}
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}"
}
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];
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
}
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()
}
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
}
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 {
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 })
}
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
}
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);
}
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));
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);
}
}
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
}
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],
}
}
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;
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,
));
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));
}
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));
}
}