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
//! Status bar widget for the inline TUI viewport.
//!
//! Shows: mode | model name | context usage bar | (conditional segments)
//!
//! # Why no `cwd` segment?
//!
//! The cwd was previously rendered as the leftmost segment (#1105),
//! but the welcome banner already shows `cwd` and it can't change
//! during a session. Carrying it in the persistent footer was pure
//! redundancy — the status bar is prime real estate that should only
//! show information that changes. Removed in #1194/#1195 follow-up;
//! the codex / gemini-cli status lines also omit cwd for the same
//! reason.
use koda_core::mcp::manager::McpStatusBarInfo;
use ratatui::{
buffer::Buffer,
layout::Rect,
style::{Color, Style},
text::{Line, Span},
widgets::Widget,
};
pub struct StatusBar<'a> {
model: &'a str,
mode_label: &'a str,
context_pct: u32,
queue_len: usize,
/// Elapsed seconds during inference (0 = idle).
elapsed_secs: u64,
/// Last turn stats (shown after inference completes).
last_turn: Option<&'a TurnStats>,
/// Scroll position info (offset, total) — shown when not at bottom.
scroll_info: Option<(usize, usize)>,
/// MCP server status (None = no servers configured, hidden).
mcp_info: Option<McpStatusBarInfo>,
/// Vim mode label (e.g. "NORMAL", "INSERT", "OPERATOR-PENDING").
/// `None` hides the segment entirely (vim editing disabled).
/// Sourced from `composer::textarea::TextArea::vim_mode_label()`
/// which the status-bar caller passes in via [`with_vim_label`].
/// Added in PR 3 of #1178 (vim mode wire-up).
vim_label: Option<&'a str>,
}
/// Stats from the most recent inference turn.
#[derive(Debug, Clone, Default)]
pub struct TurnStats {
/// Input tokens billed for this turn.
pub tokens_in: i64,
/// Output tokens generated this turn.
pub tokens_out: i64,
/// Tokens served from the prompt cache (cost $0).
pub cache_read: i64,
pub elapsed_ms: u64,
pub rate: f64,
}
impl<'a> StatusBar<'a> {
pub fn new(model: &'a str, mode_label: &'a str, context_pct: u32) -> Self {
Self {
model,
mode_label,
context_pct,
queue_len: 0,
elapsed_secs: 0,
last_turn: None,
scroll_info: None,
mcp_info: None,
vim_label: None,
}
}
pub fn with_queue(mut self, queue_len: usize) -> Self {
self.queue_len = queue_len;
self
}
pub fn with_elapsed(mut self, secs: u64) -> Self {
self.elapsed_secs = secs;
self
}
pub fn with_last_turn(mut self, stats: &'a TurnStats) -> Self {
self.last_turn = Some(stats);
self
}
pub fn with_scroll_info(mut self, offset: usize, total: usize) -> Self {
self.scroll_info = Some((offset, total));
self
}
pub fn with_mcp_info(mut self, info: McpStatusBarInfo) -> Self {
self.mcp_info = Some(info);
self
}
/// Set the active vim-mode label (NORMAL / INSERT / OPERATOR-PENDING).
///
/// `None` (or any call site that doesn't invoke this) hides the segment
/// entirely — vim editing is opt-in, so users who don't toggle it never
/// see VIM clutter in the status bar. PR 3 of #1178; sourced from
/// `composer::textarea::TextArea::vim_mode_label()`.
pub fn with_vim_label(mut self, label: Option<&'a str>) -> Self {
self.vim_label = label;
self
}
}
impl Widget for StatusBar<'_> {
fn render(self, area: Rect, buf: &mut Buffer) {
let mode_color = match self.mode_label {
"auto" => Color::Green,
"strict" => Color::Cyan,
"safe" => Color::Yellow,
_ => Color::DarkGray,
};
let bar_width: u32 = 10;
let filled = (self.context_pct * bar_width / 100).min(bar_width);
let empty = bar_width - filled;
let ctx_color = if self.context_pct >= 90 {
Color::Red
} else if self.context_pct >= 75 {
Color::Yellow
} else {
Color::DarkGray
};
// Truncate long model names to keep status bar readable
let model_display = if self.model.len() > 32 {
format!("{}…", &self.model[..31])
} else {
self.model.to_string()
};
let mut spans = vec![];
// Segment order (#1194/#1195 follow-up): mode → model → context.
// Mode is FIRST because it's the most-frequently-changing piece
// (Shift+Tab cycles Plan/Safe/Auto on demand) and has a distinct
// color, so eye-anchoring it leftmost matches user attention.
// Model is second; context bar last because it's the widest
// segment and naturally tail-anchors the always-on cluster.
spans.extend([
Span::styled(
format!(" {} ", self.mode_label),
Style::default().fg(mode_color),
),
Span::styled("\u{2502}", Style::default().fg(Color::Rgb(60, 60, 60))),
Span::styled(
format!(" {model_display} "),
Style::default().fg(Color::DarkGray),
),
Span::styled("\u{2502}", Style::default().fg(Color::Rgb(60, 60, 60))),
Span::styled(
format!(
" {}{} {}%",
"\u{2588}".repeat(filled as usize),
"\u{2591}".repeat(empty as usize),
self.context_pct,
),
Style::default().fg(ctx_color),
),
]);
// Vim mode pill (PR 3 of #1178). Hidden when vim editing is
// disabled (the textarea returns `None` from `vim_mode_label()`),
// so non-vim users never see this segment. Magenta to make the
// mode visually distinct from the trust-mode segment.
if let Some(label) = self.vim_label {
spans.push(Span::styled(
"\u{2502}",
Style::default().fg(Color::Rgb(60, 60, 60)),
));
spans.push(Span::styled(
format!(" VIM:{label} "),
Style::default().fg(Color::Magenta),
));
}
// MCP server indicator (hidden when no servers configured)
if let Some(mcp) = self.mcp_info {
let mcp_color = if mcp.failed == 0 {
Color::Green
} else if mcp.connected > 0 {
Color::Yellow
} else {
Color::Red
};
spans.push(Span::styled(
"\u{2502}",
Style::default().fg(Color::Rgb(60, 60, 60)),
));
spans.push(Span::styled(
format!(" \u{26a1}{}/{} ", mcp.connected, mcp.total),
Style::default().fg(mcp_color),
));
}
// (#1158's bg-activity pill was removed in #1210 — the live
// bg-activity overlay above the status bar shows "what's
// running and what each task is doing", which is strictly
// more useful than a count. The pill became redundant the
// moment the live surface existed.)
// Elapsed time during inference
if self.elapsed_secs > 0 {
spans.push(Span::styled(
"\u{2502}",
Style::default().fg(Color::Rgb(60, 60, 60)),
));
spans.push(Span::styled(
format!(" \u{23f3} {}s ", self.elapsed_secs),
Style::default().fg(Color::Cyan),
));
}
// Queue indicator — show count + Ctrl+U hint
if self.queue_len > 0 {
spans.push(Span::styled(
"\u{2502}",
Style::default().fg(Color::Rgb(60, 60, 60)),
));
spans.push(Span::styled(
format!(" \u{1f4cb} {} queued ", self.queue_len),
Style::default().fg(Color::Yellow),
));
spans.push(Span::styled(
"^U clear ",
Style::default().fg(Color::Rgb(100, 100, 100)),
));
}
// Last turn stats (shown after inference, cleared on next turn)
if let Some(stats) = self.last_turn {
spans.push(Span::styled(
"\u{2502}",
Style::default().fg(Color::Rgb(60, 60, 60)),
));
let time = if stats.elapsed_ms >= 1000 {
format!("{:.1}s", stats.elapsed_ms as f64 / 1000.0)
} else {
format!("{}ms", stats.elapsed_ms)
};
// Show ↑in ↓out token counts so users can see full turn cost.
let mut stat_str = format!(
" ↑{} ↓{} · {} · {:.0} t/s ",
stats.tokens_in, stats.tokens_out, time, stats.rate
);
// Cache hit indicator — only shown when nonzero (costs nothing).
if stats.cache_read > 0 && stats.tokens_in > 0 {
let pct = (stats.cache_read * 100) / stats.tokens_in;
stat_str = format!(
" ↑{} ↓{} 🗄{pct}% · {} · {:.0} t/s ",
stats.tokens_in, stats.tokens_out, time, stats.rate
);
}
spans.push(Span::styled(stat_str, Style::default().fg(Color::DarkGray)));
}
// Scroll position (when not at bottom)
if let Some((offset, total)) = self.scroll_info {
spans.push(Span::styled(
"\u{2502}",
Style::default().fg(Color::Rgb(60, 60, 60)),
));
spans.push(Span::styled(
format!(" \u{2191}{offset}/{total} "),
Style::default().fg(Color::Yellow),
));
}
Line::from(spans).render(area, buf);
}
}
#[cfg(test)]
mod tests {
use super::*;
use ratatui::buffer::Buffer;
use ratatui::layout::Rect;
use ratatui::widgets::Widget;
/// Render a StatusBar into a buffer and return the text content.
fn render_bar(bar: StatusBar<'_>, width: u16) -> String {
let area = Rect::new(0, 0, width, 1);
let mut buf = Buffer::empty(area);
bar.render(area, &mut buf);
// Extract text from buffer cells.
(0..width)
.map(|x| buf.cell((x, 0)).map(|c| c.symbol()).unwrap_or(" "))
.collect::<String>()
.trim_end()
.to_string()
}
#[test]
fn mcp_indicator_hidden_when_no_servers() {
let bar = StatusBar::new("gpt-4", "safe", 50);
let text = render_bar(bar, 120);
// No MCP info → no lightning bolt indicator.
assert!(
!text.contains('⚡'),
"MCP indicator should be hidden: {text}"
);
}
#[test]
fn mcp_indicator_shows_connected_count() {
let bar = StatusBar::new("gpt-4", "safe", 50).with_mcp_info(McpStatusBarInfo {
connected: 2,
failed: 0,
total: 3,
});
let text = render_bar(bar, 120);
assert!(text.contains("2/3"), "should show 2/3: {text}");
}
/// Find the fg color of the ⚡ MCP indicator in a rendered buffer.
fn mcp_indicator_color(info: McpStatusBarInfo) -> Color {
let bar = StatusBar::new("gpt-4", "safe", 50).with_mcp_info(info);
let area = Rect::new(0, 0, 120, 1);
let mut buf = Buffer::empty(area);
bar.render(area, &mut buf);
let mcp_cell = (0..120u16)
.find(|&x| buf.cell((x, 0)).map(|c| c.symbol()) == Some("⚡"))
.expect("should have ⚡ cell");
buf.cell((mcp_cell, 0)).unwrap().fg
}
#[test]
fn mcp_color_green_when_all_connected() {
let fg = mcp_indicator_color(McpStatusBarInfo {
connected: 3,
failed: 0,
total: 3,
});
assert_eq!(fg, Color::Green, "all connected → green");
}
#[test]
fn mcp_color_yellow_when_partial() {
let fg = mcp_indicator_color(McpStatusBarInfo {
connected: 1,
failed: 1,
total: 2,
});
assert_eq!(fg, Color::Yellow, "partial → yellow");
}
#[test]
fn mcp_color_red_when_all_failed() {
let fg = mcp_indicator_color(McpStatusBarInfo {
connected: 0,
failed: 2,
total: 2,
});
assert_eq!(fg, Color::Red, "all failed → red");
}
// ── #1194/#1195 follow-up: segment ordering ──────────────────────
// The cwd segment was removed (banner already shows it; can't
// change in a session). Mode now leads the bar because it changes
// most often (Shift+Tab cycles trust modes) and has a distinct
// color, so eye-anchoring it leftmost matches user attention.
#[test]
fn mode_renders_leftmost_before_model() {
let bar = StatusBar::new("gpt-4", "auto", 50);
let text = render_bar(bar, 200);
let mode_pos = text.find("auto").expect("mode label should render");
let model_pos = text.find("gpt-4").expect("model should render");
assert!(
mode_pos < model_pos,
"mode ({mode_pos}) must come before model ({model_pos}) in: {text}"
);
}
// (#1158's bg-pill tests removed in #1210 along with the pill
// itself; the live bg-activity overlay is covered by
// `widgets::bg_activity_overlay::tests` and `bg_activity::tests`.)
/// Vim segment is hidden when the textarea reports `None`
/// (vim editing disabled). PR 3 of #1178.
#[test]
fn vim_segment_hidden_when_label_is_none() {
let bar = StatusBar::new("gpt-4", "safe", 50).with_vim_label(None);
let out = render_bar(bar, 200);
assert!(
!out.contains("VIM"),
"vim segment must not render when label is None: {out}"
);
}
/// Vim segment renders the label when set. Covers the
/// `with_vim_label(Some(...))` happy path used by `tui_viewport`
/// when the textarea is in a vim mode.
#[test]
fn vim_segment_renders_label_when_some() {
let bar = StatusBar::new("gpt-4", "safe", 50).with_vim_label(Some("NORMAL"));
let out = render_bar(bar, 200);
assert!(
out.contains("VIM:NORMAL"),
"vim pill must render label: {out}"
);
}
}