返回 CodeWhale
infoline.rs
根目录 / crates / tui / src / tui / infoline.rs
1 //! The shell's metrics line — one row of session numbers, painted under the
2 //! posture bar at the bottom of the screen.
3 //!
4 //! It used to be a top bar. The founder's call (SHELL-DESIGN-20260901 §2.0):
5 //! *"Putting the info at the bottom is a better idea, because then you scroll
6 //! up and it feels intentional. Move the top/side bar to the bottom."* Then
7 //! (2026-09-02): *less always-on information* — the repository and branch
8 //! moved to the launch header and the git bottom view, and the DeepSeek
9 //! harness session metrics came back on screen in their place.
10 //!
11 //! Session state leads the row. A divider groups the measurements when space allows.
12 //!
13 //! ```text
14 //! deepseek-v4 ctx 22% │ $0.14 ttft 400ms 38 tok/s ↓ 1.2K Ctrl+/ help
15 //! ```
16 //!
17 //! The model is the one route fact the user checks before a turn, and it
18 //! stays clickable to the picker; the context reading stays clickable to the
19 //! inspector. Both are the floor and never shed. Everything else is a
20 //! metric: the session cost (the same number `/cost`, the roster and the
21 //! price widget print), time to first token, output rate and output tokens —
22 //! measured latency/rate averages persist between receipts; the output count
23 //! updates during streaming. Missing measurements remain absent.
24 //!
25 //! The context reading is painted here and only here — the posture bar above
26 //! used to print the same percentage a second time from the same snapshot —
27 //! and at every fullness, not only from 50% up (#5950).
28 //!
29 //! Shed order as width drops: cache, output count and billing tier, the help
30 //! hint, then rate and TTFT, then cost and balance, followed by goal and update
31 //! ([`InfoSegmentId::shed_priority`]). The model and `ctx NN%` never shed; below that floor the row clips at its
32 //! right edge.
33 //!
34 //! `/statusline` and `tui.status_items` select the session metrics;
35 //! [`crate::tui::ui::frame::info_segments`] also includes an active goal or
36 //! an available-update notice. Shedding decides what survives the
37 //! width that is left. `tui.metrics_line` sizes the row (#5950): `hidden`
38 //! gives the line back to the transcript, and `compact` starts the shed
39 //! pass with secondary counts and the help hint already gone; TTFT and rate
40 //! remain when selected and space allows
41 //! ([`InfoLine::compact`]).
42 //!
43 //! Interaction: segment geometry is recorded for parity tests, but only the
44 //! model/route segment, context reading and available-update notice advertise
45 //! actions in the live shell. Status-only facts do not brighten on hover or
46 //! pretend to be controls.
47 //!
48 //! Color: semantic ink only ([`ChromeInk`]); no hex, per the status-bar color
49 //! grammar. ASCII-safe mode substitutes every glyph through
50 //! the shared kit. Engine facts and action dispatch remain with the callers.
51
52 use super::phase_strip::{RouteFieldKind, RouteIdentityField};
53 use codewhale_palette::{ChromeInk, UiTheme};
54 use codewhale_ratatui::{
55 Caps, MetricSegment, MetricsLine, Paint, Role, Theme, color::ColorDepth, detect::Appearance,
56 };
57 use ratatui::{buffer::Buffer, layout::Rect, style::Color, widgets::Widget};
58
59 /// The kit owns segment identities and their one shared shed priority.
60 /// Existing callers retain the same model/context action identities.
61 pub use codewhale_ratatui::MetricKind as InfoSegmentId;
62
63 /// One metrics-line segment.
64 #[derive(Debug, Clone)]
65 pub struct InfoSegment {
66 pub id: InfoSegmentId,
67 pub label: String,
68 pub value: String,
69 pub ink: ChromeInk,
70 pub(crate) route_fields: Vec<RouteIdentityField>,
71 }
72
73 impl InfoSegment {
74 #[must_use]
75 pub fn new(id: InfoSegmentId, label: &str, value: impl Into<String>, ink: ChromeInk) -> Self {
76 Self {
77 id,
78 label: label.to_string(),
79 value: value.into(),
80 ink,
81 route_fields: Vec::new(),
82 }
83 }
84
85 pub(crate) fn route(mut fields: Vec<RouteIdentityField>, ascii: bool) -> Self {
86 for field in &mut fields {
87 field.text = MetricsLine::project_value(&field.text, ascii);
88 }
89 let value = fields
90 .iter()
91 .map(|field| field.text.as_str())
92 .collect::<Vec<_>>()
93 .join(if ascii { " . " } else { " · " });
94 let mut segment = Self::new(InfoSegmentId::Model, "", value, ChromeInk::MetadataValue);
95 segment.route_fields = fields;
96 segment
97 }
98 }
99
100 pub(crate) fn route_field_cells(
101 fields: &[RouteIdentityField],
102 area: Rect,
103 ) -> impl Iterator<Item = (RouteFieldKind, Rect)> + '_ {
104 fields.iter().scan(area.left(), move |x, field| {
105 let start = *x;
106 if start >= area.right() {
107 return None;
108 }
109 let width = codewhale_ratatui::text::width(&field.text)
110 .min(usize::from(area.right() - start)) as u16;
111 *x = start.saturating_add(width).saturating_add(3);
112 Some((field.kind, Rect::new(start, area.y, width, 1)))
113 })
114 }
115
116 /// What the caller owes the metrics line. Everything is injected so renders
117 /// are deterministic (golden buffers) and wall-clock keyed by the owner,
118 /// never frame-count keyed (spec §5e).
119 pub struct InfoLine<'a> {
120 pub theme: &'a UiTheme,
121 /// The single right-hand key hint, e.g. `Ctrl+/ help`. Empty means the
122 /// caller has no hint to advertise.
123 pub help_hint: &'a str,
124 /// Segments in display order.
125 pub segments: &'a [InfoSegment],
126 /// Actionable segment under the mouse. [`InfoSegmentId::Model`] and
127 /// [`InfoSegmentId::Context`] and [`InfoSegmentId::Update`] advertise
128 /// hover feedback in the live shell; each owns a click action.
129 pub hovered: Option<InfoSegmentId>,
130 /// ASCII-safe / NO_COLOR mode: every glyph goes through
131 /// the kit's native punctuation projection; language text stays intact.
132 pub ascii_safe: bool,
133 /// `tui.metrics_line = "compact"` (#5950): the shed pass starts with
134 /// secondary counts and the help hint already gone.
135 /// Selected TTFT and rate readings remain; width sheds the rest.
136 pub compact: bool,
137 }
138
139 impl<'a> InfoLine<'a> {
140 #[must_use]
141 pub fn new(theme: &'a UiTheme, help_hint: &'a str, segments: &'a [InfoSegment]) -> Self {
142 Self {
143 theme,
144 help_hint,
145 segments,
146 hovered: None,
147 ascii_safe: false,
148 compact: false,
149 }
150 }
151
152 #[must_use]
153 pub fn ascii_safe(mut self, ascii_safe: bool) -> Self {
154 self.ascii_safe = ascii_safe;
155 self
156 }
157
158 #[must_use]
159 pub fn compact(mut self, compact: bool) -> Self {
160 self.compact = compact;
161 self
162 }
163
164 #[must_use]
165 pub fn hovered(mut self, hovered: Option<InfoSegmentId>) -> Self {
166 self.hovered = hovered;
167 self
168 }
169 }
170
171 // A full-color role theme supplies distinct identities, not product colors.
172 // Named native palettes can collapse Hint/Dim or permission inks; use the
173 // uncollapsed role table so custom UiTheme slots remain independent. The
174 // existing backend applies terminal color capabilities after this adapter.
175 pub(super) fn source_theme(ascii: bool) -> Theme {
176 Theme::new(Caps {
177 depth: ColorDepth::TrueColor,
178 ascii,
179 appearance: Appearance::Dark,
180 })
181 }
182
183 pub(super) fn ink_role(ink: ChromeInk) -> Role {
184 match ink {
185 ChromeInk::Outcome | ChromeInk::Active => Role::Live,
186 // These three roles are private style identities in this adapter;
187 // they do not paint grounds or change permission authority.
188 ChromeInk::PermissionAsk => Role::Surface,
189 ChromeInk::PermissionAutoReview => Role::Hover,
190 ChromeInk::PermissionFullAccess => Role::Selected,
191 ChromeInk::Waiting => Role::BorderStrong,
192 ChromeInk::Attention => Role::Attention,
193 ChromeInk::PolicyAct
194 | ChromeInk::PolicyPlan
195 | ChromeInk::PolicyOperate
196 | ChromeInk::Identity
197 | ChromeInk::Info => Role::Accent,
198 ChromeInk::MetadataValue => Role::Foreground,
199 ChromeInk::Metadata => Role::Muted,
200 ChromeInk::MetadataHint => Role::Hint,
201 ChromeInk::MetadataDim => Role::Dim,
202 ChromeInk::Failure => Role::Danger,
203 }
204 }
205
206 const STYLE_INKS: [ChromeInk; 12] = [
207 ChromeInk::Active,
208 ChromeInk::PermissionAsk,
209 ChromeInk::PermissionAutoReview,
210 ChromeInk::PermissionFullAccess,
211 ChromeInk::Waiting,
212 ChromeInk::Attention,
213 ChromeInk::Info,
214 ChromeInk::MetadataValue,
215 ChromeInk::Metadata,
216 ChromeInk::MetadataHint,
217 ChromeInk::MetadataDim,
218 ChromeInk::Failure,
219 ];
220
221 impl InfoLine<'_> {
222 fn kit(&self) -> MetricsLine<'_> {
223 let mut line = MetricsLine::new(
224 self.segments
225 .iter()
226 .map(|segment| {
227 MetricSegment::new(segment.id, segment.label.as_str(), segment.value.as_str())
228 .role(ink_role(segment.ink))
229 })
230 .collect(),
231 )
232 .help_hint(self.help_hint)
233 .compact(self.compact);
234 if let Some(hovered) = self.hovered {
235 line = line.hovered(hovered);
236 }
237 line
238 }
239 }
240
241 /// The kit computes the visible context reading's exact pointer target.
242 #[must_use]
243 pub fn context_meter_hitbox(info: &InfoLine<'_>, area: Rect) -> Option<Rect> {
244 info.kit()
245 .context_hitbox(area, &source_theme(info.ascii_safe))
246 }
247
248 impl Widget for InfoLine<'_> {
249 fn render(self, area: Rect, buf: &mut Buffer) {
250 let area = area.intersection(buf.area);
251 let kit = self.kit();
252 paint_native_row(&kit, area, buf, self.theme, self.ascii_safe);
253 let hits = kit.hitboxes(area, &source_theme(self.ascii_safe));
254 for (i, hit) in hits.iter().enumerate() {
255 if matches!(hit.kind, InfoSegmentId::Model | InfoSegmentId::Context)
256 && let Some(segment) = self.segments.iter().find(|segment| segment.id == hit.kind)
257 {
258 let start = hit.area.left();
259 let right = hit.area.right();
260 let y = hit.area.y;
261 let projected_width =
262 |s: &str| codewhale_ratatui::text::width(s).min(u16::MAX as usize) as u16;
263 if segment.route_fields.is_empty() {
264 let offset = if segment.label.is_empty() {
265 0
266 } else {
267 projected_width(&MetricsLine::project_value(
268 &segment.label,
269 self.ascii_safe,
270 ))
271 .saturating_add(1)
272 };
273 for x in start.saturating_add(offset)..right {
274 buf[(x, y)].modifier.insert(ratatui::style::Modifier::BOLD);
275 }
276 } else {
277 for (kind, area) in route_field_cells(&segment.route_fields, hit.area) {
278 for column in area.left()..area.right() {
279 let cell = &mut buf[(column, y)];
280 if kind == RouteFieldKind::Model {
281 cell.modifier.insert(ratatui::style::Modifier::BOLD);
282 } else if self.hovered != Some(InfoSegmentId::Model) {
283 cell.set_fg(self.theme.text_soft);
284 }
285 }
286 }
287 }
288 }
289 if matches!(hit.kind, InfoSegmentId::Model | InfoSegmentId::Thinking)
290 && area.width >= 70
291 && let Some(next) = hits.get(i + 1)
292 && !matches!(next.kind, InfoSegmentId::Model | InfoSegmentId::Thinking)
293 && next.area.left().saturating_sub(hit.area.right()) >= 3
294 {
295 let cell = &mut buf[(hit.area.right() + 1, hit.area.y)];
296 cell.set_symbol(if self.ascii_safe { "|" } else { "│" });
297 cell.set_fg(self.theme.border);
298 }
299 }
300 }
301 }
302
303 /// Adapt the kit's two native chrome rows to the live host ink slots.
304 pub(super) fn paint_native_row(
305 component: &impl Paint,
306 area: Rect,
307 buf: &mut Buffer,
308 theme: &UiTheme,
309 ascii: bool,
310 ) {
311 let area = area.intersection(buf.area);
312 if area.is_empty() {
313 return;
314 }
315 let area = Rect { height: 1, ..area };
316 let source = source_theme(ascii);
317 let inks = STYLE_INKS.map(|ink| {
318 let color = match ink {
319 ChromeInk::MetadataValue => theme.text_body,
320 ChromeInk::Metadata => theme.text_soft,
321 ChromeInk::MetadataHint => theme.text_muted,
322 other => other.color(theme),
323 };
324 (source.color(ink_role(ink)), color)
325 });
326 // Render one borrowed row with a foreground sentinel. Only cells the
327 // kit writes are copied back, preserving untouched content and all
328 // host-owned backgrounds/modifiers. Wide-character continuation cells
329 // reset exactly as they do in a direct Ratatui render.
330 let untouched = Color::Indexed(0);
331 let mut row = Buffer::empty(area);
332 for x in area.left()..area.right() {
333 row[(x, area.y)].clone_from(&buf[(x, area.y)]);
334 row[(x, area.y)].fg = untouched;
335 }
336 component.paint(area, &mut row, &source);
337 for x in area.left()..area.right() {
338 let cell = &mut row[(x, area.y)];
339 if cell.fg == untouched {
340 continue;
341 }
342 if let Some((_, color)) = inks.iter().find(|(identity, _)| *identity == Some(cell.fg)) {
343 cell.fg = *color;
344 }
345 buf[(x, area.y)].clone_from(cell);
346 }
347 }
348
349 /// Host-owned action routing keeps its existing typed facade.
350 #[derive(Debug, Clone)]
351 pub struct InfoLineHitbox {
352 pub id: InfoSegmentId,
353 pub area: Rect,
354 }
355
356 /// Geometry comes from the same kit layout as painting, with no caller
357 /// width calculation, shedding pass or punctuation projection.
358 #[must_use]
359 pub fn infoline_hitboxes(info: &InfoLine<'_>, area: Rect) -> Vec<InfoLineHitbox> {
360 info.kit()
361 .hitboxes(area, &source_theme(info.ascii_safe))
362 .into_iter()
363 .map(|hit| InfoLineHitbox {
364 id: hit.kind,
365 area: hit.area,
366 })
367 .collect()
368 }
369
370 #[cfg(test)]
371 mod tests;
372
372 lines RUST