Skip to main content

ai_usagebar/tui/
context.rs

1//! TUI overlay for local Claude Code context-window sessions.
2
3use ratatui::Frame;
4use ratatui::layout::{Constraint, Direction, Layout, Rect};
5use ratatui::text::{Line, Span};
6use ratatui::widgets::{Clear, Paragraph};
7use ratatui_bubbletea_components::{Help, KeyBinding, ListItem, SelectList};
8
9use crate::config::ContextLayout;
10use crate::context::{ContextScan, ContextSession, ContextUsage};
11use crate::format::local_time_hms;
12use crate::pango::severity_for;
13use crate::theme::Theme;
14use crate::tui::panels::{self, Section};
15use crate::tui::style::bubble_theme;
16
17#[derive(Debug)]
18pub struct ContextState {
19    pub selected: usize,
20    pub detail: bool,
21    pub generation: u64,
22    pub load: ContextLoad,
23    pub layout: ContextLayout,
24    selection_id: Option<String>,
25}
26
27#[derive(Debug)]
28pub enum ContextLoad {
29    Loading,
30    Ready(ContextScan),
31    Error(String),
32}
33
34impl Default for ContextState {
35    fn default() -> Self {
36        Self {
37            selected: 0,
38            detail: false,
39            generation: 0,
40            load: ContextLoad::Loading,
41            layout: ContextLayout::default(),
42            selection_id: None,
43        }
44    }
45}
46
47impl ContextState {
48    /// Open with the configured starting layout; `v` cycles it afterwards.
49    pub fn new(layout: ContextLayout) -> Self {
50        Self {
51            layout,
52            ..Self::default()
53        }
54    }
55
56    /// Begin a scan with an identity allocated by the long-lived host app.
57    /// The host, rather than this disposable overlay, owns monotonicity across
58    /// close/reopen cycles.
59    pub fn begin_refresh(&mut self, generation: u64) {
60        if let Some(selection_id) = self
61            .selected_session()
62            .map(|session| session.session_id.clone())
63        {
64            self.selection_id = Some(selection_id);
65        }
66        self.generation = generation;
67        self.load = ContextLoad::Loading;
68    }
69
70    /// Ignore a result from an earlier `r` scan. The host also drops results
71    /// after the overlay closes by having no state to apply them to.
72    pub fn apply_scan(
73        &mut self,
74        generation: u64,
75        result: std::result::Result<ContextScan, String>,
76    ) -> bool {
77        if generation != self.generation {
78            return false;
79        }
80        self.load = match result {
81            Ok(scan) => {
82                self.selected = self
83                    .selection_id
84                    .take()
85                    .and_then(|id| {
86                        scan.sessions
87                            .iter()
88                            .position(|session| session.session_id == id)
89                    })
90                    .unwrap_or_else(|| self.selected.min(scan.sessions.len().saturating_sub(1)));
91                if scan.sessions.is_empty() {
92                    self.detail = false;
93                }
94                ContextLoad::Ready(scan)
95            }
96            Err(error) => {
97                self.selection_id = None;
98                self.detail = false;
99                ContextLoad::Error(error)
100            }
101        };
102        true
103    }
104
105    pub fn selected_session(&self) -> Option<&ContextSession> {
106        match &self.load {
107            ContextLoad::Ready(scan) => scan.sessions.get(self.selected),
108            ContextLoad::Loading | ContextLoad::Error(_) => None,
109        }
110    }
111
112    fn session_count(&self) -> usize {
113        match &self.load {
114            ContextLoad::Ready(scan) => scan.sessions.len(),
115            ContextLoad::Loading | ContextLoad::Error(_) => 0,
116        }
117    }
118}
119
120#[derive(Debug, Clone, Copy, PartialEq, Eq)]
121pub enum Action {
122    Continue,
123    Close,
124    Refresh,
125    Quit,
126}
127
128pub fn handle_key(state: &mut ContextState, code: KeyCode, mods: KeyModifiers) -> Action {
129    if matches!(code, KeyCode::Char('c')) && mods.contains(KeyModifiers::CONTROL) {
130        return Action::Quit;
131    }
132    match code {
133        KeyCode::Esc if state.detail => {
134            state.detail = false;
135            Action::Continue
136        }
137        KeyCode::Esc | KeyCode::Char('q') | KeyCode::Char('c') => Action::Close,
138        KeyCode::Char('r') => Action::Refresh,
139        KeyCode::Char('v') => {
140            state.layout = state.layout.next();
141            Action::Continue
142        }
143        KeyCode::Enter if state.selected_session().is_some() => {
144            state.detail = true;
145            Action::Continue
146        }
147        KeyCode::Up | KeyCode::Char('k') => {
148            let count = state.session_count();
149            if count > 0 {
150                state.selected = (state.selected + count - 1) % count;
151            }
152            Action::Continue
153        }
154        KeyCode::Down | KeyCode::Char('j') => {
155            let count = state.session_count();
156            if count > 0 {
157                state.selected = (state.selected + 1) % count;
158            }
159            Action::Continue
160        }
161        KeyCode::Home => {
162            state.selected = 0;
163            Action::Continue
164        }
165        KeyCode::End => {
166            let count = state.session_count();
167            state.selected = count.saturating_sub(1);
168            Action::Continue
169        }
170        _ => Action::Continue,
171    }
172}
173
174/// Render the overlay docked into `area` (the view layer decides how much of
175/// the dashboard body that is). Fills `area` like a vendor panel rather than
176/// floating, so it reads as its own surface.
177pub fn render(f: &mut Frame, area: Rect, state: &ContextState, theme: &Theme) {
178    let bubble = bubble_theme(theme);
179    f.render_widget(Clear, area);
180    let block = bubble
181        .titled_block(" Claude context ")
182        .border_style(bubble.focused_border);
183    let inner = block.inner(area);
184    f.render_widget(block, area);
185
186    let chunks = Layout::default()
187        .direction(Direction::Vertical)
188        .constraints([Constraint::Min(1), Constraint::Length(1)])
189        .split(inner);
190    match &state.load {
191        ContextLoad::Loading => panels::render(
192            f,
193            chunks[0],
194            theme,
195            &[
196                Section::Spacer,
197                Section::Text {
198                    label: String::new(),
199                    value: "  Scanning recent Claude Code sessions…".into(),
200                },
201            ],
202        ),
203        ContextLoad::Error(error) => panels::render(
204            f,
205            chunks[0],
206            theme,
207            &[
208                Section::Spacer,
209                Section::Text {
210                    label: "Error".into(),
211                    value: error.clone(),
212                },
213                Section::Spacer,
214                Section::Text {
215                    label: String::new(),
216                    value: "Press `r` to retry or `esc` to close.".into(),
217                },
218            ],
219        ),
220        ContextLoad::Ready(scan) if state.detail => {
221            if let Some(session) = scan.sessions.get(state.selected) {
222                panels::render(f, chunks[0], theme, &sections_for(session));
223            }
224        }
225        ContextLoad::Ready(scan) => render_list(f, chunks[0], state, scan, theme),
226    }
227
228    let help = if state.detail {
229        Help::new([
230            KeyBinding::with_keys(["↑/↓", "j/k"], "session"),
231            KeyBinding::new("r", "rescan"),
232            KeyBinding::new("v", "layout"),
233            KeyBinding::new("esc", "back"),
234            KeyBinding::new("q", "close"),
235        ])
236    } else {
237        Help::new([
238            KeyBinding::with_keys(["↑/↓", "j/k"], "select"),
239            KeyBinding::new("enter", "details"),
240            KeyBinding::new("r", "rescan"),
241            KeyBinding::new("v", "layout"),
242            KeyBinding::with_keys(["q", "esc"], "close"),
243        ])
244    }
245    .theme(bubble);
246    f.render_widget(&help, chunks[1]);
247}
248
249fn render_list(f: &mut Frame, area: Rect, state: &ContextState, scan: &ContextScan, theme: &Theme) {
250    let bubble = bubble_theme(theme);
251    let chunks = Layout::default()
252        .direction(Direction::Vertical)
253        .constraints([Constraint::Length(2), Constraint::Min(1)])
254        .split(area);
255
256    let showing = scan.sessions.len();
257    let mut status = format!("  {showing} recent session");
258    if showing != 1 {
259        status.push('s');
260    }
261    if scan.discovered > showing {
262        status.push_str(&format!(" · {} discovered", scan.discovered));
263    }
264    if scan.skipped > 0 {
265        status.push_str(&format!(
266            " · {} unreadable/invalid records skipped",
267            scan.skipped
268        ));
269    }
270    if scan.walk_capped {
271        status.push_str(" · directory scan capped");
272    }
273    status.push_str(&format!(" · layout: {}", state.layout.label()));
274    f.render_widget(
275        Paragraph::new(Line::from(vec![
276            Span::styled(status, bubble.muted),
277            Span::styled(
278                "\n  Input-only usage from bounded local transcript tails",
279                bubble.muted,
280            ),
281        ])),
282        chunks[0],
283    );
284
285    if scan.sessions.is_empty() {
286        f.render_widget(
287            Paragraph::new(Line::from(Span::styled(
288                "  No Claude Code session transcripts found.",
289                bubble.muted,
290            ))),
291            chunks[1],
292        );
293        return;
294    }
295
296    let items = scan
297        .sessions
298        .iter()
299        .map(|session| {
300            ListItem::new(session.display_name()).description(session_description(session))
301        })
302        .collect::<Vec<_>>();
303    let mut list = SelectList::new(items).theme(bubble);
304    list.select(Some(state.selected));
305    f.render_widget(&list, chunks[1]);
306}
307
308fn session_description(session: &ContextSession) -> String {
309    let usage = match session.usage {
310        ContextUsage::Available {
311            input_tokens,
312            percent: Some(percent),
313            ..
314        } => format!("{percent}% · {} input tokens", format_tokens(input_tokens)),
315        ContextUsage::Available { input_tokens, .. } => {
316            format!(
317                "{} input tokens · window unknown",
318                format_tokens(input_tokens)
319            )
320        }
321        ContextUsage::Compacted => "compacted · waiting for next response".into(),
322        ContextUsage::Unknown => "context usage unavailable".into(),
323    };
324    let model = session.model.as_deref().unwrap_or("unknown model");
325    format!(
326        "{} · {model} · {usage} · {}",
327        session.project,
328        local_time_hms(session.modified_at)
329    )
330}
331
332pub fn sections_for(session: &ContextSession) -> Vec<Section> {
333    let mut sections = vec![Section::Title {
334        left: session.display_name(),
335        right: Some(format!("Updated {}", local_time_hms(session.modified_at))),
336    }];
337    match session.usage {
338        ContextUsage::Available {
339            input_tokens,
340            window_tokens: Some(window_tokens),
341            percent: Some(percent),
342        } => {
343            sections.push(Section::Spacer);
344            sections.push(Section::Metric {
345                label: "Input context".into(),
346                pct: percent.min(100),
347                severity: severity_for(i32::from(percent)),
348                value_label: format!(
349                    "{percent}% · {} / {} tokens",
350                    format_tokens(input_tokens),
351                    format_tokens(window_tokens)
352                ),
353                footnote: "Latest API input; output tokens are intentionally excluded".into(),
354            });
355        }
356        ContextUsage::Available { input_tokens, .. } => {
357            sections.push(Section::Spacer);
358            sections.push(Section::Text {
359                label: "Input context".into(),
360                value: format!(
361                    "{} tokens · window size is not configured",
362                    format_tokens(input_tokens)
363                ),
364            });
365        }
366        ContextUsage::Compacted => {
367            sections.push(Section::Spacer);
368            sections.push(Section::Text {
369                label: "Input context".into(),
370                value: "Compacted · waiting for the next assistant response".into(),
371            });
372        }
373        ContextUsage::Unknown => {
374            sections.push(Section::Spacer);
375            sections.push(Section::Text {
376                label: "Input context".into(),
377                value: "Unavailable in the bounded transcript tail".into(),
378            });
379        }
380    }
381    sections.push(Section::Spacer);
382    sections.push(Section::Text {
383        label: "Project".into(),
384        value: session.project.clone(),
385    });
386    sections.push(Section::Text {
387        label: "Model".into(),
388        value: session.model.clone().unwrap_or_else(|| "unknown".into()),
389    });
390    sections.push(Section::Text {
391        label: "Session".into(),
392        value: session.session_id.clone(),
393    });
394    sections
395}
396
397fn format_tokens(value: u64) -> String {
398    let digits = value.to_string();
399    let mut out = String::with_capacity(digits.len() + digits.len() / 3);
400    for (index, ch) in digits.chars().enumerate() {
401        if index > 0 && (digits.len() - index).is_multiple_of(3) {
402            out.push(',');
403        }
404        out.push(ch);
405    }
406    out
407}
408
409pub use ratatui::crossterm::event::{KeyCode, KeyModifiers};
410
411#[cfg(test)]
412mod tests {
413    use chrono::{TimeZone, Utc};
414
415    use super::*;
416
417    fn session(id: &str, usage: ContextUsage) -> ContextSession {
418        ContextSession {
419            session_id: id.into(),
420            title: None,
421            project: "project".into(),
422            model: Some("claude-test".into()),
423            modified_at: Utc.with_ymd_and_hms(2026, 7, 20, 12, 0, 0).unwrap(),
424            usage,
425        }
426    }
427
428    fn scan(ids: &[&str]) -> ContextScan {
429        ContextScan {
430            sessions: ids
431                .iter()
432                .map(|id| session(id, ContextUsage::Unknown))
433                .collect(),
434            discovered: ids.len(),
435            skipped: 0,
436            walk_capped: false,
437        }
438    }
439
440    #[test]
441    fn stale_scan_result_is_discarded() {
442        let mut state = ContextState::default();
443        state.begin_refresh(1);
444        let first = 1;
445        state.begin_refresh(2);
446        let current = 2;
447        assert!(!state.apply_scan(first, Ok(scan(&["old"]))));
448        assert!(state.apply_scan(current, Ok(scan(&["new"]))));
449        assert_eq!(state.selected_session().unwrap().session_id, "new");
450    }
451
452    #[test]
453    fn a_result_from_a_closed_overlay_cannot_land_after_reopen() {
454        let mut reopened = ContextState::default();
455        reopened.begin_refresh(2);
456        assert!(!reopened.apply_scan(1, Ok(scan(&["closed-overlay"]))));
457        assert!(matches!(reopened.load, ContextLoad::Loading));
458    }
459
460    #[test]
461    fn rescan_preserves_the_selected_session_across_reordering() {
462        let mut state = ContextState::default();
463        let generation = 1;
464        state.begin_refresh(generation);
465        state.apply_scan(generation, Ok(scan(&["one", "two"])));
466        state.selected = 1;
467        state.detail = true;
468
469        let generation = 2;
470        state.begin_refresh(generation);
471        state.apply_scan(generation, Ok(scan(&["two", "one"])));
472        assert_eq!(state.selected, 0);
473        assert_eq!(state.selected_session().unwrap().session_id, "two");
474        assert!(state.detail);
475    }
476
477    #[test]
478    fn list_and_detail_navigation_are_bounded_and_wrap() {
479        let mut state = ContextState::default();
480        let generation = 1;
481        state.begin_refresh(generation);
482        state.apply_scan(generation, Ok(scan(&["one", "two"])));
483
484        assert_eq!(
485            handle_key(&mut state, KeyCode::Up, KeyModifiers::NONE),
486            Action::Continue
487        );
488        assert_eq!(state.selected, 1);
489        handle_key(&mut state, KeyCode::Enter, KeyModifiers::NONE);
490        assert!(state.detail);
491        assert_eq!(
492            handle_key(&mut state, KeyCode::Esc, KeyModifiers::NONE),
493            Action::Continue
494        );
495        assert!(!state.detail);
496        assert_eq!(
497            handle_key(&mut state, KeyCode::Esc, KeyModifiers::NONE),
498            Action::Close
499        );
500    }
501
502    #[test]
503    fn v_cycles_the_three_layouts_and_wraps() {
504        let mut state = ContextState::new(ContextLayout::Full);
505        state.detail = true;
506        for expected in [
507            ContextLayout::Split,
508            ContextLayout::Bottom,
509            ContextLayout::Full,
510        ] {
511            assert_eq!(
512                handle_key(&mut state, KeyCode::Char('v'), KeyModifiers::NONE),
513                Action::Continue
514            );
515            assert_eq!(state.layout, expected);
516        }
517        assert!(
518            state.detail,
519            "changing layout must not leave the detail view"
520        );
521    }
522
523    #[test]
524    fn refresh_and_global_quit_are_explicit_actions() {
525        let mut state = ContextState::default();
526        assert_eq!(
527            handle_key(&mut state, KeyCode::Char('r'), KeyModifiers::NONE),
528            Action::Refresh
529        );
530        assert_eq!(
531            handle_key(&mut state, KeyCode::Char('c'), KeyModifiers::CONTROL),
532            Action::Quit
533        );
534    }
535
536    #[test]
537    fn detail_sections_use_existing_severity_and_preserve_unknown_states() {
538        let available = session(
539            "available",
540            ContextUsage::Available {
541                input_tokens: 180_000,
542                window_tokens: Some(200_000),
543                percent: Some(90),
544            },
545        );
546        let sections = sections_for(&available);
547        assert!(sections.iter().any(|section| matches!(
548            section,
549            Section::Metric {
550                severity: crate::pacing::PaceSeverity::Critical,
551                value_label,
552                ..
553            } if value_label.contains("180,000 / 200,000")
554        )));
555
556        let compacted = sections_for(&session("compacted", ContextUsage::Compacted));
557        assert!(compacted.iter().any(|section| matches!(
558            section,
559            Section::Text { value, .. } if value.contains("waiting for the next assistant")
560        )));
561    }
562
563    #[test]
564    fn token_formatting_is_grouped_without_locale_state() {
565        assert_eq!(format_tokens(0), "0");
566        assert_eq!(format_tokens(999), "999");
567        assert_eq!(format_tokens(1_234_567), "1,234,567");
568    }
569
570    #[test]
571    fn list_and_detail_render_at_a_common_24_row_terminal() {
572        use ratatui::Terminal;
573        use ratatui::backend::TestBackend;
574
575        let mut state = ContextState::default();
576        let generation = 1;
577        state.begin_refresh(generation);
578        state.apply_scan(generation, Ok(scan(&["one", "two"])));
579        let mut terminal = Terminal::new(TestBackend::new(100, 24)).unwrap();
580        terminal
581            .draw(|frame| render(frame, frame.area(), &state, &Theme::default()))
582            .unwrap();
583
584        state.detail = true;
585        terminal
586            .draw(|frame| render(frame, frame.area(), &state, &Theme::default()))
587            .unwrap();
588    }
589}