Initial public release
Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
236
crates/luxe-tui/src/view/blocks/group.rs
Normal file
236
crates/luxe-tui/src/view/blocks/group.rs
Normal file
@@ -0,0 +1,236 @@
|
||||
//! Folded runs — a run of lookups drawn as one line, its rows, and the one still working.
|
||||
|
||||
use super::message::{clip_line, line_text};
|
||||
use super::tool::{format_tool_duration, indented, safe_tool_text, BODY_INDENT};
|
||||
use crate::app::{ConversationItem, ConvoBlock};
|
||||
use crate::glyphs::icon_label;
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
use crate::widgets::{tool_icon, GENERIC_TOOL};
|
||||
use ratatui::{
|
||||
style::Modifier,
|
||||
text::{Line, Span},
|
||||
};
|
||||
|
||||
/// Cells the run's meter occupies while it is filling.
|
||||
const GROUP_METER_CELLS: usize = 10;
|
||||
|
||||
/// Whether a folded run is still going, so its band stays neutral rather than green.
|
||||
///
|
||||
/// A run with nothing in flight has not necessarily finished: dispatch is sequential, so between
|
||||
/// one call ending and the next starting there is a moment when none is running. Asking only that
|
||||
/// question washed the line green and back on every call boundary — several flashes a second, on a
|
||||
/// line whose whole job is to be the calm one.
|
||||
pub(in crate::view) fn run_is_working(items: &[ConversationItem], arriving: bool) -> bool {
|
||||
arriving
|
||||
|| items.iter().any(|item| {
|
||||
matches!(item.block(), ConvoBlock::Tool(tool)
|
||||
if tool.activity.state == luxe_core::ToolActivityState::Running)
|
||||
})
|
||||
}
|
||||
|
||||
/// One row of a folded run, and whether a click on it opens the run.
|
||||
pub(in crate::view) struct GroupRow {
|
||||
pub(crate) line: Line<'static>,
|
||||
/// The header and the footer that offers the rest are handles; the list between them is text
|
||||
/// to select, the way a card's body is
|
||||
pub(crate) handle: bool,
|
||||
}
|
||||
|
||||
/// Calls a folded run lists by name before it counts the rest.
|
||||
///
|
||||
/// Five when that is all there is; four and a count past that, so the list never runs longer than
|
||||
/// five rows and a run of six does not list five and then say "1 more".
|
||||
const GROUP_PREVIEW_ROWS: usize = 5;
|
||||
|
||||
/// What a folded run draws: its header, then the first few calls by name.
|
||||
///
|
||||
/// The header is the run in one line, live or settled. While the run is going it is a progress
|
||||
/// line: a spinner, a meter over the run its message asked for, and the call happening now. That is
|
||||
/// the whole reason to fold live rather than after the fact — the reader watches one line move
|
||||
/// instead of seven cards land. Once it settles the meter goes away, since a bar frozen at full is
|
||||
/// a picture of something no longer happening, and what is left worth saying is how many calls it
|
||||
/// was and how long they took.
|
||||
///
|
||||
/// The list under it is what the count stands for. A header alone — `3 read calls` — says how
|
||||
/// much and never what.
|
||||
///
|
||||
/// `arriving` is what keeps live and settled apart in the gap between calls, where nothing is in
|
||||
/// flight and the run is nowhere near done. Without it the line summarizes itself as "1 read call"
|
||||
/// for a frame, every call, all the way down a run of seven.
|
||||
///
|
||||
/// Args: `(items, arriving, spinner frame, width, styles)`; `width` is the cells a row may take.
|
||||
pub(in crate::view) fn tool_group_lines(
|
||||
items: &[ConversationItem],
|
||||
arriving: bool,
|
||||
spinner_frame: usize,
|
||||
width: u16,
|
||||
styles: &ThemeStyles,
|
||||
) -> Vec<GroupRow> {
|
||||
let calls: Vec<&luxe_core::ToolActivity> = items
|
||||
.iter()
|
||||
.filter_map(|item| match item.block() {
|
||||
ConvoBlock::Tool(tool) => Some(&tool.activity),
|
||||
_ => None,
|
||||
})
|
||||
.collect();
|
||||
let Some(first) = calls.first() else {
|
||||
return Vec::new();
|
||||
};
|
||||
let first_name = first.name.as_str();
|
||||
let same_tool = calls.iter().all(|call| call.name == first_name);
|
||||
let header = group_header(&calls, same_tool, arriving, spinner_frame, styles);
|
||||
let mut rows = vec![GroupRow { line: header, handle: true }];
|
||||
|
||||
// A run its message promised is drawn at its promised size from the first call, rows waiting
|
||||
// for the calls still to come, so nothing above it moves as they land
|
||||
let total = match arriving {
|
||||
true => calls
|
||||
.iter()
|
||||
.filter_map(|call| call.run)
|
||||
.map(|run| usize::try_from(run.total).unwrap_or(usize::MAX))
|
||||
.max()
|
||||
.unwrap_or(0)
|
||||
.max(calls.len()),
|
||||
false => calls.len(),
|
||||
};
|
||||
let listed = match total > GROUP_PREVIEW_ROWS {
|
||||
true => GROUP_PREVIEW_ROWS - 1,
|
||||
false => total,
|
||||
};
|
||||
let room = usize::from(width).saturating_sub(BODY_INDENT.len()).max(1);
|
||||
for index in 0..listed {
|
||||
let line = match calls.get(index) {
|
||||
Some(call) => clip_with_ellipsis(group_row_label(call, same_tool, styles), room),
|
||||
None => Line::from(Span::styled("…", styles.muted)),
|
||||
};
|
||||
rows.push(GroupRow { line: indented(line), handle: false });
|
||||
}
|
||||
if total > listed {
|
||||
let footer = format!("⋯ {} more · {total} total · click to expand", total - listed);
|
||||
let footer = indented(Line::from(Span::styled(footer, styles.muted)));
|
||||
rows.push(GroupRow { line: footer, handle: true });
|
||||
}
|
||||
rows
|
||||
}
|
||||
|
||||
/// The run's one-line header: progress while it works, a summary once it settles.
|
||||
fn group_header(
|
||||
calls: &[&luxe_core::ToolActivity],
|
||||
same_tool: bool,
|
||||
arriving: bool,
|
||||
spinner_frame: usize,
|
||||
styles: &ThemeStyles,
|
||||
) -> Line<'static> {
|
||||
let first_name = calls[0].name.as_str();
|
||||
// A run only forms from calls that are running or done, so the icon says which tool is
|
||||
// working (or that the run is mixed) rather than repeating an outcome the wash already carries.
|
||||
let icon = if same_tool { tool_icon(first_name).glyph() } else { GENERIC_TOOL.glyph() };
|
||||
|
||||
// The call in flight, or — in the gap before the next one starts — the most recent, which is
|
||||
// the one whose place in the run the meter is still honestly reporting.
|
||||
let running = calls
|
||||
.iter()
|
||||
.find(|call| call.state == luxe_core::ToolActivityState::Running)
|
||||
.or_else(|| calls.last().filter(|_| arriving));
|
||||
if let Some(running) = running {
|
||||
return running_group_line(running, spinner_frame, styles);
|
||||
}
|
||||
|
||||
// Only lookups and one server's calls fold, so a mixed run has a real word for what it was —
|
||||
// better than "tool calls", which would describe every card in the transcript equally well.
|
||||
let mut description = match same_tool {
|
||||
true => format!("{} {first_name} calls", calls.len()),
|
||||
false => format!("{} lookups", calls.len()),
|
||||
};
|
||||
if let Some(server) = calls.iter().find_map(|call| crate::app::mcp_server(&call.label)) {
|
||||
if first_name == "mcp" {
|
||||
description.push_str(&format!(" · {server}"));
|
||||
}
|
||||
}
|
||||
let mut spans = vec![Span::styled(
|
||||
format!("{} {}", crate::glyphs::Mark::FoldClosed, icon_label(icon, &description)),
|
||||
styles.success,
|
||||
)];
|
||||
let elapsed: u64 = calls.iter().filter_map(|call| call.elapsed_ms).sum();
|
||||
if elapsed > 0 {
|
||||
spans.push(Span::styled(format!(" {}", format_tool_duration(elapsed)), styles.muted));
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// One call in a folded run's list: what it was about, under the tool's name when the run mixes
|
||||
/// tools. An MCP call drops the server its header already names.
|
||||
fn group_row_label(
|
||||
call: &luxe_core::ToolActivity,
|
||||
same_tool: bool,
|
||||
styles: &ThemeStyles,
|
||||
) -> Line<'static> {
|
||||
let label = safe_tool_text(&call.label);
|
||||
let subject = match (call.name.as_str(), crate::app::mcp_server(&label)) {
|
||||
("mcp", Some(server)) => label[server.len() + 1..].to_string(),
|
||||
_ => label.clone(),
|
||||
};
|
||||
let subject = match subject.trim().is_empty() {
|
||||
true => call.name.clone(),
|
||||
false => subject,
|
||||
};
|
||||
let mut spans = Vec::new();
|
||||
if !same_tool {
|
||||
spans.push(Span::styled(format!("{} ", call.name), styles.muted));
|
||||
}
|
||||
spans.push(Span::styled(subject, styles.text));
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// `line` cut to `width` cells, with an ellipsis where it was cut.
|
||||
fn clip_with_ellipsis(line: Line<'static>, width: usize) -> Line<'static> {
|
||||
if crate::selection::cell_width(&line_text(&line)) <= width {
|
||||
return line;
|
||||
}
|
||||
let mut clipped = clip_line(line, width.saturating_sub(1));
|
||||
let style = clipped.spans.last().map(|span| span.style).unwrap_or_default();
|
||||
clipped.spans.push(Span::styled("…", style));
|
||||
clipped
|
||||
}
|
||||
|
||||
/// The folded run while it is still moving: spinner, meter, position, and the call in flight.
|
||||
///
|
||||
/// Named for the call *in flight*, even where the run is mixed. A live line's job is to say what is
|
||||
/// happening now, and a run summarized as "lookups" while it works spends its one line on a word
|
||||
/// the reader could have guessed. The summary belongs on the settled line, which is a summary.
|
||||
fn running_group_line(
|
||||
running: &luxe_core::ToolActivity,
|
||||
spinner_frame: usize,
|
||||
styles: &ThemeStyles,
|
||||
) -> Line<'static> {
|
||||
let icon = tool_icon(&running.name).glyph();
|
||||
let mut spans = vec![Span::styled(
|
||||
format!(
|
||||
"{} {}",
|
||||
crate::statusline::spinner(spinner_frame),
|
||||
icon_label(icon, &running.name)
|
||||
),
|
||||
styles.text.add_modifier(Modifier::BOLD),
|
||||
)];
|
||||
// The denominator is the run the *message* asked for, which is known before any of it has been
|
||||
// dispatched — so the line can say "3 of 7" while the seventh call is still hypothetical.
|
||||
if let Some(batch) = running.batch {
|
||||
let percent = 100.0 * f32::from(u16::try_from(batch.index).unwrap_or(u16::MAX))
|
||||
/ f32::from(u16::try_from(batch.total).unwrap_or(u16::MAX)).max(1.0);
|
||||
let shades = styles.gauge_shades(styles.accent, styles.tool_call_bg);
|
||||
spans.push(Span::raw(" "));
|
||||
spans.extend(crate::widgets::fill_gauge(
|
||||
percent,
|
||||
GROUP_METER_CELLS,
|
||||
&shades.fill,
|
||||
&shades.rail,
|
||||
));
|
||||
// The count is the part that has to survive a bare monospace font; the meter is the shine.
|
||||
spans.push(Span::styled(format!(" {}/{}", batch.index, batch.total), styles.muted));
|
||||
}
|
||||
let label = safe_tool_text(&running.label);
|
||||
if !label.trim().is_empty() {
|
||||
spans.push(Span::styled(format!(" {label}"), styles.text));
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
302
crates/luxe-tui/src/view/blocks/message.rs
Normal file
302
crates/luxe-tui/src/view/blocks/message.rs
Normal file
@@ -0,0 +1,302 @@
|
||||
//! Messages — a user's turn with its chips, reasoning and its peek, and system prose.
|
||||
|
||||
use super::tool::safe_tool_text;
|
||||
use super::{layout_lines, BlockContext};
|
||||
use crate::app::{user_message_fits_preview, USER_MESSAGE_PREVIEW_LINES};
|
||||
use crate::glyphs::{icon_label, icon_prefix, Icon};
|
||||
use crate::markdown::{layout_markdown_in, MarkdownBlockKind, MarkdownLine, MarkdownVoice};
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
use ratatui::{
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
};
|
||||
|
||||
/// A user's turn: the message, a note when it never reached the engine, what it attached, and the
|
||||
/// handles of a message long enough to preview.
|
||||
pub(super) fn user_lines(
|
||||
text: &str,
|
||||
attached: &[String],
|
||||
chips: &[std::ops::Range<usize>],
|
||||
style: Style,
|
||||
ctx: &BlockContext<'_>,
|
||||
) -> Vec<MarkdownLine> {
|
||||
let (styles, never_sent, expanded) = (ctx.styles, ctx.never_sent, ctx.expanded);
|
||||
// No glyph — user turns are distinguished by their background band (see render).
|
||||
let previewed = !user_message_fits_preview(text);
|
||||
let mut lines = user_body_lines(text, chips, expanded, style, styles);
|
||||
if never_sent {
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(
|
||||
" {}",
|
||||
icon_label(Icon::NeverSent.glyph(), "never sent · engine unavailable")
|
||||
),
|
||||
styles.warning,
|
||||
)));
|
||||
}
|
||||
let image_count = attached.iter().filter(|item| Icon::Image.leads(item)).count();
|
||||
let file_count = attached.len().saturating_sub(image_count);
|
||||
if file_count > 0 {
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(
|
||||
" {}",
|
||||
icon_label(Icon::Attachment.glyph(), &format!("{file_count} file(s) attached"))
|
||||
),
|
||||
styles.muted,
|
||||
)));
|
||||
}
|
||||
if image_count > 0 {
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(
|
||||
" {}",
|
||||
icon_label(Icon::Image.glyph(), &format!("{image_count} image(s) attached"))
|
||||
),
|
||||
styles.muted,
|
||||
)));
|
||||
}
|
||||
let mut laid = layout_lines(lines, MarkdownBlockKind::Prose);
|
||||
// A message long enough to be previewed hides the rest behind its first row, and while
|
||||
// collapsed also behind the footer counting what is missing. Those are the rows to click;
|
||||
// the body between them is text.
|
||||
if previewed {
|
||||
mark_handles(&mut laid, !expanded);
|
||||
}
|
||||
laid
|
||||
}
|
||||
|
||||
/// Renders a user message, capping a long one at [`USER_MESSAGE_PREVIEW_LINES`] with a muted
|
||||
/// footer saying how much is hidden. A submitted message carries its pasted payload verbatim, so
|
||||
/// without the cap a single paste can bury the rest of the conversation.
|
||||
fn user_body_lines(
|
||||
text: &str,
|
||||
chips: &[std::ops::Range<usize>],
|
||||
expanded: bool,
|
||||
style: Style,
|
||||
styles: &ThemeStyles,
|
||||
) -> Vec<Line<'static>> {
|
||||
if expanded || user_message_fits_preview(text) {
|
||||
return chipped_lines(text, chips, style, styles);
|
||||
}
|
||||
let total = text.lines().count();
|
||||
let preview = text.lines().take(USER_MESSAGE_PREVIEW_LINES).collect::<Vec<_>>().join("\n");
|
||||
let mut lines = chipped_lines(&preview, chips, style, styles);
|
||||
lines.push(Line::from(Span::styled(
|
||||
format!(
|
||||
"{} +{} more lines",
|
||||
crate::glyphs::Mark::Elision,
|
||||
total - USER_MESSAGE_PREVIEW_LINES
|
||||
),
|
||||
styles.muted,
|
||||
)));
|
||||
lines
|
||||
}
|
||||
|
||||
/// A message's lines, with each reference set apart from the sentence around it.
|
||||
///
|
||||
/// A reference takes whichever ink its sentence does not. In the composer you type in body text and
|
||||
/// a chip is the accent on a tint; a sent message is already the accent, where the same tint all but
|
||||
/// vanished, so here a reference is the body ink in bold. Either way `acme/todo#12` reads as a
|
||||
/// thing you pointed at rather than as more of your sentence. A range that does not fall on this
|
||||
/// text's character boundaries is drawn as plain text rather than trusted.
|
||||
pub(super) fn chipped_lines(
|
||||
text: &str,
|
||||
chips: &[std::ops::Range<usize>],
|
||||
style: Style,
|
||||
styles: &ThemeStyles,
|
||||
) -> Vec<Line<'static>> {
|
||||
let chip_style = style.patch(styles.text).add_modifier(Modifier::BOLD);
|
||||
let mut lines = Vec::new();
|
||||
let mut start = 0usize;
|
||||
for line in text.split('\n') {
|
||||
let end = start + line.len();
|
||||
let mut spans = Vec::new();
|
||||
let mut at = start;
|
||||
for chip in chips.iter().filter(|chip| chip.start >= start && chip.end <= end) {
|
||||
if chip.start < at
|
||||
|| !text.is_char_boundary(chip.start)
|
||||
|| !text.is_char_boundary(chip.end)
|
||||
{
|
||||
continue;
|
||||
}
|
||||
if chip.start > at {
|
||||
spans.push(Span::styled(text[at..chip.start].to_string(), style));
|
||||
}
|
||||
spans.push(Span::styled(text[chip.clone()].to_string(), chip_style));
|
||||
at = chip.end;
|
||||
}
|
||||
if at < end || spans.is_empty() {
|
||||
spans.push(Span::styled(text[at..end].to_string(), style));
|
||||
}
|
||||
lines.push(Line::from(spans));
|
||||
start = end + 1;
|
||||
}
|
||||
lines
|
||||
}
|
||||
|
||||
/// Renders model reasoning as markdown in the muted italic reasoning voice.
|
||||
///
|
||||
/// No label: the muted italic voice already reads as reasoning rather than an answer, and a
|
||||
/// literal "thinking" banner above every block is noise the reader has to skip past. Reasoning is
|
||||
/// markdown in practice — GPT models lead each section with a `**title**` and name symbols in
|
||||
/// backticks — so it is rendered as markdown rather than shown with its syntax intact. A folded
|
||||
/// block is a one-line peek that says how much it stands for, and is the only part of a reasoning
|
||||
/// block a click acts on.
|
||||
pub(super) fn thinking_lines(
|
||||
text: &str,
|
||||
expanded: bool,
|
||||
ctx: &BlockContext<'_>,
|
||||
) -> Vec<MarkdownLine> {
|
||||
let rendered = layout_markdown_in(&safe_tool_text(text), ctx.styles, MarkdownVoice::Reasoning);
|
||||
if expanded {
|
||||
// Nothing here is a handle. Reasoning shown in full is prose — read, selected, copied — and
|
||||
// a click that folded it would take the paragraph out from under the reader, who cannot see
|
||||
// that the row they clicked was a control. It folds from the keyboard, where the selection
|
||||
// says which block is being acted on.
|
||||
return rendered;
|
||||
}
|
||||
vec![MarkdownLine::prose(thinking_peek(rendered, ctx.styles, ctx.prose_width)).expandable()]
|
||||
}
|
||||
|
||||
/// Marks a block's first row — and its last, when `with_footer` — as the rows a click opens it from.
|
||||
pub(super) fn mark_handles(lines: &mut [MarkdownLine], with_footer: bool) {
|
||||
if let Some(first) = lines.first_mut() {
|
||||
first.expands = true;
|
||||
}
|
||||
if with_footer {
|
||||
if let Some(last) = lines.last_mut() {
|
||||
last.expands = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Cells the reasoning itself keeps. A count that would leave a peek narrower than this is dropped
|
||||
/// instead — on a canvas that cannot carry both, the thought is the part worth reading.
|
||||
const MIN_PEEK_WIDTH: usize = 24;
|
||||
|
||||
/// A one-line preview of reasoning for a collapsed block: the first non-blank rendered line, cut to
|
||||
/// the prose measure, and a muted count of what is behind it.
|
||||
///
|
||||
/// The count is the part that earns its keep. Without it a fold is indistinguishable from text that
|
||||
/// went missing — the peek stops mid-sentence and the rest of the block is simply gone — which is
|
||||
/// how a deliberate one-line summary came to read as a rendering bug.
|
||||
///
|
||||
/// Built from the *rendered* lines rather than the source, so the peek shows a formatted title
|
||||
/// instead of the `**` that produced it.
|
||||
fn thinking_peek(rendered: Vec<MarkdownLine>, styles: &ThemeStyles, width: u16) -> Line<'static> {
|
||||
// A rendered line keeps its source breaks, so a line is not a row: the peek counts what it is
|
||||
// hiding in the breaks too, or a block written as one paragraph per break claims to hide none.
|
||||
let spoken: Vec<Line<'static>> = rendered
|
||||
.into_iter()
|
||||
.map(|layout| layout.line)
|
||||
.filter(|line| line.spans.iter().any(|span| !span.content.trim().is_empty()))
|
||||
.collect();
|
||||
let Some(first) = spoken.first().cloned() else {
|
||||
let style = styles.thinking_text.add_modifier(Modifier::ITALIC);
|
||||
return Line::from(Span::styled("(no content)", style));
|
||||
};
|
||||
let hidden = spoken
|
||||
.iter()
|
||||
.map(|line| line_text(line).lines().filter(|part| !part.trim().is_empty()).count())
|
||||
.sum::<usize>()
|
||||
.saturating_sub(1);
|
||||
let mut more = (hidden > 0)
|
||||
.then(|| format!(" · +{hidden} more {}", if hidden == 1 { "line" } else { "lines" }));
|
||||
let mut room = usize::from(width);
|
||||
if let Some(count) = more.as_deref() {
|
||||
let left = room.saturating_sub(crate::selection::cell_width(count));
|
||||
match left >= MIN_PEEK_WIDTH {
|
||||
true => room = left,
|
||||
false => more = None,
|
||||
}
|
||||
}
|
||||
|
||||
let head = truncate_at_newline(first);
|
||||
let clipped = crate::selection::cell_width(&line_text(&head)) > room;
|
||||
let mut peek = clip_line(head, if clipped { room.saturating_sub(1) } else { room });
|
||||
if clipped {
|
||||
let style = peek.spans.last().map(|span| span.style).unwrap_or_default();
|
||||
peek.spans.push(Span::styled("…", style));
|
||||
}
|
||||
if let Some(more) = more {
|
||||
peek.spans.push(Span::styled(more, styles.muted));
|
||||
}
|
||||
peek
|
||||
}
|
||||
|
||||
/// Everything up to the line's first embedded newline.
|
||||
fn truncate_at_newline(line: Line<'static>) -> Line<'static> {
|
||||
let mut spans = Vec::with_capacity(line.spans.len());
|
||||
for span in line.spans {
|
||||
match span.content.split_once('\n') {
|
||||
Some((head, _)) => {
|
||||
if !head.is_empty() {
|
||||
spans.push(Span::styled(head.to_string(), span.style));
|
||||
}
|
||||
break;
|
||||
}
|
||||
None => spans.push(span),
|
||||
}
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// Clips a styled line to `width` terminal cells, keeping each span's own style.
|
||||
pub(super) fn clip_line(line: Line<'static>, width: usize) -> Line<'static> {
|
||||
let mut spans = Vec::with_capacity(line.spans.len());
|
||||
let mut used = 0usize;
|
||||
for span in line.spans {
|
||||
let span_width = crate::selection::cell_width(&span.content);
|
||||
if used + span_width <= width {
|
||||
used += span_width;
|
||||
spans.push(span);
|
||||
continue;
|
||||
}
|
||||
let text = crate::selection::slice_columns(&span.content, 0..width - used);
|
||||
if !text.is_empty() {
|
||||
spans.push(Span::styled(text, span.style));
|
||||
}
|
||||
break;
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// A styled line's plain text.
|
||||
pub(super) fn line_text(line: &Line<'static>) -> String {
|
||||
line.spans.iter().map(|span| span.content.as_ref()).collect()
|
||||
}
|
||||
|
||||
/// A system notice's lines, like [`prefixed_text_lines`], with each `` `quoted` `` stretch drawn as
|
||||
/// inline code: a command a notice names is something to type, and should look it.
|
||||
pub(super) fn system_lines(
|
||||
icon: &str,
|
||||
text: &str,
|
||||
style: Style,
|
||||
styles: &ThemeStyles,
|
||||
) -> Vec<Line<'static>> {
|
||||
text.split('\n')
|
||||
.enumerate()
|
||||
.map(|(index, text)| {
|
||||
let mut spans = Vec::new();
|
||||
if index == 0 && !icon.is_empty() {
|
||||
spans.push(Span::styled(icon_prefix(icon), style));
|
||||
}
|
||||
spans.extend(crate::widgets::code_spans(text, style, styles));
|
||||
Line::from(spans)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
pub(super) fn prefixed_text_lines(icon: &str, text: &str, style: Style) -> Vec<Line<'static>> {
|
||||
text.split('\n')
|
||||
.enumerate()
|
||||
.map(|(index, text)| {
|
||||
if index == 0 && !icon.is_empty() {
|
||||
Line::from(vec![
|
||||
Span::styled(icon_prefix(icon), style),
|
||||
Span::styled(text.to_string(), style),
|
||||
])
|
||||
} else {
|
||||
Line::from(Span::styled(text.to_string(), style))
|
||||
}
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
8
crates/luxe-tui/src/view/blocks/tests.rs
Normal file
8
crates/luxe-tui/src/view/blocks/tests.rs
Normal file
@@ -0,0 +1,8 @@
|
||||
use super::*;
|
||||
use std::sync::OnceLock;
|
||||
|
||||
mod cards;
|
||||
mod folds;
|
||||
mod reasoning;
|
||||
|
||||
use cards::*;
|
||||
402
crates/luxe-tui/src/view/blocks/tests/cards.rs
Normal file
402
crates/luxe-tui/src/view/blocks/tests/cards.rs
Normal file
@@ -0,0 +1,402 @@
|
||||
//! Cards — notices, references and the tool card in each state.
|
||||
|
||||
use super::*;
|
||||
|
||||
/// A command a notice names is drawn as inline code, backticks dropped; the rest stays muted.
|
||||
#[test]
|
||||
fn a_notice_draws_its_commands_as_code() {
|
||||
let styles = &theme();
|
||||
let lines = system_lines("", "Use `luxe --no-tool <name>` for one", styles.muted, styles);
|
||||
let spans = &lines[0].spans;
|
||||
let code: Vec<&str> = spans
|
||||
.iter()
|
||||
.filter(|span| span.style == styles.md_code)
|
||||
.map(|span| span.content.as_ref())
|
||||
.collect();
|
||||
assert_eq!(code, ["luxe --no-tool <name>"]);
|
||||
assert!(spans.iter().all(|span| !span.content.contains('`')), "{spans:?}");
|
||||
assert_eq!(spans[0].style, styles.muted);
|
||||
}
|
||||
|
||||
/// A reference in a sent message stands apart from the accent prose around it: body ink, bold,
|
||||
/// and no tint, which on the card's own band was too faint to read.
|
||||
#[test]
|
||||
fn a_reference_in_a_message_stands_apart() {
|
||||
let styles = &theme();
|
||||
let text = "fix acme/todo#12 with test-first";
|
||||
let lines = chipped_lines(text, &[4..16, 22..32], styles.accent, styles);
|
||||
assert_eq!(lines.len(), 1);
|
||||
let spans = &lines[0].spans;
|
||||
let texts: Vec<&str> = spans.iter().map(|span| span.content.as_ref()).collect();
|
||||
assert_eq!(texts, ["fix ", "acme/todo#12", " with ", "test-first"]);
|
||||
assert_eq!(spans[1].style.fg, styles.text.fg, "the body ink");
|
||||
assert_ne!(spans[1].style.fg, spans[0].style.fg, "not the sentence's accent");
|
||||
assert!(spans[1].style.add_modifier.contains(Modifier::BOLD), "in bold");
|
||||
assert_eq!(spans[1].style.bg, styles.accent.bg, "on the card, not a tint");
|
||||
assert!(!spans[0].style.add_modifier.contains(Modifier::BOLD), "the prose is not a chip");
|
||||
// A range off this text's character boundaries is not trusted
|
||||
let inside_the_e = std::ops::Range { start: 1, end: 2 };
|
||||
let odd = chipped_lines("é", std::slice::from_ref(&inside_the_e), styles.accent, styles);
|
||||
assert_eq!(odd[0].spans.len(), 1);
|
||||
}
|
||||
|
||||
/// A transcript with no images in it, which is every block these tests build.
|
||||
pub(super) static NO_IMAGES: OnceLock<crate::graphics::ImageStore> = OnceLock::new();
|
||||
pub(super) static NO_TOOL_IMAGES: OnceLock<
|
||||
std::collections::HashMap<(String, String), Vec<ImageKey>>,
|
||||
> = OnceLock::new();
|
||||
pub(super) fn theme() -> ThemeStyles {
|
||||
let registry = luxe_core::theme::ThemeRegistry::new();
|
||||
let resolved = registry.resolve("nord").expect("a bundled theme");
|
||||
ThemeStyles::from_resolved(&resolved, "nord")
|
||||
}
|
||||
|
||||
pub(super) fn tool_item(name: &str, state: luxe_core::ToolActivityState) -> ConvoBlock {
|
||||
let mut activity =
|
||||
luxe_core::ToolActivity::running("session-a", "call-a", name, "cargo test", 1);
|
||||
activity.state = state;
|
||||
activity.elapsed_ms = Some(842);
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}))
|
||||
}
|
||||
|
||||
pub(super) fn context(styles: &ThemeStyles, spinner_frame: usize) -> BlockContext<'_> {
|
||||
BlockContext {
|
||||
styles,
|
||||
spinner_frame,
|
||||
waiting_on_user: false,
|
||||
never_sent: false,
|
||||
expanded: false,
|
||||
images: NO_IMAGES.get_or_init(crate::graphics::ImageStore::default),
|
||||
tool_images: NO_TOOL_IMAGES.get_or_init(std::collections::HashMap::new),
|
||||
image_bounds: (80, 24),
|
||||
card_width: 80,
|
||||
prose_width: 80,
|
||||
diff_layout: luxe_core::config::DiffLayout::Auto,
|
||||
tool_output_expanded: false,
|
||||
expand_chord: Some("ctrl+o".into()),
|
||||
running_ms: None,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn header(block: &ConvoBlock, styles: &ThemeStyles) -> Line<'static> {
|
||||
lines(block, &context(styles, 0)).remove(0).line
|
||||
}
|
||||
|
||||
/// The card's three voices: the tool in bold state color, the subject in body text, the clock
|
||||
/// muted. A reader's eye has to land on the command, not on `842ms`.
|
||||
#[test]
|
||||
fn a_tool_card_reads_in_three_voices() {
|
||||
let styles = theme();
|
||||
let line = header(&tool_item("bash", luxe_core::ToolActivityState::Succeeded), &styles);
|
||||
|
||||
let name = &line.spans[0];
|
||||
assert_eq!(name.content.as_ref(), format!("{} bash", tool_glyph("bash")));
|
||||
assert!(name.style.add_modifier.contains(Modifier::BOLD), "the tool name is bold");
|
||||
assert_eq!(name.style.fg, styles.success.fg, "a landed call takes its outcome color");
|
||||
|
||||
let subject = &line.spans[1];
|
||||
assert_eq!(subject.content.as_ref(), " cargo test");
|
||||
assert_eq!(subject.style.fg, styles.text.fg, "the subject is plain body text");
|
||||
assert!(!subject.style.add_modifier.contains(Modifier::BOLD));
|
||||
|
||||
let duration = &line.spans[2];
|
||||
assert_eq!(duration.content.as_ref(), " 842ms", "held off by two spaces, not one");
|
||||
assert_eq!(duration.style.fg, styles.muted.fg, "the clock is de-emphasized");
|
||||
}
|
||||
|
||||
/// A running call keeps the spinner *and* its name in the warning color, so the eye still finds
|
||||
/// the in-flight card while the subject and clock read as they do everywhere else.
|
||||
#[test]
|
||||
fn a_running_card_spins_in_the_warning_color() {
|
||||
let styles = theme();
|
||||
let block = tool_item("bash", luxe_core::ToolActivityState::Running);
|
||||
|
||||
let first = header(&block, &styles);
|
||||
assert_eq!(first.spans[0].style.fg, styles.warning.fg);
|
||||
assert!(first.spans[0].style.add_modifier.contains(Modifier::BOLD));
|
||||
assert_eq!(first.spans[1].style.fg, styles.text.fg);
|
||||
assert_ne!(
|
||||
first.spans[0].content,
|
||||
lines(&block, &context(&styles, 3)).remove(0).line.spans[0].content,
|
||||
"the leading glyph animates while the call is in flight"
|
||||
);
|
||||
}
|
||||
|
||||
/// A call the model is still writing has a card but nothing yet to say about it. The header is
|
||||
/// its mark and the tool, and no more — a subject slot filled with the tool's own name would
|
||||
/// read `write write`.
|
||||
#[test]
|
||||
fn a_card_for_an_unnamed_call_is_its_mark_and_the_tool() {
|
||||
let styles = theme();
|
||||
let card = |label: &str| {
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity: luxe_core::ToolActivity::composing("session-a", "call-a", "write", label, 1),
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}))
|
||||
};
|
||||
|
||||
let line = header(&card(""), &styles);
|
||||
assert_eq!(line.spans.len(), 1, "{line}");
|
||||
assert_eq!(line.spans[0].content.as_ref(), format!("{} write", crate::statusline::spinner(0)));
|
||||
|
||||
// Then the path arrives and takes the subject slot, on the same row.
|
||||
assert_eq!(header(&card("notes.rs"), &styles).spans[1].content.as_ref(), " notes.rs");
|
||||
}
|
||||
|
||||
/// Exactly one card looks busy, and it is whichever one is actually moving.
|
||||
///
|
||||
/// The model writing a call and the tool running it are both work, and the card says so the
|
||||
/// same way for each. Only a call written in full and waiting its turn is idle. Both halves of
|
||||
/// this were reported wrong: every un-started call drawn as running put two spinning `bash`
|
||||
/// cards side by side, and every un-started call drawn as waiting put a paused mark on a card
|
||||
/// that was visibly filling in.
|
||||
#[test]
|
||||
fn a_card_looks_busy_exactly_when_it_is() {
|
||||
let styles = theme();
|
||||
let card = |state| {
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity: luxe_core::ToolActivity {
|
||||
state,
|
||||
..luxe_core::ToolActivity::running("s", "c", "bash", "vainfo", 1)
|
||||
},
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}))
|
||||
};
|
||||
let spinner = format!("{} bash", crate::statusline::spinner(0));
|
||||
|
||||
for busy in [luxe_core::ToolActivityState::Running, luxe_core::ToolActivityState::Composing] {
|
||||
let line = header(&card(busy), &styles);
|
||||
assert_eq!(line.spans[0].content.as_ref(), spinner, "{busy:?} is work in progress");
|
||||
assert_eq!(line.spans[0].style.fg, styles.warning.fg, "{busy:?}");
|
||||
// And it animates, or the spinner is a picture of a stalled thing.
|
||||
let later = lines(&card(busy), &context(&styles, 3)).remove(0).line;
|
||||
assert_ne!(line.spans[0].content, later.spans[0].content, "{busy:?}");
|
||||
}
|
||||
|
||||
let queued = card(luxe_core::ToolActivityState::Queued);
|
||||
let line = header(&queued, &styles);
|
||||
assert_eq!(
|
||||
line.spans[0].content.as_ref(),
|
||||
format!("{} bash", Icon::Queued.glyph()),
|
||||
"a call waiting its turn wears the mark a queued submission does",
|
||||
);
|
||||
assert_eq!(line.spans[0].style.fg, styles.muted.fg, "and it recedes");
|
||||
let later = lines(&queued, &context(&styles, 3)).remove(0).line;
|
||||
assert_eq!(line.spans[0].content, later.spans[0].content, "nothing is happening to it");
|
||||
}
|
||||
|
||||
/// A header subject is a preview for a card that shows nothing else. Where the body *is* the
|
||||
/// thing the subject was cut out of, the preview is the same string rendered worse, directly
|
||||
/// above the real one.
|
||||
#[test]
|
||||
fn a_header_does_not_restate_the_body_under_it() {
|
||||
let styles = theme();
|
||||
let card = |tool: &str, arguments: serde_json::Value| {
|
||||
let mut activity = luxe_core::ToolActivity::running(
|
||||
"s",
|
||||
"c",
|
||||
tool,
|
||||
luxe_core::describe_call(tool, &arguments, "/project"),
|
||||
1,
|
||||
);
|
||||
activity.state = luxe_core::ToolActivityState::Succeeded;
|
||||
activity.elapsed_ms = Some(5);
|
||||
activity.card_body = luxe_core::tool_card_body(tool, &arguments, "/project");
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}))
|
||||
};
|
||||
|
||||
// A multi-line command is drawn in full, highlighted, right below the header.
|
||||
let script = card("bash", serde_json::json!({"command": "make build\nmake test"}));
|
||||
let row = header(&script, &styles);
|
||||
assert_eq!(row.spans.len(), 2, "the tool and the clock, and nothing else: {row}");
|
||||
assert_eq!(row.spans[1].content.as_ref(), " 5ms");
|
||||
let rendered = lines(&script, &context(&styles, 0));
|
||||
assert!(rendered[1].line.to_string().contains("make build"), "the body has the command");
|
||||
|
||||
// Same for the queries a search ran: the header named the first and the body lists them.
|
||||
let searched = card("web_search", serde_json::json!({"queries": ["one", "two"]}));
|
||||
assert_eq!(header(&searched, &styles).spans.len(), 2);
|
||||
|
||||
// A one-line command has no body, so the header is the only place it can be.
|
||||
let one = card("bash", serde_json::json!({"command": "make build"}));
|
||||
assert_eq!(header(&one, &styles).spans[1].content.as_ref(), " make build");
|
||||
|
||||
// And a `write`'s subject is the path while its body is the file: different things.
|
||||
let written = card("write", serde_json::json!({"path": "a.rs", "content": "fn main() {}"}));
|
||||
assert_eq!(header(&written, &styles).spans[1].content.as_ref(), " a.rs");
|
||||
|
||||
// So is a described command: the header says what it is for, the body what ran, folded
|
||||
let described = card(
|
||||
"bash",
|
||||
serde_json::json!({"description": "Build it", "command": "make build\nmake test"}),
|
||||
);
|
||||
assert_eq!(header(&described, &styles).spans[1].content.as_ref(), " Build it");
|
||||
let rendered = lines(&described, &context(&styles, 0));
|
||||
assert!(rendered[1].line.to_string().contains("make build"), "the command's first line");
|
||||
assert!(
|
||||
!rendered.iter().any(|row| row.line.to_string().contains("make test")),
|
||||
"the rest is folded"
|
||||
);
|
||||
}
|
||||
|
||||
/// A call in flight reports how long it has been going, which is when that answers something.
|
||||
///
|
||||
/// The projector only times a call once it has *finished*, so a card used to show no figure at
|
||||
/// all for the whole time "is this taking long?" was the live question — and then show one the
|
||||
/// moment nobody was asking.
|
||||
/// A call waiting on the reader stands still: its own glyph, in the running color, rather than a
|
||||
/// spinner hurrying someone who is reading a question. Busy again, it spins again.
|
||||
#[test]
|
||||
fn a_call_waiting_on_you_does_not_spin() {
|
||||
let styles = theme();
|
||||
let question = ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity: luxe_core::ToolActivity::running("s", "c", "question", "Which runtime?", 1),
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}));
|
||||
let icon = |waiting: bool, frame: usize| {
|
||||
let ctx = BlockContext { waiting_on_user: waiting, ..context(&styles, frame) };
|
||||
let header = lines(&question, &ctx).remove(0).line;
|
||||
(header.spans[0].content.to_string(), header.spans[0].style)
|
||||
};
|
||||
let (still, style) = icon(true, 0);
|
||||
assert!(still.contains(tool_glyph("question")), "{still:?}");
|
||||
assert_eq!(icon(true, 7), (still.clone(), style), "the same on every frame");
|
||||
let (spinning, spinning_style) = icon(false, 0);
|
||||
assert_ne!(spinning, still, "a call nobody waits on spins");
|
||||
assert_ne!(icon(false, 7).0, spinning, "and moves");
|
||||
assert_eq!(style, spinning_style, "in the running color either way");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_call_in_flight_reports_how_long_it_has_been_going() {
|
||||
let styles = theme();
|
||||
let card = |state| {
|
||||
let mut activity = luxe_core::ToolActivity::running("s", "c", "bash", "make test", 1);
|
||||
activity.state = state;
|
||||
activity.elapsed_ms =
|
||||
matches!(state, luxe_core::ToolActivityState::Succeeded).then_some(2_500);
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}))
|
||||
};
|
||||
let with_running = |block: &ConvoBlock, running_ms| {
|
||||
let ctx = BlockContext { running_ms, ..context(&styles, 0) };
|
||||
lines(block, &ctx).remove(0).line
|
||||
};
|
||||
|
||||
let running = card(luxe_core::ToolActivityState::Running);
|
||||
let live = with_running(&running, Some(12_000));
|
||||
assert_eq!(live.spans[2].content.as_ref(), " 12s", "{live}");
|
||||
|
||||
assert!(!live.to_string().contains('.'), "a live figure with a tenths digit: {live}");
|
||||
|
||||
// Before the front-end has a start to measure from, it says nothing rather than `0ms`.
|
||||
let cold = with_running(&running, None);
|
||||
assert_eq!(cold.spans.len(), 2, "no clock yet: {cold}");
|
||||
|
||||
// And for its first second it says nothing either: the only reading available down there
|
||||
// is milliseconds, which on a card redrawn every frame is three digits of noise beside a
|
||||
// spinner that is already reporting the same fact.
|
||||
let just_started = with_running(&running, Some(740));
|
||||
assert_eq!(just_started.spans.len(), 2, "under a second, no figure: {just_started}");
|
||||
assert_eq!(
|
||||
with_running(&running, Some(1_000)).spans[2].content.as_ref(),
|
||||
" 1s",
|
||||
"and then it starts counting"
|
||||
);
|
||||
|
||||
// Once it lands, the figure is the one the projector measured — not whatever the last
|
||||
// frame happened to compute.
|
||||
let done = card(luxe_core::ToolActivityState::Succeeded);
|
||||
assert_eq!(with_running(&done, Some(99_000)).spans[2].content.as_ref(), " 2s");
|
||||
}
|
||||
|
||||
/// A card reports the time the *tool* spent, not the time the reader spent deciding.
|
||||
#[test]
|
||||
fn a_card_does_not_report_the_readers_own_deliberation() {
|
||||
let styles = theme();
|
||||
let card = |tool: &str, waited_on_user_ms| {
|
||||
let mut activity = luxe_core::ToolActivity::running("s", "c", tool, "subject", 1);
|
||||
activity.state = luxe_core::ToolActivityState::Succeeded;
|
||||
activity.elapsed_ms = Some(31_000);
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms,
|
||||
}))
|
||||
};
|
||||
|
||||
// Thirty of those thirty-one seconds were a permission prompt on screen.
|
||||
let gated = header(&card("bash", 30_000), &styles);
|
||||
assert_eq!(gated.spans[2].content.as_ref(), " 1s");
|
||||
// Nothing waited on, nothing to subtract.
|
||||
let plain = header(&card("bash", 0), &styles);
|
||||
assert_eq!(plain.spans[2].content.as_ref(), " 31s");
|
||||
|
||||
// A `question` is that case taken to its limit: the whole call is a person thinking, so
|
||||
// there is no tool time to report at all.
|
||||
let asked = header(&card("question", 0), &styles);
|
||||
assert_eq!(asked.spans.len(), 2, "the tool and the prompt, no clock: {asked}");
|
||||
assert_eq!(asked.spans[1].content.as_ref(), " subject");
|
||||
}
|
||||
|
||||
/// A long subject, a question or a command, wraps under itself rather than back under the
|
||||
/// tool's name, so the card's header still reads as one block.
|
||||
#[test]
|
||||
fn a_card_header_wraps_under_its_subject() {
|
||||
let styles = theme();
|
||||
for tool in ["question", "bash"] {
|
||||
let mut activity = luxe_core::ToolActivity::running("s", "c", tool, "a long subject", 1);
|
||||
activity.state = luxe_core::ToolActivityState::Succeeded;
|
||||
let block = ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}));
|
||||
let rendered = lines(&block, &context(&styles, 0));
|
||||
assert_eq!(rendered[0].hang, Some(header_subject_column(tool)), "{tool}");
|
||||
assert!(rendered[1..].iter().all(|line| line.hang.is_none()), "only the header hangs");
|
||||
}
|
||||
}
|
||||
|
||||
/// The band's wash says how it went, so the glyph is free to say *what ran* — except for the
|
||||
/// two states that get no wash at all.
|
||||
#[test]
|
||||
fn a_landed_card_shows_its_tool_not_a_tick() {
|
||||
let styles = theme();
|
||||
for state in [luxe_core::ToolActivityState::Succeeded, luxe_core::ToolActivityState::Failed] {
|
||||
for tool in ["read", "bash", "grep"] {
|
||||
let line = header(&tool_item(tool, state), &styles);
|
||||
assert_eq!(
|
||||
line.spans[0].content.as_ref(),
|
||||
format!("{} {tool}", tool_glyph(tool)),
|
||||
"{tool} in {state:?} should wear its own icon"
|
||||
);
|
||||
}
|
||||
}
|
||||
// Cancelled and interrupted calls keep a state glyph: nothing else on the card says they
|
||||
// never finished.
|
||||
let cancelled = header(&tool_item("read", luxe_core::ToolActivityState::Cancelled), &styles);
|
||||
assert!(cancelled.spans[0].content.starts_with('⊘'));
|
||||
}
|
||||
237
crates/luxe-tui/src/view/blocks/tests/folds.rs
Normal file
237
crates/luxe-tui/src/view/blocks/tests/folds.rs
Normal file
@@ -0,0 +1,237 @@
|
||||
//! Folds — a run of calls as one line, and what it counts and meters.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn group_header_text(items: &[ConversationItem], arriving: bool) -> String {
|
||||
tool_group_lines(items, arriving, 0, 120, &theme())[0].line.to_string()
|
||||
}
|
||||
|
||||
pub(super) fn group_text(items: &[ConversationItem], width: u16) -> Vec<String> {
|
||||
tool_group_lines(items, false, 0, width, &theme())
|
||||
.into_iter()
|
||||
.map(|row| row.line.to_string())
|
||||
.collect()
|
||||
}
|
||||
|
||||
/// A settled call of `tool`, labeled `label`, as a transcript item.
|
||||
pub(super) fn labeled_call(tool: &str, label: &str, call_id: &str) -> ConversationItem {
|
||||
let mut activity = luxe_core::ToolActivity::running("session-a", call_id, tool, label, 1);
|
||||
activity.state = luxe_core::ToolActivityState::Succeeded;
|
||||
activity.summary = Some("Completed".into());
|
||||
ConversationItem::new(
|
||||
crate::app::ConversationItemId::Tool {
|
||||
session_id: "session-a".into(),
|
||||
call_id: call_id.into(),
|
||||
},
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
})),
|
||||
)
|
||||
}
|
||||
|
||||
/// A folded run says what it stands for, not only how much: the calls by name under the count,
|
||||
/// all of them when there are five or fewer.
|
||||
#[test]
|
||||
fn a_folded_run_lists_what_it_folded() {
|
||||
let run = [
|
||||
labeled_call("read", "note.md", "a"),
|
||||
labeled_call("read", "scripts/demo.py:12-40", "b"),
|
||||
labeled_call("read", "tests/example.py", "c"),
|
||||
];
|
||||
let rows = group_text(&run, 120);
|
||||
assert_eq!(
|
||||
rows[1..],
|
||||
[
|
||||
format!("{BODY_INDENT}note.md"),
|
||||
format!("{BODY_INDENT}scripts/demo.py:12-40"),
|
||||
format!("{BODY_INDENT}tests/example.py"),
|
||||
],
|
||||
"{rows:#?}"
|
||||
);
|
||||
let rows = tool_group_lines(&run, false, 0, 120, &theme());
|
||||
assert!(rows[0].handle, "the header opens the run");
|
||||
assert!(rows[1..].iter().all(|row| !row.handle), "the list is text to select");
|
||||
}
|
||||
|
||||
/// Past five, four by name and a count of the rest, which says how to see them.
|
||||
#[test]
|
||||
fn a_long_folded_run_counts_the_calls_it_does_not_list() {
|
||||
let run: Vec<ConversationItem> = (0..9)
|
||||
.map(|index| labeled_call("grep", &format!("\"pattern{index}\""), &index.to_string()))
|
||||
.collect();
|
||||
let rows = group_text(&run, 120);
|
||||
assert_eq!(rows.len(), 1 + 4 + 1, "{rows:#?}");
|
||||
assert!(rows[4].ends_with("\"pattern3\""));
|
||||
assert_eq!(rows[5], format!("{BODY_INDENT}⋯ 5 more · 9 total · click to expand"));
|
||||
let last = tool_group_lines(&run, false, 0, 120, &theme()).pop().expect("a footer");
|
||||
assert!(last.handle, "the footer offers the expand, so a click on it has to open it");
|
||||
|
||||
let five = &run[..5];
|
||||
assert_eq!(group_text(five, 120).len(), 6, "five fit whole: no '1 more'");
|
||||
}
|
||||
|
||||
/// A mixed run names each call's tool, and a row too long for the card is cut, not wrapped.
|
||||
#[test]
|
||||
fn a_mixed_run_names_each_tool_and_cuts_long_rows() {
|
||||
let run = [
|
||||
labeled_call("read", "src/a/very/long/path/to/some/file/that/goes/on.rs", "a"),
|
||||
labeled_call("grep", "\"needle\" in src", "b"),
|
||||
labeled_call("glob", "**/*.rs", "c"),
|
||||
];
|
||||
let rows = group_text(&run, 30);
|
||||
assert_eq!(rows[2], format!("{BODY_INDENT}grep \"needle\" in src"));
|
||||
assert!(rows[1].ends_with('…'), "{rows:#?}");
|
||||
assert!(rows.iter().all(|row| row.chars().count() <= 30), "{rows:#?}");
|
||||
}
|
||||
|
||||
/// An MCP run names its server once, on the header, and each call by its tool.
|
||||
#[test]
|
||||
fn an_mcp_run_names_its_server_once() {
|
||||
let run = [
|
||||
labeled_call("mcp", "search tasks", "a"),
|
||||
labeled_call("mcp", "asana/get_tasks", "b"),
|
||||
labeled_call("mcp", "asana/update_task", "c"),
|
||||
];
|
||||
let rows = group_text(&run, 120);
|
||||
assert_eq!(rows[0], format!("▸ {} 3 mcp calls · asana", tool_glyph("mcp")));
|
||||
assert_eq!(
|
||||
rows[1..],
|
||||
[
|
||||
format!("{BODY_INDENT}search tasks"),
|
||||
format!("{BODY_INDENT}get_tasks"),
|
||||
format!("{BODY_INDENT}update_task"),
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
/// A collapsed run of calls says which tool it collapsed; the wash already says they all
|
||||
/// succeeded.
|
||||
#[test]
|
||||
fn a_collapsed_group_leads_with_its_tool_icon() {
|
||||
let item = |name: &str| {
|
||||
ConversationItem::new(
|
||||
crate::app::ConversationItemId::Tool {
|
||||
session_id: "session-a".into(),
|
||||
call_id: name.into(),
|
||||
},
|
||||
tool_item(name, luxe_core::ToolActivityState::Succeeded),
|
||||
)
|
||||
};
|
||||
|
||||
// The run's time is its calls' time added up: what folding them cost, in one number.
|
||||
let same = [item("read"), item("read"), item("read")];
|
||||
let line = group_header_text(&same, false);
|
||||
assert_eq!(line, format!("▸ {} 3 read calls 2s", tool_glyph("read")));
|
||||
|
||||
// A mixed run has no one tool to name, so it takes the generic icon — and a word for what
|
||||
// the run actually was, since only lookups ever fold.
|
||||
let mixed = [item("read"), item("grep"), item("read")];
|
||||
let line = group_header_text(&mixed, false);
|
||||
assert_eq!(line, format!("▸ {} 3 lookups 2s", GENERIC_TOOL.glyph()));
|
||||
}
|
||||
|
||||
/// A run that is still moving is a progress line, and one that has stopped is not.
|
||||
///
|
||||
/// The meter is a claim that something is happening. Left on a settled run it would be a
|
||||
/// picture of work that already finished, which is the one thing a progress bar must never be.
|
||||
#[test]
|
||||
fn a_folded_run_meters_itself_only_while_it_is_moving() {
|
||||
let item = |call_id: &str, state: luxe_core::ToolActivityState, batch| {
|
||||
let mut activity =
|
||||
luxe_core::ToolActivity::running("session-a", call_id, "read", call_id, 1);
|
||||
activity.state = state;
|
||||
activity.batch = batch;
|
||||
if state == luxe_core::ToolActivityState::Succeeded {
|
||||
activity.elapsed_ms = Some(4);
|
||||
activity.summary = Some("Completed".into());
|
||||
}
|
||||
ConversationItem::new(
|
||||
crate::app::ConversationItemId::Tool {
|
||||
session_id: "session-a".into(),
|
||||
call_id: call_id.into(),
|
||||
},
|
||||
ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
})),
|
||||
)
|
||||
};
|
||||
let batch = |index| Some(luxe_core::ToolBatch { index, total: 7 });
|
||||
|
||||
let live = [
|
||||
item("a.rs", luxe_core::ToolActivityState::Succeeded, batch(1)),
|
||||
item("b.rs", luxe_core::ToolActivityState::Succeeded, batch(2)),
|
||||
item("c.rs", luxe_core::ToolActivityState::Running, batch(3)),
|
||||
];
|
||||
let line = group_header_text(&live, true);
|
||||
assert!(line.contains("3/7"), "the run says how much of it is left: {line}");
|
||||
assert!(line.contains("read"), "named for the call in flight: {line}");
|
||||
assert!(line.contains("c.rs"), "and what it is doing right now: {line}");
|
||||
assert!(line.contains('█') || line.contains('▁'), "with a meter: {line}");
|
||||
|
||||
let settled = [
|
||||
item("a.rs", luxe_core::ToolActivityState::Succeeded, batch(1)),
|
||||
item("b.rs", luxe_core::ToolActivityState::Succeeded, batch(2)),
|
||||
item("c.rs", luxe_core::ToolActivityState::Succeeded, batch(3)),
|
||||
];
|
||||
let line = group_header_text(&settled, false);
|
||||
assert_eq!(line, format!("▸ {} 3 read calls 12ms", tool_glyph("read")));
|
||||
assert!(!line.contains('█') && !line.contains('▁'), "no meter once it stopped: {line}");
|
||||
|
||||
// Between two of its calls the run has nothing in flight and is nowhere near done. Reading
|
||||
// that as settled summarized the run as "3 read calls" for a frame and washed the band
|
||||
// green — once per call, all the way down a run of seven.
|
||||
let between = &settled[..2];
|
||||
let line = group_header_text(between, true);
|
||||
assert!(line.contains("2/7"), "still a progress line: {line}");
|
||||
assert!(run_is_working(between, true), "and still wearing the working band");
|
||||
assert!(!run_is_working(&settled, false), "which it gives up when the run is done");
|
||||
}
|
||||
|
||||
/// Both ends of the scale have to read as time, not as a raw counter.
|
||||
#[test]
|
||||
fn tool_durations_are_formatted_at_a_readable_scale() {
|
||||
// Sub-millisecond calls really do happen (a small read, a rejected edit); `0ms` reads as
|
||||
// "never ran", which is exactly the wrong conclusion.
|
||||
assert_eq!(format_tool_duration(0), "<1ms");
|
||||
assert_eq!(format_tool_duration(1), "1ms");
|
||||
assert_eq!(format_tool_duration(842), "842ms");
|
||||
assert_eq!(format_tool_duration(1_500), "1s", "a tenths digit moves ten times a second");
|
||||
assert_eq!(format_tool_duration(47_608), "47s");
|
||||
assert_eq!(format_tool_duration(134_000), "2m 14s");
|
||||
assert_eq!(format_tool_duration(3_780_000), "1h 03m");
|
||||
}
|
||||
|
||||
/// A card body sits inset under its header, and a `write` says what it did to the file.
|
||||
#[test]
|
||||
fn a_write_card_carries_its_content_under_its_header() {
|
||||
let styles = theme();
|
||||
let mut activity =
|
||||
luxe_core::ToolActivity::running("session-a", "call-a", "write", "notes.rs", 1);
|
||||
activity.state = luxe_core::ToolActivityState::Succeeded;
|
||||
activity.summary = Some("Completed".into());
|
||||
activity.output_preview = Some("Created 'notes.rs' (13 bytes)".into());
|
||||
let arguments = serde_json::json!({"path": "notes.rs", "content": "fn main() {}"});
|
||||
activity.card_body = luxe_core::tool_card_body("write", &arguments, "/project");
|
||||
let block = ConvoBlock::Tool(Box::new(crate::app::ToolItem {
|
||||
activity,
|
||||
expanded: false,
|
||||
details_toggled: false,
|
||||
waited_on_user_ms: 0,
|
||||
}));
|
||||
|
||||
let rendered = lines(&block, &context(&styles, 0));
|
||||
let header = rendered[0].line.to_string();
|
||||
assert!(header.contains("write notes.rs"), "{header}");
|
||||
assert!(header.ends_with("· Created · 13 B"), "the header says what it did: {header}");
|
||||
|
||||
let body = rendered[1].line.to_string();
|
||||
// Two cells of gutter whatever the file's depth, so a body filling in sits still.
|
||||
assert_eq!(body, format!("{BODY_INDENT} 1 fn main() {{}}"));
|
||||
assert_eq!(rendered.len(), 2, "no `arguments:`/`output:` rows once a body is shown");
|
||||
}
|
||||
191
crates/luxe-tui/src/view/blocks/tests/reasoning.rs
Normal file
191
crates/luxe-tui/src/view/blocks/tests/reasoning.rs
Normal file
@@ -0,0 +1,191 @@
|
||||
//! Reasoning — folded and expanded reasoning blocks and their peeks.
|
||||
|
||||
use super::*;
|
||||
|
||||
pub(super) fn reasoning(text: &str, expanded: bool) -> ConvoBlock {
|
||||
ConvoBlock::Thinking { text: text.into(), expanded }
|
||||
}
|
||||
|
||||
/// Reasoning is markdown, and the whole point of rendering it is that its syntax stops showing:
|
||||
/// a `**title**` becomes a bold title, a backticked symbol becomes a code-colored one, and the
|
||||
/// muted italic voice survives both.
|
||||
#[test]
|
||||
fn expanded_reasoning_renders_its_markdown_in_the_reasoning_voice() {
|
||||
let styles = theme();
|
||||
let block = reasoning("**Verifying configuration**\n\nStart with `lms ls`.", true);
|
||||
let rendered = lines(&block, &context(&styles, 0));
|
||||
let text = rendered.iter().map(|line| line.line.to_string()).collect::<Vec<_>>();
|
||||
assert!(
|
||||
text.iter().all(|line| !line.contains('*') && !line.contains('`')),
|
||||
"markdown syntax must not survive rendering: {text:?}"
|
||||
);
|
||||
|
||||
let title = rendered[0]
|
||||
.line
|
||||
.spans
|
||||
.iter()
|
||||
.find(|span| span.content.contains("Verifying configuration"))
|
||||
.expect("the title renders");
|
||||
assert!(title.style.add_modifier.contains(Modifier::BOLD), "a title is bold");
|
||||
assert!(title.style.add_modifier.contains(Modifier::ITALIC), "and still italic");
|
||||
assert_eq!(
|
||||
title.style.fg, styles.thinking_text.fg,
|
||||
"a title spends weight, not a color: the block stays reasoning"
|
||||
);
|
||||
|
||||
let body = rendered.last().expect("a body line");
|
||||
let prose = body
|
||||
.line
|
||||
.spans
|
||||
.iter()
|
||||
.find(|span| span.content.contains("Start with"))
|
||||
.expect("the prose renders");
|
||||
assert_eq!(prose.style.fg, styles.thinking_text.fg);
|
||||
assert!(prose.style.add_modifier.contains(Modifier::ITALIC));
|
||||
assert!(!prose.style.add_modifier.contains(Modifier::BOLD));
|
||||
|
||||
let code = body
|
||||
.line
|
||||
.spans
|
||||
.iter()
|
||||
.find(|span| span.content.contains("lms ls"))
|
||||
.expect("the code span renders");
|
||||
assert_eq!(code.style.fg, styles.md_code.fg, "a backticked symbol keeps the code hue");
|
||||
assert!(code.style.add_modifier.contains(Modifier::ITALIC));
|
||||
}
|
||||
|
||||
/// A model's own line breaks are structure, not accident: joining them into one paragraph the
|
||||
/// way authored markdown would turns a list of separate thoughts into a wall of text.
|
||||
#[test]
|
||||
fn reasoning_keeps_the_line_breaks_the_model_wrote() {
|
||||
let styles = theme();
|
||||
let block = reasoning("first thought\nsecond thought", true);
|
||||
// `Line`'s Display drops newlines, so the break has to be read off the spans themselves.
|
||||
let text = lines(&block, &context(&styles, 0))
|
||||
.iter()
|
||||
.flat_map(|layout| layout.line.spans.iter())
|
||||
.map(|span| span.content.to_string())
|
||||
.collect::<String>();
|
||||
assert_eq!(text, "first thought\nsecond thought");
|
||||
|
||||
// An answer, by contrast, reflows: a soft break there is authored prose, not structure.
|
||||
let answer = ConvoBlock::Assistant("first thought\nsecond thought".into());
|
||||
let reflowed = lines(&answer, &context(&styles, 0))
|
||||
.iter()
|
||||
.flat_map(|layout| layout.line.spans.iter())
|
||||
.map(|span| span.content.to_string())
|
||||
.collect::<String>();
|
||||
assert_eq!(reflowed, "first thought second thought");
|
||||
}
|
||||
|
||||
/// The remediation report is for the review: the transcript shows the prose around it, and a
|
||||
/// message that was nothing but the report shows nothing.
|
||||
#[test]
|
||||
fn the_remediation_report_stays_out_of_the_transcript() {
|
||||
let styles = theme();
|
||||
let report = "```luxe-remediation\n{\"findings\":[]}\n```";
|
||||
let text = |block: &ConvoBlock| {
|
||||
lines(block, &context(&styles, 0))
|
||||
.iter()
|
||||
.map(|layout| layout.line.to_string())
|
||||
.collect::<Vec<_>>()
|
||||
.join("\n")
|
||||
};
|
||||
let answer = ConvoBlock::Assistant(format!("Fixed both.\n{report}"));
|
||||
assert_eq!(text(&answer), "Fixed both.");
|
||||
assert!(lines(&ConvoBlock::Assistant(report.into()), &context(&styles, 0)).is_empty());
|
||||
}
|
||||
|
||||
/// The collapsed peek is built from the *rendered* line, so it shows the section title rather
|
||||
/// than the asterisks that made it — and counts what it is standing in for.
|
||||
#[test]
|
||||
fn a_collapsed_reasoning_block_peeks_at_its_rendered_title() {
|
||||
let styles = theme();
|
||||
let block = reasoning("**Verifying configuration**\n\nStart with `lms ls`.", false);
|
||||
let rendered = lines(&block, &context(&styles, 0));
|
||||
assert_eq!(rendered.len(), 1, "a collapsed block is one line");
|
||||
assert_eq!(rendered[0].line.to_string(), "Verifying configuration · +1 more line");
|
||||
|
||||
// A single short thought hides nothing, so it says nothing; empty reasoning still speaks.
|
||||
let short = lines(&reasoning("just this", false), &context(&styles, 0));
|
||||
assert_eq!(short[0].line.to_string(), "just this");
|
||||
let empty = lines(&reasoning(" ", false), &context(&styles, 0));
|
||||
assert_eq!(empty[0].line.to_string(), "(no content)");
|
||||
|
||||
// A hard break hides a line as surely as a paragraph does, and is counted the same way.
|
||||
let broken = lines(&reasoning("one\ntwo\nthree", false), &context(&styles, 0));
|
||||
assert_eq!(broken[0].line.to_string(), "one · +2 more lines");
|
||||
|
||||
// An over-long first line is cut to the prose measure, ellipsis included.
|
||||
let long = "w".repeat(200);
|
||||
let capped = lines(&reasoning(&long, false), &context(&styles, 0));
|
||||
assert_eq!(capped[0].line.to_string(), format!("{}…", "w".repeat(79)));
|
||||
|
||||
// A line that fills the measure exactly is not cut: an ellipsis there would be spending a
|
||||
// character to report an elision that never happened.
|
||||
let exact = lines(&reasoning(&"w".repeat(80), false), &context(&styles, 0));
|
||||
assert_eq!(exact[0].line.to_string(), "w".repeat(80));
|
||||
let over = lines(&reasoning(&"w".repeat(81), false), &context(&styles, 0));
|
||||
assert_eq!(over[0].line.to_string(), format!("{}…", "w".repeat(79)));
|
||||
}
|
||||
|
||||
/// The peek's whole job is to be one line. A count that pushed it past the measure would wrap
|
||||
/// into a second row, which is the fold failing at the only thing it promised.
|
||||
#[test]
|
||||
fn a_peek_and_its_count_fit_the_prose_measure() {
|
||||
let styles = theme();
|
||||
let sentence = "a thought long enough to run past any measure worth wrapping at, twice \
|
||||
over, with no break in it anywhere";
|
||||
for width in [16u16, 24, 30, 40, 72, 80, 120] {
|
||||
let mut ctx = context(&styles, 0);
|
||||
ctx.prose_width = width;
|
||||
let peek = lines(&reasoning(&format!("{sentence}\nand another"), false), &ctx);
|
||||
assert_eq!(peek.len(), 1, "a peek is one line at {width}");
|
||||
let text = line_text(&peek[0].line);
|
||||
assert!(
|
||||
crate::selection::cell_width(&text) <= usize::from(width),
|
||||
"{width}: peek is {} cells: {text:?}",
|
||||
crate::selection::cell_width(&text)
|
||||
);
|
||||
// Wide enough to seat both, the count is there; too narrow, and the thought keeps the
|
||||
// cells rather than sharing them with a number.
|
||||
assert_eq!(
|
||||
text.ends_with("· +1 more line"),
|
||||
width >= 40,
|
||||
"{width}: the wrong half won the canvas: {text:?}"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
/// Reasoning shown in full is prose. A click on it must not fold it away, so no row of it is a
|
||||
/// handle — the collapsed peek is the only thing here a click acts on.
|
||||
#[test]
|
||||
fn only_a_folded_reasoning_block_is_a_click_handle() {
|
||||
let styles = theme();
|
||||
let text = "**Tracing it**\n\nThe buffering happens in `feed`.\n\nSo I will read it.";
|
||||
let shown = lines(&reasoning(text, true), &context(&styles, 0));
|
||||
assert!(shown.len() > 1, "the fixture has rows to click");
|
||||
assert!(
|
||||
shown.iter().all(|line| !line.expands),
|
||||
"nothing in fully shown reasoning opens or closes on a click"
|
||||
);
|
||||
|
||||
let folded = lines(&reasoning(text, false), &context(&styles, 0));
|
||||
assert!(folded[0].expands, "a peek is clickable, or there is no way back in with a mouse");
|
||||
}
|
||||
|
||||
/// A fence inside reasoning stays in the reasoning voice: a syntect palette in a muted italic
|
||||
/// block reads as an answer, which is exactly what it is not.
|
||||
#[test]
|
||||
fn a_reasoning_fence_is_not_syntax_highlighted() {
|
||||
let styles = theme();
|
||||
let block = reasoning("try:\n\n```rust\nlet total = 1 + 2;\n```", true);
|
||||
let rendered = lines(&block, &context(&styles, 0));
|
||||
let code = rendered
|
||||
.iter()
|
||||
.find(|line| line.line.to_string().contains("let total"))
|
||||
.expect("the fence renders");
|
||||
assert_eq!(code.line.spans.len(), 1, "one span, so nothing was tokenized");
|
||||
assert_eq!(code.line.spans[0].style.fg, styles.md_code.fg);
|
||||
assert!(code.line.spans[0].style.add_modifier.contains(Modifier::ITALIC));
|
||||
}
|
||||
258
crates/luxe-tui/src/view/blocks/tool.rs
Normal file
258
crates/luxe-tui/src/view/blocks/tool.rs
Normal file
@@ -0,0 +1,258 @@
|
||||
//! Tool blocks — a tool card's header: its icon, subject, summary and duration.
|
||||
|
||||
use super::message::mark_handles;
|
||||
use super::{image_lines, layout_lines, tool_card, BlockContext};
|
||||
use crate::app::ToolItem;
|
||||
use crate::glyphs::{icon_label, Icon};
|
||||
use crate::markdown::{MarkdownBlockKind, MarkdownLine};
|
||||
use crate::theme::styles::ThemeStyles;
|
||||
use crate::widgets::tool_glyph;
|
||||
use ratatui::{
|
||||
style::{Modifier, Style},
|
||||
text::{Line, Span},
|
||||
};
|
||||
use unicode_width::UnicodeWidthStr;
|
||||
|
||||
/// A tool call's card: its header, its body (indented unless it draws flush), its handles, and
|
||||
/// any picture it returned.
|
||||
pub(super) fn tool_lines(
|
||||
item: &ToolItem,
|
||||
style: Style,
|
||||
ctx: &BlockContext<'_>,
|
||||
) -> Vec<MarkdownLine> {
|
||||
let (styles, spinner_frame) = (ctx.styles, ctx.spinner_frame);
|
||||
let activity = &item.activity;
|
||||
// The band's success/error wash already carries the outcome, so a finished call shows
|
||||
// its *tool's* icon instead of another tick. Cancelled and interrupted calls keep a
|
||||
// state glyph — their band stays neutral, so nothing else says they never finished.
|
||||
let running = crate::statusline::spinner(spinner_frame).to_string();
|
||||
let icon = card_icon(activity, ctx.waiting_on_user, &running);
|
||||
// "Completed" is what a green card means; only a summary that adds information
|
||||
// earns a slot — a `write` trades it for what the write actually did.
|
||||
let outcome = tool_card::header_summary(activity);
|
||||
let summary = outcome.as_deref().or_else(|| {
|
||||
activity.summary.as_deref().filter(|summary| !summary.eq_ignore_ascii_case("completed"))
|
||||
});
|
||||
// Where this call sits in the run its message asked for — while it is *in* that run.
|
||||
// A card that never folds is one the reader is meant to look at, and the one thing the
|
||||
// card cannot otherwise tell them is how many more are queued behind it. Gone the
|
||||
// moment it lands: a finished call has no queue left to be part of.
|
||||
let queued = (activity.state == luxe_core::ToolActivityState::Running)
|
||||
.then_some(activity.batch)
|
||||
.flatten();
|
||||
let header = tool_header_line(
|
||||
ToolHeader {
|
||||
icon,
|
||||
tool: &activity.name,
|
||||
subject: header_subject(activity),
|
||||
elapsed_ms: header_duration(item, ctx.running_ms),
|
||||
summary,
|
||||
queued,
|
||||
},
|
||||
style,
|
||||
styles,
|
||||
);
|
||||
let mut lines = Vec::new();
|
||||
// The change, the file, or the command — always visible for the tools that have one,
|
||||
// never gated on expand, because seeing it is the whole point of the card. Everything
|
||||
// else stays a one-line card until the reader opens it. No `result:` row either way:
|
||||
// the header carries the summary, and "Completed" is what a green card means.
|
||||
let card = tool_card::body(item, &ctx.card());
|
||||
let truncated = card.truncated;
|
||||
if card.flush {
|
||||
lines.extend(card.lines);
|
||||
} else {
|
||||
lines.extend(card.lines.into_iter().map(indented));
|
||||
}
|
||||
let mut laid = vec![header_layout(header, icon, &activity.name)];
|
||||
laid.extend(layout_lines(lines, MarkdownBlockKind::Wide));
|
||||
// The header is the card's handle, and a footer that offers the expand says "click" in
|
||||
// so many words. The body between them is text to select.
|
||||
mark_handles(&mut laid, truncated);
|
||||
// Never gated on expand. For a `screenshot` the picture *is* the result, and a payload
|
||||
// hidden behind a keystroke is the mistake the card bodies already stopped making.
|
||||
let call = (activity.session_id.clone(), activity.call_id.clone());
|
||||
for key in ctx.tool_images.get(&call).into_iter().flatten() {
|
||||
let rows = image_lines(key, ctx, style);
|
||||
if !rows.is_empty() {
|
||||
laid.push(MarkdownLine::wide(Line::default()));
|
||||
laid.extend(rows);
|
||||
}
|
||||
}
|
||||
laid
|
||||
}
|
||||
|
||||
/// The glyph a card's header leads with: a spinner while it works, a state mark when it stopped
|
||||
/// short, and otherwise its tool's own icon.
|
||||
fn card_icon<'a>(
|
||||
activity: &luxe_core::ToolActivity,
|
||||
waiting_on_user: bool,
|
||||
running: &'a str,
|
||||
) -> &'a str {
|
||||
match activity.state {
|
||||
// The tool running and the model writing the call are both work in progress, and
|
||||
// the card says so the same way for each — a spinner over a card that is visibly
|
||||
// filling in, and a queued mark only over one that genuinely is not moving. A
|
||||
// model writes a message's calls in order and the engine runs them in order, so
|
||||
// exactly one card spins at a time.
|
||||
// Except the call that is waiting on the reader. A spinner says the agent is busy, and
|
||||
// over a question it is waiting on you to answer it only adds pressure; the call's
|
||||
// own glyph, in the same running color, says it is open without hurrying anyone
|
||||
luxe_core::ToolActivityState::Running if waiting_on_user => tool_glyph(&activity.name),
|
||||
luxe_core::ToolActivityState::Running | luxe_core::ToolActivityState::Composing => running,
|
||||
luxe_core::ToolActivityState::Queued => Icon::Queued.glyph(),
|
||||
luxe_core::ToolActivityState::Cancelled => crate::glyphs::Mark::Halted.glyph(),
|
||||
luxe_core::ToolActivityState::Interrupted => "!",
|
||||
_ => tool_glyph(&activity.name),
|
||||
}
|
||||
}
|
||||
|
||||
/// A tool card's header, laid out to wrap under its own subject rather than back at the margin.
|
||||
fn header_layout(line: Line<'static>, header_icon: &str, tool: &str) -> MarkdownLine {
|
||||
let mut layout = MarkdownLine::wide(line);
|
||||
layout.hang = Some(icon_label(header_icon, tool).width() + SUBJECT_GAP.len());
|
||||
layout
|
||||
}
|
||||
|
||||
/// What a tool card's one line is made of.
|
||||
struct ToolHeader<'a> {
|
||||
/// The tier's glyph for this tool, or empty where the tier draws none.
|
||||
icon: &'a str,
|
||||
/// Registered tool name.
|
||||
tool: &'a str,
|
||||
/// The command, the path, the pattern — what the call was about.
|
||||
subject: &'a str,
|
||||
/// How long the call took, once it has taken it.
|
||||
elapsed_ms: Option<u64>,
|
||||
/// An outcome worth a slot, for the tools whose result says more than a green wash.
|
||||
summary: Option<&'a str>,
|
||||
/// Where the call sits in the run its message asked for, while it is still in that run.
|
||||
queued: Option<luxe_core::ToolBatch>,
|
||||
}
|
||||
|
||||
/// The one line every tool card leads with: `{icon} {tool} {subject} {n/N} {duration} · {summary}`.
|
||||
///
|
||||
/// Three voices, so a glance lands on the subject rather than on the clock. The icon and tool name
|
||||
/// take the card's state color in bold (yellow while it runs, green/red once it lands); the subject
|
||||
/// — the command, the path, the pattern — takes plain body text, because that is the part worth
|
||||
/// reading; the duration is muted and held off by a double space, since how long a call took is the
|
||||
/// least of it. A summary that adds something rides at the end in the state color.
|
||||
fn tool_header_line(header: ToolHeader<'_>, style: Style, styles: &ThemeStyles) -> Line<'static> {
|
||||
let name_style = style.add_modifier(Modifier::BOLD);
|
||||
let mut spans = vec![Span::styled(icon_label(header.icon, header.tool), name_style)];
|
||||
let subject = safe_tool_text(header.subject);
|
||||
if !subject.trim().is_empty() {
|
||||
spans.push(Span::styled(format!("{SUBJECT_GAP}{subject}"), styles.text));
|
||||
}
|
||||
if let Some(batch) = header.queued {
|
||||
spans.push(Span::styled(format!(" {}/{}", batch.index, batch.total), styles.muted));
|
||||
}
|
||||
if let Some(elapsed) = header.elapsed_ms {
|
||||
spans.push(Span::styled(format!(" {}", format_tool_duration(elapsed)), styles.muted));
|
||||
}
|
||||
let summary = header.summary.map(safe_tool_text).filter(|text| !text.trim().is_empty());
|
||||
if let Some(summary) = summary {
|
||||
spans.push(Span::styled(format!(" · {summary}"), style));
|
||||
}
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// What the header says the call was about, or nothing when the body below it already says it.
|
||||
///
|
||||
/// A header subject is a *preview*, for a card that shows nothing else. Where the body is the same
|
||||
/// payload the subject was cut out of — a `bash` command, the queries a `web_search` ran — the
|
||||
/// header's ellipsized copy of its first line sits directly above the real thing, syntax
|
||||
/// highlighted and in full. Two renderings of one string, the worse one on top.
|
||||
///
|
||||
/// Not every card with a body restates it: a `write`'s subject is the path and its body is the
|
||||
/// file, an `edit`'s is the path and its body is the diff. Those say different things, and so does
|
||||
/// a described `bash` call: its subject is the description, its body the command, folded.
|
||||
fn header_subject(activity: &luxe_core::ToolActivity) -> &str {
|
||||
let restated = activity.card_body.as_ref().is_some_and(|body| body.collapsed_lines.is_none())
|
||||
&& matches!(activity.name.as_str(), "bash" | "web_search" | "websearch");
|
||||
if restated {
|
||||
return "";
|
||||
}
|
||||
&activity.label
|
||||
}
|
||||
|
||||
/// How long the call took, counting only the part the *tool* spent.
|
||||
///
|
||||
/// A call gated by a permission prompt is timed from dispatch to result, most of which was the
|
||||
/// reader deciding — a `bash` that ran in a second reports thirty if they took thirty to approve
|
||||
/// it, which is a card telling them about themselves.
|
||||
///
|
||||
/// A `question` is that case taken to its limit: the whole call is a person thinking, so there is
|
||||
/// no tool time to report and the figure is dropped. It was also actively in the way — a `question`
|
||||
/// lays its answer out as a *peer* of the header, so a long prompt wrapped and dropped the duration
|
||||
/// between the question and the answer to it.
|
||||
fn header_duration(item: &crate::app::ToolItem, running_ms: Option<u64>) -> Option<u64> {
|
||||
if item.activity.name == "question" {
|
||||
return None;
|
||||
}
|
||||
// A call in flight is timed by the front-end: the projector only measures one once it has
|
||||
// finished, and a card would report nothing for the whole time the answer matters most
|
||||
let running = matches!(item.activity.state, luxe_core::ToolActivityState::Running);
|
||||
let measured = match running {
|
||||
true => running_ms,
|
||||
false => item.activity.elapsed_ms,
|
||||
}?;
|
||||
let elapsed = measured.saturating_sub(item.waited_on_user_ms);
|
||||
// Below a second a live card has nothing to say but milliseconds, and those are three digits
|
||||
// rewritten on every frame. A finished call keeps them: that figure holds still, and `842ms`
|
||||
// is the only honest reading of a call that fast.
|
||||
(!running || elapsed >= 1_000).then_some(elapsed)
|
||||
}
|
||||
|
||||
/// The clearance between a card header's tool name and what the call was about.
|
||||
const SUBJECT_GAP: &str = " ";
|
||||
|
||||
/// The column a card header's subject starts in, measured at the tier that is drawing it.
|
||||
///
|
||||
/// For a body row that belongs beside the header rather than under it — a question's answer is the
|
||||
/// other half of an exchange, not content the card is previewing — so that it lands on the same
|
||||
/// column however wide the terminal's icons turn out to be, or whether it draws them at all.
|
||||
pub(in crate::view) fn header_subject_column(tool: &str) -> usize {
|
||||
icon_label(tool_glyph(tool), tool).width() + SUBJECT_GAP.len()
|
||||
}
|
||||
|
||||
/// Insets a card body row under its header, so the body reads as belonging to the card.
|
||||
pub(super) fn indented(line: Line<'static>) -> Line<'static> {
|
||||
let mut spans = Vec::with_capacity(line.spans.len() + 1);
|
||||
spans.push(Span::raw(BODY_INDENT));
|
||||
spans.extend(line.spans);
|
||||
Line::from(spans)
|
||||
}
|
||||
|
||||
/// Cells a card body sits in from the card's left edge.
|
||||
pub(in crate::view) const BODY_INDENT: &str = " ";
|
||||
|
||||
/// Formats a tool call's duration at a scale a reader can act on.
|
||||
///
|
||||
/// A bare millisecond count reads badly at both ends: `0ms` looks like the call never ran (it was
|
||||
/// simply faster than the clock's resolution — a small `read`, a rejected `edit`), and `47608ms`
|
||||
/// makes the reader do arithmetic to notice it waited 47 seconds.
|
||||
///
|
||||
/// **Whole seconds once past one**, and that is about motion rather than precision. A card in
|
||||
/// flight is re-timed on every frame, so a tenths digit is a figure changing ten times a second in
|
||||
/// the corner of the eye — which is what a spinner is for, and this is not the spinner. Nobody
|
||||
/// acts on the tenth of a second a call took; they act on whether it was one second or forty.
|
||||
pub(super) fn format_tool_duration(elapsed_ms: u64) -> String {
|
||||
const SECOND: u64 = 1_000;
|
||||
const MINUTE: u64 = 60 * SECOND;
|
||||
const HOUR: u64 = 60 * MINUTE;
|
||||
match elapsed_ms {
|
||||
0 => "<1ms".to_string(),
|
||||
ms if ms < SECOND => format!("{ms}ms"),
|
||||
ms if ms < MINUTE => format!("{}s", ms / SECOND),
|
||||
ms if ms < HOUR => format!("{}m {:02}s", ms / MINUTE, (ms % MINUTE) / SECOND),
|
||||
ms => format!("{}h {:02}m", ms / HOUR, (ms % HOUR) / MINUTE),
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn safe_tool_text(value: &str) -> String {
|
||||
value
|
||||
.chars()
|
||||
.filter(|character| !character.is_control() || *character == '\n' || *character == '\t')
|
||||
.collect()
|
||||
}
|
||||
Reference in New Issue
Block a user