Files
hx/crates/hx-tui/src/sessions.rs
T
johannesandClaude Sonnet 5.5 a94632ea3d chore: delete code comments, add ratchet lint and ADRs
Classify every comment as tautology, stale, excuse or decision record.
Tautology/stale/excuse comments are deleted (excuses filed as issues
#196-#236), decisions moved to docs/adr/0001-0034.

- scripts/lint-comments.sh + .comment-baseline: per-file comment count
  may only go down; wired into tests/all.sh
- .claude/skills/delete-comment: repeatable audit workflow
- cargo fmt applied to touched crates

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-21 13:37:32 +01:00

511 lines
17 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
use crate::theme;
use crate::transcript::{Item, Transcript};
use hx_core::session::{self, Meta};
use ratatui::layout::{Constraint, Layout, Rect};
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use ratatui::widgets::{Block, BorderType, Borders, Clear, Paragraph};
use std::path::{Path, PathBuf};
use std::time::SystemTime;
pub enum Act {
None,
Close,
Resume(PathBuf),
}
pub struct Sessions {
pub query: String,
pub sel: usize,
pub all_scope: bool,
project: Vec<Meta>,
all: Option<Vec<Meta>>,
project_dir: PathBuf,
root: PathBuf,
current: PathBuf,
pub confirm: Option<PathBuf>,
preview: Option<(PathBuf, Vec<Line<'static>>)>,
}
impl Sessions {
pub fn new(project_dir: &Path, root: &Path, current: &Path) -> Self {
Self {
query: String::new(),
sel: 0,
all_scope: false,
project: session::list(project_dir),
all: None,
project_dir: project_dir.into(),
root: root.into(),
current: current.into(),
confirm: None,
preview: None,
}
}
fn pool(&self) -> &[Meta] {
match (&self.all, self.all_scope) {
(Some(a), true) => a,
_ => &self.project,
}
}
pub fn matches(&self) -> Vec<&Meta> {
let pool = self.pool();
if self.query.is_empty() {
return pool.iter().collect();
}
let keys: Vec<String> = pool
.iter()
.map(|m| {
format!(
"{} {}",
m.title,
if self.all_scope { &m.project } else { "" }
)
})
.collect();
hx_core::command::rank(keys.iter().map(String::as_str), &self.query, usize::MAX)
.into_iter()
.filter_map(|k| keys.iter().position(|x| x == k).map(|i| &pool[i]))
.collect()
}
fn selected(&self) -> Option<PathBuf> {
self.matches().get(self.sel).map(|m| m.path.clone())
}
pub fn toggle_scope(&mut self) {
self.all_scope = !self.all_scope;
if self.all_scope && self.all.is_none() {
self.all = Some(session::list_all(&self.root));
}
self.sel = 0;
}
fn reload(&mut self) {
self.project = session::list(&self.project_dir);
if self.all.is_some() {
self.all = Some(session::list_all(&self.root));
}
self.sel = self.sel.min(self.matches().len().saturating_sub(1));
self.preview = None;
}
pub fn key(&mut self, k: crossterm::event::KeyEvent) -> Act {
use crossterm::event::{KeyCode, KeyModifiers};
let ctrl = k.modifiers.contains(KeyModifiers::CONTROL);
if let Some(p) = self.confirm.take() {
if matches!(k.code, KeyCode::Char('y' | 'Y')) {
let _ = std::fs::remove_file(&p);
self.reload();
}
return Act::None;
}
let n = self.matches().len().max(1);
match k.code {
KeyCode::Esc => return Act::Close,
KeyCode::Char('c') if ctrl => return Act::Close,
KeyCode::Char('d') if ctrl => {
self.confirm = self.selected().filter(|p| *p != self.current);
}
KeyCode::Tab => self.toggle_scope(),
KeyCode::Up => self.sel = (self.sel + n - 1) % n,
KeyCode::Down => self.sel = (self.sel + 1) % n,
KeyCode::Backspace => {
self.query.pop();
self.sel = 0;
}
KeyCode::Char(c) if !ctrl => {
self.query.push(c);
self.sel = 0;
}
KeyCode::Enter => {
if let Some(p) = self.selected() {
return Act::Resume(p);
}
}
_ => {}
}
Act::None
}
pub fn draw(&mut self, f: &mut ratatui::Frame) {
let th = theme::t();
let a = f.area();
f.render_widget(Clear, a);
let ms: Vec<Meta> = self.matches().into_iter().cloned().collect();
let [tabs, q, body, help] = Layout::vertical([
Constraint::Length(1),
Constraint::Length(3),
Constraint::Min(1),
Constraint::Length(1),
])
.areas(a);
let (on, off) = (th.plain(), th.dim());
let count = Span::styled(format!("{} of {}", ms.len(), self.pool().len()), th.sec());
let left = vec![
Span::styled("sessions", th.accent().add_modifier(Modifier::BOLD)),
Span::raw(" "),
Span::styled("this project", if self.all_scope { off } else { on }),
Span::styled(format!(" {} ", th.sym.info), th.dim()),
Span::styled("all projects", if self.all_scope { on } else { off }),
];
let lw: usize = left.iter().map(Span::width).sum();
let mut l = left;
l.push(Span::raw(" ".repeat(
(tabs.width as usize).saturating_sub(lw + count.width()),
)));
l.push(count);
f.render_widget(Line::from(l), tabs);
let frame = Block::bordered()
.border_type(BorderType::Rounded)
.border_style(th.frame());
let qi = frame.inner(q);
f.render_widget(frame, q);
f.render_widget(
Line::from(vec![
Span::styled(format!("{} ", th.sym.user), th.accent()),
Span::styled(self.query.clone(), th.plain()),
]),
qi,
);
f.set_cursor_position((qi.x + 2 + self.query.chars().count() as u16, qi.y));
let [list, rule, prev] = Layout::horizontal([
Constraint::Percentage(45),
Constraint::Length(2),
Constraint::Min(1),
])
.areas(body);
let top = self
.sel
.saturating_sub(list.height.saturating_sub(1) as usize);
let w = list.width as usize;
let rows: Vec<Line> = if ms.is_empty() {
vec![Line::styled(" no sessions", th.dim())]
} else {
ms.iter()
.enumerate()
.skip(top)
.take(list.height as usize)
.map(|(i, m)| self.row(m, i == self.sel, w))
.collect()
};
f.render_widget(Paragraph::new(rows), list);
f.render_widget(
Block::new().borders(Borders::LEFT).border_style(th.dim()),
Rect {
x: rule.x + 1,
width: 1,
..rule
},
);
if let Some(m) = ms.get(self.sel) {
if self.preview.as_ref().is_none_or(|(p, _)| *p != m.path) {
let mut ls = vec![
Line::styled(m.title.clone(), th.plain().add_modifier(Modifier::BOLD)),
Line::styled(self.meta_line(m), th.sec()),
Line::default(),
];
ls.extend(preview(&m.path, prev.width.saturating_sub(1)));
self.preview = Some((m.path.clone(), ls));
}
if let Some((_, ls)) = &self.preview {
let pr = Rect {
x: prev.x + 1,
width: prev.width.saturating_sub(1),
..prev
};
let room = pr.height as usize;
let shown: Vec<Line> = if ls.len() > room && room > 4 {
let mut v = ls[..room - 1].to_vec();
v.push(Line::styled(
format!("{} more lines", th.sym.ellipsis),
th.dim(),
));
v
} else {
ls.clone()
};
f.render_widget(Paragraph::new(shown), pr);
}
}
let help_text = match &self.confirm {
Some(p) => Line::styled(format!("delete {}? [y/n]", p.display()), th.warn()),
None => Line::styled(
"type filter · tab project/all · ↑↓ select · enter resume · ctrl-d delete · esc close",
th.dim(),
),
};
f.render_widget(help_text, help);
}
fn meta_line(&self, m: &Meta) -> String {
let mut v = vec![];
if self.all_scope {
v.push(m.project.clone());
}
if let Some(md) = &m.model {
v.push(md.strip_prefix("claude-").unwrap_or(md).to_string());
}
v.push(format!("{} msgs", m.messages));
if m.branches > 1 {
v.push(format!("{} branches", m.branches));
}
v.push(ago(m.modified));
v.join(&format!(" {} ", theme::t().sym.info))
}
fn row(&self, m: &Meta, sel: bool, w: usize) -> Line<'static> {
let th = theme::t();
let st = if sel {
th.sel().add_modifier(Modifier::BOLD)
} else {
th.plain()
};
let band = if sel { th.sel() } else { Style::default() };
let cur = if m.path == self.current {
th.sym.dirty
} else {
" "
};
let mut right = short_age(m.modified);
if self.all_scope {
right = format!("{} {right}", cut(&m.project, 16));
}
let room = w.saturating_sub(right.chars().count() + 5);
let title = cut(&m.title, room);
let pad = w.saturating_sub(title.chars().count() + right.chars().count() + 4);
Line::from(vec![
Span::styled(format!(" {cur} "), band.patch(th.accent())),
Span::styled(title, st),
Span::styled(" ".repeat(pad), band),
Span::styled(right, band.patch(th.sec())),
Span::styled(" ", band),
])
}
}
fn short_age(t: SystemTime) -> String {
let s = SystemTime::now()
.duration_since(t)
.unwrap_or_default()
.as_secs();
match s {
0..60 => "now".into(),
60..3600 => format!("{}m", s / 60),
3600..86400 => format!("{}h", s / 3600),
86400..604800 => format!("{}d", s / 86400),
_ => format!("{}w", s / 604800),
}
}
fn cut(s: &str, n: usize) -> String {
if s.chars().count() <= n {
return s.into();
}
let mut t: String = s.chars().take(n.saturating_sub(1)).collect();
t.push('…');
t
}
fn preview(p: &Path, width: u16) -> Vec<Line<'static>> {
let Ok(s) = session::Session::open(p) else {
return vec![];
};
let mut t = Transcript::default();
history(&mut t, &s.messages());
t.lines(false, width)
}
pub fn history(t: &mut Transcript, msgs: &[hx_ai::Message]) {
use hx_ai::{ContentBlock as B, Role};
for m in msgs {
for b in &m.content {
match (m.role, b) {
(Role::User, B::Text { text }) => t.push(Item::User(text.clone())),
(Role::Assistant, B::Text { text }) => t.push(Item::Assistant(text.clone())),
(Role::Assistant, B::ToolUse { id, name, input }) => t.push(Item::Tool {
id: id.clone(),
name: name.clone(),
args: input.clone(),
result: None,
started: std::time::Instant::now(),
took: None,
}),
(
Role::User,
B::ToolResult {
tool_use_id,
content,
is_error,
},
) => {
if let Some(Item::Tool { result, .. }) = t
.items
.iter_mut()
.rev()
.find(|i| matches!(i, Item::Tool { id, .. } if id == tool_use_id))
{
*result = Some((content.clone(), *is_error));
}
}
_ => {}
}
}
}
}
pub fn ago(t: SystemTime) -> String {
let s = SystemTime::now()
.duration_since(t)
.unwrap_or_default()
.as_secs();
match s {
0..60 => "just now".into(),
60..3600 => format!("{}m ago", s / 60),
3600..86400 => format!("{}h ago", s / 3600),
86400..172800 => "yesterday".into(),
_ => format!("{}d ago", s / 86400),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use hx_ai::{ContentBlock, Message, Role};
use ratatui::backend::TestBackend;
use serde_json::json;
fn k(c: KeyCode) -> KeyEvent {
KeyEvent::new(c, KeyModifiers::NONE)
}
fn seed(root: &Path) -> (PathBuf, PathBuf) {
let proj = root.join("proj");
let mut a = session::Session::open(proj.join("1.jsonl")).unwrap();
a.append(Message::user("parser: handle trailing commas"))
.unwrap();
a.append_by(
Message {
role: Role::Assistant,
content: vec![
ContentBlock::Text {
text: "Fixing the grammar.".into(),
},
ContentBlock::ToolUse {
id: "t1".into(),
name: "edit".into(),
input: json!({"path": "src/parse.rs"}),
},
],
},
Some("opus".into()),
)
.unwrap();
a.append(Message {
role: Role::User,
content: vec![ContentBlock::ToolResult {
tool_use_id: "t1".into(),
content: "edited\n+a\n-b".into(),
is_error: false,
}],
})
.unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let mut b = session::Session::open(proj.join("2.jsonl")).unwrap();
b.append(Message::user("review PR 73")).unwrap();
std::thread::sleep(std::time::Duration::from_millis(20));
let mut c = session::Session::open(root.join("other/3.jsonl")).unwrap();
c.append(Message::user("elsewhere")).unwrap();
(proj.join("1.jsonl"), proj.join("2.jsonl"))
}
fn screen(s: &mut Sessions, w: u16, h: u16) -> Vec<String> {
let mut term = ratatui::Terminal::new(TestBackend::new(w, h)).unwrap();
term.draw(|f| s.draw(f)).unwrap();
let buf = term.backend().buffer().clone();
(0..h)
.map(|y| (0..w).map(|x| buf[(x, y)].symbol().to_string()).collect())
.collect()
}
#[test]
fn filter_preview_scope_delete() {
let t = tempfile::tempdir().unwrap();
let (first, second) = seed(t.path());
let mut s = Sessions::new(&t.path().join("proj"), t.path(), &second);
let titles = |s: &Sessions| {
s.matches()
.iter()
.map(|m| m.title.clone())
.collect::<Vec<_>>()
};
assert_eq!(
titles(&s),
["review PR 73", "parser: handle trailing commas"]
);
for c in "pars".chars() {
s.key(k(KeyCode::Char(c)));
}
assert_eq!(titles(&s), ["parser: handle trailing commas"]);
let rows = screen(&mut s, 100, 20);
let all = rows.join("\n");
assert!(
rows[0].starts_with("sessions this project · all projects")
&& rows[0].ends_with("1 of 2"),
"{all}"
);
assert!(rows[2].contains("❯ pars"), "{all}");
assert!(
rows[4].contains(" parser: handle trailing commas") && rows[4].contains(" now "),
"{all}"
);
assert!(all.contains("opus · 3 msgs · just now"), "meta: {all}");
assert!(
all.contains("❯ parser: handle trailing commas"),
"preview: {all}"
);
assert!(
all.contains("● edit src/parse.rs"),
"preview tool line: {all}"
);
assert!(
rows[19].starts_with("type filter · tab project/all"),
"{all}"
);
s.query.clear();
s.key(k(KeyCode::Tab));
assert_eq!(titles(&s)[0], "elsewhere");
let rows = screen(&mut s, 100, 20);
assert!(
rows[4].contains("elsewhere") && rows[4].contains("other"),
"{rows:#?}"
);
s.key(k(KeyCode::Tab));
let rows = screen(&mut s, 100, 20);
assert!(rows[4].starts_with(" ● review PR 73"), "{rows:#?}");
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
assert!(s.confirm.is_none());
s.key(k(KeyCode::Down));
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
assert_eq!(s.confirm.as_ref(), Some(&first));
assert!(screen(&mut s, 100, 20)[19].contains("[y/n]"));
s.key(k(KeyCode::Char('n')));
assert!(first.exists());
s.key(KeyEvent::new(KeyCode::Char('d'), KeyModifiers::CONTROL));
s.key(k(KeyCode::Char('y')));
assert!(!first.exists());
assert_eq!(titles(&s), ["review PR 73"]);
assert!(matches!(s.key(k(KeyCode::Enter)), Act::Resume(p) if p == second));
assert!(matches!(s.key(k(KeyCode::Esc)), Act::Close));
}
}