use ratatui::layout::{Constraint, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Cell, HighlightSpacing, Row as TableRow, Table, TableState};
use ratatui::Frame;
use tam_proto::{AgentInfo, AgentState, ShellInfo};
use crate::chat::{Chat, Closes};
use crate::task::{Member, Task, TaskStatus};
use super::app::{self, App, Branch, Order, Pick, Row};
use super::branch::Observation;
use super::fuzzy;
use super::theme;
use super::triage::{age, one_line};
use super::ui::{agent_detail_line, context_display, first_line, status_display, CONTEXT_GAUGE};
const NOTE_FROM: u16 = 100;
const NOTE_MIN: u16 = 20;
const TASK_WANTED: u16 = 20;
const SPACING: u16 = 1;
const MARK: u16 = 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Col {
Status,
Age,
Task,
Repo,
Branch,
Ctx,
Note,
}
const DROP_ORDER: [Col; 5] = [Col::Note, Col::Ctx, Col::Branch, Col::Repo, Col::Age];
impl Col {
fn header(self) -> &'static str {
match self {
Col::Status => "STATUS",
Col::Age | Col::Note => "",
Col::Task => "TASK",
Col::Repo => "REPO",
Col::Branch => "BRANCH",
Col::Ctx => "CTX",
}
}
fn fixed_width(self) -> Option<u16> {
match self {
Col::Status => Some(10), Col::Age => Some(4), Col::Ctx => Some(5 + CONTEXT_GAUGE as u16), _ => None,
}
}
}
pub fn render(frame: &mut Frame, area: Rect, app: &mut App) {
let t = theme::get();
let width = area.width.saturating_sub(MARK);
let now = crate::task::now();
let rows = app.rows();
let focused = app.focused_member().map(|(_, m)| m.id().to_string());
let selected = app.pick();
let mut cols = vec![Col::Status, Col::Age, Col::Task];
if app.order == Order::Attention {
cols.push(Col::Repo);
}
cols.extend([Col::Branch, Col::Ctx]);
if width >= NOTE_FROM {
cols.push(Col::Note);
}
let cell = |row: &Row, col| match *row {
Row::Group(_) | Row::Chats | Row::Shells => Line::default(),
Row::Chat(chat) => chat_cell(col, chat, app, now),
Row::Shell { shell, tree } => shell_cell(col, shell, tree, app),
Row::Task(task) => task_cell(col, task, app, now),
Row::Member { task, member, last } => {
let marked = focused.as_deref() == Some(member.id());
member_cell(col, task, member, last, marked, app, now)
}
};
let mut cells: Vec<Vec<Line<'static>>> = rows
.iter()
.map(|row| cols.iter().map(|&col| cell(row, col)).collect())
.collect();
let widths = fit(&mut cols, &mut cells, width);
let task_width = cols
.iter()
.position(|&c| c == Col::Task)
.map_or(0, |i| widths[i]);
let note_width = width.saturating_sub(
widths.iter().sum::<u16>() + SPACING * (cols.len() as u16).saturating_sub(1),
);
let header =
TableRow::new(cols.iter().map(|c| Cell::from(c.header()))).style(Style::new().fg(t.muted));
let table_rows: Vec<TableRow> = rows
.iter()
.zip(cells)
.map(|(row, cells)| match row {
Row::Group(task) => header_row(app::repo_group(task), width, cols.len(), app),
Row::Chats => header_row("chats".into(), width, cols.len(), app),
Row::Shells => header_row("shells".into(), width, cols.len(), app),
Row::Chat(chat) => TableRow::new(cols.iter().zip(cells).map(|(&col, line)| {
Cell::from(match col {
Col::Task => chat_name(chat, app, now, task_width),
Col::Note => ellipsize(line, note_width),
_ => line,
})
})),
_ => TableRow::new(cols.iter().zip(cells).map(|(&col, line)| {
Cell::from(match col {
Col::Task => ellipsize(line, task_width),
Col::Note => ellipsize(line, note_width),
_ => line,
})
})),
})
.collect();
let constraints: Vec<Constraint> = cols
.iter()
.zip(&widths)
.map(|(&col, &w)| match col {
Col::Note => Constraint::Fill(1),
_ => Constraint::Length(w),
})
.collect();
let selected_row = rows.iter().position(|r| match (r, &selected) {
(Row::Task(t), Some(Pick::Task(name))) => t.name == *name,
(Row::Chat(c), Some(Pick::Chat(id))) => c.info.id == *id,
(Row::Shell { shell, .. }, Some(Pick::Shell(id))) => shell.id == *id,
_ => false,
});
let block = selected_row.map(|i| {
let header = i > 0 && matches!(rows[i - 1], Row::Group(_) | Row::Chats | Row::Shells);
let start = if header { i - 1 } else { i };
let below = match rows[i] {
Row::Task(_) => rows[i + 1..]
.iter()
.take_while(|r| matches!(r, Row::Member { .. } | Row::Shell { tree: Some(_), .. }))
.count(),
_ => 0,
};
(start, i, i + 1 + below)
});
let height = area.height.saturating_sub(1) as usize;
let mut offset = app.table_offset.min(rows.len().saturating_sub(height));
if let Some((start, row, end)) = block {
if start < offset {
offset = start;
} else if end > offset + height {
offset = (end - height).min(row);
}
}
let mut index = 0;
let mut task = 0;
let row_tasks: Vec<Option<(usize, Option<String>)>> = rows
.iter()
.map(|row| match row {
Row::Group(_) | Row::Chats | Row::Shells => None,
Row::Task(_) => {
task = index;
index += 1;
Some((task, None))
}
Row::Chat(_) | Row::Shell { .. } => {
index += 1;
Some((index - 1, None))
}
Row::Member { member, .. } => Some((task, Some(member.id().to_string()))),
})
.collect();
drop(rows);
let table = Table::new(table_rows, constraints)
.header(header)
.column_spacing(SPACING)
.row_highlight_style(t.selection)
.highlight_symbol(Line::styled(
"▌",
Style::new().fg(if t.rainbow {
theme::rainbow(0, app.spin.unwrap_or(0) * 2)
} else {
t.accent
}),
))
.highlight_spacing(HighlightSpacing::Always);
let mut state = TableState::new()
.with_offset(offset)
.with_selected(selected_row);
frame.render_stateful_widget(table, area, &mut state);
app.table_offset = state.offset();
app.hits.list = Rect {
y: area.y + 1,
height: area.height.saturating_sub(1),
..area
};
app.hits.rows = row_tasks
.into_iter()
.skip(app.table_offset)
.take(height)
.collect();
}
fn header_row(name: String, width: u16, cols: usize, app: &App) -> TableRow<'static> {
let t = theme::get();
let rule = (width as usize).saturating_sub(Span::raw(name.as_str()).width() + 1);
let mut spans = vec![
Span::styled(name, Style::new().fg(t.accent).add_modifier(Modifier::BOLD)),
Span::raw(" "),
];
if t.rainbow {
let tick = app.spin.unwrap_or(0);
spans.extend(theme::rainbow_spans(&"─".repeat(rule), tick, Style::new()));
} else {
spans.push(Span::styled("─".repeat(rule), Style::new().fg(t.subtle)));
}
TableRow::new([Cell::from(Line::from(spans)).column_span(cols as u16)])
}
fn name_line(name: &str, query: &str, style: Style) -> Line<'static> {
match fuzzy::fuzzy(query, name).filter(|m| !m.positions.is_empty()) {
Some(m) => fuzzy::highlight(
name,
&m.positions,
style,
style.fg(theme::get().accent).add_modifier(Modifier::BOLD),
),
None => Line::styled(name.to_string(), style),
}
}
fn fit(cols: &mut Vec<Col>, cells: &mut [Vec<Line<'static>>], width: u16) -> Vec<u16> {
let natural = |cols: &[Col], cells: &[Vec<Line>], i: usize| {
cols[i].fixed_width().unwrap_or_else(|| {
cells
.iter()
.map(|row| row[i].width() as u16)
.chain([cols[i].header().len() as u16])
.max()
.unwrap_or(0)
})
};
let others = |cols: &[Col], cells: &[Vec<Line>]| {
let mut sum = SPACING * (cols.len() as u16).saturating_sub(1);
for (i, col) in cols.iter().enumerate() {
sum += match col {
Col::Task => 0,
Col::Note => NOTE_MIN,
_ => natural(cols, cells, i),
};
}
sum
};
let task = cols
.iter()
.position(|&c| c == Col::Task)
.expect("task column");
let wanted = natural(cols, cells, task).min(TASK_WANTED);
for drop in DROP_ORDER {
if others(cols, cells) + wanted <= width {
break;
}
if let Some(i) = cols.iter().position(|&c| c == drop) {
cols.remove(i);
for row in cells.iter_mut() {
row.remove(i);
}
}
}
let room = width.saturating_sub(others(cols, cells));
let task_width = if cols.contains(&Col::Note) {
natural(
cols,
cells,
cols.iter().position(|&c| c == Col::Task).unwrap(),
)
.min(room)
} else {
room
};
(0..cols.len())
.map(|i| match cols[i] {
Col::Task => task_width,
Col::Note => 0,
_ => natural(cols, cells, i),
})
.collect()
}
fn task_cell(col: Col, task: &Task, app: &App, now: u64) -> Line<'static> {
if let [member] = &task.members[..] {
return match col {
Col::Task => name_line(&task.name, app.filter.value(), Style::new()),
Col::Repo => Line::raw(member.info.repo.clone()),
_ => member_cell(col, task, member, false, false, app, now),
};
}
match col {
Col::Task => name_line(
&task.name,
app.filter.value(),
Style::new().add_modifier(Modifier::BOLD),
),
Col::Repo => Line::raw(app::repo_group(task)),
_ => Line::default(),
}
}
fn member_cell(
col: Col,
task: &Task,
member: &Member,
last: bool,
marked: bool,
app: &App,
now: u64,
) -> Line<'static> {
let agent = member.agent_info.as_ref();
match col {
Col::Status => status_cell(task.member_status(member), app.spin),
Col::Age => age_cell(task, member, now),
Col::Task => {
let tree = if last { "└" } else { "├" };
let (mark, style) = if marked {
("▸", Style::new().add_modifier(Modifier::BOLD))
} else {
(" ", Style::new())
};
let mut line = name_line(&member.info.name, app.filter.value(), style);
line.spans.splice(
0..0,
[
Span::styled(format!(" {tree}"), Style::new().fg(theme::get().subtle)),
Span::styled(mark, style),
],
);
line
}
Col::Repo => Line::default(),
Col::Branch => branch_cell(member, app.branches.get(member.id())),
Col::Ctx => agent
.and_then(|a| a.context_percent)
.map(context_display)
.unwrap_or_default(),
Col::Note => match agent {
Some(agent) => agent_note(agent),
None => match crate::health::problem(&member.info) {
Some(problem) => Line::styled(problem, Style::new().fg(theme::get().bad)),
None => Line::default(),
},
},
}
}
fn chat_cell(col: Col, chat: &Chat, app: &App, now: u64) -> Line<'static> {
let dim = Style::new().fg(theme::get().muted);
let agent = chat.agent.as_ref();
match col {
Col::Status => status_cell(chat.status(), app.spin),
Col::Age => {
let since = agent.and_then(|a| a.state_since).unwrap_or(chat.last());
Line::styled(age(now.saturating_sub(since)), dim).right_aligned()
}
Col::Task => chat_name(chat, app, now, u16::MAX),
Col::Repo => Line::raw(chat.info.repo.clone()),
Col::Branch => match app.order {
Order::Repo => Line::styled(chat.info.repo.clone(), dim),
Order::Attention => Line::styled("chat", dim),
},
Col::Ctx => agent
.and_then(|a| a.context_percent)
.map(context_display)
.unwrap_or_default(),
Col::Note => match (agent, &chat.info.last_prompt) {
(Some(agent), _) => agent_note(agent),
(None, Some(prompt)) => Line::styled(one_line(prompt), dim),
(None, None) => Line::default(),
},
}
}
fn shell_cell(col: Col, shell: &ShellInfo, tree: Option<Branch>, app: &App) -> Line<'static> {
let t = theme::get();
let dim = Style::new().fg(t.muted);
let Some(tree) = tree else {
return match col {
Col::Task => Line::raw(shell.name()),
Col::Repo => Line::raw(shell.repo.clone()),
Col::Branch => match app.order {
Order::Repo => Line::styled(shell.repo.clone(), dim),
Order::Attention => Line::styled("shell", dim),
},
_ => Line::default(),
};
};
if col != Col::Task {
return Line::default();
}
let trunk = match tree.member_last {
None => "",
Some(false) => " │",
Some(true) => " ",
};
let fork = if tree.last { "└" } else { "├" };
Line::from(vec![
Span::styled(format!("{trunk} {fork}"), Style::new().fg(t.subtle)),
Span::raw(format!(" {}", shell.name())),
])
}
fn chat_name(chat: &Chat, app: &App, now: u64, width: u16) -> Line<'static> {
let t = theme::get();
let info = &chat.info;
let closes = Closes::of(info, now);
let mark = match closes {
_ if closes.last_day() => Some(Span::styled("◔", Style::new().fg(t.warn))),
Closes::Kept => Some(Span::styled("∞", Style::new().fg(t.muted))),
_ => None,
};
let untitled = info.name.is_none() && info.title.is_none();
let style = if untitled || closes.last_day() {
Style::new().fg(t.muted)
} else {
Style::new()
};
let name = name_line(&info.label(), app.filter.value(), style);
let Some(mark) = mark else {
return ellipsize(name, width);
};
let mut line = ellipsize(name, width.saturating_sub(2));
line.spans.extend([Span::raw(" "), mark]);
line
}
fn status_cell(status: TaskStatus, spin: Option<usize>) -> Line<'static> {
const FRAMES: [&str; 10] = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
let (text, color) = status_display(&status);
if let (TaskStatus::Run, Some(frame)) = (status, spin) {
let name = text.split_once(' ').map_or(text, |(_, name)| name);
return Line::styled(
format!("{} {name}", FRAMES[frame % FRAMES.len()]),
Style::new().fg(if theme::get().rainbow {
theme::rainbow(0, frame * 3)
} else {
color
}),
);
}
let style = Style::new().fg(color);
match status {
TaskStatus::Block | TaskStatus::Question | TaskStatus::Error | TaskStatus::Ready => {
Line::styled(text, style.add_modifier(Modifier::BOLD))
}
_ => Line::styled(text, style),
}
}
fn age_cell(task: &Task, member: &Member, now: u64) -> Line<'static> {
let since = match &member.agent_info {
Some(agent) => agent.state_since,
None => task.last_activity,
};
match since {
Some(since) => Line::styled(
age(now.saturating_sub(since)),
Style::new().fg(theme::get().muted),
)
.right_aligned(),
None => Line::default(),
}
}
fn branch_cell(member: &Member, observation: Option<&Observation>) -> Line<'static> {
let dim = Style::new().fg(theme::get().muted);
if member.is_unhealthy() {
return Line::default();
}
let state = match observation.and_then(|o| o.state.as_ref()) {
None => return Line::styled("…", dim),
Some(Err(_)) => return Line::styled("?", dim),
Some(Ok(state)) => state,
};
let mut parts = Vec::new();
if state.ahead > 0 {
parts.push(Span::styled(
format!("↑{}", state.ahead),
Style::new().fg(theme::get().ok),
));
}
if state.behind > 0 {
parts.push(Span::styled(format!("↓{}", state.behind), dim));
}
if state.uncommitted > 0 {
parts.push(Span::styled(
format!("*{}", state.uncommitted),
Style::new().fg(theme::get().warn),
));
}
if parts.is_empty() {
return Line::styled("=", dim);
}
let mut spans = Vec::new();
for part in parts {
if !spans.is_empty() {
spans.push(Span::raw(" "));
}
spans.push(part);
}
Line::from(spans)
}
fn agent_note(agent: &AgentInfo) -> Line<'static> {
let dim = Style::new().fg(theme::get().muted);
if let Some((text, color)) = agent_detail_line(agent.state, &agent.detail) {
return Line::styled(one_line(&text), Style::new().fg(color));
}
match (&agent.detail.last_message, agent.state) {
(Some(message), AgentState::Ready) => Line::styled(one_line(first_line(message)), dim),
_ => Line::default(),
}
}
pub(super) fn ellipsize(line: Line<'static>, width: u16) -> Line<'static> {
let width = width as usize;
if line.width() <= width {
return line;
}
let mut left = width.saturating_sub(1);
let mut spans = Vec::new();
let mut last_style = Style::new();
for span in line.spans {
last_style = span.style;
let mut text = String::new();
for c in span.content.chars() {
let w = Span::raw(c.to_string()).width();
if w > left {
left = 0;
break;
}
left -= w;
text.push(c);
}
spans.push(Span::styled(text, span.style));
if left == 0 {
break;
}
}
if width > 0 {
spans.push(Span::styled("…", last_style));
}
Line::from(spans).style(line.style)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ellipsizing_keeps_styles_and_width() {
let line = Line::from(vec![
Span::raw("ab"),
Span::styled("cdef", Style::new().fg(theme::get().bad)),
]);
let cut = ellipsize(line.clone(), 4);
assert_eq!(cut.width(), 4);
assert_eq!(cut.to_string(), "abc…");
assert_eq!(cut.spans.last().unwrap().style.fg, Some(theme::get().bad));
assert_eq!(ellipsize(line.clone(), 6).to_string(), "abcdef");
assert_eq!(ellipsize(Line::raw("漢字漢字"), 5).to_string(), "漢字…");
}
}