tinyharness-ui 0.3.2

ui library for tinyharness
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
// ── Status bar widget ───────────────────────────────────────────────────────
//
// Displays mode, model name, token count, session name, and message count
// at the top of the TUI screen.

use crate::tui::cell::{Cell, Color, Style};
use crate::tui::layout::Rect;
use crate::tui::screen::Screen;
use crate::tui::widget::{Widget, styles};

/// The status bar at the top of the screen.
///
/// Shows: mode label | model name | token count | message count | session name
///
/// Example (not valid Rust — for illustration only):
///
/// ```text
/// [agent] TinyHarness | llama3.1:8b | 12.4k/128k (9.6%) | 42 msgs | 3 files | session-name
/// ```
pub struct StatusBarWidget {
    pub mode_label: String,
    pub mode_color: Color,
    pub model_name: String,
    pub token_count: Option<(u32, u32)>, // (used, total)
    pub message_count: usize,
    pub pinned_file_count: usize,
    pub session_name: String,
    pub is_streaming: bool,
    /// Cumulative tool calls in this session.
    pub tool_call_count: u64,
    /// Cumulative total tokens used across all LLM calls.
    pub total_tokens_used: u64,
    /// Label for the currently focused widget (e.g., "input", "chat", "sidebar", "files").
    pub focus_label: String,
}

impl StatusBarWidget {
    pub fn new(mode_label: &str, model_name: &str) -> Self {
        let mode_color = match mode_label {
            "casual" => styles::MODE_CASUAL_FG,
            "planning" => styles::MODE_PLANNING_FG,
            "agent" => styles::MODE_AGENT_FG,
            "research" => styles::MODE_RESEARCH_FG,
            _ => Color::WHITE,
        };

        Self {
            mode_label: mode_label.to_string(),
            mode_color,
            model_name: model_name.to_string(),
            token_count: None,
            message_count: 0,
            pinned_file_count: 0,
            session_name: String::from("unnamed"),
            is_streaming: false,
            tool_call_count: 0,
            total_tokens_used: 0,
            focus_label: String::from("input"),
        }
    }

    /// Update the mode label and model name.
    pub fn update_labels(&mut self, mode_label: &str, model_name: &str) {
        self.mode_label = mode_label.to_string();
        self.mode_color = match mode_label {
            "casual" => styles::MODE_CASUAL_FG,
            "planning" => styles::MODE_PLANNING_FG,
            "agent" => styles::MODE_AGENT_FG,
            "research" => styles::MODE_RESEARCH_FG,
            _ => Color::WHITE,
        };
        self.model_name = model_name.to_string();
    }

    /// Set the session name.
    pub fn set_session_name(&mut self, name: &str) {
        self.session_name = name.to_string();
    }

    /// Set the message count.
    pub fn set_message_count(&mut self, count: usize) {
        self.message_count = count;
    }

    /// Set the token count (used, total).
    pub fn set_token_count(&mut self, used: u64, total: Option<u64>) {
        self.token_count = total.map(|t| (used as u32, t as u32));
    }

    /// Set the cumulative tool call count.
    pub fn set_tool_call_count(&mut self, count: u64) {
        self.tool_call_count = count;
    }

    /// Set the cumulative total tokens used.
    pub fn set_total_tokens_used(&mut self, count: u64) {
        self.total_tokens_used = count;
    }

    /// Set whether the assistant is currently streaming.
    pub fn set_streaming(&mut self, streaming: bool) {
        self.is_streaming = streaming;
    }

    /// Set the focus indicator label (e.g., "input", "chat", "files").
    pub fn set_focus_label(&mut self, label: &str) {
        self.focus_label = label.to_string();
    }

    /// Format token count for display.
    fn format_tokens(&self) -> String {
        match self.token_count {
            Some((used, total)) => {
                let used_str = if used >= 1000 {
                    format!("{:.1}k", used as f64 / 1000.0)
                } else {
                    used.to_string()
                };
                let total_str = if total >= 1000 {
                    format!("{:.0}k", total as f64 / 1000.0)
                } else {
                    total.to_string()
                };
                let pct = if total > 0 {
                    format!("{:.0}%", (used as f64 / total as f64) * 100.0)
                } else {
                    "?%".to_string()
                };
                format!("{used_str}/{total_str} ({pct})")
            }
            None => "? tokens".to_string(),
        }
    }
}

impl Widget for StatusBarWidget {
    fn render(&mut self, area: Rect, screen: &mut Screen) {
        if area.is_empty() || area.height < 1 {
            return;
        }

        // Fill the status bar background
        screen.fill_rect(
            area,
            Cell {
                char: ' ',
                fg: styles::STATUS_BAR_FG,
                bg: styles::STATUS_BAR_BG,
                style: Style::default(),
                wide: false,
            },
        );

        // Build the status line content
        let row = area.y;

        // Mode label with color
        let mode_text = format!(" {} ", self.mode_label);
        screen.write_str(
            row,
            area.x,
            &mode_text,
            self.mode_color,
            styles::STATUS_BAR_BG,
            Style::bold(),
        );

        // Separator
        let mut col = area.x + mode_text.len() as u16;
        screen.write_str(
            row,
            col,
            " │ ",
            Color::Ansi(240),
            styles::STATUS_BAR_BG,
            Style::default(),
        );
        col += 3;

        // Model name
        let model_text = &self.model_name;
        screen.write_str(
            row,
            col,
            model_text,
            Color::WHITE,
            styles::STATUS_BAR_BG,
            Style::default(),
        );
        col += model_text.len() as u16;

        // Separator
        screen.write_str(
            row,
            col,
            " │ ",
            Color::Ansi(240),
            styles::STATUS_BAR_BG,
            Style::default(),
        );
        col += 3;

        // Token count
        let token_text = self.format_tokens();
        let token_color = match self.token_count {
            Some((used, total)) if total > 0 => {
                let pct = used as f64 / total as f64;
                if pct > 0.9 {
                    Color::RED
                } else if pct > 0.7 {
                    Color::YELLOW
                } else {
                    Color::GREEN
                }
            }
            _ => Color::GRAY,
        };
        screen.write_str(
            row,
            col,
            &token_text,
            token_color,
            styles::STATUS_BAR_BG,
            Style::default(),
        );
        col += token_text.len() as u16;

        // Separator
        screen.write_str(
            row,
            col,
            " │ ",
            Color::Ansi(240),
            styles::STATUS_BAR_BG,
            Style::default(),
        );
        col += 3;

        // Message count
        let msg_text = format!("{} msgs", self.message_count);
        screen.write_str(
            row,
            col,
            &msg_text,
            Color::WHITE,
            styles::STATUS_BAR_BG,
            Style::dim(),
        );
        col += msg_text.len() as u16;

        // Pinned files
        if self.pinned_file_count > 0 {
            screen.write_str(
                row,
                col,
                " │ ",
                Color::Ansi(240),
                styles::STATUS_BAR_BG,
                Style::default(),
            );
            col += 3;
            let file_text = format!("{} files", self.pinned_file_count);
            screen.write_str(
                row,
                col,
                &file_text,
                Color::WHITE,
                styles::STATUS_BAR_BG,
                Style::dim(),
            );
            col += file_text.len() as u16;
        }

        // Tool call count (only if > 0)
        if self.tool_call_count > 0 {
            screen.write_str(
                row,
                col,
                " │ ",
                Color::Ansi(240),
                styles::STATUS_BAR_BG,
                Style::default(),
            );
            col += 3;
            let tool_text = format!("{} tools", self.tool_call_count);
            screen.write_str(
                row,
                col,
                &tool_text,
                Color::WHITE,
                styles::STATUS_BAR_BG,
                Style::dim(),
            );
            col += tool_text.len() as u16;
        }

        // Total tokens used (only if > 0)
        if self.total_tokens_used > 0 {
            screen.write_str(
                row,
                col,
                " │ ",
                Color::Ansi(240),
                styles::STATUS_BAR_BG,
                Style::default(),
            );
            col += 3;
            let total_text = format!(
                "{} total",
                if self.total_tokens_used >= 1000 {
                    format!("{:.1}k", self.total_tokens_used as f64 / 1000.0)
                } else {
                    self.total_tokens_used.to_string()
                }
            );
            screen.write_str(
                row,
                col,
                &total_text,
                Color::WHITE,
                styles::STATUS_BAR_BG,
                Style::dim(),
            );
            col += total_text.len() as u16;
        }

        // Focus indicator (right of left-section, before session name)
        let focus_text = format!(" ▸ {} ", self.focus_label);
        let focus_color = Color::Ansi(178); // warm amber to stand out
        // Place it just before the session name if there's room
        let session_text = format!(" {} ", self.session_name);
        let session_start = area.x + area.width.saturating_sub(session_text.len() as u16);
        let focus_start = session_start.saturating_sub(focus_text.len() as u16);
        if focus_start > col {
            screen.write_str(
                row,
                focus_start,
                &focus_text,
                focus_color,
                styles::STATUS_BAR_BG,
                Style::bold(),
            );
        }

        // Session name (right-aligned)
        if session_start > col {
            screen.write_str(
                row,
                session_start,
                &session_text,
                Color::Ansi(240),
                styles::STATUS_BAR_BG,
                Style::default(),
            );
        }

        // Streaming indicator
        if self.is_streaming && col + 4 < area.x + area.width {
            screen.write_str(
                row,
                col,
                " ⋯",
                Color::ORANGE,
                styles::STATUS_BAR_BG,
                Style::default(),
            );
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_status_bar_render() {
        let mut screen = Screen::new(80, 24);
        let mut widget = StatusBarWidget::new("agent", "llama3.1:8b");
        let area = Rect::new(0, 0, 80, 1);
        widget.render(area, &mut screen);

        // Should have content in the first row
        assert_ne!(screen.get(0, 0).unwrap().char, '\0');
    }

    #[test]
    fn test_format_tokens() {
        let widget = StatusBarWidget::new("agent", "llama3.1:8b");
        assert_eq!(widget.format_tokens(), "? tokens");

        let mut widget = StatusBarWidget::new("agent", "llama3.1:8b");
        widget.token_count = Some((12000, 128000));
        let tokens = widget.format_tokens();
        // 12000/128000 = 9.375%, which rounds to 9%
        assert!(tokens.contains("%") && tokens.contains("12.0k") && tokens.contains("128k"));
    }

    #[test]
    fn test_status_bar_with_tokens() {
        let mut screen = Screen::new(80, 24);
        let mut widget = StatusBarWidget::new("agent", "llama3.1:8b");
        widget.token_count = Some((5000, 128000));
        widget.message_count = 42;
        let area = Rect::new(0, 0, 80, 1);
        widget.render(area, &mut screen);

        // Should have rendered content
        assert_ne!(screen.get(0, 0).unwrap().char, '\0');
    }
}