返回 CodeWhale
phase_strip.rs
根目录 / crates / tui / src / tui / phase_strip.rs
1 //! The posture bar and the route-identity shedding it shares with the
2 //! metrics line.
3 //!
4 //! Two one-row bands sit under the composer and never trade places with
5 //! it: the **posture bar** (this module's widget — permission, mode, live
6 //! counts, the one hint that applies now, with the remote-control state or
7 //! a live notice pinned right) and the **metrics line**
8 //! (`crate::tui::infoline` — model, context, cost, ttft, tok/s, output
9 //! tokens). Both rows are reserved in every frame, so a turn moving between
10 //! idle, thinking, tool use, approval, completion, failure, and cancellation
11 //! changes text inside fixed rows and never displaces the composer.
12 //!
13 //! One owner per fact: the context reading and the price are the metrics
14 //! line's; mode, permission and the working clock are this bar's. The module
15 //! name is the historical one — the phase word it painted also lives in the
16 //! transcript's active row, but the bar keeps its own copy beside the clock
17 //! (#5914): a bare duration cannot say whether the session is producing
18 //! tokens or parked waiting on a tool, a sub-agent, or you.
19
20 use codewhale_ratatui::{PostureBar, PostureFact};
21 use ratatui::{buffer::Buffer, layout::Rect};
22 use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
23
24 use crate::tui::{
25 app::App,
26 underwater::{LiveActivity, ShellPhase, ShellTier, phase_marker_with_activity},
27 };
28 use codewhale_localization::{MessageId, tr};
29 use codewhale_palette::ChromeInk;
30
31 /// Fixed one-row reservation for the identity band below the composer.
32 #[must_use]
33 pub fn height() -> u16 {
34 1
35 }
36
37 /// Route identity for a rail or info line segment, shed field by field until it
38 /// fits `budget`.
39 ///
40 /// The old version composed the full `provider · model · effort` label and
41 /// then `truncate_to_width`'d it to a fixed 24/44/64 columns, which happily
42 /// rendered `deepseek-v4-flash-prev…`. A clipped model name is worse than no
43 /// model name: routes share prefixes, so the ellipsis is the rail admitting
44 /// it will not tell you which model is answering. Shed the qualifiers
45 /// instead — provider first, then effort — and if the bare model name still
46 /// does not fit, shed the whole group. `/model` and `/status` own the full
47 /// route either way.
48 pub(crate) fn route_identity_fields(
49 app: &App,
50 tier: ShellTier,
51 budget: usize,
52 ) -> Option<Vec<RouteIdentityField>> {
53 let (provider, model) = app.effective_route_identity_display();
54 // A route that cannot prove its effective tier states no effort field
55 // rather than `high→effective unavailable` (#5950): a placeholder that
56 // can never resolve is noise, not a reading. First-party routes keep
57 // their tier and `req→eff` labels.
58 // Labeled, so a bare "max" never sits on the row unexplained (mark 8).
59 let effort = app
60 .provable_reasoning_effort_label()
61 .map(|level| {
62 app.tr(MessageId::InfoLineThinking)
63 .replace("{level}", &level)
64 })
65 .unwrap_or_default();
66 if model.is_empty() {
67 return None;
68 }
69 let field = |kind, text: String| RouteIdentityField { kind, text };
70 let mut candidates: Vec<Vec<RouteIdentityField>> = Vec::new();
71 if tier != ShellTier::Compact && !provider.is_empty() {
72 // The smallest shell never repeats the provider: model and effort are
73 // the two facts that change what comes back.
74 let mut fields = vec![
75 field(RouteFieldKind::Provider, provider),
76 field(RouteFieldKind::Model, model.clone()),
77 ];
78 if !effort.is_empty() {
79 fields.push(field(RouteFieldKind::Effort, effort.clone()));
80 }
81 candidates.push(fields);
82 }
83 if !effort.is_empty() {
84 candidates.push(vec![
85 field(RouteFieldKind::Model, model.clone()),
86 field(RouteFieldKind::Effort, effort),
87 ]);
88 }
89 candidates.push(vec![field(RouteFieldKind::Model, model)]);
90 candidates.into_iter().find(|fields| {
91 let width = fields.iter().map(|field| field.text.width()).sum::<usize>()
92 + fields.len().saturating_sub(1) * ITEM_SEPARATOR_WIDTH;
93 width <= budget
94 })
95 }
96
97 /// Which route fact a rendered field is. The info line needs this to send a
98 /// click to the surface that owns the fact the user pointed at: the provider
99 /// name to `/provider`, the model and its effort tier to `/model`.
100 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
101 pub(crate) enum RouteFieldKind {
102 Provider,
103 Model,
104 Effort,
105 }
106
107 /// One rendered route field: what it says, and what it is.
108 #[derive(Debug, Clone, PartialEq, Eq)]
109 pub(crate) struct RouteIdentityField {
110 pub kind: RouteFieldKind,
111 pub text: String,
112 }
113
114 /// The info line's route budget: reserve 60 columns for other metrics, with
115 /// a floor that grows from 24 to 32 columns with half the row's width. This
116 /// keeps longer effort labels at 80 columns without crowding narrower rows.
117 ///
118 /// One owner. The rule used to be written out at the call site in
119 /// `ui/frame.rs` and copied again into two tests with a comment pointing
120 /// back at the original, which is how a shed rule drifts.
121 pub(crate) fn info_route_budget(width: u16) -> usize {
122 let width = usize::from(width);
123 width.saturating_sub(60).max((width / 2).clamp(24, 32))
124 }
125
126 pub(crate) fn bare_model_reading(model: String, width: u16, context: Option<(&str, u8)>) -> String {
127 let Some((label, percent)) = context else {
128 return model;
129 };
130 let context_width = label.width() + 1 + format!("{percent}%").width();
131 if model.width() + ITEM_SEPARATOR_WIDTH + context_width > usize::from(width) {
132 "/model".to_owned()
133 } else {
134 model
135 }
136 }
137
138 /// Split a notice at its joints, coarsest first.
139 ///
140 /// A rail notice is prose, and prose has joints. Cutting at a joint keeps
141 /// every word that survives true; cutting mid-phrase and hanging an ellipsis
142 /// off the end only advertises that the row lost the argument. Sentence stops
143 /// are the joint we want; the inner marks are the fallback for a one-sentence
144 /// notice that is still too long for a narrow rail — losing the second half
145 /// of `Auto-denied exec_shell: denied earlier` beats losing the warning.
146 fn notice_clauses<'a>(text: &'a str, marks: &[char]) -> Vec<&'a str> {
147 let mut clauses = Vec::new();
148 let mut start = 0usize;
149 let mut chars = text.char_indices().peekable();
150 while let Some((idx, ch)) = chars.next() {
151 if !marks.contains(&ch) {
152 continue;
153 }
154 // Full-width marks carry no trailing space, so they break on sight.
155 // Other marks only break before whitespace, which keeps `0.9.11`,
156 // `docs/TELEMETRY.md`, and `https://…` in one piece.
157 let breaks =
158 ch.width() == Some(2) || chars.peek().is_none_or(|(_, next)| next.is_whitespace());
159 if !breaks {
160 continue;
161 }
162 // `1.` opening a numbered step is a list ordinal, not a sentence
163 // stop — breaking there leaves the toast ending on a bare `1.`
164 // (the send-blocked clip: `…not found. 1.`). Only the pure
165 // number-and-stop shape is exempt; `Version 1.` still ends a clause.
166 if ch == '.'
167 && text[start..idx].trim().bytes().all(|b| b.is_ascii_digit())
168 && !text[start..idx].trim().is_empty()
169 {
170 continue;
171 }
172 let end = idx + ch.len_utf8();
173 let clause = text[start..end].trim();
174 if !clause.is_empty() {
175 clauses.push(clause);
176 }
177 start = end;
178 }
179 let rest = text[start..].trim();
180 if !rest.is_empty() {
181 clauses.push(rest);
182 }
183 clauses
184 }
185
186 /// Sentence stops — the joint a notice prefers to be cut at.
187 const SENTENCE_MARKS: [char; 7] = ['.', '!', '?', '…', '。', '!', '?'];
188 /// Inner joints, used only when one sentence still will not fit the rail.
189 const CLAUSE_MARKS: [char; 8] = [';', ':', ',', '—', ';', ':', ',', '、'];
190
191 fn join_while_fitting(clauses: &[&str], budget: usize) -> Option<String> {
192 let mut fitted = String::new();
193 for clause in clauses {
194 // A full-width stop already carries its own breathing room; putting
195 // a Latin space after `。` is a typographic accent in the wrong
196 // language.
197 let space =
198 usize::from(!fitted.is_empty() && !fitted.ends_with(|ch: char| ch.width() == Some(2)));
199 let candidate = fitted.width() + space + clause.width();
200 if candidate > budget {
201 break;
202 }
203 if space == 1 {
204 fitted.push(' ');
205 }
206 fitted.push_str(clause);
207 }
208 // A phrase that ends on `:` or `;` is still telling you more is coming —
209 // the same lie an ellipsis tells. Cut the mark and let the phrase stand.
210 let fitted = fitted
211 .trim_end_matches(|ch| CLAUSE_MARKS.contains(&ch) || ch == ' ')
212 .to_string();
213 (!fitted.is_empty()).then_some(fitted)
214 }
215
216 /// Fit a notice into `budget` by dropping whole trailing clauses.
217 ///
218 /// Returns `None` only when not even the first inner phrase fits and the
219 /// notice is not urgent; an urgent notice is truncated rather than dropped.
220 /// Notices get first call on the row: identity and the ledger chips have
221 /// already stood down by the time this is asked, and the key hints stand down
222 /// after it if that is what the notice needs.
223 fn fit_notice(text: &str, budget: usize, urgent: bool) -> Option<String> {
224 let text = text.trim();
225 if text.is_empty() || budget == 0 {
226 return None;
227 }
228 if text.width() <= budget {
229 return Some(text.to_string());
230 }
231 let sentences = notice_clauses(text, &SENTENCE_MARKS);
232 if let Some(fitted) = join_while_fitting(&sentences, budget) {
233 return Some(fitted);
234 }
235 let first = sentences.first().copied().unwrap_or(text);
236 let clauses = notice_clauses(first, &CLAUSE_MARKS);
237 let Some(fitted) = join_while_fitting(&clauses, budget) else {
238 return if urgent {
239 truncate_notice(text, budget)
240 } else {
241 None
242 };
243 };
244 // A one-word label whose value was shed is not a notice, it is a false
245 // one: `Thinking: high → max · model qwen` cut to `Thinking` sat in an
246 // idle footer reading as if a turn were thinking (experience mark 8).
247 // A phrase before the colon (`Auto-denied exec_shell`) still stands.
248 let bare_label = clauses
249 .first()
250 .is_some_and(|label| label.ends_with([':', ':']))
251 && !fitted.contains(char::is_whitespace);
252 if bare_label {
253 return if urgent {
254 truncate_notice(text, budget)
255 } else {
256 None
257 };
258 }
259 Some(fitted)
260 }
261
262 fn truncate_notice(text: &str, budget: usize) -> Option<String> {
263 let text = text.trim();
264 if text.is_empty() || budget == 0 {
265 return None;
266 }
267 let mut fitted = String::new();
268 let mut used = 0usize;
269 for ch in text.chars() {
270 let width = ch.width().unwrap_or(0);
271 if used + width + 1 > budget {
272 break;
273 }
274 fitted.push(ch);
275 used += width;
276 }
277 let mut fitted = fitted.trim_end().to_string();
278 if let Some(space) = fitted.rfind(char::is_whitespace) {
279 fitted.truncate(space);
280 }
281 let fitted = fitted.trim_end();
282 (!fitted.is_empty()).then(|| format!("{fitted}…"))
283 }
284
285 /// Map the boot surface's typed severity through the same semantic palette as
286 /// every other footer fact. Keeping this conversion closed makes the plugin
287 /// warning/failure distinction testable without guessing from its text.
288 fn boot_activity_ink(level: crate::tui::session_boot::SessionBootActivityLevel) -> ChromeInk {
289 match level {
290 crate::tui::session_boot::SessionBootActivityLevel::Active => ChromeInk::Active,
291 crate::tui::session_boot::SessionBootActivityLevel::Attention => ChromeInk::Attention,
292 crate::tui::session_boot::SessionBootActivityLevel::Failure => ChromeInk::Failure,
293 }
294 }
295
296 /// Pick the notice a band owes its row to right now, if any. Shared by the
297 /// classic activity band and the Tideline merged footer so the two can never
298 /// disagree about which toast is live. Completion may land in the same event
299 /// drain as an approval denial: unresolved Warning/Error receipts stay
300 /// visible after `done`, only routine informational copy yields.
301 fn fit_notice_candidates(
302 text: &str,
303 fallbacks: &[String],
304 budget: usize,
305 urgent: bool,
306 ) -> Option<String> {
307 if text.trim().width() <= budget {
308 return fit_notice(text, budget, urgent);
309 }
310 if let Some(candidate) = fallbacks
311 .iter()
312 .map(|item| item.trim())
313 .find(|item| !item.is_empty() && item.width() <= budget)
314 {
315 return Some(candidate.to_string());
316 }
317 fit_notice(text, budget, urgent)
318 }
319
320 fn selected_notice(
321 status_toast: Option<crate::tui::app::StatusToast>,
322 phase_label: &str,
323 ) -> Option<(String, Vec<String>, ChromeInk, bool)> {
324 status_toast
325 .filter(|toast| !toast.text.trim().is_empty() && toast.text.trim() != phase_label)
326 .map(|toast| {
327 let urgent = matches!(
328 toast.level,
329 crate::tui::app::StatusToastLevel::Warning
330 | crate::tui::app::StatusToastLevel::Error
331 );
332 (
333 toast.text.clone(),
334 toast.fallback_texts.clone(),
335 toast.level.ink(),
336 urgent,
337 )
338 })
339 }
340
341 /// Provider/model fields retain their internal separator width when shed.
342 const ITEM_SEPARATOR_WIDTH: usize = 3;
343
344 #[cfg(test)]
345 mod tests {
346 use super::*;
347 use crate::tui::app::TuiOptions;
348 use codewhale_runtime::config::Config;
349 use std::path::PathBuf;
350
351 fn test_app() -> App {
352 App::new(
353 TuiOptions {
354 model: "deepseek-v4-flash".to_string(),
355 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
356 },
357 &Config::default(),
358 )
359 }
360
361 #[test]
362 fn done_footer_preserves_unresolved_notice_behind_later_routine_info() {
363 use crate::tui::app::StatusToastLevel;
364 for (level, ink) in [
365 (StatusToastLevel::Warning, ChromeInk::Attention),
366 (StatusToastLevel::Error, ChromeInk::Failure),
367 ] {
368 let mut app = test_app();
369 app.runtime_turn_status = Some("completed".into());
370 app.push_status_toast("Unresolved issue", level, Some(12_000));
371 app.push_status_toast("Routine update", StatusToastLevel::Info, Some(5_000));
372 assert_eq!(ShellPhase::from_app(&app), ShellPhase::Done);
373 assert!(
374 app.history.is_empty(),
375 "the transcript must not satisfy this fixture"
376 );
377 let facts = tideline_footer_from_app(&mut app, 140);
378 assert_eq!(facts.right, Some(("Unresolved issue".into(), ink)));
379 let mut buf = Buffer::empty(Rect::new(0, 0, 140, 1));
380 render_tideline_footer(
381 Rect::new(0, 0, 140, 1),
382 &mut buf,
383 &facts.widget(&app.ui_theme, false),
384 );
385 let text: String = buf.content.iter().map(|cell| cell.symbol()).collect();
386 assert!(text.contains("Unresolved issue"), "{text}");
387 assert!(!text.contains("Routine update"));
388 }
389 }
390
391 #[test]
392 fn boot_activity_levels_keep_plugin_attention_and_failure_distinct() {
393 use crate::tui::session_boot::SessionBootActivityLevel;
394
395 assert_eq!(
396 boot_activity_ink(SessionBootActivityLevel::Active),
397 ChromeInk::Active
398 );
399 assert_eq!(
400 boot_activity_ink(SessionBootActivityLevel::Attention),
401 ChromeInk::Attention
402 );
403 assert_eq!(
404 boot_activity_ink(SessionBootActivityLevel::Failure),
405 ChromeInk::Failure
406 );
407 }
408
409 #[test]
410 fn notice_clauses_split_on_sentences_and_keep_versions_and_paths_whole() {
411 assert_eq!(
412 notice_clauses(
413 "Counts are on. Code is never collected. See docs/T.md",
414 &SENTENCE_MARKS
415 ),
416 vec![
417 "Counts are on.",
418 "Code is never collected.",
419 "See docs/T.md"
420 ]
421 );
422 assert_eq!(
423 notice_clauses("Updated to 0.9.11 from 0.9.10", &SENTENCE_MARKS),
424 vec!["Updated to 0.9.11 from 0.9.10"]
425 );
426 // Full-width stops carry no trailing space, so they break on sight.
427 assert_eq!(
428 notice_clauses(
429 "匿名の利用回数は有効です。会話とコードは収集されません。",
430 &SENTENCE_MARKS
431 ),
432 vec![
433 "匿名の利用回数は有効です。",
434 "会話とコードは収集されません。"
435 ]
436 );
437 // A colon inside a URL is not a joint.
438 assert_eq!(
439 notice_clauses("Docs: https://example.test/x", &CLAUSE_MARKS),
440 vec!["Docs:", "https://example.test/x"]
441 );
442 }
443
444 #[test]
445 fn shed_clauses_rejoin_without_a_latin_space_after_a_full_width_stop() {
446 const JA: &str = "匿名の利用状況集計はオンです。会話やコードは一切収集しません。/settings で変更できます。スキーマ: docs/TELEMETRY.md";
447 let clauses = notice_clauses(JA, &SENTENCE_MARKS);
448 let joined = join_while_fitting(&clauses, 200).expect("fits");
449 assert!(!joined.contains("。 "), "{joined:?}");
450 assert!(joined.ends_with("docs/TELEMETRY.md"), "{joined:?}");
451 }
452
453 #[test]
454 fn a_notice_sheds_whole_clauses_and_never_dangles() {
455 const NOTICE: &str = "Usage reporting is on. Conversations and code are never collected. Change this in /settings; schema: docs/TELEMETRY.md";
456 assert_eq!(fit_notice(NOTICE, 200, false).as_deref(), Some(NOTICE));
457 assert_eq!(
458 fit_notice(NOTICE, 80, false).as_deref(),
459 Some("Usage reporting is on. Conversations and code are never collected.")
460 );
461 assert_eq!(
462 fit_notice(NOTICE, 40, false).as_deref(),
463 Some("Usage reporting is on.")
464 );
465 assert_eq!(fit_notice(" ", 40, false), None);
466 }
467
468 /// Experience mark 8: a `/model` thinking change on a narrow rail used to
469 /// shed to a bare `Thinking`, which read as a live indicator with nothing
470 /// running. A label whose value cannot fit says nothing instead.
471 #[test]
472 fn a_label_never_sheds_to_a_bare_word_that_reads_as_activity() {
473 let notice = "Thinking: high → max · model deepseek-v4-flash";
474 assert_eq!(fit_notice(notice, 40, false), None);
475 assert_eq!(
476 fit_notice("思考:高 → 最高 · 模型 deepseek-v4-flash", 12, false),
477 None
478 );
479 // Room for the whole reading keeps it whole.
480 assert_eq!(fit_notice(notice, 60, false).as_deref(), Some(notice));
481 // A phrase before the colon is still a notice on its own.
482 assert_eq!(
483 fit_notice(
484 "Auto-denied exec_shell: denied earlier this turn",
485 30,
486 false
487 )
488 .as_deref(),
489 Some("Auto-denied exec_shell")
490 );
491 }
492
493 /// The failure this caught: a one-sentence warning longer than the row
494 /// used to have no sentence joint to shed at, so the rail dropped the
495 /// whole warning. Inner joints are the fallback, and the phrase that
496 /// survives never ends on a `:` or `;` — that mark says "more is coming"
497 /// as loudly as an ellipsis does.
498 #[test]
499 fn a_clause_less_warning_sheds_at_inner_joints_rather_than_vanishing() {
500 const WARNING: &str =
501 "Auto-denied exec_shell: denied earlier; restart Codewhale to re-enable it.";
502 assert_eq!(fit_notice(WARNING, 120, false).as_deref(), Some(WARNING));
503 assert_eq!(
504 fit_notice(WARNING, 60, false).as_deref(),
505 Some("Auto-denied exec_shell: denied earlier")
506 );
507 assert_eq!(
508 fit_notice(WARNING, 30, false).as_deref(),
509 Some("Auto-denied exec_shell")
510 );
511 }
512
513 #[test]
514 fn session_metrics_strip_is_on_by_default() {
515 assert!(
516 codewhale_runtime::config::StatusItem::default_footer()
517 .contains(&codewhale_runtime::config::StatusItem::Ttft)
518 && codewhale_runtime::config::StatusItem::default_footer()
519 .contains(&codewhale_runtime::config::StatusItem::OutputRate)
520 );
521 assert_eq!(
522 codewhale_runtime::config::StatusItem::from_key("session_metrics"),
523 Some(codewhale_runtime::config::StatusItem::SessionMetrics)
524 );
525 }
526
527 /// The route identity (the info line Model segment's value) sheds whole
528 /// fields — provider first, then the effort label — and stands down
529 /// entirely rather than clip a model name. Ported from the identity
530 /// band to `route_identity_fields`, the live shedding authority the
531 /// info line calls with the same budget rule.
532 #[test]
533 fn route_identity_sheds_qualifiers_before_it_would_clip_a_model_name() {
534 let model = "deepseek-v4-flash-preview-2026-05-01";
535 let mut app = App::new(
536 TuiOptions {
537 model: model.to_string(),
538 ..crate::tui::test_support::test_tui_options(PathBuf::from("."))
539 },
540 &Config::default(),
541 );
542 app.ui_locale = codewhale_localization::Locale::En;
543
544 // Use the info line's own budget rule, including its adaptive floor.
545 let fields = |width: u16| {
546 route_identity_fields(
547 &app,
548 ShellTier::for_chrome_width(width),
549 info_route_budget(width),
550 )
551 };
552
553 let wide = fields(140).expect("wide budget keeps the route");
554 assert!(
555 wide.iter().any(|f| f.text.contains("DeepSeek"))
556 && wide.iter().any(|f| f.text == model),
557 "{wide:?}"
558 );
559
560 // Below the group's width the provider sheds first; the model stays
561 // whole or the whole group stands down — never a clipped name.
562 for width in [30u16, 34, 40, 46, 50, 60] {
563 let shed = fields(width).unwrap_or_default();
564 for field in &shed {
565 assert!(
566 !field.text.contains('…'),
567 "{width} dangled a clipped field: {shed:?}"
568 );
569 }
570 if shed.iter().any(|f| f.text.contains("deepseek-v4-flash-p")) {
571 assert!(
572 shed.iter().any(|f| f.text == model),
573 "{width} clipped the model name: {shed:?}"
574 );
575 }
576 }
577 }
578
579 /// A named custom route can carry a long provider identity next to a
580 /// long model id; whole fields shed (provider first, effort label next)
581 /// and neither name is ever clipped. Ported from the identity band to
582 /// `route_identity_fields`.
583 #[test]
584 fn unproven_effort_keeps_named_provider_when_the_route_fits() {
585 let mut app = test_app();
586 app.set_provider_identity(codewhale_config::ProviderKind::Custom, "lab-gateway");
587 app.model = "unlisted-model".to_string();
588 assert!(app.provable_reasoning_effort_label().is_none());
589 let fields = route_identity_fields(&app, ShellTier::for_chrome_width(160), 100).unwrap();
590 assert_eq!(
591 fields.iter().map(|field| field.kind).collect::<Vec<_>>(),
592 vec![RouteFieldKind::Provider, RouteFieldKind::Model]
593 );
594 assert_eq!(fields[0].text, "lab-gateway");
595 assert_eq!(fields[1].text, "unlisted-model");
596 let compact = route_identity_fields(&app, ShellTier::Compact, 100).unwrap();
597 assert_eq!(compact.len(), 1);
598 assert_eq!(compact[0].kind, RouteFieldKind::Model);
599 let narrow = route_identity_fields(&app, ShellTier::for_chrome_width(160), 14).unwrap();
600 assert_eq!(narrow.len(), 1);
601 assert_eq!(narrow[0].text, "unlisted-model");
602 }
603
604 #[test]
605 fn long_custom_route_names_shed_whole_fields_across_width_tiers() {
606 let model = "deepseek-v4-flash-vision-preview-2026-08-01";
607 let mut app = test_app();
608 app.ui_locale = codewhale_localization::Locale::En;
609 app.set_provider_identity(
610 codewhale_config::ProviderKind::Custom,
611 "acme-research-gateway-eu-central",
612 );
613 app.model = model.to_string();
614
615 for width in [30u16, 40, 50, 60, 70, 80, 160] {
616 let shed = route_identity_fields(
617 &app,
618 ShellTier::for_chrome_width(width),
619 info_route_budget(width),
620 )
621 .unwrap_or_default();
622 for field in &shed {
623 assert!(
624 !field.text.contains('…'),
625 "{width} dangled a clipped field: {shed:?}"
626 );
627 }
628 if shed
629 .iter()
630 .any(|f| f.text.contains("deepseek-v4-flash-vision"))
631 {
632 assert!(
633 shed.iter().any(|f| f.text == model),
634 "{width} clipped the model name: {shed:?}"
635 );
636 }
637 assert!(
638 !shed
639 .iter()
640 .any(|f| f.text.contains("acme-research-gateway-eu-c")
641 && f.text != "acme-research-gateway-eu-central"),
642 "{width} clipped the provider name: {shed:?}"
643 );
644 }
645 }
646 }
647
648 // ---------------------------------------------------------------------------
649 // Tideline merged footer (spec §3 slots 6+8 merged, §5a "Footer"): one
650 // band — phase·cost on the left, the notice/keys slot on the right.
651 // Wired into `ui/frame.rs` as the shell's single footer row: the classic
652 // activity band (slot 6) and identity band (slot 8) collapsed into it, with
653 // the permission dial chip carried in the left half.
654 // ---------------------------------------------------------------------------
655 // The posture bar (SHELL-DESIGN-20260901 §2.0 item 3, §2.3b; founder
656 // direction 2026-09-02): the first row under the composer, in Claude Code's
657 // grammar —
658 //
659 // ● full access Shift+Tab to change 2 agents, 1 task Esc to interrupt rc connected
660 //
661 // the permission dial chip first (never sheds, #5796), marked `●` so the
662 // current stop reads without color (experience mark 8) and followed by what
663 // its key does, then the turn clock, the
664 // live counts, the session clock, then the one hint that applies right now;
665 // the remote-control state or a live notice pinned right. No cost: the
666 // roster owns per-agent elapsed and the metrics line owns the price. The
667 // context reading is the metrics line's; this row only says what to do about
668 // it at the cap.
669 //
670 // The clock came back in #5914. It was the `worked Nm Ss` chip on the
671 // classic footer until `146ab7f756` deleted that path, and the phase band's
672 // `working_detail` until `329960fcbf` (the 0.9.12 mega shell) merged the
673 // bands and left the elapsed reading to the transcript's active row. A
674 // multi-hour session scrolls that row out of sight, so the founder
675 // looking straight at the screen had no way to tell how long the session had
676 // been working or whether the current turn was stuck. The fixed row is where
677 // a glancing user looks; the clock lives here.
678 // ---------------------------------------------------------------------------
679
680 pub struct TidelineFooter<'a> {
681 pub theme: &'a codewhale_palette::UiTheme,
682 /// Permission dial chip (`Ask` / `Accept Edits` / `Plan` / `Auto-Review` /
683 /// `Full Access`, plus the filesystem scope notice when it deviates) in
684 /// its ink. Never sheds.
685 pub permission_chip: (&'a str, codewhale_palette::ChromeInk),
686 /// What the permission key does, when the binding is live for the
687 /// current focus and not yet learned (`Shift+Tab to change`). Painted
688 /// after the chip in hint ink.
689 pub permission_key: Option<&'a str>,
690 /// The turn half of the working clock (`working 1m 15s`): what the
691 /// session is doing right now, including a pending decision between timed turns.
692 pub turn_clock: Option<(&'a str, codewhale_palette::ChromeInk)>,
693 /// Live counts (`2 agents`, `1 task`) in their own inks, joined with
694 /// `, `.
695 pub counts: &'a [(String, ChromeInk)],
696 /// The session half of the working clock (`worked 41m 12s`): how long
697 /// this session has actually worked — the reading the founder went
698 /// looking for and could not find (#5914). Outlives the turn half, and
699 /// sheds before the hint and the counts. `None` until the session has
700 /// worked a minute, and while it would repeat the turn reading (#6041).
701 pub session_clock: Option<(&'a str, codewhale_palette::ChromeInk)>,
702 /// The one hint that applies right now (`Esc to interrupt`).
703 pub hint: Option<(&'a str, codewhale_palette::ChromeInk)>,
704 /// Context window percentage 0–100. The metrics line paints the reading;
705 /// this bar only uses it to decide whether the ≥80% cap warning outranks
706 /// `hint`.
707 pub context_percent: u8,
708 /// Pinned right: a live notice (status toast / boot activity chip) or
709 /// the remote-control state.
710 pub right: Option<(&'a str, codewhale_palette::ChromeInk)>,
711 pub ascii_safe: bool,
712 pub locale: codewhale_localization::Locale,
713 /// `tui.posture_bar = "compact"` (#5950): start the shed ladder at
714 /// the kit's compact rung instead of rung 0, so the row states its posture —
715 /// the permission dial chip, and the cap warning when it is owed —
716 /// and nothing live. Width sheds the rest exactly as it always did.
717 pub compact: bool,
718 working_glow: Option<(
719 codewhale_ratatui::Caps,
720 std::time::Duration,
721 codewhale_ratatui::MotionMode,
722 )>,
723 }
724
725 impl<'a> TidelineFooter<'a> {
726 #[must_use]
727 pub fn new(
728 theme: &'a codewhale_palette::UiTheme,
729 permission_chip: (&'a str, codewhale_palette::ChromeInk),
730 ) -> Self {
731 Self {
732 theme,
733 permission_chip,
734 permission_key: None,
735 turn_clock: None,
736 counts: &[],
737 session_clock: None,
738 hint: None,
739 context_percent: 0,
740 right: None,
741 ascii_safe: false,
742 locale: codewhale_localization::Locale::En,
743 compact: false,
744 working_glow: None,
745 }
746 }
747
748 #[must_use]
749 pub fn locale(mut self, locale: codewhale_localization::Locale) -> Self {
750 self.locale = locale;
751 self
752 }
753
754 #[must_use]
755 pub fn permission_key(mut self, key: Option<&'a str>) -> Self {
756 self.permission_key = key;
757 self
758 }
759
760 #[must_use]
761 pub fn turn_clock(mut self, clock: Option<(&'a str, codewhale_palette::ChromeInk)>) -> Self {
762 self.turn_clock = clock;
763 self
764 }
765
766 #[must_use]
767 pub fn session_clock(mut self, clock: Option<(&'a str, codewhale_palette::ChromeInk)>) -> Self {
768 self.session_clock = clock;
769 self
770 }
771
772 #[must_use]
773 pub fn counts(mut self, counts: &'a [(String, ChromeInk)]) -> Self {
774 self.counts = counts;
775 self
776 }
777
778 #[must_use]
779 pub fn hint(mut self, hint: Option<(&'a str, codewhale_palette::ChromeInk)>) -> Self {
780 self.hint = hint;
781 self
782 }
783
784 #[must_use]
785 pub fn context_percent(mut self, percent: u8) -> Self {
786 self.context_percent = percent;
787 self
788 }
789
790 #[must_use]
791 pub fn right(mut self, right: Option<(&'a str, codewhale_palette::ChromeInk)>) -> Self {
792 self.right = right;
793 self
794 }
795
796 #[must_use]
797 pub fn ascii_safe(mut self, ascii_safe: bool) -> Self {
798 self.ascii_safe = ascii_safe;
799 self
800 }
801
802 #[must_use]
803 pub fn compact(mut self, compact: bool) -> Self {
804 self.compact = compact;
805 self
806 }
807
808 pub(crate) fn working_glow(
809 mut self,
810 glow: Option<(
811 codewhale_ratatui::Caps,
812 std::time::Duration,
813 codewhale_ratatui::MotionMode,
814 )>,
815 ) -> Self {
816 self.working_glow = glow;
817 self
818 }
819
820 pub(crate) fn working_clock_visible(&self, area: Rect) -> bool {
821 self.kit()
822 .turn_clock_hitbox(area, &crate::tui::infoline::source_theme(self.ascii_safe))
823 .is_some()
824 }
825
826 fn kit(&self) -> PostureBar<'_> {
827 use crate::tui::infoline::ink_role;
828 let mut bar = PostureBar::new(self.permission_chip.0)
829 .permission_role(ink_role(self.permission_chip.1))
830 .context_percent(self.context_percent)
831 .cap_warning(tr(self.locale, MessageId::PostureDepthWarn))
832 .compact(self.compact);
833 bar.permission_key = self.permission_key.map(Into::into);
834 bar.turn_clock = self.turn_clock.map(posture_fact);
835 bar.awaiting_decision = self
836 .turn_clock
837 .is_some_and(|(_, ink)| ink == ChromeInk::Waiting);
838 bar.counts = self
839 .counts
840 .iter()
841 .map(|(text, ink)| PostureFact::new(text.as_str(), ink_role(*ink)))
842 .collect();
843 bar.session_clock = self.session_clock.map(posture_fact);
844 bar.hint = self.hint.map(posture_fact);
845 bar.right = self.right.map(posture_fact);
846 bar
847 }
848 }
849
850 fn posture_fact((text, ink): (&str, ChromeInk)) -> PostureFact<'_> {
851 PostureFact::new(text, crate::tui::infoline::ink_role(ink))
852 }
853
854 /// Paint the posture bar and return each live count's exact visible cells.
855 /// The kit owns the one shared shedding, projection, clipping and pointer
856 /// layout. Engine facts, localized text, clock lifecycle, live theme and
857 /// action routing remain with the callers.
858 pub fn render_tideline_footer(
859 area: Rect,
860 buf: &mut Buffer,
861 footer: &TidelineFooter<'_>,
862 ) -> Vec<(usize, Rect)> {
863 use crate::tui::infoline::{paint_native_row, source_theme};
864 let area = area.intersection(buf.area);
865 let bar = footer.kit();
866 let count_rects = bar.count_hitboxes(area, &source_theme(footer.ascii_safe));
867 paint_native_row(&bar, area, buf, footer.theme, footer.ascii_safe);
868 if let Some((mut caps, elapsed, motion)) = footer.working_glow
869 && let Some((label, _)) = footer.turn_clock
870 && let Some(clock_area) = bar.turn_clock_hitbox(area, &source_theme(footer.ascii_safe))
871 && let Some(appearance) =
872 codewhale_ratatui::detect::appearance_for_background(footer.theme.footer_bg)
873 {
874 caps.appearance = appearance;
875 let theme = codewhale_ratatui::Theme::new(caps);
876 codewhale_ratatui::paint_working_glow_oklab(
877 buf,
878 clock_area,
879 label,
880 elapsed,
881 codewhale_ratatui::MotionPolicy::new(motion, &theme),
882 footer.theme.text_body,
883 footer.theme.footer_bg,
884 );
885 }
886 count_rects
887 }
888
889 /// Owned posture facts, built from real `App` state at render time and lent
890 /// to [`TidelineFooter`] for painting.
891 pub(crate) struct TidelineFooterFacts {
892 pub permission_chip: (String, codewhale_palette::ChromeInk),
893 /// `Shift+Tab to change`, localized, while the binding is live and not
894 /// yet learned.
895 pub permission_key: Option<String>,
896 pub turn_clock: ClockReading,
897 pub counts: Vec<(String, ChromeInk)>,
898 pub session_clock: ClockReading,
899 /// The action each entry of `counts` runs when clicked — same
900 /// length, same order.
901 pub count_actions: Vec<crate::tui::tideline::InteractionAction>,
902 pub hint: Option<(String, codewhale_palette::ChromeInk)>,
903 pub context_percent: u8,
904 pub right: Option<(String, codewhale_palette::ChromeInk)>,
905 pub locale: codewhale_localization::Locale,
906 }
907
908 impl TidelineFooterFacts {
909 /// Borrow the facts as the deterministic widget's input.
910 pub(crate) fn widget<'a>(
911 &'a self,
912 theme: &'a codewhale_palette::UiTheme,
913 ascii_safe: bool,
914 ) -> TidelineFooter<'a> {
915 let borrow = |chip: &'a Option<(String, ChromeInk)>| {
916 chip.as_ref().map(|(text, ink)| (text.as_str(), *ink))
917 };
918 TidelineFooter::new(
919 theme,
920 (self.permission_chip.0.as_str(), self.permission_chip.1),
921 )
922 .permission_key(self.permission_key.as_deref())
923 .turn_clock(borrow(&self.turn_clock))
924 .counts(&self.counts)
925 .session_clock(borrow(&self.session_clock))
926 .hint(borrow(&self.hint))
927 .context_percent(self.context_percent)
928 .right(borrow(&self.right))
929 .ascii_safe(ascii_safe)
930 .locale(self.locale)
931 }
932 }
933
934 /// The session has to have worked this long before the bar states a total.
935 /// A fresh launch that says `worked 4s` is furniture, not information; the
936 /// classic footer's `worked` chip used the same floor (#448).
937 const CLOCK_SESSION_FLOOR_SECS: u64 = 60;
938
939 /// One half of the working clock: its text and the ink that says whether the
940 /// clock is running. `None` when that half has nothing true to say.
941 pub(crate) type ClockReading = Option<(String, ChromeInk)>;
942
943 /// The working clock (#5914), as its two halves — `(turn, session)`.
944 ///
945 /// * the **turn** reading is `{phase_label} {elapsed}` — the phase word is
946 /// the transcript's own, so `working 1m 15s` and `waiting on you 1m 15s`
947 /// and `sub-agents underway 1m 15s` all say what the clock is counting.
948 /// A duration alone cannot distinguish a session producing tokens from one
949 /// parked on a tool, a sub-agent, or an unanswered prompt. A pending decision
950 /// without a turn clock carries its phase label alone.
951 /// * the **session** reading is the classic `worked {elapsed}` chip (#448):
952 /// `App::cumulative_turn_duration` (the sum of finished turns) plus the
953 /// live turn, so it ticks continuously and never jumps at `TurnComplete`.
954 /// It is model work, not wall clock since launch — an idle TUI does not
955 /// claim to have been working. Quiet ink while no turn is running, because
956 /// the clock is stopped. Suppressed while it would repeat the turn
957 /// reading — on a session's first turn the two are the same duration
958 /// (#6041); it returns as soon as a finished turn makes the totals
959 /// different.
960 pub(crate) fn working_clock(
961 app: &App,
962 phase: ShellPhase,
963 phase_label: &str,
964 ) -> (ClockReading, ClockReading) {
965 let turn = app.turn_started_at.map(|started| started.elapsed());
966 let ink = match phase {
967 ShellPhase::Waiting | ShellPhase::Approval => ChromeInk::Waiting,
968 ShellPhase::Failed => ChromeInk::Attention,
969 _ => ChromeInk::Active,
970 };
971 let turn_clock = turn
972 .map(|turn| {
973 (
974 format!(
975 "{phase_label} {}",
976 codewhale_command_contract::elapsed::format_elapsed_secs(turn.as_secs())
977 ),
978 ink,
979 )
980 })
981 .or_else(|| {
982 matches!(phase, ShellPhase::Waiting | ShellPhase::Approval)
983 .then(|| (phase_label.to_owned(), ink))
984 });
985 let worked = app
986 .cumulative_turn_duration
987 .saturating_add(turn.unwrap_or_default());
988 // #6041: on a session's first turn there is no finished-turn total, so
989 // the session reading would print the same duration the turn reading
990 // already carries. The turn half names what is happening; the worked
991 // chip earns its place only once a finished turn makes it a different
992 // number.
993 let repeats_turn = turn.is_some_and(|turn| turn.as_secs() == worked.as_secs());
994 let session_clock =
995 (worked.as_secs() >= CLOCK_SESSION_FLOOR_SECS && !repeats_turn).then(|| {
996 (
997 tr(app.ui_locale, MessageId::FooterWorkedChip).replace(
998 "{duration}",
999 &codewhale_command_contract::elapsed::format_elapsed_secs(worked.as_secs()),
1000 ),
1001 if turn.is_some() {
1002 ink
1003 } else {
1004 ChromeInk::MetadataValue
1005 },
1006 )
1007 });
1008 (turn_clock, session_clock)
1009 }
1010
1011 /// Context window percentage — the snapshot the metrics line's reading
1012 /// paints, and the posture bar's ≥80% cap-warning trigger.
1013 pub(crate) fn context_percent_from_app(app: &App) -> u8 {
1014 crate::tui::ui::context_usage_snapshot(app)
1015 .map(|(_, _, percent)| percent.round().clamp(0.0, 100.0) as u8)
1016 .unwrap_or(0)
1017 }
1018
1019 /// The live counts: running sub-agents, live shells, background tasks, and
1020 /// scheduled automation. Each count is zero-suppressed — the bar never
1021 /// grows furniture for work that is not happening.
1022 fn live_counts(
1023 app: &App,
1024 tier: ShellTier,
1025 ) -> (
1026 Vec<(String, ChromeInk)>,
1027 Vec<crate::tui::tideline::InteractionAction>,
1028 ) {
1029 use crate::tui::background_indicator::{PendingItemKind, pending_work_from_app};
1030 use crate::tui::tideline::InteractionAction;
1031 use crate::tui::work_surface::RailPanel;
1032 let mut counts = Vec::new();
1033 let mut panels = Vec::new();
1034 let agents = crate::tui::subagent_routing::running_agent_count(app);
1035 match agents {
1036 0 => {}
1037 1 => {
1038 counts.push((
1039 tr(app.ui_locale, MessageId::FooterAgentSingular).into_owned(),
1040 ChromeInk::Active,
1041 ));
1042 panels.push(InteractionAction::ShowDockPanel(RailPanel::Agents));
1043 }
1044 n => {
1045 counts.push((
1046 tr(app.ui_locale, MessageId::FooterAgentsPlural).replace("{count}", &n.to_string()),
1047 ChromeInk::Active,
1048 ));
1049 panels.push(InteractionAction::ShowDockPanel(RailPanel::Agents));
1050 }
1051 }
1052 let shells = app
1053 .task_panel
1054 .iter()
1055 .filter(|entry| crate::tui::background_indicator::is_live_shell_entry(entry))
1056 .count();
1057 if shells > 0 {
1058 counts.push((
1059 format!("{shells} {}", PendingItemKind::Shell.plural_noun(shells)),
1060 ChromeInk::Active,
1061 ));
1062 panels.push(InteractionAction::ShowDockPanel(RailPanel::Background));
1063 }
1064 let tasks = pending_work_from_app(app).count(PendingItemKind::Task);
1065 if tasks > 0 {
1066 counts.push((
1067 format!("{tasks} {}", PendingItemKind::Task.plural_noun(tasks)),
1068 ChromeInk::Active,
1069 ));
1070 panels.push(InteractionAction::ShowDockPanel(RailPanel::Background));
1071 }
1072 // Scheduled automation: the `AutomationPanelState` projection stays the
1073 // single owner; Compact keeps the abbreviated count (chrome sheds
1074 // before content) and the ink says whether a run failed unacknowledged.
1075 let automation = if tier == ShellTier::Compact {
1076 app.automation_panel.activity_slot_compact()
1077 } else {
1078 app.automation_panel.activity_slot(app.ui_locale)
1079 };
1080 if let Some(automation) = automation {
1081 counts.push((automation, app.automation_panel.activity_ink()));
1082 panels.push(InteractionAction::OpenAutomations);
1083 }
1084 (counts, panels)
1085 }
1086
1087 /// Build the posture bar's facts from live `App` state. `width` is the
1088 /// row's width — notices clause-shed against it, never dangle.
1089 pub(crate) fn tideline_footer_from_app(app: &mut App, width: u16) -> TidelineFooterFacts {
1090 use crate::tui::shell_key_routing::{ShellBindingId, binding};
1091 let activity = LiveActivity::from_app(app);
1092 let phase = ShellPhase::from_app_with_activity(app, activity);
1093 let (_, phase_label) = phase_marker_with_activity(app, phase, activity);
1094 let tier = ShellTier::for_chrome_width(width);
1095 let focus = app.focus();
1096
1097 let (dial_text, dial_ink) = crate::tui::underwater::dial_chip(app);
1098 let permission_chip = (dial_text.into_owned(), dial_ink);
1099 // Cycle keys come from the binding table and only when that binding is
1100 // live for the current focus.
1101 let live_chord = |id: ShellBindingId| -> Option<&'static str> {
1102 let binding = binding(id);
1103 binding.focus.admits(focus).then_some(binding.footer_chord)
1104 };
1105
1106 // The one hint that applies now: the interrupt affordance while a turn is
1107 // running, else the arrow keys the empty composer lends to the agent
1108 // roster. Each hint retires once its binding has been used enough times
1109 // (`footer_hints::retired`): a taught binding renders the bare state,
1110 // never more chrome.
1111 let hint = if matches!(phase, ShellPhase::Working | ShellPhase::Verifying) {
1112 // #6502: when Esc closes, leaves or clears something else first (the
1113 // workbar, a menu, agent focus, vim Insert), the turn keeps running,
1114 // so the interrupt promise would be false.
1115 crate::tui::composer_ui::esc_interrupts(app).then(|| {
1116 (
1117 tr(app.ui_locale, MessageId::FooterHintEscInterrupt).into_owned(),
1118 ChromeInk::MetadataHint,
1119 crate::tui::footer_hints::ESC_INTERRUPT,
1120 )
1121 })
1122 } else if crate::tui::agent_focus::shell_shortcuts_available(app, false) {
1123 Some((
1124 crate::tui::agent_focus::footer_agent_hints(app),
1125 ChromeInk::MetadataHint,
1126 crate::tui::footer_hints::AGENT_ARROWS,
1127 ))
1128 } else {
1129 None
1130 };
1131 let hint = hint
1132 .filter(|(_, _, key)| !crate::tui::footer_hints::retired(&app.footer_hint_uses, key))
1133 .map(|(text, ink, _)| (text, ink));
1134 // While a turn runs, the arrow keys stay live beside Esc, so the row reads
1135 // `Esc to interrupt · ← for agents · ↓ to manage` — the running agents and
1136 // workflows are what a user wants to reach mid-turn.
1137 let hint = if matches!(phase, ShellPhase::Working | ShellPhase::Verifying)
1138 && crate::tui::agent_focus::shell_shortcuts_available(app, false)
1139 && !crate::tui::footer_hints::retired(
1140 &app.footer_hint_uses,
1141 crate::tui::footer_hints::AGENT_ARROWS,
1142 ) {
1143 let arrows = crate::tui::agent_focus::footer_agent_hints(app);
1144 Some(match hint {
1145 Some((text, ink)) => (format!("{text} · {arrows}"), ink),
1146 None => (arrows, ChromeInk::MetadataHint),
1147 })
1148 } else {
1149 hint
1150 };
1151
1152 // The right slot: the live status toast if one is owed, else the compact
1153 // MCP or plugin boot chip, else the remote-control state when it is on.
1154 // Clause-shed against half the row — the posture facts own the other
1155 // half — and, while a turn runs, against what the turn clock leaves.
1156 let notice_budget = (usize::from(width) / 2)
1157 .max(8)
1158 .min(usize::from(width).saturating_sub(permission_chip.0.width() + 5));
1159 let (turn_clock, session_clock) = working_clock(app, phase, &phase_label);
1160 let beside_clock = turn_clock.as_ref().map(|(clock, _)| {
1161 usize::from(width).saturating_sub(permission_chip.0.width() + clock.width() + 8)
1162 });
1163 let beside_hint = beside_clock.zip(hint.as_ref()).map(|(budget, (hint, _))| {
1164 notice_budget.min(budget.saturating_sub(hint.width() + ITEM_SEPARATOR_WIDTH))
1165 });
1166 let notice_budget = beside_clock.map_or(notice_budget, |budget| notice_budget.min(budget));
1167 let right = selected_notice(app.active_status_toast(phase), &phase_label)
1168 .map(|(text, fallbacks, ink, urgent)| {
1169 (
1170 text,
1171 fallbacks,
1172 if ink == ChromeInk::Info {
1173 ChromeInk::Metadata
1174 } else {
1175 ink
1176 },
1177 urgent,
1178 )
1179 })
1180 .or_else(|| {
1181 // The launch screen carries the full MCP block — every state, with
1182 // the failing and unauthorized servers named. Repeating a squeezed
1183 // one-server chip down here would give the same fact two homes and
1184 // show strictly less of it. Suppress the chip, not the surface:
1185 // `SessionBootSurface::from_app` stays untouched so every other
1186 // consumer of boot state, including the launch block itself, is
1187 // unaffected.
1188 if app.launch.visible {
1189 return None;
1190 }
1191 let boot = crate::tui::session_boot::SessionBootSurface::from_app(app)
1192 .quiet_announced(&app.mcp_announced_problems);
1193 boot.activity_notice(notice_budget)
1194 .map(|chip| (chip.text, Vec::new(), boot_activity_ink(chip.level), false))
1195 })
1196 .and_then(|(text, fallbacks, ink, urgent)| {
1197 beside_hint
1198 .and_then(|budget| {
1199 std::iter::once(&text)
1200 .chain(&fallbacks)
1201 .map(|candidate| candidate.trim())
1202 .find(|candidate| !candidate.is_empty() && candidate.width() <= budget)
1203 .map(str::to_string)
1204 })
1205 .or_else(|| fit_notice_candidates(&text, &fallbacks, notice_budget, urgent))
1206 .map(|fitted| (fitted, ink))
1207 })
1208 .or_else(|| {
1209 if app.remote_control.status() == codewhale_app_server::remote_control::Status::Failed {
1210 let notice = format!("/rc status · {}", tr(app.ui_locale, MessageId::PhaseFailed));
1211 fit_notice(&notice, notice_budget, false)
1212 .or_else(|| fit_notice("/rc status", notice_budget, false))
1213 .map(|text| (text, ChromeInk::Failure))
1214 } else {
1215 app.remote_control
1216 .status_word()
1217 .map(|word| (format!("/rc {word}"), ChromeInk::Info))
1218 }
1219 });
1220
1221 let (counts, count_actions) = live_counts(app, tier);
1222 TidelineFooterFacts {
1223 permission_chip,
1224 permission_key: live_chord(ShellBindingId::PermissionCycle)
1225 .filter(|_| {
1226 matches!(
1227 app.approval_mode,
1228 codewhale_execpolicy::ApprovalMode::Auto
1229 | codewhale_execpolicy::ApprovalMode::Bypass
1230 ) || !crate::tui::footer_hints::retired(
1231 &app.footer_hint_uses,
1232 crate::tui::footer_hints::PERMISSION_CYCLE,
1233 )
1234 })
1235 .map(|chord| {
1236 if turn_clock.is_some() {
1237 chord.to_string()
1238 } else {
1239 tr(app.ui_locale, MessageId::FooterPermissionKeyHint).replace("{key}", chord)
1240 }
1241 }),
1242 turn_clock,
1243 counts,
1244 session_clock,
1245 count_actions,
1246 hint,
1247 context_percent: context_percent_from_app(app),
1248 right,
1249 locale: app.ui_locale,
1250 }
1251 }
1252
1253 #[cfg(test)]
1254 mod tideline_tests;
1255
1256 #[cfg(test)]
1257 mod posture_tests;
1258
1258 lines RUST