返回 CodeWhale
rows.rs
根目录 / crates / tui / src / tui / work_surface / render / rows.rs
1 //! Per-row composition: the columns a sub-agent row resolves to at a given
2 //! width, and the style every row is painted with.
3
4 use ratatui::style::{Color, Modifier, Style};
5 use unicode_width::UnicodeWidthStr;
6
7 use crate::tui::app::App;
8 use crate::tui::work_surface::model::{AgentRowFacts, WorkRow, WorkTone};
9 use codewhale_tui_kit::ui_text::truncate_line_to_width;
10
11 /// Gap between the agent-type column and the objective.
12 pub(super) const AGENT_ROLE_GUTTER: usize = 2;
13 /// Minimum gap between the objective and the right-aligned receipt.
14 const AGENT_RECEIPT_GUTTER: usize = 2;
15 /// Columns the objective must keep before an optional column may stay. Below
16 /// this the objective is a shrug — "Streaming d…" answers nothing — so the
17 /// optional column loses instead.
18 const AGENT_OBJECTIVE_MIN: usize = 24;
19
20 /// How much of a sub-agent row survives at the current width.
21 ///
22 /// Degradation order, widest to narrowest: the token figure goes first, then
23 /// the remaining receipt, then the agent identity column. The objective is the
24 /// last
25 /// thing to go — a fleet row that cannot say what the agent is doing has
26 /// stopped being worth a row.
27 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
28 pub(super) enum AgentRowTier {
29 /// Type, objective, elapsed, tokens.
30 Full,
31 /// Type, objective, elapsed.
32 NoTokens,
33 /// Type, objective.
34 NoReceipt,
35 /// Objective only.
36 ObjectiveOnly,
37 }
38
39 const AGENT_ROW_TIERS: [AgentRowTier; 4] = [
40 AgentRowTier::Full,
41 AgentRowTier::NoTokens,
42 AgentRowTier::NoReceipt,
43 AgentRowTier::ObjectiveOnly,
44 ];
45
46 /// A sub-agent row resolved to painted columns.
47 #[derive(Debug, Clone, Default, PartialEq, Eq)]
48 pub(super) struct AgentRowText {
49 /// Agent-type column, padded to the shared width. Empty once dropped.
50 pub(super) role: String,
51 /// Status word column (`running`, `completed`, …), padded to the shared
52 /// width. Dropped only with the identity column: a fleet row that cannot
53 /// say its state in words has lost the fact the owner asked for back
54 /// (2026-08-04 regression report).
55 pub(super) status: String,
56 pub(super) objective: String,
57 /// `deepseek-v4-pro · 12m 33s · ↓ 111.9k tokens`. Empty once dropped.
58 pub(super) receipt: String,
59 /// Spaces separating the objective from the receipt.
60 pub(super) gap: usize,
61 }
62
63 /// The right-aligned receipt at a given tier. A figure the runtime never
64 /// reported is absent, never zero: an agent with no usage envelope shows no
65 /// token count at all.
66 pub(super) fn agent_receipt(facts: &AgentRowFacts, tier: AgentRowTier) -> String {
67 let model = facts
68 .model
69 .as_deref()
70 .filter(|model| !model.is_empty())
71 .filter(|_| matches!(tier, AgentRowTier::Full | AgentRowTier::NoTokens))
72 .map(str::to_string);
73 let elapsed = facts
74 .elapsed_secs
75 .filter(|_| matches!(tier, AgentRowTier::Full | AgentRowTier::NoTokens))
76 .map(codewhale_command_contract::elapsed::format_elapsed_secs);
77 let tokens = facts
78 .tokens
79 .filter(|_| tier == AgentRowTier::Full)
80 .map(|tokens| {
81 format!(
82 "↓ {} tokens",
83 crate::tui::footer_ui::format_token_count_compact(tokens)
84 )
85 });
86 // Only paint a remaining chip when a real ledger reported unsettled
87 // work. `None` (no list) and `Some(0)` (list fully settled) stay quiet —
88 // a fabricated `0 left` is strip noise.
89 let todos_left = facts
90 .todos_remaining
91 .filter(|n| *n > 0)
92 .filter(|_| matches!(tier, AgentRowTier::Full | AgentRowTier::NoTokens))
93 .map(|n| format!("{n} left"));
94 [model, elapsed, tokens, todos_left]
95 .into_iter()
96 .flatten()
97 .collect::<Vec<_>>()
98 .join(" · ")
99 }
100
101 /// Ceiling on the shared identity column, as a fraction of the row. The
102 /// column is shared, so without a cap a single long nickname would widen it
103 /// for every row and starve every objective on the surface. An identity wider
104 /// than this is dropped for *that* row only.
105 const AGENT_IDENTITY_CAP_NUMERATOR: usize = 2;
106 const AGENT_IDENTITY_CAP_DENOMINATOR: usize = 5;
107
108 /// Widest identity the shared column will carry at this row width.
109 pub(super) fn agent_identity_cap(width: usize) -> usize {
110 width
111 .saturating_mul(AGENT_IDENTITY_CAP_NUMERATOR)
112 .saturating_div(AGENT_IDENTITY_CAP_DENOMINATOR)
113 }
114
115 /// Which spelling of a sub-agent's identity fits the column: its nickname
116 /// first, then its fleet role, then nothing.
117 ///
118 /// Names are never truncated, only dropped. `Fluke the Deep…` and
119 /// `general-purpo…` both misidentify an agent, and roles that share a prefix
120 /// would become indistinguishable. A shell row's label is a command rather
121 /// than a name, so it is truncated instead of dropped: falling back to the
122 /// bare `shell` role would label every command row the same (#6931).
123 pub(super) fn agent_identity(row: &WorkRow, cap: usize) -> std::borrow::Cow<'_, str> {
124 use std::borrow::Cow;
125 let Some(facts) = row.agent.as_ref() else {
126 return Cow::Borrowed("");
127 };
128 if row.id.0.starts_with("shell:")
129 && !row.label.is_empty()
130 && UnicodeWidthStr::width(row.label.as_str()) > cap
131 {
132 return Cow::Owned(truncate_line_to_width(&row.label, cap));
133 }
134 for candidate in [row.label.as_str(), facts.role_label.as_str()] {
135 if !candidate.is_empty() && UnicodeWidthStr::width(candidate) <= cap {
136 return Cow::Borrowed(candidate);
137 }
138 }
139 Cow::Borrowed("")
140 }
141
142 /// Shared width of the identity column across the rows painted this frame, so
143 /// the objectives line up the way a fleet listing should read. Rows whose
144 /// identity exceeded the cap contribute nothing, so one outlier cannot widen
145 /// the column for everyone else.
146 pub(super) fn agent_identity_column(rows: &[&WorkRow], cap: usize) -> usize {
147 rows.iter()
148 .filter(|row| row.agent.is_some())
149 .map(|row| UnicodeWidthStr::width(agent_identity(row, cap).as_ref()))
150 .max()
151 .unwrap_or(0)
152 }
153
154 /// Shared width of the status-word column across the rows painted this frame.
155 /// Statuses come from a fixed vocabulary, so no cap is needed.
156 pub(super) fn agent_status_column(rows: &[&WorkRow]) -> usize {
157 rows.iter()
158 .filter_map(|row| row.agent.as_ref())
159 .map(|facts| UnicodeWidthStr::width(facts.status.as_str()))
160 .max()
161 .unwrap_or(0)
162 }
163
164 /// Fit one sub-agent row into `width`, dropping optional columns in
165 /// [`AGENT_ROW_TIERS`] order until the objective has room to say something.
166 /// Every column truncates; nothing ever wraps.
167 pub(super) fn layout_agent_row(
168 width: usize,
169 prefix_width: usize,
170 identity: &str,
171 identity_column: usize,
172 status_column: usize,
173 facts: &AgentRowFacts,
174 ) -> AgentRowText {
175 for tier in AGENT_ROW_TIERS {
176 let receipt = agent_receipt(facts, tier);
177 let role = if tier == AgentRowTier::ObjectiveOnly || identity_column == 0 {
178 String::new()
179 } else {
180 // A row whose own identity was dropped still reserves the column,
181 // so every objective on the surface stays on the same axis.
182 let pad = identity_column.saturating_sub(UnicodeWidthStr::width(identity));
183 format!("{identity}{}", " ".repeat(pad))
184 };
185 // The status word degrades with the identity: it survives the loss of
186 // tokens and elapsed, and yields only when the row is down to the
187 // objective alone.
188 let status = if tier == AgentRowTier::ObjectiveOnly || status_column == 0 {
189 String::new()
190 } else {
191 let pad = status_column.saturating_sub(UnicodeWidthStr::width(facts.status.as_str()));
192 format!("{}{}", facts.status, " ".repeat(pad))
193 };
194 let role_cost = if role.is_empty() {
195 0
196 } else {
197 UnicodeWidthStr::width(role.as_str()).saturating_add(AGENT_ROLE_GUTTER)
198 };
199 let status_cost = if status.is_empty() {
200 0
201 } else {
202 UnicodeWidthStr::width(status.as_str()).saturating_add(AGENT_ROLE_GUTTER)
203 };
204 let receipt_cost = if receipt.is_empty() {
205 0
206 } else {
207 UnicodeWidthStr::width(receipt.as_str()).saturating_add(AGENT_RECEIPT_GUTTER)
208 };
209 let budget = width
210 .saturating_sub(prefix_width)
211 .saturating_sub(role_cost)
212 .saturating_sub(status_cost)
213 .saturating_sub(receipt_cost);
214 if budget < AGENT_OBJECTIVE_MIN && tier != AgentRowTier::ObjectiveOnly {
215 continue;
216 }
217 let objective = truncate_line_to_width(&facts.objective, budget);
218 let gap = width
219 .saturating_sub(prefix_width)
220 .saturating_sub(role_cost)
221 .saturating_sub(status_cost)
222 .saturating_sub(UnicodeWidthStr::width(objective.as_str()))
223 .saturating_sub(UnicodeWidthStr::width(receipt.as_str()));
224 return AgentRowText {
225 role,
226 status,
227 objective,
228 receipt,
229 gap,
230 };
231 }
232 AgentRowText::default()
233 }
234
235 /// Normal-text and muted styles for one sub-agent row.
236 ///
237 /// Three colour roles and no more: the objective is normal text, every
238 /// secondary figure (type, `(+N)`, elapsed, tokens) is muted, and
239 /// `accent_primary` means "this is the row you have selected" and nothing
240 /// else. Status is carried by the glyph, never by colour.
241 pub(super) fn agent_row_styles(
242 app: &App,
243 selected: bool,
244 hovered: bool,
245 opened: bool,
246 ) -> (Style, Style) {
247 let bg = if selected {
248 app.ui_theme.selection_bg
249 } else if hovered {
250 app.ui_theme.elevated_bg
251 } else {
252 app.ui_theme.composer_bg
253 };
254 let mut normal = Style::default().fg(app.ui_theme.text_body).bg(bg);
255 let mut muted = Style::default().fg(app.ui_theme.text_muted).bg(bg);
256 if opened {
257 normal = normal.fg(app.ui_theme.accent_primary);
258 muted = muted.fg(app.ui_theme.accent_primary);
259 }
260 if selected {
261 normal = normal.add_modifier(Modifier::BOLD);
262 muted = muted.add_modifier(Modifier::BOLD);
263 }
264 if opened {
265 normal = normal.add_modifier(Modifier::UNDERLINED);
266 muted = muted.add_modifier(Modifier::UNDERLINED);
267 }
268 (normal, muted)
269 }
270
271 /// The one place a `WorkTone` becomes ink. Failure red is spent here and
272 /// nowhere else in the work surface; `tone_color_reserves_failure_red` pins
273 /// that against every selectable theme.
274 ///
275 /// Headings (group headers like `▾ Subagents 2`) are muted structure, not
276 /// interaction — accent_primary is reserved for selection/focus. GrokBuild
277 /// uses the same gray-on-header treatment.
278 pub(super) fn tone_color(tone: WorkTone, theme: &codewhale_palette::UiTheme) -> Color {
279 match tone {
280 WorkTone::Heading | WorkTone::Muted => theme.text_muted,
281 WorkTone::Live => theme.status_working,
282 WorkTone::Attention => theme.warning,
283 WorkTone::Failure => theme.error_fg,
284 WorkTone::Success => theme.success,
285 }
286 }
287
288 pub(super) fn row_style(
289 app: &App,
290 row: &WorkRow,
291 selected: bool,
292 hovered: bool,
293 opened: bool,
294 ) -> Style {
295 let fg = tone_color(row.tone, &app.ui_theme);
296 let mut style = Style::default().fg(fg).bg(app.ui_theme.composer_bg);
297 if row.tone == WorkTone::Heading {
298 style = style.add_modifier(Modifier::BOLD);
299 }
300 if !row.selectable {
301 return style;
302 }
303 if opened {
304 style = style
305 .fg(app.ui_theme.accent_primary)
306 .add_modifier(Modifier::BOLD | Modifier::UNDERLINED);
307 }
308 if selected {
309 style = style
310 .fg(codewhale_palette::enforce_contrast(
311 fg,
312 app.ui_theme.selection_bg,
313 4.5,
314 ))
315 .bg(app.ui_theme.selection_bg)
316 .add_modifier(Modifier::BOLD);
317 } else if hovered {
318 style = style.bg(app.ui_theme.elevated_bg);
319 }
320 style
321 }
322
323 #[cfg(test)]
324 mod tests {
325 use super::{WorkTone, tone_color};
326
327 /// Failure red is reserved for actual failure, on every preset — not just
328 /// the whale default (`docs/design/STATUS_BAR_COLOR_GRAMMAR.md`). Waiting,
329 /// blocked and stale work used to share `error_fg` with a crashed agent,
330 /// which spent the loudest ink in the palette on the routine case.
331 #[test]
332 fn tone_color_reserves_failure_red() {
333 for theme_id in codewhale_palette::SELECTABLE_THEMES {
334 let theme = theme_id.ui_theme();
335 for tone in [
336 WorkTone::Heading,
337 WorkTone::Live,
338 WorkTone::Attention,
339 WorkTone::Success,
340 WorkTone::Muted,
341 ] {
342 assert_ne!(
343 tone_color(tone, &theme),
344 theme.error_fg,
345 "theme '{}' spends Failure red on {tone:?}",
346 theme_id.name()
347 );
348 }
349 assert_eq!(
350 tone_color(WorkTone::Failure, &theme),
351 theme.error_fg,
352 "theme '{}' must still paint a real failure red",
353 theme_id.name()
354 );
355 }
356 }
357 }
358
358 lines RUST