use super::app::{self, Activity, App, Block, Menu, NoteKind, Picker, ToolState, Welcome};
use crate::approve::Choice;
use crate::status;
use ratatui::layout::{Alignment, Constraint, Layout, Rect};
use ratatui::style::{Color, Modifier, Style};
use ratatui::text::{Line, Span, Text};
use ratatui::widgets::{Block as Box_, BorderType, Clear, Paragraph, Wrap};
use ratatui::Frame;
use unicode_width::UnicodeWidthStr;
const ACCENT: Color = rgb(eclipse_core::palette::ACCENT);
const WORDMARK_TOP: Color = rgb(eclipse_core::palette::WORDMARK_TOP);
const WORDMARK_FOOT: Color = rgb(eclipse_core::palette::WORDMARK_FOOT);
const USER: Color = rgb(eclipse_core::palette::USER);
const OK: Color = rgb(eclipse_core::palette::OK);
const BAD: Color = rgb(eclipse_core::palette::BAD);
const WARN: Color = rgb(eclipse_core::palette::WARN);
const DIM: Color = Color::DarkGray;
const FAINT: Color = rgb(eclipse_core::palette::FAINT);
const fn rgb((r, g, b): (u8, u8, u8)) -> Color {
Color::Rgb(r, g, b)
}
const SPINNER: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
pub fn draw(f: &mut Frame, app: &App, committed: usize, room: usize) {
let area = f.area();
let badge_row = u16::from(app.update.is_some());
let rows = Layout::vertical([
Constraint::Length(badge_row),
Constraint::Min(0), Constraint::Length(1), Constraint::Length(1), Constraint::Length(1), ])
.split(area);
if badge_row > 0 {
badge(f, app, rows[0]);
}
transcript(f, app, rows[1], committed, room);
rule(f, rows[2]);
composer(f, app, rows[3]);
readout(f, app, rows[4]);
if let Some(p) = &app.picker {
picker(f, area, p);
} else if let Some(a) = &app.approval {
approval(f, area, &a.tool, &a.summary, a.choice);
} else if let Some(m) = &app.menu {
menu(f, area, rows[3], m);
}
}
fn badge(f: &mut Frame, app: &App, area: Rect) {
let Some(behind) = &app.update else {
return;
};
let text = behind.line();
let pad = (area.width as usize).saturating_sub(text.chars().count());
let spans = vec![
Span::raw(" ".repeat(pad)),
Span::styled(
format!("↑ {} available", behind.shown_latest()),
Style::default().fg(WARN),
),
Span::styled(" · eclipse upgrade", Style::default().fg(FAINT)),
];
f.render_widget(Paragraph::new(Line::from(spans)), area);
}
pub fn header_line(app: &App, width: usize) -> Line<'static> {
let mut spans = vec![
Span::styled(" ◐ ", Style::default().fg(ACCENT)),
Span::styled(
"eclipse",
Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
),
Span::styled(
format!(" {} ", env!("CARGO_PKG_VERSION")),
Style::default().fg(FAINT),
),
];
if let Some(p) = &app.profile {
spans.push(Span::styled(format!(" · {p}"), Style::default().fg(DIM)));
}
spans.push(Span::styled(" · ", Style::default().fg(FAINT)));
spans.push(Span::styled(
app.session.clone().unwrap_or_else(|| "new session".into()),
Style::default().fg(DIM),
));
spans.push(Span::styled(" · ", Style::default().fg(FAINT)));
let used: usize = spans.iter().map(|s| s.content.chars().count()).sum();
let room = width.saturating_sub(used + 1);
if room > 8 {
spans.push(Span::styled(
super::app::short_path(&app.workspace, room),
Style::default().fg(FAINT),
));
}
Line::from(spans)
}
fn rule(f: &mut Frame, area: Rect) {
let line = "─".repeat(area.width as usize);
f.render_widget(
Paragraph::new(Line::from(Span::styled(line, Style::default().fg(FAINT)))),
area,
);
}
const REASONING_PREVIEW: usize = 5;
fn clamp_chars(wrapped: &[String], chars: usize) -> (usize, bool) {
let mut used = 0usize;
for (i, line) in wrapped.iter().enumerate() {
let len = line.chars().count();
if used + len > chars {
return (i, true);
}
used += len;
}
(wrapped.len(), false)
}
#[cfg(test)]
pub fn lines_for_test(app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
build_lines_of(&app.blocks, app, width, height)
}
pub fn transcript_lines(app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
build_lines_of(&app.blocks, app, width, height)
}
pub fn last_folded_printed_reasoning(app: &App) -> Option<usize> {
let upto = app.fold.len().min(app.blocks.len()).min(app.printed);
(0..upto).rev().find(|&i| {
app.fold.get(i).copied().flatten() == Some(false)
&& matches!(&app.blocks[i], Block::Reasoning { text, .. }
if text.lines().count() > REASONING_PREVIEW)
})
}
pub fn reasoning_echo(app: &App, index: usize, width: usize) -> Vec<Line<'static>> {
let indent = " ";
let text = match app.blocks.get(index) {
Some(Block::Reasoning { text, .. }) => text,
_ => return Vec::new(),
};
let wrapped = wrap(text, width.saturating_sub(4));
let mut out = vec![
Line::from(""),
rule_line(width),
Line::from(Span::styled(
format!(
"{indent}💭 reasoning, printed again · {} line(s)",
wrapped.len()
),
Style::default().fg(FAINT),
)),
];
for (i, l) in wrapped.iter().enumerate() {
let head = if i == 0 { "💭 " } else { " " };
out.push(Line::from(vec![
Span::styled(format!("{indent}{head}"), Style::default().fg(FAINT)),
Span::styled(l.clone(), Style::default().fg(DIM)),
]));
}
out.push(rule_line(width));
out.push(Line::from(""));
out
}
pub fn finished_blocks(app: &App) -> usize {
match app.blocks.last() {
Some(Block::Reply { done: false, .. })
| Some(Block::Reasoning { done: false, .. })
| Some(Block::Tool {
state: ToolState::Running,
..
}) => app.blocks.len().saturating_sub(1),
_ => app.blocks.len(),
}
}
pub fn line_offset_of(app: &App, blocks: usize, width: usize, height: usize) -> usize {
let upto = blocks.min(app.blocks.len());
build_lines_of(&app.blocks[..upto], app, width, height).len()
}
#[cfg(test)]
pub fn stable_line_count(app: &App, width: usize, height: usize) -> usize {
line_offset_of(app, finished_blocks(app), width, height)
}
fn rule_line(width: usize) -> Line<'static> {
Line::from(Span::styled(
"─".repeat(width.max(1)),
Style::default().fg(FAINT),
))
}
fn build_lines_of(blocks: &[Block], app: &App, width: usize, height: usize) -> Vec<Line<'static>> {
let mut out: Vec<Line<'static>> = Vec::new();
let indent = " ";
let mut on_rule = false;
for (out_block_index, block) in blocks.iter().enumerate() {
match block {
Block::Welcome(welcome) => {
out.extend(welcome_fitted(
welcome,
app.session.as_deref(),
width,
height,
));
on_rule = false;
}
Block::User(text) => {
out.push(rule_line(width));
let wrapped = wrap(text, width.saturating_sub(2));
for (i, l) in wrapped.iter().enumerate() {
if i == 0 {
out.push(Line::from(vec![
Span::styled("❯ ", Style::default().fg(ACCENT)),
Span::styled(l.clone(), Style::default().fg(USER)),
]));
} else {
out.push(Line::from(vec![
Span::styled(indent.to_string(), Style::default()),
Span::styled(l.clone(), Style::default().fg(USER)),
]));
}
}
out.push(rule_line(width));
out.push(Line::from(""));
on_rule = true;
}
Block::Reply { text, done } => {
if text.trim().is_empty() && *done {
continue;
}
if !on_rule {
out.push(rule_line(width));
}
out.push(Line::from(vec![
Span::styled("◐ ", Style::default().fg(ACCENT)),
Span::styled("eclipse", Style::default().fg(ACCENT)),
]));
let wrapped = wrap(text, width.saturating_sub(2));
for l in &wrapped {
out.push(Line::from(vec![
Span::styled(indent.to_string(), Style::default()),
Span::styled(l.clone(), Style::default()),
]));
}
if !done {
out.push(Line::from(Span::styled(
format!("{indent}▌"),
Style::default().fg(ACCENT),
)));
}
if *done {
out.push(rule_line(width));
}
out.push(Line::from(""));
on_rule = *done;
}
Block::Reasoning { text, done } => {
let display = app.display_for(out_block_index);
if display.hidden() {
continue;
}
let wrapped = wrap(text, width.saturating_sub(4));
let open = app.fold_for(out_block_index) || display.unfolded();
let cut = display.clamp().map(|chars| clamp_chars(&wrapped, chars));
let shown: &[String] = if open {
&wrapped
} else {
match &cut {
Some(cut) => &wrapped[..wrapped.len().min(cut.0)],
None => &wrapped[..wrapped.len().min(REASONING_PREVIEW)],
}
};
for (i, l) in shown.iter().enumerate() {
let head = if i == 0 { "💭 " } else { " " };
let body = match &cut {
Some((_, true)) if !open && i + 1 == shown.len() => format!("{l}…"),
_ => l.clone(),
};
out.push(Line::from(vec![
Span::styled(format!("{indent}{head}"), Style::default().fg(FAINT)),
Span::styled(body, Style::default().fg(DIM)),
]));
}
let hidden = wrapped.len().saturating_sub(shown.len());
if hidden > 0 || !done || !shown.is_empty() {
let mut tail = String::new();
if hidden > 0 {
tail.push_str(&format!("+{hidden} line(s)"));
}
if !*done {
if !tail.is_empty() {
tail.push_str(" · ");
}
tail.push_str("thinking");
}
if !open && (hidden > 0 || !*done) {
if !tail.is_empty() {
tail.push_str(" · ");
}
if app.fold.get(out_block_index).copied().flatten() == Some(false) {
tail.push_str("^T prints it below");
} else {
tail.push_str("^T shows it all");
}
}
if !tail.is_empty() {
let colour = if *done { FAINT } else { ACCENT };
out.push(Line::from(vec![
Span::styled(format!("{indent} "), Style::default()),
Span::styled(tail, Style::default().fg(colour)),
]));
}
}
out.push(Line::from(""));
}
Block::Tool {
name,
args,
state,
output,
..
} => {
let refused = *state == ToolState::Failed && output.contains("declined");
let (glyph, colour) = match state {
ToolState::Running => ("⏺", WARN),
ToolState::Ok => ("✓", OK),
ToolState::Failed if refused => ("⊘", WARN),
ToolState::Failed => ("✗", BAD),
};
let call = one_line(args);
let call = if call.is_empty() {
name.clone()
} else {
format!("{name}({call})")
};
let body = if *state == ToolState::Failed {
colour
} else {
DIM
};
let room = width.saturating_sub(indent.len() + 2);
out.push(Line::from(vec![
Span::styled(format!("{indent}{glyph} "), Style::default().fg(colour)),
Span::styled(truncate(&call, room), Style::default().fg(body)),
]));
on_rule = false;
}
Block::Note { kind, text } => {
let (glyph, colour) = match kind {
NoteKind::Info => ("·", DIM),
NoteKind::Warn => ("!", WARN),
NoteKind::Error => ("✗", BAD),
};
on_rule = false;
for (i, l) in wrap(text, width.saturating_sub(4)).iter().enumerate() {
let head = if i == 0 { glyph } else { " " };
out.push(Line::from(vec![
Span::styled(format!("{indent}{head} "), Style::default().fg(colour)),
Span::styled(l.clone(), Style::default().fg(colour)),
]));
}
}
}
}
out
}
const WORDMARK: [[&str; 5]; 7] = [
["█████", "█ ", "████ ", "█ ", "█████"], ["▄███▄", "█ ", "█ ", "█ ", "▀███▀"], ["█ ", "█ ", "█ ", "█ ", "█████"], ["█████", " █ ", " █ ", " █ ", "█████"], ["████ ", "█ █", "████ ", "█ ", "█ "], ["▄███▄", "█ ", "▀███▄", " █", "▀███▀"], ["█████", "█ ", "████ ", "█ ", "█████"], ];
const WORDMARK_COLS: usize = 7 * 5 + 6 * 2;
fn wordmark() -> Vec<String> {
(0..5)
.map(|row| {
WORDMARK
.iter()
.map(|letter| letter[row])
.collect::<Vec<_>>()
.join(" ")
})
.collect()
}
fn wordmark_row_colour(row: usize, rows: usize) -> Color {
let t = if rows <= 1 {
0.0
} else {
row as f32 / (rows - 1) as f32
};
let (Color::Rgb(r0, g0, b0), Color::Rgb(r1, g1, b1)) = (WORDMARK_TOP, WORDMARK_FOOT) else {
return WORDMARK_TOP;
};
let mix = |a: u8, b: u8| (a as f32 + (b as f32 - a as f32) * t).round() as u8;
Color::Rgb(mix(r0, r1), mix(g0, g1), mix(b0, b1))
}
fn fitting(pairs: Vec<(String, Style)>, width: usize) -> Line<'static> {
let mut spans: Vec<Span<'static>> = Vec::new();
let mut used = 0usize;
for (text, style) in pairs {
let room = width.saturating_sub(used);
if room == 0 {
break;
}
let text = truncate(&text, room);
let n = text.chars().count();
if n == 0 {
break;
}
used += n;
spans.push(Span::styled(text, style));
if used >= width {
break;
}
}
Line::from(spans)
}
#[cfg(test)]
fn welcome_lines(welcome: &Welcome, session: Option<&str>, width: usize) -> Vec<Line<'static>> {
welcome_fitted(welcome, session, width, usize::MAX)
}
fn welcome_fitted(
welcome: &Welcome,
session: Option<&str>,
width: usize,
height: usize,
) -> Vec<Line<'static>> {
let facts = facts(welcome, session);
for (art, tools, skills) in [
(true, true, true),
(true, true, false),
(true, false, false),
(false, false, false),
] {
let lines = pane(welcome, &facts, width, art, tools, skills);
if lines.len() <= height {
return lines;
}
}
pane(welcome, &facts, width, false, false, false)
}
fn facts(welcome: &Welcome, session: Option<&str>) -> Vec<(&'static str, String)> {
let mut facts: Vec<(&'static str, String)> = vec![
("version", welcome.version.clone()),
("endpoint", welcome.endpoint.clone()),
("workspace", welcome.workspace.clone()),
(
"session",
session
.map(crate::status::short_session)
.unwrap_or_else(|| "new".to_string()),
),
];
if let Some(profile) = &welcome.profile {
facts.insert(1, ("profile", profile.clone()));
}
facts.push((
"approvals",
if welcome.approvals { "auto" } else { "ask" }.to_string(),
));
facts
}
fn label_width(facts: &[(&str, String)]) -> usize {
facts
.iter()
.map(|(l, _)| l.chars().count())
.max()
.unwrap_or(0)
+ 2
}
fn hints(width: usize) -> Vec<(String, Style)> {
const SEP: &str = " · ";
let accent = Style::default().fg(ACCENT);
let faint = Style::default().fg(FAINT);
let tiers: [&[(&str, Style)]; 3] = [
&[
("/", accent),
(" commands", faint),
(SEP, faint),
("!command", accent),
(" runs a shell command", faint),
(SEP, faint),
("^D", accent),
(" quits", faint),
],
&[
("/", accent),
(" commands", faint),
(SEP, faint),
("!command", accent),
(" runs a shell", faint),
(SEP, faint),
("^D", accent),
(" quits", faint),
],
&[
("/", accent),
(" commands", faint),
(SEP, faint),
("!", accent),
(" shell", faint),
(SEP, faint),
("^D", accent),
(" quits", faint),
],
];
let fits =
|t: &[(&str, Style)]| -> usize { t.iter().map(|(text, _)| text.chars().count()).sum() };
let chosen = tiers
.iter()
.find(|t| fits(t) <= width)
.or(tiers.last())
.copied()
.unwrap_or_default();
chosen
.iter()
.map(|(text, style)| (text.to_string(), *style))
.collect()
}
fn pane(
welcome: &Welcome,
facts: &[(&'static str, String)],
width: usize,
with_art: bool,
with_tools: bool,
with_skills: bool,
) -> Vec<Line<'static>> {
let mut out: Vec<Line<'static>> = Vec::new();
let label_width = label_width(facts);
if with_art && width >= WORDMARK_COLS {
out.push(Line::from(""));
out.push(Line::from(""));
for (row, line) in wordmark().iter().enumerate() {
out.push(Line::from(Span::styled(
line.clone(),
Style::default().fg(wordmark_row_colour(row, 5)),
)));
}
out.push(Line::from(""));
out.push(Line::from(""));
} else {
out.push(Line::from(vec![
Span::styled("ECLIPSE", Style::default().fg(ACCENT)),
Span::styled(format!(" {}", welcome.version), Style::default().fg(DIM)),
]));
out.push(Line::from(""));
}
for (label, value) in facts.iter() {
out.push(fitting(
vec![
(format!("{label:<label_width$}"), Style::default().fg(FAINT)),
(value.clone(), Style::default().fg(colour_for(label, value))),
],
width,
));
}
if with_tools {
out.push(Line::from(""));
let count = welcome.tool_count();
out.push(fitting(
vec![
("tools".to_string(), Style::default().fg(FAINT)),
(format!(" {count}"), Style::default().fg(OK)),
(" offered".to_string(), Style::default().fg(FAINT)),
],
width,
));
for (source, names) in &welcome.groups {
wrapped_group(&mut out, source, names, width);
}
}
if with_skills && welcome.skill_count() > 0 {
out.push(fitting(
vec![
("skills".to_string(), Style::default().fg(FAINT)),
(
format!(" {}", welcome.skill_count()),
Style::default().fg(OK),
),
(" available".to_string(), Style::default().fg(FAINT)),
],
width,
));
for (source, names) in &welcome.skills {
wrapped_group(&mut out, source, names, width);
}
}
out.push(Line::from(""));
out.push(fitting(hints(width), width));
out.push(Line::from(""));
out
}
fn wrapped_group(out: &mut Vec<Line<'static>>, source: &str, names: &[String], width: usize) {
let mut line = truncate(&format!(" {source}: "), width.saturating_sub(1));
for (i, name) in names.iter().enumerate() {
let piece = if i == 0 {
name.clone()
} else {
format!(", {name}")
};
if line.chars().count() + piece.chars().count() > width.saturating_sub(1) {
out.push(Line::from(Span::styled(
line.trim_end().to_string(),
Style::default().fg(DIM),
)));
line = format!(" {name}");
continue;
}
line.push_str(&piece);
}
out.push(Line::from(Span::styled(line, Style::default().fg(DIM))));
}
fn colour_for(label: &str, value: &str) -> Color {
match (label, value) {
("model", _) => USER,
("profile", _) => OK,
("approvals", "auto") => ACCENT,
_ => DIM,
}
}
fn transcript(f: &mut Frame, app: &App, area: Rect, printed: usize, room: usize) {
let lines = build_lines_of(&app.blocks, app, area.width as usize, room);
let skip = line_offset_of(app, printed, area.width as usize, room);
let rest: Vec<Line> = lines.into_iter().skip(skip).collect();
let (height, total) = (area.height as usize, rest.len());
let visible = if total > height {
rest.into_iter().skip(total - height).collect()
} else {
rest
};
f.render_widget(Paragraph::new(Text::from(visible)), area);
}
fn picker(f: &mut Frame, area: Rect, picker: &Picker) {
let w = (area.width as f32 * 0.7) as u16;
let count = picker.items.len() as u16;
let per_row = match picker.kind {
crate::tui::app::PickerKind::Provider => 3,
_ => 2,
};
let want = count.saturating_mul(per_row).saturating_add(7);
let h = want.min(area.height);
let x = area.x + (area.width.saturating_sub(w)) / 2;
let y = area.y + (area.height.saturating_sub(h)) / 2;
let rect = Rect {
x,
y,
width: w,
height: h,
};
f.render_widget(Clear, rect);
let count = format!(" {}", picker.count_label());
let mut lines = vec![
Line::from(vec![
Span::styled(
match picker.kind {
crate::tui::app::PickerKind::Model => "Switch ",
crate::tui::app::PickerKind::Provider => "Ask ",
crate::tui::app::PickerKind::Sessions => "Resume ",
crate::tui::app::PickerKind::Tasks => "Open ",
},
Style::default().fg(DIM),
),
Span::styled(picker.title, Style::default().fg(ACCENT)),
Span::styled(count, Style::default().fg(FAINT)),
]),
Line::from(vec![
Span::styled(
format!(
" {} ",
if picker.query.is_empty() {
"filter"
} else {
" "
}
),
Style::default().fg(FAINT),
),
Span::styled(picker.query.clone(), Style::default().fg(DIM)),
if picker.query.is_empty() {
Span::styled("type to narrow", Style::default().fg(FAINT))
} else {
Span::raw("")
},
]),
Line::from(""),
];
let room = rect.height.saturating_sub(6) as usize;
let detail = room >= picker.items.len() * per_row as usize;
let rows = if detail {
room / per_row as usize
} else {
room
};
let first = picker.cursor.saturating_sub(rows.saturating_sub(1));
for (i, item) in picker.items.iter().enumerate().skip(first).take(rows) {
let current = i == picker.cursor;
let mut spans = Vec::new();
if current {
spans.push(Span::styled(" › ", Style::default().fg(ACCENT)));
spans.push(Span::styled(
item.label(),
Style::default().add_modifier(Modifier::BOLD),
));
} else {
spans.push(Span::styled(
format!(" {}", item.label()),
Style::default().fg(DIM),
));
}
if !item.note.is_empty() && picker.kind == crate::tui::app::PickerKind::Model {
spans.push(Span::styled(
format!(" {}", item.note),
Style::default().fg(FAINT),
));
}
lines.push(Line::from(spans));
if !item.note.is_empty() && picker.kind != crate::tui::app::PickerKind::Model {
lines.push(Line::from(Span::styled(
format!(" {}", item.note),
Style::default().fg(FAINT),
)));
if picker.kind == crate::tui::app::PickerKind::Provider && detail {
lines.push(Line::from(Span::styled(
format!(" {}", item.preview),
Style::default().fg(FAINT),
)));
}
if picker.kind == crate::tui::app::PickerKind::Tasks && detail {
lines.push(Line::from(Span::styled(
format!(" {} · {}", item.id, item.preview),
Style::default().fg(FAINT),
)));
}
} else if picker.kind == crate::tui::app::PickerKind::Provider && detail {
lines.push(Line::from(Span::styled(
format!(" {}", item.preview),
Style::default().fg(FAINT),
)));
} else if detail && picker.kind == crate::tui::app::PickerKind::Sessions {
let pinned = if item.note.is_empty() {
String::new()
} else {
format!(" · {}", item.note)
};
lines.push(Line::from(Span::styled(
format!(
" {} · {} {}{} · {}",
item.ago,
item.messages,
if item.messages == 1 {
"message"
} else {
"messages"
},
pinned,
item.id
),
Style::default().fg(FAINT),
)));
}
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
"↑↓ choose · type to filter · enter open · esc clear/close",
Style::default().fg(FAINT),
)));
let block = Box_::bordered()
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(ACCENT))
.title(Span::styled(
match picker.kind {
crate::tui::app::PickerKind::Sessions => " resume ",
crate::tui::app::PickerKind::Provider => " provider ",
crate::tui::app::PickerKind::Model => " model ",
crate::tui::app::PickerKind::Tasks => " tasks ",
},
Style::default().fg(ACCENT),
));
f.render_widget(
Paragraph::new(Text::from(lines))
.block(block)
.wrap(Wrap { trim: false })
.alignment(Alignment::Left),
rect,
);
}
const MENU_ROWS: usize = 8;
fn menu_lines(menu: &Menu, rows: usize, width: usize) -> Vec<Line<'static>> {
if menu.items.is_empty() {
return vec![Line::from(Span::styled(
truncate(" no command matches — esc closes this", width),
Style::default().fg(FAINT),
))];
}
let rows = rows.min(MENU_ROWS).min(menu.items.len());
let label_width = menu
.items
.iter()
.map(|c| c.label().chars().count())
.max()
.unwrap_or(0);
let first = menu.cursor.saturating_sub(rows.saturating_sub(1));
let mut lines: Vec<Line<'static>> = menu
.items
.iter()
.enumerate()
.skip(first)
.take(rows)
.map(|(i, c)| {
let current = i == menu.cursor;
let mark = if current { "› " } else { " " };
let text = truncate(
&format!("{mark}{:<label_width$} {}", c.label(), c.help),
width,
);
if current {
Line::from(Span::styled(
text,
Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
))
} else {
Line::from(Span::styled(text, Style::default().fg(DIM)))
}
})
.collect();
let hidden = menu.items.len() - lines.len();
if hidden > 0 {
lines.push(Line::from(Span::styled(
truncate(&format!(" … {hidden} more"), width),
Style::default().fg(FAINT),
)));
}
lines
}
fn menu(f: &mut Frame, area: Rect, composer: Rect, menu: &Menu) {
let room = composer.y.saturating_sub(area.y + 1) as usize;
if room < 3 || area.width < 6 {
return;
}
let wanted = menu.items.len().max(1);
let mut rows = MENU_ROWS.min(wanted).min(room - 2);
if wanted > rows && rows + 3 > room {
rows = rows.saturating_sub(1).max(1);
}
let mut lines = menu_lines(menu, rows, area.width as usize - 2);
lines.truncate(room - 2);
let h = (lines.len() + 2) as u16;
let rect = Rect {
x: area.x,
y: composer.y - h,
width: area.width,
height: h,
};
f.render_widget(Clear, rect);
let block = Box_::bordered()
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(ACCENT))
.title(Span::styled(" commands ", Style::default().fg(ACCENT)));
f.render_widget(Paragraph::new(Text::from(lines)).block(block), rect);
}
fn composer(f: &mut Frame, app: &App, area: Rect) {
let prompt = Span::styled("❯ ", Style::default().fg(ACCENT));
if app.approval.is_some() {
f.render_widget(
Paragraph::new(Line::from(vec![
prompt,
Span::styled("waiting for a decision (y / n)", Style::default().fg(WARN)),
])),
area,
);
return;
}
let hint = if app.busy() {
Some(Span::styled(
" esc stops the run",
Style::default().fg(FAINT),
))
} else if app.input.is_empty() {
Some(Span::styled(
" ask anything, or / for commands",
Style::default().fg(FAINT),
))
} else {
None
};
let room = area.width.saturating_sub(2) as usize;
let chars: Vec<char> = app.input.chars().collect();
let cursor = app.cursor.min(chars.len());
let (first, before_cursor) = prompt_window(&chars, cursor, room);
let shown: String = chars[first..].iter().collect();
let shown = truncate(&shown, room);
let mut spans = vec![prompt, Span::styled(shown, Style::default())];
if let Some(h) = hint {
spans.push(h);
}
f.render_widget(Paragraph::new(Line::from(spans)), area);
if !app.busy() && app.approval.is_none() {
let x = area.x + 2 + before_cursor as u16;
let x = x.min(area.x + area.width.saturating_sub(1));
f.set_cursor_position((x, area.y));
}
}
fn readout(f: &mut Frame, app: &App, area: Rect) {
let s = &app.status;
let glyph = match &app.activity {
Activity::Idle => "·".to_string(),
Activity::Requesting => SPINNER[(app.ticks % 10) as usize].to_string(),
Activity::Streaming => SPINNER[(app.ticks % 10) as usize].to_string(),
Activity::Tool(_) => "⚙".to_string(),
};
let state = match &app.activity {
Activity::Idle => String::new(),
Activity::Requesting => " thinking".to_string(),
Activity::Streaming => " streaming".to_string(),
Activity::Tool(t) => format!(" {t}"),
};
let mut left = vec![
Span::styled(format!(" {glyph} "), Style::default().fg(ACCENT)),
Span::styled(s.model.clone(), Style::default().fg(DIM)),
Span::styled(state, Style::default().fg(WARN)),
];
if app.running {
left.push(Span::styled(
format!(" · {:.1}s", s.started.elapsed().as_secs_f64()),
Style::default().fg(FAINT),
));
}
if app.listing_models {
left.push(Span::styled(
" · listing models",
Style::default().fg(FAINT),
));
}
if let Some(effort) = &s.effort {
left.push(Span::styled(
format!(" · effort {}", effort.label),
Style::default().fg(if effort.session { ACCENT } else { FAINT }),
));
}
if app.yolo.on() {
left.push(Span::styled(
" · approvals: auto",
Style::default().fg(ACCENT),
));
} else if s.judged {
left.push(Span::styled(
" · approvals: judged",
Style::default().fg(ACCENT),
));
}
let mut right: Vec<Span> = Vec::new();
let passed = app::context_passed(s);
let text = app::context_text(s, 10);
let mut rest = text.split(status::MARKER);
if let Some(head) = rest.next() {
right.push(Span::styled(
head.to_string(),
Style::default().fg(if passed { WARN } else { DIM }),
));
}
for part in rest {
right.push(Span::styled(
status::MARKER.to_string(),
Style::default().fg(BAD),
));
if !part.is_empty() {
right.push(Span::styled(
part.to_string(),
Style::default().fg(if passed { WARN } else { DIM }),
));
}
}
if let Some(last) = &s.last {
right.push(Span::styled(" · ", Style::default().fg(FAINT)));
right.push(Span::styled(
app::tokens_per_sec_text(last),
Style::default().fg(DIM),
));
if let Some(share) = app::cache_share(last) {
right.push(Span::styled(" · ", Style::default().fg(FAINT)));
right.push(Span::styled(
format!("⚡{:.0}%", share * 100.0),
Style::default().fg(OK),
));
}
}
if s.totals.turns > 1 {
right.push(Span::styled(" · ", Style::default().fg(FAINT)));
right.push(Span::styled(
format!(
"Σ {}/{}",
status::short_tokens(s.totals.prompt_tokens),
status::short_tokens(s.totals.completion_tokens)
),
Style::default().fg(FAINT),
));
}
right.push(Span::styled(" · ", Style::default().fg(FAINT)));
right.push(Span::styled(
if app.busy() {
"esc stop "
} else {
"/help · ⌃D quit "
},
Style::default().fg(FAINT),
));
let left_text: String = left.iter().map(|s| s.content.as_ref()).collect();
let right_text: String = right.iter().map(|s| s.content.as_ref()).collect();
let width = area.width as usize;
let pad = width
.saturating_sub(left_text.chars().count() + right_text.chars().count())
.max(1);
let mut spans = left;
spans.push(Span::raw(" ".repeat(pad)));
spans.extend(right);
f.render_widget(Paragraph::new(Line::from(spans)), area);
}
fn approval(f: &mut Frame, area: Rect, tool: &str, summary: &str, choice: Choice) {
let w = (area.width as f32 * 0.7) as u16;
let h = (7 + Choice::ALL.len() as u16).min(area.height);
let x = area.x + (area.width.saturating_sub(w)) / 2;
let y = area.y + (area.height.saturating_sub(h)) / 2;
let rect = Rect {
x,
y,
width: w,
height: h,
};
f.render_widget(Clear, rect);
let mut lines = vec![
Line::from(vec![
Span::styled("Allow ", Style::default().fg(DIM)),
Span::styled(
tool.to_string(),
Style::default().fg(ACCENT).add_modifier(Modifier::BOLD),
),
Span::styled("?", Style::default().fg(DIM)),
]),
Line::from(""),
Line::from(Span::styled(summary.to_string(), Style::default())),
Line::from(""),
];
for option in Choice::ALL {
let label = option.label(tool);
lines.push(if option == choice {
Line::from(vec![
Span::styled(" › ", Style::default().fg(ACCENT)),
Span::styled(label, Style::default().add_modifier(Modifier::BOLD)),
])
} else {
Line::from(Span::styled(
format!(" {label}"),
Style::default().fg(DIM),
))
});
}
lines.push(Line::from(""));
lines.push(Line::from(Span::styled(
"↑↓ move · enter confirm · esc deny",
Style::default().fg(FAINT),
)));
let text = Text::from(lines);
let block = Box_::bordered()
.border_type(BorderType::Rounded)
.border_style(Style::default().fg(WARN))
.title(Span::styled(" approval ", Style::default().fg(WARN)));
f.render_widget(
Paragraph::new(text)
.block(block)
.wrap(Wrap { trim: false })
.alignment(Alignment::Left),
rect,
);
}
fn one_line(s: &str) -> String {
s.split_whitespace().collect::<Vec<_>>().join(" ")
}
fn prompt_window(chars: &[char], cursor: usize, room: usize) -> (usize, usize) {
let cursor = cursor.min(chars.len());
let tail = room.saturating_sub(1);
let mut cells = 0;
let mut first = cursor;
while first > 0 {
let w = unicode_width::UnicodeWidthChar::width(chars[first - 1]).unwrap_or(0);
if cells + w > tail {
break;
}
cells += w;
first -= 1;
}
(first, cells)
}
fn split_at_cells(s: &str, width: usize) -> (String, String) {
let mut head = String::new();
let mut used = 0;
let mut at = s.len();
for (i, ch) in s.char_indices() {
let w = unicode_width::UnicodeWidthChar::width(ch).unwrap_or(0);
if used + w > width {
at = i;
break;
}
head.push(ch);
used += w;
}
(head, s[at..].to_string())
}
fn truncate(s: &str, width: usize) -> String {
if unicode_width::UnicodeWidthStr::width(s) <= width {
return s.to_string();
}
let keep = width.saturating_sub(1);
let (head, _) = split_at_cells(s, keep);
head + "…"
}
pub fn wrap(text: &str, width: usize) -> Vec<String> {
let width = width.max(1);
let mut out = Vec::new();
for para in text.split('\n') {
if para.is_empty() {
out.push(String::new());
continue;
}
let mut line = String::new();
for word in para.split(' ') {
let w = UnicodeWidthStr::width(word);
if line.is_empty() {
let mut word = word.to_string();
while UnicodeWidthStr::width(word.as_str()) > width {
let (head, rest) = split_at_cells(&word, width);
if head.is_empty() {
out.push(word.clone());
word = String::new();
break;
}
out.push(head);
word = rest;
}
line = word;
} else if UnicodeWidthStr::width(line.as_str()) + 1 + w <= width {
line.push(' ');
line.push_str(word);
} else {
out.push(std::mem::take(&mut line));
let mut word = word.to_string();
while UnicodeWidthStr::width(word.as_str()) > width {
let (head, rest) = split_at_cells(&word, width);
if head.is_empty() {
out.push(word.clone());
word = String::new();
break;
}
out.push(head);
word = rest;
}
line = word;
}
}
if !line.is_empty() {
out.push(line);
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_wrapped_paragraph_fits_the_pane_in_cells_not_chars() {
let para = "中文中文中文中文中文中文中文中文中文中文";
for width in [4usize, 9, 20, 41] {
let lines = wrap(para, width);
for line in &lines {
assert!(
UnicodeWidthStr::width(line.as_str()) <= width,
"a {}-cell pane got a {}-cell line: {line:?}",
width,
UnicodeWidthStr::width(line.as_str())
);
}
let out: usize = lines
.iter()
.map(|l| UnicodeWidthStr::width(l.as_str()))
.sum();
assert_eq!(out, UnicodeWidthStr::width(para), "width {width}");
}
}
#[test]
fn truncate_counts_cells_so_a_wide_line_stops_at_the_edge() {
assert_eq!(truncate("中文中文中文", 5), "中文…");
assert_eq!(
UnicodeWidthStr::width(truncate("中文中文中文", 5).as_str()),
5
);
assert_eq!(truncate("中文", 4), "中文");
assert_eq!(truncate("abc", 3), "abc");
assert_eq!(truncate("abcdef", 4), "abc…");
assert_eq!(UnicodeWidthStr::width(truncate("🙂🙂🙂", 3).as_str()), 3);
}
#[test]
fn the_prompt_window_measures_the_cursor_in_cells() {
let wide: Vec<char> = "中文中文".chars().collect();
assert_eq!(prompt_window(&wide, 2, 20), (0, 4));
assert_eq!(prompt_window(&wide, 4, 5), (2, 4));
let narrow: Vec<char> = "abcdef".chars().collect();
assert_eq!(prompt_window(&narrow, 6, 20), (0, 6));
assert_eq!(prompt_window(&narrow, 6, 4), (3, 3));
assert_eq!(prompt_window(&narrow, 99, 20), (0, 6));
}
#[test]
fn the_launch_hints_name_the_bang_command() {
let row = |width: usize| -> String {
hints(width)
.into_iter()
.map(|(text, _)| text)
.collect::<String>()
};
let widest = row(100);
assert!(
widest.contains("!command runs a shell command"),
"the widest row must name it in full: {widest:?}"
);
assert!(widest.contains("/ commands") && widest.contains("^D quits"));
assert!(row(61).contains("!command runs a shell command"));
assert!(
row(53).contains("!command runs a shell"),
"a tighter row says less about it, not nothing: {:?}",
row(53)
);
assert!(
row(52).contains("! shell"),
"the floor still says `!` exists: {:?}",
row(52)
);
assert!(
row(20).contains("! shell"),
"and it is the floor, never a gap"
);
for width in [61usize, 53, 39] {
assert!(
row(width).chars().count() <= width,
"at {width} columns the hint row overflows: {:?}",
row(width)
);
}
let w = sample_welcome();
let pane = text_of(&welcome_fitted(&w, None, 100, 60));
assert!(
pane.lines()
.any(|l| l.contains("!command runs a shell command")),
"the launch pane must carry the row: {pane}"
);
}
#[test]
fn a_printed_folded_block_promises_the_echo_not_an_opening() {
let mut a = App::new(
status::Status::new("m", "h:1", 1000, "/w".into()),
"m",
"/w",
None,
);
a.blocks.clear();
a.blocks.push(Block::Reasoning {
text: (1..=30).map(|i| format!("thought {i}\n")).collect(),
done: true,
});
a.freeze_printed(finished_blocks(&a));
let on_screen = text_of(&transcript_lines(&a, 80, 24));
assert!(
on_screen.contains("line(s) · ^T prints it below"),
"the hidden count and the promise survive: {on_screen}"
);
assert!(
on_screen.contains("^T prints it below"),
"and the promise changes with the block: {on_screen}"
);
assert!(!on_screen.contains("^T shows it all"));
let echo = text_of(&reasoning_echo(&a, 0, 80));
assert!(echo.contains("reasoning, printed again"));
for i in [1usize, 17, 30] {
assert!(
echo.contains(&format!("thought {i}")),
"line {i} missing from the echo"
);
}
assert_eq!(last_folded_printed_reasoning(&a), Some(0));
}
#[test]
fn wrapping_respects_words_and_newlines() {
assert_eq!(wrap("a b c", 10), ["a b c"]);
assert_eq!(wrap("aaa bbb", 3), ["aaa", "bbb"]);
assert_eq!(wrap("one\ntwo", 10), ["one", "two"]);
assert_eq!(wrap("", 5), [""]);
}
#[test]
fn a_word_longer_than_the_line_is_cut_not_overflowed() {
assert_eq!(wrap("abcdefgh", 3), ["abc", "def", "gh"]);
for line in wrap("abcdefgh", 3) {
assert!(line.chars().count() <= 3);
}
}
#[test]
fn truncation_keeps_character_boundaries() {
assert_eq!(truncate("héllo", 10), "héllo");
assert_eq!(truncate("héllo", 4), "hél…");
assert_eq!(truncate("héllo", 1), "…");
}
#[test]
fn tool_output_is_summarised_to_one_line_for_the_head() {
assert_eq!(one_line("a\n b\tc"), "a b c");
}
fn sample_welcome() -> Welcome {
Welcome {
approvals: false,
version: "0.1.0".into(),
model: "basalt-inkling2".into(),
endpoint: "127.0.0.1:18045".into(),
profile: None,
workspace: "/home/max/projects".into(),
groups: vec![
(
"builtin".to_string(),
vec!["fetch".to_string(), "shell".to_string()],
),
("plugin:notes".to_string(), vec!["note_write".to_string()]),
],
skills: vec![
("shared".to_string(), vec!["backup".to_string()]),
(
"workspace".to_string(),
vec!["deploy".to_string(), "release-notes".to_string()],
),
],
}
}
fn text_of(lines: &[Line]) -> String {
lines
.iter()
.map(|l| {
l.spans
.iter()
.map(|s| s.content.as_ref())
.collect::<String>()
})
.collect::<Vec<_>>()
.join("\n")
}
#[test]
fn the_pane_draws_the_wordmark_when_there_is_room_and_spells_it_out_when_there_is_not() {
let wide = text_of(&welcome_lines(&sample_welcome(), None, 100));
let art_rows = wide.lines().filter(|l| l.contains('█')).count();
assert_eq!(art_rows, 5, "five rows of letters:\n{wide}");
assert!(
!wide.contains('\u{2800}'),
"and no braille ring beside them:\n{wide}"
);
assert!(
!wide.lines().next().unwrap().contains("ECLIPSE"),
"the name is not spelled out as well:\n{wide}"
);
let narrow = text_of(&welcome_lines(&sample_welcome(), None, 40));
assert!(narrow.contains("ECLIPSE"), "{narrow}");
assert!(!narrow.contains('█'), "no half-drawn wordmark:\n{narrow}");
assert!(narrow.contains("workspace"), "the facts stay:\n{narrow}");
}
#[test]
fn the_facts_sit_under_the_name() {
let lines = welcome_lines(&sample_welcome(), None, 100);
let shown: Vec<String> = lines
.iter()
.map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
.collect();
let last_art = shown
.iter()
.rposition(|l| l.contains('█'))
.expect("the wordmark is drawn");
assert!(
shown[last_art + 1].trim().is_empty() && shown[last_art + 2].trim().is_empty(),
"two blank rows under the letters, so they do not crowd `version`: {shown:?}"
);
assert!(
shown[last_art + 3].contains("version"),
"the facts start under that: {shown:?}"
);
for (i, line) in shown.iter().enumerate() {
assert!(
!(line.contains('█') && line.contains("workspace")),
"line {i} draws a fact over the art: {line:?}"
);
}
}
#[test]
fn the_pane_never_draws_past_the_width() {
for width in (20..140).step_by(3) {
for line in welcome_lines(&sample_welcome(), Some("1795875858162-956151-0"), width) {
let drawn: usize = line.spans.iter().map(|s| s.content.chars().count()).sum();
assert!(drawn <= width, "{drawn} chars at width {width}: {line:?}");
}
}
}
#[test]
fn a_wrapped_tool_list_does_not_start_its_continuation_with_a_comma() {
let mut welcome = sample_welcome();
welcome.groups = vec![(
"builtin".to_string(),
(0..40).map(|i| format!("tool{i}")).collect(),
)];
let shown = text_of(&welcome_lines(&welcome, None, 60));
for line in shown.lines().skip(1) {
assert!(
!line.trim_start().starts_with(','),
"a line opens with a comma:\n{shown}"
);
}
assert!(shown.contains("tool0"), "{shown}");
assert!(shown.contains("tool39"), "the last one is still listed");
}
#[test]
fn the_pane_never_asks_for_more_lines_than_the_terminal_has() {
for width in [40usize, 64, 80, 96, 140] {
for height in 12usize..=44 {
let lines = welcome_fitted(&sample_welcome(), None, width, height);
assert!(
lines.len() <= height,
"{width}x{height}: the pane asks for {} lines",
lines.len()
);
}
}
}
#[test]
fn the_pane_says_approvals_and_ambers_the_automatic_one() {
let mut welcome = sample_welcome();
welcome.approvals = false;
let said = text_of(&welcome_lines(&welcome, None, 96));
assert!(said.contains("approvals"), "{said}");
assert!(
said.lines()
.any(|l| l.contains("approvals") && l.contains("ask")),
"{said}"
);
assert_eq!(colour_for("approvals", "ask"), DIM);
assert_eq!(colour_for("approvals", "auto"), ACCENT, "amber while on");
welcome.approvals = true;
let said = text_of(&welcome_lines(&welcome, None, 96));
assert!(
said.lines()
.any(|l| l.contains("approvals") && l.contains("auto")),
"{said}"
);
}
#[test]
fn a_short_terminal_gives_up_the_lists_then_the_letters() {
let roomy = welcome_fitted(&sample_welcome(), None, 96, 30);
assert!(text_of(&roomy).contains("skills"));
let tight = welcome_fitted(&sample_welcome(), None, 96, 17);
let shown = text_of(&tight);
assert!(shown.contains('█'), "the letters stay:\n{shown}");
assert!(shown.contains("workspace"), "the facts stay:\n{shown}");
assert!(!shown.contains("skills"), "the lists go first:\n{shown}");
assert!(shown.contains("!command"), "the keys stay");
let cramped = text_of(&welcome_fitted(&sample_welcome(), None, 96, 10));
assert!(
cramped.contains("ECLIPSE"),
"one line when nothing else fits:\n{cramped}"
);
}
#[test]
fn the_pane_fits_the_eighty_columns_a_default_terminal_gives() {
for width in [80usize, 120] {
let shown = text_of(&welcome_lines(&sample_welcome(), None, width));
assert!(
shown.contains('█') || shown.contains("ECLIPSE"),
"the name is drawn one way or the other: {shown}"
);
assert!(shown.contains("workspace"), "{shown}");
let widest = welcome_lines(&sample_welcome(), None, width)
.iter()
.map(|l| {
l.spans
.iter()
.map(|s| s.content.chars().count())
.sum::<usize>()
})
.max()
.unwrap();
assert!(widest <= width, "nothing overflows at {width}: {widest}");
}
}
#[test]
fn the_pane_counts_the_tools_that_are_offered() {
assert_eq!(sample_welcome().tool_count(), 3);
let shown = text_of(&welcome_lines(&sample_welcome(), None, 100));
assert!(shown.contains("3 offered"), "{shown}");
}
#[test]
fn the_pane_lists_skills_by_source_without_counting_them_as_tools() {
let shown = text_of(&welcome_lines(&sample_welcome(), None, 100));
assert!(shown.contains("skills 3 available"), "{shown}");
assert!(shown.contains("shared: backup"), "{shown}");
assert!(
shown.contains("workspace: deploy, release-notes"),
"{shown}"
);
assert!(
shown.contains("3 offered"),
"tools are counted apart: {shown}"
);
assert_eq!(sample_welcome().skill_count(), 3);
}
#[test]
fn the_pane_has_no_skills_section_when_there_are_no_skills() {
let bare = Welcome {
skills: Vec::new(),
..sample_welcome()
};
let shown = text_of(&welcome_lines(&bare, None, 100));
assert!(!shown.contains("skills"), "{shown}");
}
#[test]
fn the_session_column_follows_the_app_not_the_snapshot() {
let before = text_of(&welcome_lines(&sample_welcome(), None, 100));
assert!(before.contains("new"), "{before}");
let after = text_of(&welcome_lines(
&sample_welcome(),
Some("1795875858162-956151-0"),
100,
));
assert!(!after.contains(" session new"), "{after}");
assert!(
after.contains("956151-0"),
"the tail of the id shows: {after}"
);
}
fn menu_of(n: usize, cursor: usize) -> Menu {
let all = eclipse_core::commands::COMMANDS;
Menu {
items: all.iter().take(n).collect(),
cursor,
}
}
#[test]
fn the_menu_shows_the_command_its_arguments_and_its_help_with_the_cursor_marked() {
let lines = menu_lines(&menu_of(8, 2), 8, 100);
let text = text_of(&lines);
assert_eq!(lines.len(), 8);
assert!(
text.contains("/resume") && text.contains("open a stored session"),
"{text}"
);
assert!(
text.contains("/model") && !text.contains("[number|name]"),
"{text}"
);
assert!(
text.contains("pick a model (↑↓, enter)"),
"the row says what happens, in the shape /resume already had: {text}"
);
let marked: Vec<&Line> = lines
.iter()
.filter(|l| l.spans.iter().any(|s| s.content.starts_with("› ")))
.collect();
assert_eq!(marked.len(), 1);
assert!(
marked[0].spans[0].content.contains("/retry"),
"row 2 is /retry now: {:?}",
marked[0].spans[0].content
);
}
#[test]
fn a_long_list_shows_eight_rows_and_counts_the_rest() {
let mut long = menu_of(8, 0);
let extra = eclipse_core::commands::COMMANDS.iter().cycle().take(11);
long.items.extend(extra);
let lines = menu_lines(&long, 99, 100);
assert_eq!(lines.len(), 9, "eight rows and the count");
assert!(text_of(&lines).contains("… 11 more"), "{}", text_of(&lines));
long.cursor = 15;
let text = text_of(&menu_lines(&long, 99, 100));
assert_eq!(text.matches("› ").count(), 1, "{text}");
}
fn rendered(app: &App) -> Vec<String> {
transcript_lines(app, 60, usize::MAX)
.iter()
.map(|l| l.spans.iter().map(|s| s.content.as_ref()).collect())
.collect()
}
#[test]
fn a_turn_is_framed_by_rules_and_the_answer_has_a_name() {
let mut app = App::new(
status::Status::new("m", "h:1", 1000, "/w".into()),
"m",
"/w",
None,
);
app.blocks.clear();
app.blocks.push(Block::User("why is the sky blue".into()));
app.blocks.push(Block::Reply {
text: "Rayleigh scattering.".into(),
done: true,
});
let lines = rendered(&app);
let rules: Vec<usize> = lines
.iter()
.enumerate()
.filter(|(_, l)| l.starts_with('─') && l.chars().all(|c| c == '─'))
.map(|(i, _)| i)
.collect();
assert_eq!(
rules.len(),
3,
"above the question, below it, and after the answer: {lines:#?}"
);
assert!(
lines[rules[0] + 1].starts_with("❯ "),
"the question is inside its frame"
);
assert_eq!(
lines[rules[1] + 2],
"◐ eclipse",
"the answer is named: {lines:#?}"
);
for pair in rules.windows(2) {
assert!(
pair[1] - pair[0] > 1,
"never two rules in a row: {lines:#?}"
);
}
assert_eq!(lines[rules[2] + 1], "");
}
#[test]
fn a_tool_call_is_one_line_and_says_how_it_went() {
let mut app = App::new(
status::Status::new("m", "h:1", 1000, "/w".into()),
"m",
"/w",
None,
);
app.blocks.clear();
for (state, output, want) in [
(ToolState::Ok, "2026-11-30", "✓"),
(ToolState::Failed, "exit code: 1", "✗"),
(ToolState::Failed, "declined: not mine to write", "⊘"),
] {
app.blocks.clear();
app.blocks.push(Block::Tool {
call_id: "c1".into(),
name: "shell".into(),
args: r#"{"command":"date"}"#.into(),
state,
output: output.into(),
});
let lines = rendered(&app);
assert_eq!(
lines.len(),
1,
"one line per call, whatever it printed: {lines:#?}"
);
assert!(
lines[0].contains(want),
"{state:?} wants {want}: {}",
lines[0]
);
assert!(
lines[0].contains(r#"shell({"command":"date"})"#),
"the call is named, not its output: {}",
lines[0]
);
assert!(
!lines[0].contains("exit code") && !lines[0].contains("stdout"),
"the output stays in the log: {}",
lines[0]
);
}
}
#[test]
fn a_turn_with_no_text_draws_no_card() {
let mut app = App::new(
status::Status::new("m", "h:1", 1000, "/w".into()),
"m",
"/w",
None,
);
app.blocks.clear();
app.blocks.push(Block::User("date".into()));
app.blocks.push(Block::Tool {
call_id: "c1".into(),
name: "shell".into(),
args: "{}".into(),
state: ToolState::Ok,
output: String::new(),
});
app.blocks.push(Block::Reply {
text: String::new(),
done: true,
});
let lines = rendered(&app);
assert!(
!lines.iter().any(|l| l == "◐ eclipse"),
"no name without an answer: {lines:#?}"
);
}
#[test]
fn a_block_is_only_finished_once_it_stops_changing() {
let mut app = App::new(
status::Status::new("m", "h:1", 1000, "/w".into()),
"m",
"/w",
None,
);
app.blocks.clear();
app.blocks.push(Block::User("hi".into()));
app.blocks.push(Block::Reply {
text: "one\ntwo".into(),
done: false,
});
let everything = lines_for_test(&app, 40, 12).len();
let stable = stable_line_count(&app, 40, 12);
assert!(
stable < everything,
"an unfinished reply is held back: {stable} of {everything}"
);
assert!(
stable >= 2,
"the prompt above it is already final: {stable}"
);
if let Some(Block::Reply { done, .. }) = app.blocks.last_mut() {
*done = true;
}
assert_eq!(
stable_line_count(&app, 40, 12),
lines_for_test(&app, 40, 12).len(),
"once it stops changing, all of it may be printed"
);
}
#[test]
fn no_menu_line_is_wider_than_the_width_it_was_given() {
for width in [4, 12, 30, 80] {
for line in menu_lines(&menu_of(8, 1), 8, width) {
let w: usize = line.spans.iter().map(|s| s.content.chars().count()).sum();
assert!(w <= width, "{w} > {width}");
}
}
}
#[test]
fn the_reasoning_dial_changes_what_the_transcript_draws() {
use crate::reasoning_cli::{Live, Mode};
let long: String = (0..12)
.map(|i| format!("thought line {i}\n"))
.collect::<String>();
let mut app = App::new(
status::Status::new("m", "h:1", 1000, "/w".into()),
"m",
"/w",
None,
);
app.blocks.push(app::Block::Reasoning {
text: long,
done: true,
});
let dial: eclipse_core::reasoning::Shared =
std::sync::Arc::new(eclipse_core::reasoning::Dial::new(None));
let folded = text_of(&transcript_lines(&app, 80, 24));
assert!(folded.contains("thought line 0"), "{folded}");
assert!(folded.contains("line(s)"), "the count takes over: {folded}");
app.reasoning = Some(Live::bare(std::sync::Arc::clone(&dial)));
if let Some(live) = app.reasoning.as_mut() {
live.display = Mode::Full;
}
let full = text_of(&transcript_lines(&app, 80, 24));
assert!(
full.contains("thought line 11"),
"the tail is drawn: {full}"
);
if let Some(live) = app.reasoning.as_mut() {
live.display = Mode::Hidden;
}
let hidden = text_of(&transcript_lines(&app, 80, 24));
assert!(!hidden.contains("thought line"), "{hidden}");
if let Some(live) = app.reasoning.as_mut() {
live.display = Mode::Clamp(40);
}
let clamped = text_of(&transcript_lines(&app, 80, 24));
assert!(clamped.contains("thought line 0"), "{clamped}");
assert!(clamped.contains("…"), "the cut is marked once: {clamped}");
assert_eq!(
clamped.matches('…').count(),
1,
"one ellipsis, not one per line: {clamped}"
);
}
#[test]
fn a_menu_with_nothing_matching_says_so_in_one_row() {
let menu = Menu {
items: Vec::new(),
cursor: 0,
};
let lines = menu_lines(&menu, 8, 60);
assert_eq!(lines.len(), 1, "one row, not none");
let text = text_of(&lines);
assert!(text.contains("no command matches"), "{text}");
assert!(text.contains("esc"), "and the way out: {text}");
assert!(!text.contains("›"), "nothing is highlighted: {text}");
let narrow = text_of(&menu_lines(&menu, 8, 12));
assert!(narrow.chars().count() <= 12, "{narrow:?}");
}
#[test]
fn the_menu_draws_inside_any_frame_without_overflowing_it() {
use ratatui::backend::TestBackend;
let mut app = App::new(
status::Status::new("m", "h:1", 1000, "/w".into()),
"m",
"/w",
None,
);
app.input = "/".into();
app.cursor = 1;
app.refilter_menu();
assert!(app.menu.is_some());
for (w, h) in [(80, 24), (30, 12), (20, 6), (8, 5), (80, 4), (3, 3)] {
let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).expect("test terminal");
term.draw(|f| draw(f, &app, 0, usize::MAX))
.expect("the draw must not panic");
}
let mut term = ratatui::Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
let screen: String = term
.backend()
.buffer()
.content()
.iter()
.map(|c| c.symbol())
.collect();
assert!(
screen.contains("commands") && screen.contains("/bg") && screen.contains("more"),
"{screen}"
);
}
#[test]
fn the_provider_picker_draws_each_route_with_the_endpoint_it_points_at() {
use ratatui::backend::TestBackend;
let mut app = App::new(
status::Status::new("inkling-2-mini", "h:1", 1000, "/w".into()),
"inkling-2-mini",
"/w",
None,
);
let routes = vec![
eclipse_core::router::RouteInfo {
name: "local".into(),
model: "inkling-2-mini".into(),
endpoint: "http://127.0.0.1:18045/v1".into(),
},
eclipse_core::router::RouteInfo {
name: "cloud".into(),
model: "big".into(),
endpoint: "https://ollama.example/v1".into(),
},
];
app.open_providers(&routes, Some("local"));
let mut term = ratatui::Terminal::new(TestBackend::new(80, 22)).expect("test terminal");
term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
let screen: String = term
.backend()
.buffer()
.content()
.iter()
.map(|c| c.symbol())
.collect();
assert!(screen.contains("Ask"), "{screen}");
assert!(screen.contains("provider"), "{screen}");
assert!(screen.contains("2 configured"), "{screen}");
assert!(screen.contains("local"), "{screen}");
assert!(screen.contains("cloud"), "{screen}");
assert!(screen.contains("127.0.0.1:18045"), "{screen}");
assert!(screen.contains("ollama.example"), "{screen}");
assert!(screen.contains("current"), "{screen}");
assert!(!screen.contains("served"), "{screen}");
assert!(!screen.contains("stored"), "{screen}");
}
#[test]
fn the_model_picker_lists_what_the_endpoint_serves_and_marks_the_one_in_use() {
use ratatui::backend::TestBackend;
let mut app = App::new(
status::Status::new("inkling-2-mini", "h:1", 1000, "/w".into()),
"inkling-2-mini",
"/w",
None,
);
app.set_models_from(
None,
vec![
"gemma-4-12b".into(),
"inkling-2-mini".into(),
"qwen-3.8-27b".into(),
],
);
let picker = app.picker.as_ref().expect("the list is up");
assert_eq!(picker.kind, crate::tui::app::PickerKind::Model);
assert_eq!(picker.items.len(), 3);
assert_eq!(
picker.cursor, 1,
"the cursor starts on the model in use, not on the first row"
);
assert_eq!(picker.items[1].note, "current");
assert_eq!(picker.items[0].note, "");
let mut term = ratatui::Terminal::new(TestBackend::new(72, 20)).expect("test terminal");
term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
let screen: String = term
.backend()
.buffer()
.content()
.iter()
.map(|c| c.symbol())
.collect();
assert!(screen.contains("Switch"), "{screen}");
assert!(screen.contains("model"), "{screen}");
assert!(screen.contains("3 served"), "{screen}");
assert!(screen.contains("gemma-4-12b"), "{screen}");
assert!(screen.contains("qwen-3.8-27b"), "{screen}");
assert!(screen.contains("current"), "{screen}");
assert!(!screen.contains("stored"), "{screen}");
assert!(!screen.contains("messages"), "{screen}");
assert!(screen.contains("↑↓ choose"), "{screen}");
let buffer = term.backend().buffer();
let area = buffer.area;
let mut lines: Vec<String> = Vec::new();
for y in area.y..area.y + area.height {
let mut line = String::new();
for x in area.x..area.x + area.width {
line.push_str(buffer[(x, y)].symbol());
}
lines.push(line.trim_end().to_string());
}
let model_line = lines
.iter()
.find(|l| l.contains("inkling-2-mini"))
.expect("the model row is on screen");
assert!(
model_line.contains("current"),
"the current mark is on the model's own row: {model_line:?}"
);
}
fn rows_of(term: &ratatui::Terminal<ratatui::backend::TestBackend>) -> Vec<String> {
let buffer = term.backend().buffer();
let area = buffer.area;
(area.y..area.y + area.height)
.map(|y| {
(area.x..area.x + area.width)
.map(|x| buffer[(x, y)].symbol())
.collect::<String>()
})
.collect()
}
#[test]
fn the_update_badge_takes_one_row_and_never_displaces_the_readout() {
use ratatui::backend::TestBackend;
let mut app = App::new(
status::Status::new("inkling-2-mini", "h:1", 327_680, "/w".into()),
"inkling-2-mini",
"/w",
None,
);
app.update = Some(eclipse_core::update::Behind {
installed: "0.7.0".into(),
latest: "v0.8.0".into(),
});
let mut term = ratatui::Terminal::new(TestBackend::new(80, 24)).expect("test terminal");
term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
let rows = rows_of(&term);
assert!(
rows[0].contains("↑ 0.8.0 available"),
"the badge is on the first row, without the tag's v: {:?}",
rows[0]
);
assert!(
rows[0].trim_end().ends_with("eclipse upgrade"),
"and it is right-aligned to the edge: {:?}",
rows[0]
);
assert!(
rows[0].chars().count() <= 80,
"one row at eighty columns: {:?}",
rows[0]
);
assert!(
rows[23].contains("inkling-2-mini"),
"the readout still names the model on the last row: {:?}",
rows[23]
);
app.update = None;
term.draw(|f| draw(f, &app, 0, usize::MAX)).expect("draw");
let rows = rows_of(&term);
assert!(
!rows.iter().any(|r| r.contains("available")),
"no badge, no row: {rows:?}"
);
assert!(
rows[23].contains("inkling-2-mini"),
"the readout is where it was: {:?}",
rows[23]
);
}
}