use std::time::{Duration, Instant};
use crossterm::{
event::{self, Event, KeyCode, KeyEventKind, KeyModifiers},
execute,
terminal::{EnterAlternateScreen, LeaveAlternateScreen, disable_raw_mode, enable_raw_mode},
};
use ratatui::{
Frame, Terminal,
backend::CrosstermBackend,
layout::{Constraint, Direction, Layout},
style::{Color, Modifier, Style},
text::{Line, Span},
widgets::{Block, Borders, Clear, List, ListItem, ListState, Paragraph},
};
use tokio::sync::mpsc;
use crate::monitor::dashboard::{IndexRow, format_count};
use crate::monitor::search_client::{ReindexEvent, SearchClient, resolve_search_url};
use crate::monitor::utils::{ActivityLog, DaemonStatus, fmt_uptime};
const REFRESH_INTERVAL: Duration = Duration::from_millis(2000);
const INPUT_POLL: Duration = Duration::from_millis(50);
const SEARCH_TOP_K: usize = 5;
const LEFT_PANEL_MAX: u16 = 28;
pub const VERSION: &str = env!("CARGO_PKG_VERSION");
pub const KEY_HINT: &str =
"[Tab] focus [r] reindex [↑↓] select [Enter] search [q] quit [?] help";
pub const ALL_LABEL: &str = "All indexes";
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum SearchFocus {
#[default]
List,
Input,
}
#[derive(Debug, Clone)]
pub struct SearchTuiState {
pub base_url: String,
pub daemon_status: DaemonStatus,
pub indexes: Vec<IndexRow>,
pub selected: usize,
pub scroll_offset: usize,
pub log: ActivityLog,
pub input: String,
pub focus: SearchFocus,
pub show_help: bool,
}
impl SearchTuiState {
pub fn new(base_url: impl Into<String>) -> Self {
Self {
base_url: base_url.into(),
daemon_status: DaemonStatus::Connecting,
indexes: Vec::new(),
selected: 0,
scroll_offset: 0,
log: ActivityLog::new(),
input: String::new(),
focus: SearchFocus::List,
show_help: false,
}
}
pub fn toggle_focus(&mut self) {
self.focus = match self.focus {
SearchFocus::List => SearchFocus::Input,
SearchFocus::Input => SearchFocus::List,
};
}
pub fn select_up(&mut self) {
self.selected = self.selected.saturating_sub(1);
}
pub fn select_down(&mut self) {
if self.selected < self.last_row() {
self.selected += 1;
}
}
fn last_row(&self) -> usize {
self.indexes.len()
}
pub fn clamp_selection(&mut self) {
if self.selected > self.last_row() {
self.selected = self.last_row();
}
}
pub fn sync_scroll(&mut self, visible: usize) {
let window = visible.max(1);
if self.selected >= self.scroll_offset + window {
self.scroll_offset = self.selected + 1 - window;
} else if self.selected < self.scroll_offset {
self.scroll_offset = self.selected;
}
}
pub fn is_all_selected(&self) -> bool {
self.selected == 0
}
pub fn selected_id(&self) -> Option<&str> {
if self.selected == 0 {
return None;
}
self.indexes.get(self.selected - 1).map(|i| i.id.as_str())
}
pub fn scope_filter(&self) -> Option<&str> {
self.selected_id()
}
}
pub async fn run() -> anyhow::Result<()> {
run_with_url(resolve_search_url()).await
}
pub async fn run_with_url(base_url: String) -> anyhow::Result<()> {
let mut client = SearchClient::new(base_url.clone());
let mut state = SearchTuiState::new(base_url);
enable_raw_mode()?;
let mut stdout = std::io::stdout();
execute!(stdout, EnterAlternateScreen)?;
let backend = CrosstermBackend::new(stdout);
let mut terminal = Terminal::new(backend)?;
let result = run_loop(&mut terminal, &mut state, &mut client).await;
disable_raw_mode()?;
execute!(terminal.backend_mut(), LeaveAlternateScreen)?;
terminal.show_cursor()?;
result
}
async fn poll_daemon(state: &mut SearchTuiState, client: &mut SearchClient) {
if !state.daemon_status.is_online() {
let resolved = resolve_search_url();
if resolved != client.base_url() {
client.set_base_url(resolved.clone());
state.base_url = resolved;
}
}
match client.fetch_all().await {
Ok(data) => {
state.daemon_status = DaemonStatus::Online {
version: data.version,
uptime_secs: data.uptime_secs,
};
state.indexes = data.indexes;
state.clamp_selection();
}
Err(e) => {
state.daemon_status = DaemonStatus::Offline {
last_error: e.to_string(),
};
}
}
}
async fn run_search(state: &mut SearchTuiState, client: &SearchClient) {
let query = state.input.trim().to_string();
if query.is_empty() {
return;
}
if state.is_all_selected() {
run_search_all(state, client, &query).await;
} else if let Some(id) = state.selected_id().map(str::to_string) {
run_search_one(state, client, &id, &query).await;
} else {
state.log.push("search: no index selected");
}
state.input.clear();
}
async fn run_search_one(state: &mut SearchTuiState, client: &SearchClient, id: &str, query: &str) {
match client.search(id, query, SEARCH_TOP_K).await {
Ok(hits) => {
state
.log
.push_scoped(id, format!("search \"{query}\" → {} results", hits.len()));
for hit in &hits {
state
.log
.push_raw_scoped(id, format!(" {}:{} {}", hit.file, hit.line, hit.snippet));
}
}
Err(e) => state
.log
.push_scoped(id, format!("search \"{query}\" failed: {e}")),
}
}
async fn run_search_all(state: &mut SearchTuiState, client: &SearchClient, query: &str) {
let ids: Vec<String> = state.indexes.iter().map(|i| i.id.clone()).collect();
if ids.is_empty() {
state.log.push("search (all): no indexes registered");
return;
}
state
.log
.push(format!("search \"{query}\" (all) → {} indexes", ids.len()));
let mut total = 0usize;
for id in &ids {
match client.search(id, query, SEARCH_TOP_K).await {
Ok(hits) => {
total += hits.len();
state
.log
.push_raw_scoped(id, format!(" · {id}: {} results", hits.len()));
}
Err(e) => state
.log
.push_raw_scoped(id, format!(" · {id}: failed: {e}")),
}
}
state.log.push(format!(
"search \"{query}\" (all) → {total} results across {} indexes",
ids.len()
));
}
#[derive(Debug, Clone)]
pub struct ScopedReindexEvent {
pub index_id: String,
pub event: ReindexEvent,
}
pub fn apply_reindex_event(state: &mut SearchTuiState, scoped: ScopedReindexEvent) {
let id = scoped.index_id;
match scoped.event {
ReindexEvent::Started { total_files } => {
state
.log
.push_scoped(&id, format!("reindex started: {total_files} files"));
}
ReindexEvent::Progress {
indexed,
total_files,
} => {
let pct = if total_files > 0 {
indexed.saturating_mul(100) / total_files
} else {
0
};
state
.log
.push_scoped(&id, format!("indexing: {indexed}/{total_files} ({pct}%)"));
}
ReindexEvent::Complete {
total_chunks,
status,
} => {
state.log.push_scoped(
&id,
format!("reindex {status}: {} chunks", format_count(total_chunks)),
);
}
ReindexEvent::Failed(message) => {
state
.log
.push_scoped(&id, format!("reindex error: {message}"));
}
}
}
async fn run_loop<B: ratatui::backend::Backend>(
terminal: &mut Terminal<B>,
state: &mut SearchTuiState,
client: &mut SearchClient,
) -> anyhow::Result<()> {
poll_daemon(state, client).await;
let mut last_poll = Instant::now();
let (reindex_tx, mut reindex_rx) = mpsc::channel::<ScopedReindexEvent>(64);
loop {
terminal.draw(|f| render(f, state))?;
while let Ok(event) = reindex_rx.try_recv() {
apply_reindex_event(state, event);
}
let key = if event::poll(INPUT_POLL)? {
match event::read()? {
Event::Key(key) => Some(key),
_ => None,
}
} else {
None
};
if let Some(key) = key
&& key.kind != KeyEventKind::Release
{
if key.modifiers.contains(KeyModifiers::CONTROL) && key.code == KeyCode::Char('c') {
return Ok(());
}
if state.show_help {
if matches!(key.code, KeyCode::Char('?') | KeyCode::Esc) {
state.show_help = false;
} else if key.code == KeyCode::Char('q') {
return Ok(());
}
continue;
}
match (state.focus, key.code) {
(_, KeyCode::Char('?')) => state.show_help = true,
(_, KeyCode::Tab) => state.toggle_focus(),
(_, KeyCode::Esc) => return Ok(()),
(SearchFocus::List, KeyCode::Char('q')) => return Ok(()),
(SearchFocus::List, KeyCode::Up) => state.select_up(),
(SearchFocus::List, KeyCode::Down) => state.select_down(),
(SearchFocus::List, KeyCode::Char('r')) => {
let targets: Vec<String> = if state.is_all_selected() {
state.indexes.iter().map(|i| i.id.clone()).collect()
} else {
state
.selected_id()
.map(str::to_string)
.into_iter()
.collect()
};
if targets.is_empty() {
if state.is_all_selected() {
state.log.push("reindex (all): no indexes registered");
} else {
state.log.push("reindex: no index selected");
}
} else {
if state.is_all_selected() {
state
.log
.push(format!("reindex triggered: all {} indexes", targets.len()));
}
for id in targets {
state
.log
.push_scoped(&id, format!("reindex triggered: {id}"));
spawn_reindex(client.clone(), reindex_tx.clone(), id);
}
}
}
(SearchFocus::Input, KeyCode::Enter) => {
run_search(state, client).await;
poll_daemon(state, client).await;
last_poll = Instant::now();
}
(SearchFocus::Input, KeyCode::Backspace) => {
state.input.pop();
}
(SearchFocus::Input, KeyCode::Char(c)) => state.input.push(c),
_ => {}
}
}
if last_poll.elapsed() >= REFRESH_INTERVAL {
poll_daemon(state, client).await;
last_poll = Instant::now();
}
}
}
fn spawn_reindex(client: SearchClient, out: mpsc::Sender<ScopedReindexEvent>, index_id: String) {
let (inner_tx, mut inner_rx) = mpsc::channel::<ReindexEvent>(64);
let stream_id = index_id.clone();
tokio::spawn(async move {
client.reindex_stream(&stream_id, inner_tx).await;
});
tokio::spawn(async move {
while let Some(event) = inner_rx.recv().await {
let scoped = ScopedReindexEvent {
index_id: index_id.clone(),
event,
};
if out.send(scoped).await.is_err() {
break; }
}
});
}
pub fn help_text() -> String {
[
" Tab switch focus between the index list and the search bar",
" ↑ / ↓ move the index selection (when the list has focus)",
" All the top list row fans queries / stats across every index",
" r reindex the selected index — or all, when 'All' is selected",
" Enter run a search against the selected index — or all of them",
" ? toggle this help overlay",
" q / Esc quit",
]
.join("\n")
}
pub fn left_panel_width(width: u16) -> u16 {
LEFT_PANEL_MAX.min(width / 3)
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct IndexListRow {
pub text: String,
pub selected: bool,
pub is_all: bool,
}
pub fn index_lines(state: &SearchTuiState) -> Vec<IndexListRow> {
let mut rows: Vec<IndexListRow> = Vec::with_capacity(state.indexes.len() + 1);
let total_chunks: u64 = state.indexes.iter().map(|i| i.chunk_count).sum();
let all_selected = state.selected == 0;
let all_marker = if all_selected { ">" } else { " " };
rows.push(IndexListRow {
text: format!(
"{all_marker} {:<12} {:>8} ∗",
truncate(ALL_LABEL, 12),
format_count(total_chunks),
),
selected: all_selected,
is_all: true,
});
if state.indexes.is_empty() {
rows.push(IndexListRow {
text: " (no indexes registered)".to_string(),
selected: false,
is_all: false,
});
return rows;
}
for (i, idx) in state.indexes.iter().enumerate() {
let row = i + 1;
let selected = row == state.selected;
let marker = if selected { ">" } else { " " };
rows.push(IndexListRow {
text: format!(
"{marker} {:<12} {:>8} ✓",
truncate(&idx.id, 12),
format_count(idx.chunk_count),
),
selected,
is_all: false,
});
}
rows
}
pub fn stats_lines(state: &SearchTuiState) -> Vec<String> {
if state.is_all_selected() {
let total: u64 = state.indexes.iter().map(|i| i.chunk_count).sum();
let mut lines = vec![
format!("Scope: {ALL_LABEL}"),
format!("Indexes: {}", state.indexes.len()),
format!("Total chunks: {}", format_count(total)),
];
if state.indexes.is_empty() {
lines.push("(no indexes registered)".to_string());
} else {
lines.push(String::new());
for idx in &state.indexes {
lines.push(format!(
" · {:<14} {:>8}",
truncate(&idx.id, 14),
format_count(idx.chunk_count),
));
}
}
return lines;
}
match state.indexes.get(state.selected.saturating_sub(1)) {
Some(idx) => vec![
format!("Index: {}", idx.id),
format!("Chunks: {}", format_count(idx.chunk_count)),
format!(
"Root path: {}",
if idx.root_path.is_empty() {
"(unknown)"
} else {
idx.root_path.as_str()
}
),
],
None => vec!["(no index selected)".to_string()],
}
}
pub fn truncate(s: &str, max: usize) -> String {
if s.chars().count() <= max {
s.to_string()
} else {
let kept: String = s.chars().take(max.saturating_sub(1)).collect();
format!("{kept}…")
}
}
pub fn title_line(state: &SearchTuiState) -> String {
let (glyph, label) = state.daemon_status.badge();
match &state.daemon_status {
DaemonStatus::Online { uptime_secs, .. } => format!(
"trusty-search v{VERSION} [{glyph}] {label} uptime: {}",
fmt_uptime(*uptime_secs)
),
_ => format!(
"trusty-search v{VERSION} [{glyph}] {label} {}",
state.base_url
),
}
}
const ACTIVITY_PERCENT: u16 = 60;
pub fn render(frame: &mut Frame, state: &mut SearchTuiState) {
let area = frame.area();
let rows = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Length(1), Constraint::Min(4), Constraint::Length(3), Constraint::Length(1), ])
.split(area);
frame.render_widget(
Paragraph::new(Line::from(Span::styled(
title_line(state),
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
))),
rows[0],
);
let split = Layout::default()
.direction(Direction::Horizontal)
.constraints([
Constraint::Length(left_panel_width(area.width)),
Constraint::Min(10),
])
.split(rows[1]);
let list_focused = state.focus == SearchFocus::List;
let index_items: Vec<ListItem> = index_lines(state)
.into_iter()
.map(|row| {
let style = if row.selected {
Style::default()
.fg(Color::Black)
.bg(Color::Cyan)
.add_modifier(Modifier::BOLD)
} else if row.is_all {
Style::default()
.fg(Color::Yellow)
.add_modifier(Modifier::BOLD)
} else {
Style::default()
};
ListItem::new(Line::from(Span::styled(row.text, style)))
})
.collect();
let index_visible = split[0].height.saturating_sub(2) as usize;
state.sync_scroll(index_visible);
let mut index_state = ListState::default()
.with_offset(state.scroll_offset)
.with_selected(Some(state.selected));
frame.render_stateful_widget(
List::new(index_items).block(panel_block("INDEXES", list_focused)),
split[0],
&mut index_state,
);
let right = Layout::default()
.direction(Direction::Vertical)
.constraints([
Constraint::Percentage(ACTIVITY_PERCENT),
Constraint::Percentage(100 - ACTIVITY_PERCENT),
])
.split(split[1]);
let scope = state.scope_filter();
let activity_title = match scope {
Some(id) => format!("ACTIVITY — {id}"),
None => format!("ACTIVITY — {ALL_LABEL}"),
};
let activity_height = right[0].height.saturating_sub(2) as usize;
let activity_items: Vec<ListItem> = if state.log.has_scoped(scope) {
state
.log
.tail_scoped(scope, activity_height.max(1))
.map(|line| ListItem::new(line.as_str()))
.collect()
} else {
vec![ListItem::new("(no activity yet)")]
};
frame.render_widget(
List::new(activity_items).block(panel_block(&activity_title, false)),
right[0],
);
let stats_items: Vec<ListItem> = stats_lines(state).into_iter().map(ListItem::new).collect();
frame.render_widget(
List::new(stats_items).block(panel_block("STATISTICS", false)),
right[1],
);
let input_focused = state.focus == SearchFocus::Input;
let cursor = if input_focused { "_" } else { "" };
let input_style = if input_focused {
Style::default().fg(Color::Cyan)
} else {
Style::default().fg(Color::DarkGray)
};
frame.render_widget(
Paragraph::new(Line::from(vec![
Span::styled("SEARCH ▶ ", Style::default().fg(Color::Yellow)),
Span::styled(format!("{}{cursor}", state.input), input_style),
]))
.block(panel_block("SEARCH", input_focused)),
rows[2],
);
frame.render_widget(
Paragraph::new(Line::from(Span::styled(
KEY_HINT,
Style::default().fg(Color::DarkGray),
))),
rows[3],
);
if state.show_help {
render_help_overlay(frame);
}
}
fn panel_block(name: &str, focused: bool) -> Block<'static> {
let border_style = if focused {
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD)
} else {
Style::default().fg(Color::DarkGray)
};
Block::default()
.borders(Borders::ALL)
.border_style(border_style)
.title(Span::styled(
format!(" {name} "),
Style::default()
.fg(Color::Cyan)
.add_modifier(Modifier::BOLD),
))
}
fn render_help_overlay(frame: &mut Frame) {
let area = frame.area();
let w = 60.min(area.width);
let h = 9.min(area.height);
let rect = ratatui::layout::Rect {
x: area.x + area.width.saturating_sub(w) / 2,
y: area.y + area.height.saturating_sub(h) / 2,
width: w,
height: h,
};
frame.render_widget(Clear, rect);
frame.render_widget(
Paragraph::new(help_text())
.style(Style::default().fg(Color::White))
.block(
Block::default()
.borders(Borders::ALL)
.title(" Help — press ? or Esc to close "),
),
rect,
);
}
#[cfg(test)]
mod tests {
use super::*;
use crate::monitor::utils::timestamped;
use ratatui::{Terminal, backend::TestBackend};
fn sample_state() -> SearchTuiState {
let mut state = SearchTuiState::new("http://127.0.0.1:7878");
state.daemon_status = DaemonStatus::Online {
version: "0.3.65".into(),
uptime_secs: 7440,
};
state.indexes = vec![
IndexRow {
id: "cto".into(),
chunk_count: 1_200,
root_path: "/tmp/cto".into(),
},
IndexRow {
id: "trusty".into(),
chunk_count: 18_994,
root_path: "/tmp/trusty".into(),
},
IndexRow {
id: "duetto".into(),
chunk_count: 900,
root_path: "/tmp/duetto".into(),
},
];
state
}
#[test]
fn test_new_state_defaults() {
let state = SearchTuiState::new("http://127.0.0.1:7878");
assert_eq!(state.base_url, "http://127.0.0.1:7878");
assert!(matches!(state.daemon_status, DaemonStatus::Connecting));
assert!(state.indexes.is_empty());
assert_eq!(state.selected, 0);
assert!(state.log.is_empty());
assert!(state.input.is_empty());
assert_eq!(state.focus, SearchFocus::List);
assert!(!state.show_help);
}
#[test]
fn test_toggle_focus() {
let mut state = SearchTuiState::new("http://x");
assert_eq!(state.focus, SearchFocus::List);
state.toggle_focus();
assert_eq!(state.focus, SearchFocus::Input);
state.toggle_focus();
assert_eq!(state.focus, SearchFocus::List);
}
#[test]
fn test_selected_clamp() {
let mut state = sample_state();
for _ in 0..10 {
state.select_down();
}
assert_eq!(state.selected, 3, "clamped to indexes.len()");
for _ in 0..10 {
state.select_up();
}
assert_eq!(state.selected, 0);
state.selected = 3;
state.indexes.truncate(1);
state.clamp_selection();
assert_eq!(state.selected, 1);
state.indexes.clear();
state.selected = 5;
state.clamp_selection();
assert_eq!(state.selected, 0);
}
#[test]
fn test_selected_id() {
let mut state = sample_state();
assert!(state.is_all_selected());
assert_eq!(state.selected_id(), None);
state.select_down();
assert_eq!(state.selected_id(), Some("cto"));
state.select_down();
assert_eq!(state.selected_id(), Some("trusty"));
state.indexes.clear();
state.clamp_selection();
assert_eq!(state.selected_id(), None);
}
#[test]
fn test_all_selector() {
let mut state = sample_state();
assert!(state.is_all_selected());
assert_eq!(state.scope_filter(), None);
state.select_down();
assert!(!state.is_all_selected());
assert_eq!(state.scope_filter(), Some("cto"));
state.select_up();
assert!(state.is_all_selected());
assert_eq!(state.scope_filter(), None);
let rows = index_lines(&state);
assert_eq!(rows.len(), 4, "1 'All' row + 3 indexes");
assert!(rows[0].is_all);
assert!(rows[0].text.contains(ALL_LABEL));
assert!(rows[0].selected, "'All' is selected by default");
assert!(!rows[1].is_all);
assert!(rows[1].text.contains("cto"));
}
#[test]
fn test_stats_lines() {
let mut state = sample_state();
let all = stats_lines(&state);
assert!(
all.iter()
.any(|l| l.contains("Indexes:") && l.contains('3'))
);
assert!(all.iter().any(|l| l.contains("Total chunks:")));
assert!(all.iter().any(|l| l.contains("cto")));
assert!(all.iter().any(|l| l.contains("trusty")));
state.select_down(); let one = stats_lines(&state);
assert!(
one.iter()
.any(|l| l.contains("Index:") && l.contains("cto"))
);
assert!(
one.iter()
.any(|l| l.contains("Chunks:") && l.contains("1,200"))
);
assert!(one.iter().any(|l| l.contains("/tmp/cto")));
}
#[test]
fn test_log_append() {
let mut state = SearchTuiState::new("http://x");
for i in 0..(ActivityLog::MAX_ENTRIES + 50) {
state.log.push(format!("event {i}"));
}
assert_eq!(state.log.len(), ActivityLog::MAX_ENTRIES);
}
#[test]
fn test_timestamped_format() {
let line = timestamped("reindex started");
assert!(line.starts_with('['));
assert!(line.ends_with(" reindex started"));
assert_eq!(line.as_bytes()[9], b']');
}
fn scoped(event: ReindexEvent) -> ScopedReindexEvent {
ScopedReindexEvent {
index_id: "cto".into(),
event,
}
}
#[test]
fn test_apply_reindex_event() {
let mut state = SearchTuiState::new("http://x");
apply_reindex_event(
&mut state,
scoped(ReindexEvent::Started { total_files: 1200 }),
);
apply_reindex_event(
&mut state,
scoped(ReindexEvent::Progress {
indexed: 600,
total_files: 1200,
}),
);
apply_reindex_event(
&mut state,
scoped(ReindexEvent::Complete {
total_chunks: 19_012,
status: "complete".into(),
}),
);
let lines: Vec<&String> = state.log.iter().collect();
assert_eq!(lines.len(), 3);
assert!(lines[0].contains("reindex started: 1200 files"));
assert!(lines[1].contains("600/1200 (50%)"));
assert!(lines[2].contains("reindex complete: 19.0k chunks"));
assert_eq!(state.log.tail_scoped(Some("cto"), 100).count(), 3);
assert_eq!(state.log.tail_scoped(Some("trusty"), 100).count(), 0);
apply_reindex_event(&mut state, scoped(ReindexEvent::Failed("disk full".into())));
assert!(
state
.log
.iter()
.last()
.expect("entry")
.contains("reindex error: disk full")
);
}
#[test]
fn test_left_panel_width() {
assert_eq!(left_panel_width(200), LEFT_PANEL_MAX);
assert_eq!(left_panel_width(60), 20);
}
#[test]
fn test_index_lines() {
let state = sample_state();
let rows = index_lines(&state);
assert_eq!(rows.len(), 4);
assert!(rows[0].is_all);
assert!(rows[0].selected);
assert!(rows[0].text.starts_with('>'));
assert!(rows[0].text.contains(ALL_LABEL));
assert!(!rows[1].is_all && !rows[1].selected);
assert!(rows[1].text.contains("cto"));
assert!(rows[2].text.contains("trusty"));
assert!(rows[2].text.contains("19.0k"));
let empty = SearchTuiState::new("http://x");
let rows = index_lines(&empty);
assert_eq!(rows.len(), 2);
assert!(rows[0].is_all);
assert!(rows[1].text.contains("no indexes"));
}
#[test]
fn test_truncate() {
assert_eq!(truncate("short", 12), "short");
assert_eq!(truncate("a-very-long-index-id", 8), "a-very-…");
}
#[test]
fn test_title_line() {
let state = sample_state();
let title = title_line(&state);
assert!(title.contains("trusty-search v"));
assert!(title.contains("online"));
assert!(title.contains("uptime: 2h 4m"));
let mut offline = SearchTuiState::new("http://127.0.0.1:7878");
offline.daemon_status = DaemonStatus::Offline {
last_error: "refused".into(),
};
let title = title_line(&offline);
assert!(title.contains("offline"));
assert!(title.contains("http://127.0.0.1:7878"));
}
#[test]
fn test_help_text_lists_bindings() {
let text = help_text();
for token in ["Tab", "r ", "Enter", "?", "q "] {
assert!(text.contains(token), "help text missing {token}");
}
}
#[test]
fn test_scroll_offset() {
let mut state = sample_state();
for row in 0..=state.last_row() {
state.selected = row;
state.sync_scroll(8);
assert_eq!(state.scroll_offset, 0, "no scroll while the list fits");
}
state.indexes = (0..40)
.map(|n| IndexRow {
id: format!("idx-{n}"),
chunk_count: 1,
root_path: String::new(),
})
.collect();
let window = 5;
for row in 0..=state.last_row() {
state.selected = row;
state.sync_scroll(window);
assert!(
row >= state.scroll_offset && row < state.scroll_offset + window,
"row {row} must be inside [{}, {})",
state.scroll_offset,
state.scroll_offset + window,
);
}
assert_eq!(state.scroll_offset, state.last_row() + 1 - window);
for row in (0..=state.last_row()).rev() {
state.selected = row;
state.sync_scroll(window);
assert!(
row >= state.scroll_offset && row < state.scroll_offset + window,
"row {row} must stay visible while scrolling up",
);
}
assert_eq!(state.scroll_offset, 0, "back at the top");
}
#[test]
fn test_render_smoke() {
let mut state = sample_state();
state.log.push("daemon started");
state.log.push_scoped("cto", "reindex started: 1200 files");
state
.log
.push_scoped("trusty", "search \"fn embed\" → 5 results");
state.input = "fn authenticate".into();
state.focus = SearchFocus::Input;
for (w, h) in [(120u16, 30u16), (80, 24)] {
let backend = TestBackend::new(w, h);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal
.draw(|f| render(f, &mut state))
.expect("render (All) must not panic");
}
state.selected = 1;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal
.draw(|f| render(f, &mut state))
.expect("render (single index) must not panic");
state.indexes = (0..60)
.map(|n| IndexRow {
id: format!("idx-{n}"),
chunk_count: 100,
root_path: String::new(),
})
.collect();
state.selected = state.last_row();
let backend = TestBackend::new(120, 20);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal
.draw(|f| render(f, &mut state))
.expect("overflowing list render must not panic");
assert!(state.scroll_offset > 0, "long list scrolled to the cursor");
state.show_help = true;
state.daemon_status = DaemonStatus::Connecting;
let backend = TestBackend::new(120, 30);
let mut terminal = Terminal::new(backend).expect("test terminal");
terminal
.draw(|f| render(f, &mut state))
.expect("help render must not panic");
}
}