返回 CodeWhale
underwater.rs
根目录 / crates / tui / src / tui / underwater.rs
1 //! Coherent shell grammar for the underwater TUI.
2 //!
3 //! This module owns phase, responsive density, the empty-state composition,
4 //! and the compact header/footer fact budget. Product data still belongs to
5 //! [`App`]; this is only its terminal projection. Keeping these decisions in
6 //! one place prevents the default UI from drifting back into a header +
7 //! sidebar + dashboard + footer composition with four owners for one fact.
8
9 use std::borrow::Cow;
10
11 use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
12 use ratatui::{
13 layout::Rect,
14 style::{Color, Modifier, Style},
15 text::{Line, Span},
16 };
17 use unicode_width::UnicodeWidthStr;
18
19 use crate::tui::{
20 app::{App, OnboardingState},
21 ocean::COMPLETION_BREATH_MS,
22 views::ModalKind,
23 };
24 use codewhale_config::AppMode;
25 use codewhale_execpolicy::ApprovalMode;
26 use codewhale_localization::{Locale, MessageId, tr};
27 use codewhale_palette::ChromeInk;
28 use codewhale_tui_kit::ui_text::{semantic_truncate, text_display_width};
29
30 /// Responsive density tier. It changes how much truth is shown, never the
31 /// underlying state grammar.
32 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
33 pub enum ShellTier {
34 Compact,
35 Normal,
36 Wide,
37 }
38
39 /// What one launch key produces. The composer holds focus and takes every
40 /// ordinary key, so the only launch-owned input is F1 help; the card's
41 /// rows are driven by Up/Down + Enter (and the mouse) through
42 /// [`run_launch_card_row`].
43 #[derive(Debug, Clone, PartialEq, Eq)]
44 pub enum LaunchAction {
45 None,
46 ConnectModel,
47 /// The prominent new-session entry: begin a fresh session in the
48 /// current workspace.
49 NewSession,
50 ReturnToSession,
51 /// Resume one recent-work row by session id.
52 ResumeSession(String),
53 /// The see-all overflow: open the full session picker.
54 BrowseSessions,
55 ShowRecent,
56 /// Inspect and manage the servers counted by the MCP summary.
57 McpManager,
58 Skills,
59 Help,
60 }
61
62 /// Translate a launch key into one product action. Reached only through
63 /// [`LaunchComposerKey::MenuChord`]; every other key belongs to the
64 /// composer authority.
65 pub fn handle_launch_key(
66 _launch: &mut crate::tui::app::LaunchState,
67 key: KeyEvent,
68 _locale: Locale,
69 ) -> LaunchAction {
70 match key.code {
71 KeyCode::F(1) => LaunchAction::Help,
72 _ => LaunchAction::None,
73 }
74 }
75
76 /// One interactive row on the startup card: the prominent new-session
77 /// entry, one recent-work row, or the see-all overflow. Labels are
78 /// localized; `detail` is right-aligned metadata (a recent row's age).
79 #[derive(Debug, Clone, PartialEq, Eq)]
80 pub struct LaunchCardRow {
81 pub id: crate::tui::app::LaunchRowId,
82 pub label: String,
83 pub detail: String,
84 /// The new-session entry paints prominent (bold accent) when it is
85 /// neither keyboard-selected nor hovered.
86 pub prominent: bool,
87 warning: bool,
88 }
89
90 /// A recent session projected for the card: the display title plus its
91 /// right-aligned detail line. Preformatted by the caller so the renderer
92 /// stays deterministic for golden buffers.
93 #[derive(Debug, Clone, PartialEq, Eq)]
94 pub struct LaunchRecentEntry {
95 pub id: String,
96 pub title: String,
97 pub detail: String,
98 }
99
100 /// The card's rows in paint/click/keyboard order: the prominent
101 /// new-session entry first, then recent work, then the see-all overflow
102 /// when more sessions sit behind the inline list. The single ordering
103 /// keyboard, mouse, and paint share.
104 #[must_use]
105 pub fn launch_card_rows(
106 locale: Locale,
107 recent: &[LaunchRecentEntry],
108 has_more: bool,
109 ) -> Vec<LaunchCardRow> {
110 let mut rows = Vec::with_capacity(recent.len() + 2);
111 rows.push(LaunchCardRow {
112 id: crate::tui::app::LaunchRowId::NewSession,
113 label: tr(locale, MessageId::LaunchNewSession).into_owned(),
114 detail: String::new(),
115 prominent: true,
116 warning: false,
117 });
118 rows.extend(recent.iter().map(|entry| LaunchCardRow {
119 id: crate::tui::app::LaunchRowId::Recent(entry.id.clone()),
120 label: entry.title.clone(),
121 detail: entry.detail.clone(),
122 prominent: false,
123 warning: false,
124 }));
125 if has_more {
126 rows.push(LaunchCardRow {
127 id: crate::tui::app::LaunchRowId::SeeAll,
128 label: tr(locale, MessageId::LaunchSeeAllSessions).into_owned(),
129 detail: String::new(),
130 prominent: false,
131 warning: false,
132 });
133 }
134 rows
135 }
136
137 /// Project the launch state's loaded recent-work list into card entries:
138 /// display titles with right-aligned relative ages, like the resume
139 /// picker. Pure projection of loaded state — no disk reads.
140 fn launch_recent_entries(app: &App) -> (Vec<LaunchRecentEntry>, bool) {
141 let recent = app
142 .launch
143 .recent
144 .iter()
145 .map(|session| {
146 let raw = codewhale_engine::session_manager::extract_title(&session.title);
147 let title = if raw == "Session" || raw.trim().is_empty() {
148 codewhale_engine::session_manager::truncate_id(&session.id).to_string()
149 } else {
150 raw.to_string()
151 };
152 let age = crate::tui::session_picker::format_relative_time(
153 &session.updated_at,
154 app.ui_locale,
155 );
156 LaunchRecentEntry {
157 id: session.id.clone(),
158 title,
159 detail: if session.interrupted {
160 format!(
161 "{} · {age}",
162 tr(app.ui_locale, MessageId::AgentStatusInterrupted)
163 )
164 } else {
165 age
166 },
167 }
168 })
169 .collect::<Vec<_>>();
170 // More sessions than the inline cap, or sessions the card's filter
171 // dropped that `/resume` still lists (empty auto-created shells):
172 // either way the see-all row is how the truth stays reachable.
173 let has_more = app.launch.total_workspace_sessions > recent.len()
174 || (recent.is_empty() && app.launch.has_scoped_sessions);
175 (recent, has_more)
176 }
177
178 /// Both painting and input use the same primary action on revisited home.
179 fn home_card_rows(
180 app: &App,
181 recent: &[LaunchRecentEntry],
182 has_more: bool,
183 show_connect_model: bool,
184 ) -> Vec<LaunchCardRow> {
185 let mut rows = launch_card_rows(app.ui_locale, recent, has_more);
186 if !app.launch.recent_expanded
187 && has_more
188 && !app.launch.recent.is_empty()
189 && let Some(row) = rows
190 .iter_mut()
191 .find(|r| r.id == crate::tui::app::LaunchRowId::SeeAll)
192 {
193 row.id = crate::tui::app::LaunchRowId::ShowRecent;
194 row.label = format!(
195 "{} {}",
196 tr(app.ui_locale, MessageId::LaunchRecentHeading),
197 app.launch.total_workspace_sessions
198 );
199 row.detail = if crate::tui::color_compat::ascii_safe_enabled() {
200 "Up"
201 } else {
202 "↑"
203 }
204 .into();
205 }
206 if app.launch.return_to_session {
207 if let Some(row) = rows
208 .iter_mut()
209 .find(|r| r.id == crate::tui::app::LaunchRowId::NewSession)
210 {
211 row.id = crate::tui::app::LaunchRowId::ReturnToSession;
212 row.label = tr(app.ui_locale, MessageId::HomeBackToConversation).into_owned();
213 row.detail = "Esc".into();
214 }
215 } else if show_connect_model {
216 if let Some(row) = rows
217 .iter_mut()
218 .find(|r| r.id == crate::tui::app::LaunchRowId::NewSession)
219 {
220 row.prominent = false;
221 }
222 rows.insert(
223 0,
224 LaunchCardRow {
225 id: crate::tui::app::LaunchRowId::ConnectModel,
226 label: tr(app.ui_locale, MessageId::ConnectionSetupTitle).into_owned(),
227 detail: "/connect".to_string(),
228 prominent: true,
229 warning: false,
230 },
231 );
232 }
233 rows
234 }
235
236 fn launch_extension_rows(app: &App) -> Vec<LaunchCardRow> {
237 use crate::tui::app::LaunchRowId;
238 let mut rows = Vec::new();
239 let servers = app
240 .mcp_snapshot
241 .as_ref()
242 .map(|snapshot| snapshot.servers.as_slice());
243 let configured = servers.map_or(app.mcp_configured_count, |rows| rows.len());
244 if configured > 0 {
245 let required_problems = servers
246 .unwrap_or_default()
247 .iter()
248 .filter(|s| {
249 s.enabled && s.required && !s.connected && (s.error.is_some() || s.auth_required)
250 })
251 .count();
252 let connectors = tr(app.ui_locale, MessageId::ExtensionsTabConnectors);
253 let label = if required_problems > 0 {
254 format!(
255 "{connectors} · {} ({required_problems})",
256 tr(app.ui_locale, MessageId::ExtensionsStateError)
257 )
258 } else {
259 format!("{connectors} {configured}")
260 };
261 rows.push(LaunchCardRow {
262 id: LaunchRowId::McpManager,
263 label,
264 detail: "/mcp".into(),
265 prominent: false,
266 warning: required_problems > 0,
267 });
268 }
269 rows.push(LaunchCardRow {
270 id: LaunchRowId::Skills,
271 label: tr(app.ui_locale, MessageId::HelpSkills).into_owned(),
272 detail: "/skills".into(),
273 prominent: false,
274 warning: false,
275 });
276 rows
277 }
278
279 /// The card's rows for live `App` state, for keyboard navigation and Enter.
280 ///
281 /// The painted rows are the authority. Paint sheds the tail of the recent
282 /// list to fit a short pane and turns the overflow row on when it does, so a
283 /// list built here from scratch would let Up/Down land on — and Enter resume
284 /// — a session the screen is not showing. `row_hitboxes` is what the last
285 /// frame actually drew, in paint order, and `mouse_ui` indexes that same
286 /// list: one ordering for paint, mouse, and keyboard, with no second state.
287 #[must_use]
288 pub fn launch_rows_for_app(app: &App) -> Vec<LaunchCardRow> {
289 let (recent, _) = launch_recent_entries(app);
290 // An empty pane has no navigable rows, including before its first paint.
291 // A preserved multiline draft can legitimately leave no room for home.
292 let recent = if app.launch.recent_expanded {
293 recent.as_slice()
294 } else {
295 &[]
296 };
297 let mut superset = home_card_rows(
298 app,
299 recent,
300 true,
301 app.onboarding_needs_api_key && !app.launch.return_to_session,
302 );
303 superset.extend(launch_extension_rows(app));
304 app.launch
305 .row_hitboxes
306 .iter()
307 .filter_map(|(id, _)| superset.iter().find(|row| &row.id == id).cloned())
308 .collect()
309 }
310
311 /// Re-anchor the card's clickable rows on what `area` just painted.
312 ///
313 /// The frame renderer calls this instead of rebuilding hitboxes inline, so
314 /// the row list keyboard and mouse read back cannot describe a row the
315 /// transcript did not draw.
316 pub fn refresh_launch_row_hitboxes(app: &mut App, area: Rect) {
317 let state = launch_empty_state(app, area);
318 app.launch.row_hitboxes = state
319 .rows
320 .into_iter()
321 .filter_map(|(id, row)| {
322 let y = area.y.checked_add(u16::try_from(row).ok()?)?;
323 (y < area.y.saturating_add(area.height)).then_some((
324 id,
325 Rect::new(area.x + state.text_column.x, y, state.text_column.width, 1),
326 ))
327 })
328 .collect();
329 // A pane that shrank can leave the highlight past the last painted row.
330 // Clear it rather than clamping: clamping would silently move the
331 // selection onto a different session.
332 let painted = app.launch.row_hitboxes.len();
333 if app
334 .launch
335 .menu_selected
336 .is_some_and(|index| index >= painted)
337 {
338 app.launch.menu_selected = None;
339 }
340 if app.launch.hovered_row.is_some_and(|index| index >= painted) {
341 app.launch.hovered_row = None;
342 }
343 }
344
345 /// The click twin of [`run_launch_card_row`]: one card row id runs the
346 /// same action the keyboard's Enter runs, so mouse and keyboard share one
347 /// contract.
348 #[must_use]
349 pub fn launch_row_click_action(id: &crate::tui::app::LaunchRowId) -> LaunchAction {
350 match id {
351 crate::tui::app::LaunchRowId::ConnectModel => LaunchAction::ConnectModel,
352 crate::tui::app::LaunchRowId::NewSession => LaunchAction::NewSession,
353 crate::tui::app::LaunchRowId::ReturnToSession => LaunchAction::ReturnToSession,
354 crate::tui::app::LaunchRowId::Recent(session_id) => {
355 LaunchAction::ResumeSession(session_id.clone())
356 }
357 crate::tui::app::LaunchRowId::SeeAll => LaunchAction::BrowseSessions,
358 crate::tui::app::LaunchRowId::ShowRecent => LaunchAction::ShowRecent,
359 crate::tui::app::LaunchRowId::McpManager => LaunchAction::McpManager,
360 crate::tui::app::LaunchRowId::Skills => LaunchAction::Skills,
361 }
362 }
363
364 /// Ask before resuming: open the confirmation popup for `session_id`.
365 ///
366 /// Both the card's Enter and a click on a recent row route here. Resuming
367 /// replaces the whole session context, and the popup is where that is said —
368 /// an arming line over the composer read as chrome rather than as a question.
369 pub fn open_launch_resume_confirm(app: &mut App, session_id: &str) {
370 if app.view_stack.top_kind() == Some(crate::tui::views::ModalKind::LaunchResumeConfirm) {
371 return;
372 }
373 let entry = app
374 .launch
375 .recent
376 .iter()
377 .find(|entry| entry.id == session_id);
378 let title = entry
379 .map(|entry| entry.title.clone())
380 .unwrap_or_else(|| session_id.to_string());
381 let detail = entry
382 .map(|entry| {
383 let when =
384 crate::tui::session_picker::format_relative_time(&entry.updated_at, app.ui_locale);
385 format!(
386 "{when} · {}",
387 crate::tui::session_picker::format_message_count(
388 entry.message_count,
389 app.ui_locale
390 )
391 )
392 })
393 .unwrap_or_default();
394 app.view_stack.push(
395 crate::tui::launch_resume_confirm::LaunchResumeConfirmView::new(
396 session_id.to_string(),
397 title,
398 detail,
399 app.ui_locale,
400 ),
401 );
402 app.needs_redraw = true;
403 }
404 /// Run the card's highlighted row. Enter on the card is the list's runner;
405 /// an untouched list runs nothing.
406 pub fn run_launch_card_row(rows: &[LaunchCardRow], menu_selected: Option<usize>) -> LaunchAction {
407 let Some(selected) = menu_selected else {
408 return LaunchAction::None;
409 };
410 match rows.get(selected) {
411 None => LaunchAction::None,
412 Some(row) => launch_row_click_action(&row.id),
413 }
414 }
415
416 /// What the pre-session composer layer decided about one key.
417 ///
418 /// This is only an admission guard, never an input implementation: the
419 /// startup composer is the session's own [`crate::tui::app::ComposerState`],
420 /// and every editing key is answered by the conversation composer match in
421 /// the event loop — the single composer input authority — exactly as it
422 /// would be in a live session. Word motion, selection, completion menus,
423 /// attachments, history, paste bursts, and vim behaviour therefore cannot
424 /// drift from the shell. Only three things are launch-specific here: an
425 /// empty Enter, F1 help, and submitting.
426 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
427 pub enum LaunchComposerKey {
428 /// The key is fully consumed and does nothing more (Enter on an empty
429 /// composer with no menu entry highlighted: there is no row to run and
430 /// nothing to send; Esc clearing the menu highlight or bringing the
431 /// card back).
432 Consumed,
433 /// Submit the composed message through the normal dispatch path.
434 Submit,
435 /// The launch chord (F1 help): the same key is then handed to
436 /// [`handle_launch_key`]. It deliberately wins over its composer
437 /// meaning while the launch screen is up.
438 MenuChord,
439 /// Not launch-specific: the conversation composer match below owns the
440 /// key. The event loop must not run [`handle_launch_key`] for it.
441 ComposerAuthority,
442 /// Move the launch card's row selection (Up/Down while the card is up).
443 MenuNavigate(i32),
444 /// Run the card's highlighted row. Revisited home retains its draft;
445 /// on startup, only an empty composer yields Enter to the card.
446 MenuRun,
447 }
448
449 /// Admit one key for the pre-session composer.
450 ///
451 /// Editing keys are never handled here — they fall through to the
452 /// conversation composer match so there is exactly one composer input
453 /// system. Only F1 help stays launch-owned via
454 /// [`LaunchComposerKey::MenuChord`].
455 pub fn handle_launch_composer_key(app: &mut App, key: KeyEvent) -> LaunchComposerKey {
456 if app.launch.return_to_session && key.code == KeyCode::Esc {
457 app.launch.dismiss();
458 return LaunchComposerKey::Consumed;
459 }
460 let multiline = app.composer_multiline_mode;
461 let card_up = app.launch.dissolve_started_ms.is_none();
462 match key.code {
463 KeyCode::Enter
464 if app.use_paste_burst_detection
465 && !app.bracketed_paste_seen
466 && !(app.bracketed_paste_trusted && app.use_bracketed_paste)
467 && key.modifiers == KeyModifiers::NONE
468 && app
469 .paste_burst
470 .newline_should_insert_instead_of_submit(std::time::Instant::now()) =>
471 {
472 if app.launch.return_to_session {
473 app.launch.dismiss();
474 } else {
475 app.launch.dissolve_card(app.ambient_clock_ms);
476 }
477 LaunchComposerKey::ComposerAuthority
478 }
479 KeyCode::Enter
480 if crate::tui::composer_ui::composer_submit_chord(key, multiline).is_some() =>
481 {
482 if key.modifiers != KeyModifiers::NONE
483 && let Some(pending) = app.flush_paste_burst_before_modified_input_if_enabled()
484 {
485 app.insert_str(&pending);
486 }
487 let row_selected = card_up
488 && app
489 .launch
490 .menu_selected
491 .is_some_and(|index| index < app.launch.row_hitboxes.len());
492 if row_selected && (app.launch.return_to_session || app.input.trim().is_empty()) {
493 LaunchComposerKey::MenuRun
494 } else if app.composer_shows_send() {
495 LaunchComposerKey::Submit
496 } else {
497 LaunchComposerKey::Consumed
498 }
499 }
500 KeyCode::Up if card_up => LaunchComposerKey::MenuNavigate(-1),
501 KeyCode::Down if card_up => LaunchComposerKey::MenuNavigate(1),
502 // Esc walks back one step: a highlighted row is unhighlighted;
503 // an empty composer with the card gone brings the card back. A draft
504 // in the composer keeps Esc's composer meaning.
505 KeyCode::Esc if card_up && app.launch.menu_selected.is_some() => {
506 app.launch.menu_selected = None;
507 LaunchComposerKey::Consumed
508 }
509 KeyCode::Esc if card_up && app.launch.recent_expanded => {
510 app.launch.recent_expanded = false;
511 app.launch.hovered_row = None;
512 LaunchComposerKey::Consumed
513 }
514 KeyCode::Esc if !card_up && app.input.is_empty() => {
515 app.launch.restore_card();
516 LaunchComposerKey::Consumed
517 }
518 KeyCode::F(1) => LaunchComposerKey::MenuChord,
519 // Every other key — text, caret motion, word motion, selection,
520 // newline chords, Home/End, kill/chord editing, vim motions, Esc,
521 // Tab, history — is answered by the conversation composer authority.
522 _ => {
523 // Typing goes straight to the composer, and the first keystroke
524 // dissolves the card (founder decision, 2026-09-02).
525 if card_up
526 && matches!(key.code, KeyCode::Char(_))
527 && !key
528 .modifiers
529 .intersects(KeyModifiers::CONTROL | KeyModifiers::ALT | KeyModifiers::SUPER)
530 {
531 if app.launch.return_to_session {
532 app.launch.dismiss();
533 } else {
534 app.launch.dissolve_card(app.ambient_clock_ms);
535 }
536 }
537 LaunchComposerKey::ComposerAuthority
538 }
539 }
540 }
541
542 impl ShellTier {
543 // `for_area` (the two-dimensional variant) went with the empty state's
544 // tier branch: the idle caption sheds detail continuously now, so nothing
545 // was left that wanted a coarse three-way answer about a whole Rect. The
546 // row and column floors it encoded still exist, spelled out as
547 // `AMBIENT_MIN_CHAT_HEIGHT` / `AMBIENT_MIN_CHAT_WIDTH` where the layout
548 // can honour them.
549 #[must_use]
550 pub fn for_chrome_width(width: u16) -> Self {
551 if width < 60 {
552 Self::Compact
553 } else if width < 110 {
554 Self::Normal
555 } else {
556 Self::Wide
557 }
558 }
559 }
560
561 /// Perceptual session phase. Every treatment reads from this same enum so a
562 /// footer cannot say `idle` while the transcript is asking for approval.
563 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
564 pub enum ShellPhase {
565 Idle,
566 Typing,
567 Working,
568 /// A live verification pass (tests/checks/lints). Same clock family as
569 /// `Working` but rendered as the metered braille tick — checking, not
570 /// searching (ocean state model).
571 Verifying,
572 Waiting,
573 Approval,
574 Done,
575 Failed,
576 }
577
578 /// The one truthful verb shown while a turn is live. This deliberately stays
579 /// smaller than the tool taxonomy: the phase strip only needs to distinguish
580 /// hidden reasoning, read-shaped exploration, other tool use, verification,
581 /// and generic model work. It never exposes reasoning text or tool arguments.
582 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
583 pub(crate) enum LiveActivityKind {
584 Working,
585 Compacting,
586 AutoCompacting,
587 Reasoning,
588 Reading,
589 UsingTool,
590 UsingSubagents,
591 Verifying,
592 }
593
594 /// Bounded projection of live turn activity. Completed entries are ignored,
595 /// so an `ActiveCell` retained until `TurnComplete` cannot keep the shell in a
596 /// false working state.
597 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
598 pub(crate) struct LiveActivity {
599 kind: LiveActivityKind,
600 running_tools: usize,
601 }
602
603 impl LiveActivity {
604 #[must_use]
605 pub(crate) fn from_app(app: &App) -> Self {
606 let tools = running_tool_facts(app);
607 let kind = if app
608 .active_compaction
609 .as_ref()
610 .is_some_and(|compaction| compaction.auto)
611 {
612 LiveActivityKind::AutoCompacting
613 } else if app.active_compaction.is_some() {
614 LiveActivityKind::Compacting
615 } else if tools.verifying {
616 LiveActivityKind::Verifying
617 } else if app_has_unfinished_subagents(app) {
618 LiveActivityKind::UsingSubagents
619 } else if tools.count > 0 && tools.all_reading {
620 LiveActivityKind::Reading
621 } else if tools.count > 0 {
622 LiveActivityKind::UsingTool
623 } else if app.streaming_thinking_active_entry.is_some() {
624 LiveActivityKind::Reasoning
625 } else {
626 LiveActivityKind::Working
627 };
628 Self {
629 kind,
630 running_tools: tools.count,
631 }
632 }
633
634 #[must_use]
635 pub(crate) fn kind(self) -> LiveActivityKind {
636 self.kind
637 }
638
639 #[must_use]
640 fn is_explicit(self) -> bool {
641 !matches!(self.kind, LiveActivityKind::Working)
642 }
643
644 #[must_use]
645 fn label(self, locale: Locale) -> Cow<'static, str> {
646 match self.kind {
647 LiveActivityKind::Working => tr(locale, MessageId::PhaseWorking),
648 LiveActivityKind::Compacting => tr(locale, MessageId::ContextManualCompacting),
649 LiveActivityKind::AutoCompacting => tr(locale, MessageId::ContextAutoCompacting),
650 LiveActivityKind::Reasoning => tr(locale, MessageId::PhaseReasoning),
651 LiveActivityKind::Reading => tr(locale, MessageId::PhaseReading),
652 LiveActivityKind::UsingTool => tr(locale, MessageId::PhaseUsingTool),
653 LiveActivityKind::UsingSubagents => tr(locale, MessageId::PhaseSubagents),
654 LiveActivityKind::Verifying => tr(locale, MessageId::PhaseVerifying),
655 }
656 }
657 }
658
659 #[derive(Debug, Clone, Copy)]
660 struct RunningToolFacts {
661 count: usize,
662 all_reading: bool,
663 verifying: bool,
664 }
665
666 /// True when any sub-agent spawned by this session is still running: live
667 /// progress rows win over the cache, whose Running entries are the persisted
668 /// view of the same actors.
669 fn app_has_unfinished_subagents(app: &App) -> bool {
670 !app.agent_progress.is_empty()
671 || app.subagent_cache.iter().any(|agent| {
672 matches!(
673 agent.status,
674 codewhale_engine::tools::subagent::SubAgentStatus::Running
675 )
676 })
677 }
678
679 impl Default for RunningToolFacts {
680 fn default() -> Self {
681 Self {
682 count: 0,
683 all_reading: true,
684 verifying: false,
685 }
686 }
687 }
688
689 impl RunningToolFacts {
690 fn observe(&mut self, reading: bool, verifying: bool) {
691 self.count = self.count.saturating_add(1);
692 self.all_reading &= reading;
693 self.verifying |= verifying;
694 }
695 }
696
697 const WORKING_BUBBLE_FRAMES: [&str; 8] = ["⠀", "⢀", "⣀", "⣄", "⣤", "⣦", "⣶", "⣿"];
698 const COMPLETION_RELEASE_MS: u128 = 560;
699 // The idle whale portrait rows (IDLE_WHALE_ROWS / UWU_IDLE_WHALE_ROWS) and
700 // their caustic shimmer were deleted per the 2026-08-29 founder directive:
701 // hand-drawn whale art is out; the only sanctioned terminal mark is the one
702 // generated from the brand master path. The ambient empty-state surface
703 // (wordmark, context caption, prompt) below is not whale art and stays.
704
705 impl ShellPhase {
706 #[must_use]
707 pub fn from_app(app: &App) -> Self {
708 Self::from_app_with_activity(app, LiveActivity::from_app(app))
709 }
710
711 #[must_use]
712 pub(crate) fn from_app_with_activity(app: &App, activity: LiveActivity) -> Self {
713 if matches!(
714 app.view_stack.top_kind(),
715 Some(ModalKind::Approval | ModalKind::Elevation | ModalKind::UserInput)
716 ) {
717 return Self::Approval;
718 }
719 if matches!(
720 activity.kind(),
721 LiveActivityKind::Compacting | LiveActivityKind::AutoCompacting
722 ) {
723 // A typed CompactionStarted event is newer and more specific than
724 // a prior turn's failed projection. Keep the recovery operation
725 // visible until its matching terminal event arrives.
726 return Self::Working;
727 }
728 if app.turn_error_posted
729 || matches!(app.runtime_turn_status.as_deref(), Some("failed" | "error"))
730 {
731 return Self::Failed;
732 }
733 // A child agent's unanswered approval or question is the person's
734 // move, even while other agents keep working: the footer says
735 // "waiting on you", not "agents underway" (#6565).
736 if app.pending_user_input_prompt.is_some()
737 || !app.pending_child_requests.is_empty()
738 || app
739 .task_panel
740 .iter()
741 .any(|task| matches!(task.status.as_str(), "waiting" | "needs_user"))
742 {
743 return Self::Waiting;
744 }
745 if app.is_loading
746 || matches!(app.runtime_turn_status.as_deref(), Some("in_progress"))
747 || activity.is_explicit()
748 {
749 if activity.kind() == LiveActivityKind::Verifying {
750 return Self::Verifying;
751 }
752 return Self::Working;
753 }
754 if !app.input.is_empty() {
755 return Self::Typing;
756 }
757 if matches!(app.runtime_turn_status.as_deref(), Some("completed")) {
758 return Self::Done;
759 }
760 Self::Idle
761 }
762
763 #[must_use]
764 pub fn label(self, locale: Locale) -> Cow<'static, str> {
765 match self {
766 Self::Idle => tr(locale, MessageId::PhaseIdle),
767 Self::Typing => tr(locale, MessageId::PhaseDraft),
768 Self::Working => tr(locale, MessageId::PhaseWorking),
769 Self::Verifying => tr(locale, MessageId::PhaseVerifying),
770 Self::Waiting | Self::Approval => tr(locale, MessageId::PhaseWaitingOnYou),
771 Self::Done => tr(locale, MessageId::PhaseDone),
772 Self::Failed => tr(locale, MessageId::PhaseFailed),
773 }
774 }
775 }
776
777 /// Exhaustive on purpose: a new [`AppMode`] must be handed a Policy ink
778 /// deliberately rather than inheriting act's by falling through a wildcard.
779 pub(crate) fn header_mode_ink(mode: AppMode) -> ChromeInk {
780 match mode {
781 AppMode::Plan => ChromeInk::PolicyPlan,
782 AppMode::Agent => ChromeInk::PolicyAct,
783 }
784 }
785
786 pub(crate) fn header_permission_ink(mode: ApprovalMode) -> ChromeInk {
787 match mode {
788 ApprovalMode::Suggest | ApprovalMode::AcceptEdits | ApprovalMode::Never => {
789 ChromeInk::PermissionAsk
790 }
791 ApprovalMode::Auto => ChromeInk::PermissionAutoReview,
792 ApprovalMode::Bypass => ChromeInk::PermissionFullAccess,
793 }
794 }
795
796 /// One posture word with its ink — the unit the classic header's lockup was
797 /// made of, now carried as merged-footer chips.
798 pub(crate) type PostureChip = (Cow<'static, str>, ChromeInk);
799
800 /// The permission dial stop as the Tideline footer's one posture chip: the
801 /// Plan word in [`header_mode_ink`] while planning, otherwise the posture
802 /// phrase in [`header_permission_ink`]. The filesystem scope notice, when it
803 /// deviates, folds into the chip's text.
804 pub(crate) fn dial_chip(app: &App) -> PostureChip {
805 let mut chip = dial_chip_for(app.ui_locale, app.mode, app.approval_mode);
806 if let Some(scope) = filesystem_scope_notice(app) {
807 chip.0 = format!("{} · {scope}", chip.0).into();
808 }
809 if let Some(label) = app.conversation_mode_label() {
810 chip.0 = format!("{label} · {}", chip.0).into();
811 }
812 chip
813 }
814
815 pub(crate) fn dial_chip_for(locale: Locale, mode: AppMode, approval: ApprovalMode) -> PostureChip {
816 if mode == AppMode::Plan {
817 return (mode_label(locale, mode), header_mode_ink(mode));
818 }
819 (
820 codewhale_engine::core::authority::permission_label_for(locale, mode, approval),
821 header_permission_ink(approval),
822 )
823 }
824
825 /// Summarize only tools whose lifecycle is actually `Running`. A read label
826 /// is earned only when every running entry is read/exploration-shaped; mixed
827 /// work stays the neutral `using tool`. Verification wins because it is the
828 /// existing stronger promise made by the phase strip.
829 fn running_tool_facts(app: &App) -> RunningToolFacts {
830 use crate::tui::history::{HistoryCell, ToolCell, ToolStatus};
831 use crate::tui::widgets::tool_card::{ToolFamily, tool_family_for_name};
832
833 let mut facts = RunningToolFacts::default();
834 let Some(active) = app.active_cell.as_ref() else {
835 return facts;
836 };
837 for cell in active.entries() {
838 let HistoryCell::Tool(tool) = cell else {
839 continue;
840 };
841 match tool {
842 ToolCell::Exec(exec) if exec.status.is_active() => {
843 facts.observe(false, exec_is_verification(&exec.command));
844 }
845 ToolCell::Generic(generic) if generic.status.is_active() => {
846 let family = tool_family_for_name(&generic.name);
847 facts.observe(
848 matches!(family, ToolFamily::Read | ToolFamily::Find),
849 family == ToolFamily::Verify || generic.name == "read_lints",
850 );
851 }
852 ToolCell::Exploring(exploring) => {
853 for entry in &exploring.entries {
854 if entry.status.is_active() {
855 facts.observe(true, false);
856 }
857 }
858 }
859 ToolCell::WebSearch(search) if search.status.is_active() => {
860 facts.observe(true, false);
861 }
862 other if other.status().is_some_and(ToolStatus::is_active) => {
863 facts.observe(false, false);
864 }
865 _ => {}
866 }
867 }
868 facts
869 }
870
871 fn exec_is_verification(command: &str) -> bool {
872 let trimmed = command.trim_start();
873 let mut tokens = trimmed.split_whitespace();
874 let first = tokens.next().unwrap_or("");
875 let second = tokens.next().unwrap_or("");
876 match first {
877 "cargo" => matches!(second, "test" | "check" | "clippy" | "nextest"),
878 "go" => matches!(second, "test" | "vet"),
879 "npm" | "pnpm" | "yarn" | "bun" => matches!(second, "test" | "lint" | "check"),
880 "make" => matches!(second, "test" | "check" | "lint"),
881 "python" | "python3" => trimmed.contains("-m pytest") || trimmed.contains("-m unittest"),
882 "pytest" | "jest" | "vitest" | "tsc" | "eslint" | "ruff" | "mypy" | "clippy-driver"
883 | "golangci-lint" | "shellcheck" => true,
884 _ => false,
885 }
886 }
887
888 fn completion_elapsed_ms(app: &App) -> Option<u128> {
889 if !app.motion_policy().allows_decorative() {
890 return None;
891 }
892 app.ocean_completion_started_at
893 .map(|started| started.elapsed().as_millis())
894 .filter(|elapsed| *elapsed < COMPLETION_BREATH_MS)
895 }
896
897 /// Truthful window-title activity verb for the OSC-0 whale animation.
898 ///
899 /// Uses short English fragments (with fixed-width ellipsis) so alt-tabbed
900 /// sessions stay legible without depending on the full localized phase strip.
901 #[must_use]
902 pub(crate) fn title_activity_verb(app: &App) -> &'static str {
903 let activity = LiveActivity::from_app(app);
904 let phase = ShellPhase::from_app_with_activity(app, activity);
905 match phase {
906 ShellPhase::Waiting | ShellPhase::Approval => "waiting on you…",
907 ShellPhase::Verifying => "verifying…",
908 ShellPhase::Done => "done",
909 ShellPhase::Failed => "failed",
910 ShellPhase::Typing => "drafting…",
911 ShellPhase::Idle => "idle",
912 ShellPhase::Working => match activity.kind() {
913 LiveActivityKind::Compacting | LiveActivityKind::AutoCompacting => {
914 "compacting context…"
915 }
916 LiveActivityKind::Reasoning => "thinking…",
917 LiveActivityKind::Reading => "reading…",
918 LiveActivityKind::UsingTool => "using tool…",
919 LiveActivityKind::UsingSubagents => "fleet underway…",
920 LiveActivityKind::Verifying => "verifying…",
921 LiveActivityKind::Working => "working…",
922 },
923 }
924 }
925
926 /// Push the current shell phase into the terminal title whale animation.
927 pub(crate) fn sync_title_activity(app: &App) {
928 crate::tui::notifications::set_title_motion_enabled(
929 app.motion_policy().allows_decorative() && app.status_indicator != "off",
930 );
931 // Keep the `[title] …` window-title prefix in step with the session and
932 // config defaults; change detection inside makes this free when nothing
933 // moved.
934 crate::tui::notifications::set_title_prefix(app.window_title_prefix());
935 if app.is_loading
936 || matches!(
937 ShellPhase::from_app(app),
938 ShellPhase::Working
939 | ShellPhase::Verifying
940 | ShellPhase::Waiting
941 | ShellPhase::Approval
942 | ShellPhase::Typing
943 )
944 {
945 crate::tui::notifications::set_title_activity_verb(title_activity_verb(app));
946 }
947 }
948
949 pub(crate) fn phase_marker_with_activity(
950 app: &App,
951 phase: ShellPhase,
952 activity: LiveActivity,
953 ) -> (&'static str, Cow<'static, str>) {
954 let locale = app.ui_locale;
955 match phase {
956 ShellPhase::Idle => ("·", phase.label(locale)),
957 ShellPhase::Typing => ("›", phase.label(locale)),
958 ShellPhase::Working => {
959 // The footer and the live tool card share one wall-clock cadence,
960 // so the two primary liveness marks never look like unrelated
961 // spinners. The shared helper also preserves the 400ms
962 // "motion is earned" delay and reduced/still fallback.
963 let policy = app.motion_policy();
964 let animated =
965 codewhale_tui_kit::spinner::braille_spinner_frame(app.turn_started_at, false);
966 let earned = app.turn_started_at.is_none_or(|started| {
967 started.elapsed().as_millis()
968 >= u128::from(codewhale_tui_kit::spinner::LIVE_MARKER_DELAY_MS)
969 });
970 let frame = policy.spinner_glyph(animated, earned);
971 (frame, activity.label(locale))
972 }
973 ShellPhase::Verifying => {
974 // Metered braille tick on the shared live clock — checking, not
975 // searching. Reduced motion holds the legible mid frame.
976 let policy = app.motion_policy();
977 let animated =
978 codewhale_tui_kit::spinner::verification_tick_frame(app.turn_started_at, false);
979 let earned = app.turn_started_at.is_none_or(|started| {
980 started.elapsed().as_millis()
981 >= u128::from(codewhale_tui_kit::spinner::LIVE_MARKER_DELAY_MS)
982 });
983 let frame = policy.spinner_glyph(animated, earned);
984 (frame, phase.label(locale))
985 }
986 ShellPhase::Waiting | ShellPhase::Approval => ("◆", phase.label(locale)),
987 ShellPhase::Done => match completion_elapsed_ms(app) {
988 Some(elapsed) if elapsed < COMPLETION_RELEASE_MS => {
989 let index = ((elapsed / 140) as usize + 4).min(WORKING_BUBBLE_FRAMES.len() - 1);
990 (WORKING_BUBBLE_FRAMES[index], phase.label(locale))
991 }
992 _ => (codewhale_tui_kit::glyphs::DONE, phase.label(locale)),
993 },
994 ShellPhase::Failed => (codewhale_tui_kit::glyphs::FAILED, phase.label(locale)),
995 }
996 }
997
998 pub(crate) fn mode_label(locale: Locale, mode: AppMode) -> Cow<'static, str> {
999 match mode {
1000 AppMode::Agent => tr(locale, MessageId::ChipModeAct),
1001 AppMode::Plan => tr(locale, MessageId::ChipModePlan),
1002 }
1003 }
1004
1005 /// Permission chip words. This maps from the typed [`ApprovalMode`] state —
1006 /// never from the English `permission_chip_label()` strings — so localizing
1007 /// (or rewording) the upstream chip labels can never silently break the chip.
1008 ///
1009 /// Tool-approval posture only. Filesystem scope is a separate fact and only
1010 /// earns header columns when it is worth reading — see
1011 /// [`filesystem_scope_notice`].
1012 pub(crate) fn permission_label(app: &App) -> Cow<'static, str> {
1013 codewhale_engine::core::authority::permission_label_for(
1014 app.ui_locale,
1015 app.mode,
1016 app.approval_mode,
1017 )
1018 }
1019
1020 /// The effective filesystem scope — but only when it says something the
1021 /// permission word beside it does not already say.
1022 ///
1023 /// This chip exists because "Full Access" (tool approval) was being read as
1024 /// unrestricted disk writes (user report, 2026-07-23), and because a policy
1025 /// with no enforcement backend used to name a boundary nobody applied
1026 /// (2026-08-04 audit). Both of those are deviations. The default — an
1027 /// enforced workspace-write boundary — is what every ordinary session already
1028 /// has, and printing `files: workspace` on every frame of every session spent
1029 /// seventeen columns of the primary chrome saying so. A notice that is always
1030 /// on cannot signal anything; folding the expected case away is what lets
1031 /// `files: workspace (unenforced)` and the Full-Access-but-confined case land
1032 /// as warnings when they do appear.
1033 ///
1034 /// `read-only` under Plan is dropped for the same reason from the other side:
1035 /// the permission word there is already the literal phrase "read only".
1036 #[must_use]
1037 fn filesystem_scope_notice(app: &App) -> Option<Cow<'static, str>> {
1038 // Spelled out because the old `fs:` prefix read as an unexplained
1039 // acronym (user report, 2026-07-23): this chip states which files the
1040 // session may write.
1041 let policy = codewhale_engine::core::authority::sandbox_policy_for_turn(
1042 app.mode,
1043 app.approval_mode,
1044 app.configured_sandbox_mode.as_deref(),
1045 &app.workspace,
1046 codewhale_engine::core::authority::SandboxNetworkAccess::from_config(
1047 app.configured_sandbox_network,
1048 ),
1049 );
1050 // A policy is an intent; enforcement needs a backend. On default Linux
1051 // (bubblewrap is opt-in) and on all Windows there is none. Say
1052 // "unenforced" rather than name a boundary that is not applied.
1053 // `DangerFullAccess` is already honest, and `ExternalSandbox` is enforced
1054 // by the external runner, not by us.
1055 let unenforced = app.sandbox_backend.is_none()
1056 && !matches!(
1057 policy,
1058 codewhale_sandbox::SandboxPolicy::DangerFullAccess
1059 | codewhale_sandbox::SandboxPolicy::ExternalSandbox { .. }
1060 );
1061 match policy {
1062 codewhale_sandbox::SandboxPolicy::ReadOnly { .. } if unenforced => {
1063 Some(Cow::Borrowed("files: read-only (unenforced)"))
1064 }
1065 codewhale_sandbox::SandboxPolicy::ReadOnly { .. } => {
1066 (app.mode != AppMode::Plan).then_some(Cow::Borrowed("files: read-only"))
1067 }
1068 // `DangerFullAccess` only ever arises from the Bypass posture
1069 // (`sandbox_policy_for_turn`), whose permission chip already reads
1070 // "Full Access" two words to the left. The name is the disclosure;
1071 // restating it as `files: full disk` spent columns saying it twice.
1072 // The scope chip speaks in this posture only when the scope is
1073 // *narrower* than the name implies (the WorkspaceWrite arm below).
1074 codewhale_sandbox::SandboxPolicy::DangerFullAccess => None,
1075 codewhale_sandbox::SandboxPolicy::ExternalSandbox { .. } => {
1076 Some(Cow::Borrowed("files: external sandbox"))
1077 }
1078 codewhale_sandbox::SandboxPolicy::WorkspaceWrite { .. } if unenforced => {
1079 Some(Cow::Borrowed("files: workspace (unenforced)"))
1080 }
1081 // The unremarkable case: writes are confined to the workspace and the
1082 // OS is actually enforcing it. Saying so on every frame of every
1083 // session spends the header on a fact nobody is asking about — with
1084 // one exception. When the permission chip reads "Full Access", the
1085 // scope chip is the only thing on screen that says the writes are
1086 // still confined. Suppressing it there recreates precisely the
1087 // misreading the chip was added for (tool-approval "Full Access" taken
1088 // to mean unrestricted disk writes), and that pairing is reachable:
1089 // Bypass with a configured `workspace-write` is clamped to this policy
1090 // by `sandbox_policy_for_turn`.
1091 codewhale_sandbox::SandboxPolicy::WorkspaceWrite { .. } => {
1092 (app.approval_mode == ApprovalMode::Bypass).then_some(Cow::Borrowed("files: workspace"))
1093 }
1094 }
1095 }
1096
1097 fn truncate_to_width(text: &str, width: usize) -> String {
1098 if text.width() <= width {
1099 return text.to_string();
1100 }
1101 if width == 0 {
1102 return String::new();
1103 }
1104 if width <= 3 {
1105 return ".".repeat(width);
1106 }
1107 let mut result = String::new();
1108 let mut used = 0;
1109 for grapheme in unicode_segmentation::UnicodeSegmentation::graphemes(text, true) {
1110 let grapheme_width = codewhale_tui_kit::ui_text::grapheme_display_width(grapheme);
1111 if used + grapheme_width + 1 > width {
1112 break;
1113 }
1114 result.push_str(grapheme);
1115 used += grapheme_width;
1116 }
1117 result.push('…');
1118 result
1119 }
1120
1121 /// The transcript rows the idle brand mark needs before it will draw at all.
1122 ///
1123 /// Named so the *layout* can honour it before the frame is split. Anything that reserves rows above
1124 /// the transcript must subtract against this constant rather than guess, or
1125 /// the reservation and the render gate drift and the mark is evicted by
1126 /// chrome that was sized without knowing the mark existed.
1127 pub(crate) const AMBIENT_MIN_CHAT_HEIGHT: u16 = 16;
1128 /// Companion column floor, same reasoning as [`AMBIENT_MIN_CHAT_HEIGHT`].
1129 pub(crate) const AMBIENT_MIN_CHAT_WIDTH: u16 = 60;
1130
1131 /// Build the post-launch idle composition: brand, workspace context, and one
1132 /// direct invitation. Commands stay in the command surface instead of reading
1133 /// like onboarding homework.
1134 ///
1135 /// Expressed in terms of the ambient floor constants so the layout rule that
1136 /// reserves the rows and the gate that spends them cannot disagree. (The old
1137 /// spelling also tested `height >= 14 && width >= 28`, which was dead: the
1138 /// tier check already demands 16 rows and 60 columns.)
1139 #[must_use]
1140 pub(crate) fn empty_state_mark_visible(area: Rect) -> bool {
1141 area.height >= AMBIENT_MIN_CHAT_HEIGHT && area.width >= AMBIENT_MIN_CHAT_WIDTH
1142 }
1143
1144 #[must_use]
1145 pub(crate) fn decorative_shell_motion_enabled(app: &App) -> bool {
1146 app.motion_policy().allows_decorative()
1147 && !app.attention_hold_active()
1148 && app.onboarding == OnboardingState::None
1149 && !app.launch.visible
1150 && app.view_stack.is_empty()
1151 }
1152
1153 #[must_use]
1154 pub(crate) fn ambient_life_motion_enabled(app: &App) -> bool {
1155 app.theme_id == codewhale_palette::ThemeId::Underwater
1156 && app.motion_policy().allows_decorative()
1157 && !app.attention_hold_active()
1158 && app.onboarding == OnboardingState::None
1159 && app.view_stack.is_empty()
1160 && app.viewport.transcript_scroll.is_at_tail()
1161 && app.viewport.ocean_caps.is_none_or(|caps| {
1162 matches!(
1163 caps.depth,
1164 codewhale_ratatui::color::ColorDepth::TrueColor
1165 | codewhale_ratatui::color::ColorDepth::Ansi256
1166 )
1167 })
1168 }
1169
1170 #[must_use]
1171 pub(crate) fn ambient_motion_terminal_supported(app: &App) -> bool {
1172 app.synchronized_output_enabled && !crate::tui::display_refresh::terminal_is_apple_terminal()
1173 }
1174
1175 /// Shorten a workspace path to its trailing components, marked with a leading
1176 /// ellipsis so it reads as "somewhere above here" rather than as a real path.
1177 fn shorten_workspace(workspace: &str, keep: usize) -> String {
1178 let sep = if workspace.contains('/') { '/' } else { '\\' };
1179 let parts: Vec<&str> = workspace.split(sep).filter(|p| !p.is_empty()).collect();
1180 if parts.len() <= keep {
1181 return workspace.to_string();
1182 }
1183 let tail = parts[parts.len() - keep..].join(&sep.to_string());
1184 let shortened = format!("…{sep}{tail}");
1185 // Only elide when it actually buys width. `~/code/app` -> `…/code/app` is
1186 // the same length and throws away the `~`, which carries more meaning than
1187 // the ellipsis does.
1188 if shortened.width() >= workspace.width() {
1189 return workspace.to_string();
1190 }
1191 shortened
1192 }
1193
1194 /// Compose the empty-state caption so the caller's centering can survive.
1195 ///
1196 /// This line sits between the wordmark and "What do you want to accomplish?",
1197 /// and every other element of that block is centered. It used to be built at
1198 /// full length and then handed to `truncate_to_width(.., width)`, which made it
1199 /// exactly `width` wide — so the caller's `(width - context.width()) / 2` inset
1200 /// evaluated to zero and the caption rendered flush-left, full-bleed, cutting
1201 /// the composition in half. The clipping also destroyed the information: an
1202 /// absolute path truncated mid-directory ("…/34267917-11f4-4d15-911a-…") tells
1203 /// the reader nothing about where they are.
1204 ///
1205 /// So the caption sheds detail rather than getting cut. In order of what goes
1206 /// first: the MCP count, then the branch, then the leading path components. The
1207 /// folder you are in is the last thing to go, because it is the only part a
1208 /// person actually reads here.
1209 ///
1210 /// One rule was added after watching it at 120 columns: the margin is
1211 /// proportional, not a flat four. A flat four let a 114-column path "fit" a
1212 /// 119-column lane, which put the centring inset back at two and reproduced
1213 /// the full-bleed banner this function exists to prevent — the same failure,
1214 /// arrived at from the other direction. A sixth of the lane, split either
1215 /// side, means the caption is always visibly a caption.
1216 fn empty_state_caption(
1217 workspace: &str,
1218 branch: &str,
1219 mcp_label: &str,
1220 mcp_count: usize,
1221 width: usize,
1222 ) -> String {
1223 // Leave a margin so the line is visibly inset rather than merely fitting,
1224 // and scale it, because "four columns" is only a margin at 60 columns.
1225 let budget = width.saturating_sub((width / 6).max(4)).max(8);
1226 let candidates = [
1227 format!("{workspace} · {branch} · {mcp_label} {mcp_count}"),
1228 format!("{workspace} · {branch}"),
1229 workspace.to_string(),
1230 format!("{} · {branch}", shorten_workspace(workspace, 2)),
1231 shorten_workspace(workspace, 2),
1232 shorten_workspace(workspace, 1),
1233 ];
1234 for candidate in &candidates {
1235 if candidate.width() <= budget {
1236 return candidate.clone();
1237 }
1238 }
1239 // Nothing fit: the last resort is the folder name alone, and the caller
1240 // still clamps. Better a bare name than a path clipped mid-component.
1241 shorten_workspace(workspace, 1)
1242 }
1243
1244 /// The launch card as the idle transcript's own content, plus where its
1245 /// clickable rows landed.
1246 ///
1247 /// The opening screen used to be a second surface: its own layout, its own
1248 /// composer widget, its own input authority. Founder ruling: "we don't have
1249 /// to have a different look for the opening screen ... we can make it an
1250 /// asset that exists there instead". So it is drawn as the empty state of the
1251 /// ordinary transcript — the ocean, the water and the chrome underneath it are
1252 /// the ones every other screen already uses, and the composer below it is the
1253 /// real one.
1254 pub struct LaunchEmptyState {
1255 pub lines: Vec<Line<'static>>,
1256 /// Text lane relative to the paint area. Outer whitespace is not a
1257 /// control; selection and pointer targets share this lane.
1258 text_column: Rect,
1259 /// Clickable rows as `(id, row index within `lines`)`. The caller turns
1260 /// these into rects against the painted area, so hitboxes and glyphs
1261 /// cannot drift apart.
1262 pub rows: Vec<(crate::tui::app::LaunchRowId, usize)>,
1263 }
1264
1265 /// Minimum left indent. Wider terminals balance the bounded reading lane
1266 /// inside the transcript rather than leaving it stranded against one edge.
1267 const LAUNCH_BLOCK_INDENT: usize = 2;
1268 /// The card's reading measure: a row is a title with its detail set against
1269 /// it, and without a ceiling the detail right-aligns against the terminal's
1270 /// far edge. The title is primary; the relative age is secondary.
1271 const LAUNCH_CARD_MEASURE: usize = 72;
1272 /// Gap between a row's title and its right-aligned detail.
1273 const LAUNCH_ROW_GAP: usize = 3;
1274 /// Below this the row spends its whole lane on the title and sheds the detail.
1275 const LAUNCH_ROW_MIN_TITLE: usize = 28;
1276 /// Labels align with their heading; the action cue has its own gutter.
1277 /// Blank rows the card spends on rhythm when the pane is tall enough.
1278 const LAUNCH_SEPARATORS: usize = 3;
1279 /// Blank rows per separator when the pane can afford them.
1280 const LAUNCH_GAP_ROOMY: usize = 2;
1281 /// Below this width the block gives up its left indent.
1282 const LAUNCH_INDENT_MIN_WIDTH: usize = 12;
1283
1284 pub fn empty_state_lines(app: &App, area: Rect) -> Vec<Line<'static>> {
1285 if area.width == 0 || area.height == 0 {
1286 return Vec::new();
1287 }
1288 // The opening screen is this screen: the launch card is the idle
1289 // transcript's own content, not a second surface painted over it.
1290 let motion_allowed = app.motion_policy().allows_decorative();
1291 if app.launch.visible
1292 || app
1293 .launch
1294 .session_handoff_active(app.ambient_clock_ms, motion_allowed)
1295 {
1296 // The first keystroke starts the dissolve clock; the card sinks by
1297 // ink, not by position — every span eases toward the water behind it
1298 // over `LAUNCH_CARD_DISSOLVE_MS`, and at the end the ambient surface
1299 // (wordmark, caption, prompt) is what remains. Reduced motion takes
1300 // the endpoint at once.
1301 let dissolve = app
1302 .launch
1303 .card_dissolve_progress(app.ambient_clock_ms, motion_allowed);
1304 if dissolve < 1.0 {
1305 let mut state = launch_empty_state(app, area);
1306 if dissolve > 0.0 {
1307 fade_lines(&mut state.lines, dissolve, app.ui_theme.surface_bg);
1308 }
1309 return state.lines;
1310 }
1311 }
1312 let width = usize::from(area.width);
1313 let mut lines = vec![Line::from(""); usize::from(area.height / 4)];
1314 // The idle whale portrait that used to open this block was deleted per
1315 // the 2026-08-29 founder directive; the ambient empty-state surface
1316 // (wordmark, context caption, prompt) is not whale art and stays.
1317
1318 let identity = crate::tui::workspace_context::identity_from_context(
1319 &app.workspace,
1320 app.workspace_context.as_deref(),
1321 );
1322 let workspace = codewhale_util::utils::display_path(&app.workspace);
1323 let branch = identity.branch.as_deref().map_or_else(
1324 || tr(app.ui_locale, MessageId::EmptyStateNoGit),
1325 |branch| Cow::Owned(branch.to_string()),
1326 );
1327 // Compact used to bypass the caption entirely and print the bare branch,
1328 // which in a plain folder rendered as the single centred word "no git" —
1329 // a whole row of the hero spent naming something that is not there. The
1330 // shedding ladder already degrades gracefully at any width, so every tier
1331 // now goes through it.
1332 let context = empty_state_caption(
1333 &workspace,
1334 &branch,
1335 tr(app.ui_locale, MessageId::EmptyStateMcpLabel).as_ref(),
1336 app.mcp_configured_count,
1337 width,
1338 );
1339 let brand = "codewhale";
1340 let brand_inset = " ".repeat(width.saturating_sub(brand.width()) / 2);
1341 lines.push(Line::from(Span::styled(
1342 format!("{brand_inset}{brand}"),
1343 Style::default()
1344 .fg(app.ui_theme.text_body)
1345 .add_modifier(Modifier::BOLD),
1346 )));
1347 let context = truncate_to_width(&context, width);
1348 let inset = " ".repeat(width.saturating_sub(context.width()) / 2);
1349 lines.push(Line::from(Span::styled(
1350 format!("{inset}{context}"),
1351 Style::default().fg(app.ui_theme.text_soft),
1352 )));
1353 if area.height >= 4 {
1354 lines.push(Line::from(""));
1355 let prompt = tr(app.ui_locale, MessageId::EmptyStatePrompt);
1356 let prompt = truncate_to_width(prompt.as_ref(), width);
1357 let inset = " ".repeat(width.saturating_sub(prompt.width()) / 2);
1358 lines.push(Line::from(Span::styled(
1359 format!("{inset}{prompt}"),
1360 Style::default().fg(app.ui_theme.text_body),
1361 )));
1362 }
1363 lines
1364 }
1365
1366 fn fade_lines(lines: &mut [Line<'static>], dissolve: f32, water: Color) {
1367 for line in lines.iter_mut() {
1368 for span in line.spans.iter_mut() {
1369 for ink in [&mut span.style.fg, &mut span.style.bg]
1370 .into_iter()
1371 .flatten()
1372 {
1373 *ink = codewhale_tui_kit::mark::lerp_color(*ink, water, dissolve);
1374 }
1375 }
1376 }
1377 }
1378
1379 /// How much of the card fits the pane. `New session` is never shed: it is the
1380 /// screen's one actionable choice.
1381 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
1382 struct LaunchFit {
1383 brand: bool,
1384 context: bool,
1385 help: bool,
1386 notice: bool,
1387 whats_new: usize,
1388 /// The "no model connected · run /provider" line (UX-3).
1389 setup: bool,
1390 heading: bool,
1391 blanks: usize,
1392 shown: usize,
1393 see_all: bool,
1394 extensions: usize,
1395 /// Blank rows per separator. A pane with height to spare spends it on
1396 /// breathing room before it spends it on more content: one blank line
1397 /// between blocks packs the card into the top-left corner of a tall
1398 /// terminal and reads as clutter even when every row is earning its place.
1399 /// This is the first thing shed, so a short pane is unaffected.
1400 gap: usize,
1401 }
1402
1403 impl LaunchFit {
1404 const fn rows(self) -> usize {
1405 (self.brand as usize)
1406 + (self.context as usize)
1407 + (self.help as usize)
1408 + (self.notice as usize)
1409 + self.whats_new
1410 + (self.setup as usize)
1411 + self.blanks * self.gap
1412 + 1
1413 + (self.heading as usize)
1414 + self.shown
1415 + (self.see_all as usize)
1416 + self.extensions
1417 }
1418 }
1419
1420 /// Shed the card down to `height`, in a fixed order: rhythm, the migration
1421 /// notice, release notes, identity/help chrome, then the tail of
1422 /// the recent list. The overflow row keeps any hidden sessions reachable.
1423 /// The "no model connected" line goes last of all: on a keyless first run
1424 /// it is the only thing on the card that explains why nothing will answer.
1425 ///
1426 /// The MCP block gives up its rows before the recent list does (recent work
1427 /// is what the screen is *for*) but keeps its summary line until almost
1428 /// everything else has gone, because "2 failed" in one row still tells the
1429 /// truth that the footer chip could not.
1430 fn launch_fit(
1431 height: usize,
1432 recent: Option<usize>,
1433 has_more: bool,
1434 notice: bool,
1435 whats_new: usize,
1436 extensions: usize,
1437 setup: bool,
1438 ) -> LaunchFit {
1439 let expanded = recent.is_some();
1440 let recent = recent.unwrap_or_default();
1441 let mut fit = LaunchFit {
1442 brand: true,
1443 context: true,
1444 help: expanded,
1445 notice,
1446 whats_new,
1447 setup,
1448 heading: expanded && (recent > 0 || has_more),
1449 blanks: if expanded { LAUNCH_SEPARATORS } else { 1 },
1450 shown: recent,
1451 see_all: has_more,
1452 extensions,
1453 gap: LAUNCH_GAP_ROOMY,
1454 };
1455 let mut step = 0u8;
1456 while fit.rows() > height {
1457 match step {
1458 // Breathing room is the first luxury to go, before any content.
1459 0 => fit.gap = 1,
1460 1 => fit.blanks = 1,
1461 2 => fit.blanks = 0,
1462 3 => {
1463 fit.extensions = fit.extensions.min(1);
1464 if fit.rows() > height {
1465 fit.notice = false;
1466 }
1467 }
1468 4 => {
1469 while fit.whats_new > 0 && fit.rows() > height {
1470 fit.whats_new -= 1;
1471 }
1472 }
1473 5 => fit.help = false,
1474 6 => fit.context = false,
1475 7 => fit.heading = false,
1476 8 => fit.brand = false,
1477 9 => {
1478 while fit.shown > 0 && fit.rows() > height {
1479 fit.shown -= 1;
1480 fit.see_all = true;
1481 }
1482 }
1483 10 => fit.extensions = 0,
1484 11 => fit.see_all = false,
1485 12 => fit.setup = false,
1486 _ => break,
1487 }
1488 step += 1;
1489 }
1490 fit
1491 }
1492
1493 fn whats_new_launch_lines(app: &App, text_width: usize) -> Vec<(String, bool)> {
1494 let Some(notice) = app.launch.whats_new.as_ref() else {
1495 return Vec::new();
1496 };
1497 if app.launch.return_to_session {
1498 return Vec::new();
1499 }
1500 let headline = notice.headline();
1501 let mut lines: Vec<(String, bool)> = if text_display_width(&headline) <= text_width {
1502 vec![(headline, false)]
1503 } else {
1504 let mut rows = crate::tui::onboarding::wrap_words(&notice.updated, text_width);
1505 if let Some(summary) = &notice.summary {
1506 for paragraph in summary.lines() {
1507 rows.extend(crate::tui::onboarding::wrap_words(paragraph, text_width));
1508 }
1509 } else if let Some(counts) = &notice.counts {
1510 rows.extend(crate::tui::onboarding::wrap_words(counts, text_width));
1511 }
1512 rows.into_iter().map(|row| (row, false)).collect()
1513 };
1514 let notes = [notice.notes_with_command(), notice.notes.clone()]
1515 .into_iter()
1516 .find(|line| text_display_width(line) <= text_width)
1517 .unwrap_or_else(|| notice.url.clone());
1518 lines.push((notes, true));
1519 lines
1520 }
1521
1522 pub fn launch_empty_state(app: &App, area: Rect) -> LaunchEmptyState {
1523 build_launch_card(app, area, env!("CODEWHALE_BUILD_VERSION"))
1524 }
1525
1526 fn build_launch_card(app: &App, area: Rect, build_version: &str) -> LaunchEmptyState {
1527 if area.width == 0 || area.height == 0 {
1528 return LaunchEmptyState {
1529 lines: Vec::new(),
1530 rows: Vec::new(),
1531 text_column: Rect::default(),
1532 };
1533 }
1534 let width = usize::from(area.width);
1535 let height = usize::from(area.height);
1536 let theme = &app.ui_theme;
1537 let locale = app.ui_locale;
1538 let mut lines: Vec<Line<'static>> = Vec::new();
1539 let mut rows: Vec<(crate::tui::app::LaunchRowId, usize)> = Vec::new();
1540
1541 // One reading lane: identity never steals width from session titles.
1542 // Reserve a two-cell action gutter where the terminal can afford it.
1543 let measure = if app.launch.recent_expanded
1544 || app.launch.claude_code_detected
1545 || app.launch.whats_new.is_some()
1546 {
1547 LAUNCH_CARD_MEASURE
1548 } else {
1549 60
1550 };
1551 let block_indent = if width >= LAUNCH_INDENT_MIN_WIDTH {
1552 LAUNCH_BLOCK_INDENT.max(width.saturating_sub(measure + 2) / 2)
1553 } else {
1554 0
1555 };
1556 let action_gutter = if width >= LAUNCH_INDENT_MIN_WIDTH {
1557 2
1558 } else {
1559 0
1560 };
1561 let text_indent = block_indent + action_gutter;
1562 let text_width = width
1563 .saturating_sub(text_indent + block_indent)
1564 .min(measure);
1565 if text_width == 0 {
1566 return LaunchEmptyState {
1567 lines: Vec::new(),
1568 rows: Vec::new(),
1569 text_column: Rect::default(),
1570 };
1571 }
1572
1573 let (entries, has_more) = if app.launch.recent_expanded {
1574 launch_recent_entries(app)
1575 } else {
1576 (
1577 Vec::new(),
1578 app.launch.has_scoped_sessions || !app.launch.recent.is_empty(),
1579 )
1580 };
1581 // Nothing will answer a message until a model is connected; the card
1582 // says so instead of letting the first Enter fail silently (UX-3).
1583 let no_model_connected = app.onboarding_needs_api_key && !app.launch.return_to_session;
1584 let extensions = launch_extension_rows(app);
1585 let whats_new_lines = whats_new_launch_lines(app, text_width);
1586 let fit = launch_fit(
1587 height,
1588 app.launch.recent_expanded.then_some(entries.len()),
1589 has_more,
1590 app.launch.claude_code_detected,
1591 whats_new_lines.len(),
1592 extensions.len(),
1593 no_model_connected,
1594 );
1595 let ascii = crate::tui::color_compat::ascii_safe_enabled();
1596 let mark = if fit.brand && fit.context && !ascii {
1597 crate::tui::whales::LaunchWhale::fitting(
1598 text_width.saturating_sub(21),
1599 height.saturating_sub(fit.rows()) + 2,
1600 )
1601 } else {
1602 None
1603 };
1604 let mark_width = mark.map_or(0, |mark| mark.width + 2);
1605 let header_width = text_width.saturating_sub(mark_width);
1606 let spacious = fit.blanks == LAUNCH_SEPARATORS;
1607 let visible: Vec<LaunchRecentEntry> = entries.into_iter().take(fit.shown).collect();
1608 let mut card_rows = home_card_rows(app, &visible, fit.see_all, fit.setup);
1609 card_rows.extend(extensions.into_iter().take(fit.extensions));
1610
1611 // The text column, in order. `None` is a blank row.
1612 let mut text: Vec<Option<Line<'static>>> = Vec::new();
1613 if fit.brand {
1614 let brand = "codewhale";
1615 let mut spans = vec![Span::styled(
1616 semantic_truncate(brand, header_width),
1617 Style::default().fg(theme.text_body).bold(),
1618 )];
1619 let room = width.saturating_sub(text_indent + mark_width + brand.len() + 2);
1620 if let Some(version) = [build_version, env!("CARGO_PKG_VERSION")]
1621 .into_iter()
1622 .find(|v| v.len() < room)
1623 {
1624 spans.push(Span::styled(
1625 format!(" v{version}"),
1626 Style::default().fg(theme.text_muted),
1627 ));
1628 }
1629 text.push(Some(Line::from(spans)));
1630 }
1631 if fit.context {
1632 let identity = crate::tui::workspace_context::identity_from_context(
1633 &app.workspace,
1634 app.workspace_context.as_deref(),
1635 );
1636 let mut spans = Vec::new();
1637 let branch_width = identity
1638 .branch
1639 .as_ref()
1640 .filter(|_| header_width >= 8)
1641 .map_or(0, |b| text_display_width(b).min(header_width / 2));
1642 let name_budget = if branch_width > 0 {
1643 header_width.saturating_sub(branch_width + 3)
1644 } else {
1645 header_width
1646 };
1647 let path = codewhale_util::utils::display_path(&app.workspace);
1648 let name =
1649 crate::tui::workspace_context::truncate_left(&shorten_workspace(&path, 2), name_budget);
1650 spans.push(Span::styled(name, Style::default().fg(theme.text_body)));
1651 if branch_width > 0
1652 && let Some(branch) = identity.branch
1653 {
1654 spans.push(Span::styled(
1655 if ascii { " / " } else { " · " },
1656 Style::default().fg(theme.text_muted),
1657 ));
1658 spans.push(Span::styled(
1659 crate::tui::workspace_context::truncate_left(&branch, branch_width),
1660 Style::default().fg(theme.accent_secondary),
1661 ));
1662 }
1663 text.push(Some(Line::from(spans)));
1664 }
1665 if let Some(mark) = mark {
1666 use codewhale_ratatui::{
1667 color::{mix_oklab, specular_lift},
1668 whale_motion::arrival,
1669 };
1670 let accent = crate::tui::widgets::composer_chat_color(app).unwrap_or(theme.accent_primary);
1671 let base = [
1672 Color::Reset,
1673 mix_oklab(theme.accent_secondary, theme.text_body, 0.72),
1674 mix_oklab(accent, theme.accent_secondary, 0.74),
1675 accent,
1676 mix_oklab(accent, theme.panel_bg, 0.37),
1677 ];
1678 let mut inks = [Style::default(); 5 * arrival::RIM_LEVELS];
1679 let motion = app.motion_policy().allows_decorative()
1680 && !app.low_motion
1681 && !app.launch.return_to_session;
1682 let elapsed = app
1683 .launch
1684 .mark_reveal_started_at
1685 .filter(|_| motion)
1686 .map(|start| start.elapsed())
1687 .filter(|elapsed| *elapsed < arrival::DURATION);
1688 for (i, style) in inks.iter_mut().enumerate().take(if elapsed.is_some() {
1689 5 * arrival::RIM_LEVELS
1690 } else {
1691 5
1692 }) {
1693 if i % 5 == 0 {
1694 continue;
1695 }
1696 let amount = (i / 5) as f32 / (arrival::RIM_LEVELS - 1) as f32;
1697 let ink = base[i % 5];
1698 let light = if matches!(
1699 theme.mode,
1700 codewhale_palette::PaletteMode::Light
1701 | codewhale_palette::PaletteMode::SolarizedLight
1702 ) {
1703 mix_oklab(ink, theme.text_body, amount * 0.8)
1704 } else {
1705 specular_lift(ink, theme.text_body, amount * 0.95)
1706 };
1707 *style = Style::default().fg(light);
1708 }
1709 let rows = mark.rows(elapsed);
1710 let identity = std::mem::take(&mut text);
1711 let offset = (rows.len() - identity.len()) / 2;
1712 let mut identity = identity.into_iter();
1713 for (y, runs) in rows.iter().enumerate() {
1714 let mut spans = runs
1715 .iter()
1716 .map(|(tone, dots)| Span::styled(dots.as_str(), inks[*tone]))
1717 .collect::<Vec<_>>();
1718 if y >= offset
1719 && let Some(Some(line)) = identity.next()
1720 {
1721 spans.push(Span::raw(" "));
1722 spans.extend(line.spans);
1723 }
1724 text.push(Some(Line::from(spans)));
1725 }
1726 }
1727 for (line, muted) in whats_new_lines.iter().take(fit.whats_new) {
1728 let ink = if *muted {
1729 theme.text_muted
1730 } else {
1731 theme.text_body
1732 };
1733 text.push(Some(Line::from(Span::styled(
1734 semantic_truncate(line, text_width),
1735 Style::default().fg(ink),
1736 ))));
1737 }
1738 // The migration notice, while there is still a question to answer. It
1739 // retires for good once `/import-claude` has been run.
1740 if fit.notice {
1741 text.push(Some(Line::from(Span::styled(
1742 semantic_truncate(&tr(locale, MessageId::LaunchNoticeClaude), text_width),
1743 Style::default().fg(theme.text_muted),
1744 ))));
1745 }
1746 if fit.blanks >= 1 {
1747 for _ in 0..fit.gap {
1748 text.push(None);
1749 }
1750 }
1751
1752 for (index, row) in card_rows.iter().enumerate() {
1753 let style = if row.warning {
1754 Style::default().fg(theme.warning)
1755 } else if row.prominent {
1756 Style::default().fg(theme.text_body).bold()
1757 } else {
1758 Style::default().fg(theme.text_body)
1759 };
1760 if matches!(row.id, crate::tui::app::LaunchRowId::SeeAll) && spacious {
1761 for _ in 0..fit.gap {
1762 text.push(None);
1763 }
1764 }
1765 let lane = text_width.saturating_sub(usize::from(text_width >= LAUNCH_INDENT_MIN_WIDTH));
1766 // Age is context: when the lane cannot hold a readable title
1767 // beside it, drop the age whole
1768 // rather than ellipsing the title to a stub. This is also the
1769 // fallback for a locale that spends more cells on the same fact.
1770 let min_title = if matches!(row.id, crate::tui::app::LaunchRowId::Recent(_)) {
1771 row.label.width().min(LAUNCH_ROW_MIN_TITLE)
1772 } else {
1773 row.label.width()
1774 };
1775 let cue = if app.launch.menu_selected == Some(index) {
1776 Some(("Enter", tr(locale, MessageId::LaunchHintOpen)))
1777 } else if index == 0 && app.launch.menu_selected.is_none() {
1778 let arrows = if ascii { "Up/Down" } else { "↑↓" };
1779 Some((arrows, tr(locale, MessageId::LaunchHintMove)))
1780 } else {
1781 None
1782 };
1783 let mut detail = row.detail.clone();
1784 if let Some((keys, verb)) = cue {
1785 let full = format!("{keys} {verb}");
1786 for (hint, title_gap, separator) in [
1787 (full.as_str(), LAUNCH_ROW_GAP, " "),
1788 (full.as_str(), 1, " "),
1789 (keys, 1, " "),
1790 ] {
1791 let separator = if detail.is_empty() { "" } else { separator };
1792 if min_title + title_gap + detail.width() + separator.len() + hint.width() <= lane {
1793 detail.push_str(separator);
1794 detail.push_str(hint);
1795 break;
1796 }
1797 }
1798 }
1799 let detail_width = text_display_width(&detail);
1800 let gap = lane
1801 .saturating_sub(min_title + detail_width)
1802 .min(LAUNCH_ROW_GAP);
1803 let label_budget = if detail.is_empty() || gap == 0 {
1804 detail.clear();
1805 lane
1806 } else {
1807 lane - gap - detail_width
1808 };
1809 let label = semantic_truncate(&row.label, label_budget);
1810 let label_width = text_display_width(&label);
1811 let mut spans = Vec::with_capacity(4);
1812 spans.push(Span::styled(label, style));
1813 if !detail.is_empty() {
1814 let pad = lane
1815 .saturating_sub(label_width)
1816 .saturating_sub(detail_width);
1817 spans.push(Span::raw(" ".repeat(pad)));
1818 spans.push(Span::styled(detail, Style::default().fg(theme.text_muted)));
1819 }
1820 rows.push((row.id.clone(), text.len()));
1821 text.push(Some(Line::from(spans)));
1822 if matches!(
1823 row.id,
1824 crate::tui::app::LaunchRowId::NewSession
1825 | crate::tui::app::LaunchRowId::ReturnToSession
1826 ) && fit.heading
1827 {
1828 // An empty workspace needs only the invitation and composer.
1829 // Real history, including filtered sessions reachable via See all,
1830 // still gets a heading; zero counts are not content.
1831 if spacious {
1832 for _ in 0..fit.gap {
1833 text.push(None);
1834 }
1835 }
1836 let label = semantic_truncate(&tr(locale, MessageId::LaunchRecentHeading), text_width);
1837 let mut remaining = text_width.saturating_sub(text_display_width(&label) + 2);
1838 let mut spans = vec![Span::styled(
1839 label,
1840 Style::default().fg(theme.text_soft).bold(),
1841 )];
1842 let resume = tr(locale, MessageId::LaunchRecentResumeHint);
1843 if card_rows
1844 .iter()
1845 .any(|row| matches!(row.id, crate::tui::app::LaunchRowId::Recent(_)))
1846 && remaining >= text_display_width(&resume) + 6
1847 {
1848 remaining = remaining.saturating_sub(text_display_width(&resume) + 2);
1849 spans.push(Span::styled(
1850 format!(" {resume}"),
1851 Style::default().fg(theme.text_hint),
1852 ));
1853 }
1854 if remaining >= 4 {
1855 let rule = if crate::tui::color_compat::ascii_safe_enabled() {
1856 "-"
1857 } else {
1858 "─"
1859 };
1860 spans.push(Span::styled(
1861 format!(" {}", rule.repeat(remaining)),
1862 Style::default().fg(theme.border),
1863 ));
1864 }
1865 text.push(Some(Line::from(spans)));
1866 }
1867 }
1868
1869 // Keep the invitation and recent work ahead of command instructions.
1870 if fit.help {
1871 if text.len() + 1 < height {
1872 text.push(None);
1873 }
1874 text.push(Some(Line::from(Span::styled(
1875 semantic_truncate(
1876 &tr(locale, MessageId::LaunchHelpLine).replace(
1877 "{dock}",
1878 crate::tui::shell_key_routing::binding(
1879 crate::tui::shell_key_routing::ShellBindingId::ViewCycle,
1880 )
1881 .footer_chord,
1882 ),
1883 text_width,
1884 ),
1885 Style::default().fg(theme.text_hint),
1886 ))));
1887 }
1888
1889 let top = height.saturating_sub(text.len()) / 2;
1890 lines.resize_with(top, || Line::from(""));
1891 let block_rows = text.len().min(height.saturating_sub(lines.len()));
1892 let mut row_offsets = Vec::with_capacity(block_rows);
1893 for (row, line) in text.iter().take(block_rows).enumerate() {
1894 let action = rows.iter().position(|(_, y)| *y == row);
1895 let selected = action.is_some_and(|i| app.launch.menu_selected == Some(i));
1896 let hovered = action.is_some_and(|i| app.launch.hovered_row == Some(i));
1897 let style = if selected {
1898 codewhale_tui_kit::menu_style::theme_selected_row_style(theme)
1899 } else if hovered {
1900 codewhale_tui_kit::menu_style::hovered_row_style().bg(theme.elevated_bg)
1901 } else if let Some(index) = action {
1902 Style::default().bg(if card_rows[index].prominent {
1903 theme.elevated_bg
1904 } else {
1905 theme.panel_bg
1906 })
1907 } else {
1908 Style::default()
1909 };
1910 let mut spans = vec![Span::raw(" ".repeat(block_indent))];
1911 if action_gutter > 0 {
1912 let (marker, ink) = if selected {
1913 (if ascii { "> " } else { "▸ " }, theme.accent_primary)
1914 } else if hovered {
1915 (if ascii { "> " } else { "› " }, theme.accent_primary)
1916 } else {
1917 match action.map(|i| &rows[i].0) {
1918 Some(crate::tui::app::LaunchRowId::NewSession) => ("+ ", theme.accent_primary),
1919 Some(_) => (if ascii { "> " } else { "› " }, theme.text_muted),
1920 None => (" ", theme.text_muted),
1921 }
1922 };
1923 spans.push(Span::styled(marker, style.fg(ink)));
1924 }
1925 if let Some(line) = line {
1926 spans.extend(line.spans.iter().cloned().enumerate().map(|(i, mut span)| {
1927 span.style = span.style.patch(style);
1928 if hovered && i == 0 {
1929 span.style = span.style.add_modifier(Modifier::UNDERLINED);
1930 }
1931 span
1932 }));
1933 if action.is_some() {
1934 spans.push(Span::styled(
1935 " ".repeat(text_width.saturating_sub(line.width())),
1936 style,
1937 ));
1938 }
1939 }
1940 row_offsets.push(lines.len());
1941 lines.push(Line::from(spans));
1942 }
1943
1944 // Re-point the hitboxes at the composed rows. A row the block could not
1945 // fit has no offset, so it has no hitbox either.
1946 let rows = rows
1947 .into_iter()
1948 .filter_map(|(id, text_row)| row_offsets.get(text_row).map(|y| (id, *y)))
1949 .collect();
1950
1951 LaunchEmptyState {
1952 lines,
1953 rows,
1954 text_column: Rect::new(
1955 block_indent as u16,
1956 0,
1957 (text_width + action_gutter) as u16,
1958 area.height,
1959 ),
1960 }
1961 }
1962
1963 #[cfg(test)]
1964 mod launch_card_tests {
1965 use super::{
1966 LAUNCH_CARD_MEASURE, LaunchAction, launch_empty_state, launch_fit, launch_recent_entries,
1967 launch_rows_for_app, refresh_launch_row_hitboxes, run_launch_card_row, text_display_width,
1968 };
1969 use crate::tui::app::{App, LaunchRecentSession, LaunchRowId};
1970 use codewhale_localization::{Locale, MessageId, tr};
1971 use ratatui::layout::Rect;
1972 use ratatui::text::Line;
1973 use unicode_segmentation::UnicodeSegmentation;
1974
1975 fn app_with_recent(titles: &[&str], total: usize) -> App {
1976 let mut app = crate::tui::test_support::test_app_with_options(
1977 crate::tui::test_support::test_tui_options(std::env::temp_dir()),
1978 );
1979 app.launch.visible = true;
1980 app.launch.recent_expanded = true;
1981 app.launch.claude_code_detected = false;
1982 app.cached_skills.clear();
1983 app.launch.recent = titles
1984 .iter()
1985 .enumerate()
1986 .map(|(index, title)| LaunchRecentSession {
1987 id: format!("{index}0abcdef-session"),
1988 title: (*title).to_string(),
1989 updated_at: chrono::Utc::now()
1990 - chrono::Duration::hours(i64::try_from(index).unwrap_or(0) + 1),
1991 message_count: 40 + index,
1992 interrupted: false,
1993 })
1994 .collect();
1995 app.launch.total_workspace_sessions = total;
1996 app
1997 }
1998
1999 #[test]
2000 fn launch_primary_action_has_readable_ink_in_every_theme() {
2001 for theme in codewhale_palette::SELECTABLE_THEMES {
2002 let mut app = app_with_recent(&["Recent proof"], 1);
2003 app.ui_theme = theme.ui_theme();
2004 app.theme_id = *theme;
2005 let card = launch_empty_state(&app, Rect::new(0, 0, 100, 24));
2006 let span = card
2007 .lines
2008 .iter()
2009 .flat_map(|line| &line.spans)
2010 .find(|span| span.content.contains("New session"))
2011 .unwrap();
2012 assert_eq!(
2013 span.style.fg,
2014 Some(app.ui_theme.text_body),
2015 "{}",
2016 theme.name()
2017 );
2018 if let Some(ratio) =
2019 codewhale_palette::contrast_ratio(span.style.fg.unwrap(), app.ui_theme.panel_bg)
2020 {
2021 assert!(
2022 ratio >= 4.5,
2023 "{} New session contrast {ratio}",
2024 theme.name()
2025 );
2026 }
2027 }
2028 }
2029
2030 #[test]
2031 fn completion_settle_keeps_done_label_stable() {
2032 let mut app = app_with_recent(&[], 0);
2033 app.low_motion = false;
2034 app.fancy_animations = true;
2035 let activity = super::LiveActivity::from_app(&app);
2036 for elapsed in [0, 280, 700] {
2037 app.ocean_completion_started_at =
2038 Some(std::time::Instant::now() - std::time::Duration::from_millis(elapsed));
2039 let (_, label) =
2040 super::phase_marker_with_activity(&app, super::ShellPhase::Done, activity);
2041 assert_eq!(label, super::ShellPhase::Done.label(app.ui_locale));
2042 }
2043 }
2044
2045 #[test]
2046 fn launch_reveal_stops_scheduling_after_its_endpoint() {
2047 let mut app = app_with_recent(&[], 0);
2048 app.onboarding = crate::tui::app::OnboardingState::None;
2049 app.theme_id = codewhale_palette::ThemeId::Shoreline;
2050 app.low_motion = false;
2051 app.fancy_animations = true;
2052 app.launch.mark_reveal_started_at = Some(std::time::Instant::now());
2053 assert!(super::launch_motion_active(&app, false, true));
2054 assert!(!super::launch_motion_active(&app, true, true));
2055 app.low_motion = true;
2056 assert!(!super::launch_motion_active(&app, false, true));
2057 app.low_motion = false;
2058 app.launch.mark_reveal_started_at =
2059 Some(std::time::Instant::now() - codewhale_ratatui::whale_motion::arrival::DURATION);
2060 assert!(!super::launch_motion_active(&app, false, true));
2061 }
2062
2063 /// The founder's own shape: many servers, a couple genuinely broken, a
2064 /// pile sitting unauthenticated, the rest fine.
2065 fn with_mcp(mut app: App) -> App {
2066 use codewhale_engine::mcp::{
2067 McpManagerSnapshot, McpServerCapabilityMetadata, McpServerSnapshot,
2068 };
2069 let mut servers = Vec::new();
2070 let mut push = |name: &str, connected: bool, error: Option<&str>, auth: bool| {
2071 servers.push(McpServerSnapshot {
2072 name: name.to_string(),
2073 enabled: true,
2074 required: false,
2075 transport: "stdio".to_string(),
2076 command_or_url: format!("cmd-{name}"),
2077 connect_timeout: 5,
2078 execute_timeout: 5,
2079 read_timeout: 5,
2080 connected,
2081 error: error.map(str::to_string),
2082 auth_required: auth,
2083 capability_metadata: McpServerCapabilityMetadata::NotObserved,
2084 tools: Vec::new(),
2085 resources: Vec::new(),
2086 prompts: Vec::new(),
2087 });
2088 };
2089 for name in ["github", "linear", "supabase", "posthog", "vercel"] {
2090 push(name, true, None, false);
2091 }
2092 push(
2093 "alibaba-cloud-ops",
2094 false,
2095 Some("Invalid request parameters"),
2096 false,
2097 );
2098 push("aws-mcp", false, Some("Stdio transport closed"), false);
2099 for name in ["slack", "notion", "stripe", "figma", "excalidraw"] {
2100 push(name, false, Some("401 Unauthorized"), true);
2101 }
2102 app.mcp_configured_count = servers.len();
2103 app.mcp_snapshot = Some(McpManagerSnapshot {
2104 config_path: std::path::PathBuf::from("mcp.json"),
2105 config_exists: true,
2106 reload_required: false,
2107 servers,
2108 });
2109 app.set_mcp_boot_initializing(false);
2110 app.mcp_connecting = Vec::new();
2111 app
2112 }
2113
2114 fn flatten(line: &Line<'_>) -> String {
2115 line.spans
2116 .iter()
2117 .map(|span| span.content.to_string())
2118 .collect::<String>()
2119 }
2120
2121 fn painted(app: &App, width: u16, height: u16) -> Vec<String> {
2122 launch_empty_state(app, Rect::new(0, 0, width, height))
2123 .lines
2124 .iter()
2125 .map(|line| flatten(line).trim_end().to_string())
2126 .collect()
2127 }
2128
2129 fn row_ids(app: &App) -> Vec<LaunchRowId> {
2130 app.launch
2131 .row_hitboxes
2132 .iter()
2133 .map(|(id, _)| id.clone())
2134 .collect()
2135 }
2136
2137 /// The recent row's own text, with the block indent stripped. Only used at
2138 /// widths narrow enough that the detail has shed, so what remains is the
2139 /// title alone.
2140 fn recent_row_title(app: &App, width: u16, height: u16) -> String {
2141 let state = launch_empty_state(app, Rect::new(0, 0, width, height));
2142 let (_, row) = state
2143 .rows
2144 .iter()
2145 .find(|(id, _)| matches!(id, LaunchRowId::Recent(_)))
2146 .expect("a recent row painted");
2147 flatten(&state.lines[*row])
2148 .trim()
2149 .trim_start_matches("› ")
2150 .trim_start_matches("> ")
2151 .to_string()
2152 }
2153
2154 fn is_grapheme_prefix(candidate: &str, full: &str) -> bool {
2155 let mut source = full.graphemes(true);
2156 candidate.graphemes(true).all(|g| source.next() == Some(g))
2157 }
2158
2159 // --- one ordering for paint, mouse, and keyboard -------------------
2160
2161 #[test]
2162 fn keyboard_rows_are_exactly_the_rows_the_pane_painted() {
2163 let mut app = app_with_recent(&["one", "two", "three", "four", "five"], 9);
2164
2165 refresh_launch_row_hitboxes(&mut app, Rect::new(0, 0, 120, 30));
2166 let tall = launch_rows_for_app(&app);
2167 assert_eq!(
2168 tall.iter().map(|row| row.id.clone()).collect::<Vec<_>>(),
2169 row_ids(&app),
2170 "keyboard list must be the painted list",
2171 );
2172 assert!(tall.len() >= 7, "{:?}", row_ids(&app));
2173
2174 // Highlight the last row, then shrink the pane under it.
2175 app.launch.menu_selected = Some(tall.len() - 1);
2176 refresh_launch_row_hitboxes(&mut app, Rect::new(0, 0, 120, 4));
2177 let short = launch_rows_for_app(&app);
2178 assert_eq!(
2179 short.iter().map(|row| row.id.clone()).collect::<Vec<_>>(),
2180 row_ids(&app),
2181 );
2182 assert!(short.len() < tall.len(), "the short pane shed nothing");
2183
2184 // The stale highlight is gone, so Enter cannot resume a row that is
2185 // no longer on screen.
2186 assert_eq!(app.launch.menu_selected, None);
2187 assert_eq!(
2188 run_launch_card_row(&short, app.launch.menu_selected),
2189 LaunchAction::None,
2190 );
2191 }
2192
2193 #[test]
2194 fn no_keyboard_row_names_a_session_the_pane_is_not_showing() {
2195 let mut app = app_with_recent(&["one", "two", "three", "four", "five"], 5);
2196 for height in 0u16..=14 {
2197 refresh_launch_row_hitboxes(&mut app, Rect::new(0, 0, 120, height));
2198 let painted: Vec<LaunchRowId> = row_ids(&app);
2199 for row in launch_rows_for_app(&app) {
2200 assert!(
2201 painted.contains(&row.id),
2202 "height {height}: {:?} is runnable but was not painted",
2203 row.id,
2204 );
2205 }
2206 // Every arrow position runs a painted row or nothing at all.
2207 for index in 0..painted.len() + 3 {
2208 let rows = launch_rows_for_app(&app);
2209 match run_launch_card_row(&rows, Some(index)) {
2210 LaunchAction::None => {}
2211 LaunchAction::ResumeSession(id) => assert!(
2212 painted.contains(&LaunchRowId::Recent(id.clone())),
2213 "height {height}: Enter at {index} would resume unpainted {id}",
2214 ),
2215 _ => {}
2216 }
2217 }
2218 }
2219 }
2220
2221 #[test]
2222 fn shed_sessions_stay_reachable_through_the_overflow_row() {
2223 let mut app = app_with_recent(&["one", "two", "three", "four", "five"], 5);
2224 // Five sessions, none behind the inline list: a tall pane needs no
2225 // overflow row, a short one sheds and therefore must offer it.
2226 refresh_launch_row_hitboxes(&mut app, Rect::new(0, 0, 120, 30));
2227 assert!(!row_ids(&app).contains(&LaunchRowId::SeeAll));
2228 refresh_launch_row_hitboxes(&mut app, Rect::new(0, 0, 120, 4));
2229 let ids = row_ids(&app);
2230 assert!(ids.contains(&LaunchRowId::SeeAll), "{ids:?}");
2231 assert!(
2232 launch_rows_for_app(&app)
2233 .iter()
2234 .any(|row| row.id == LaunchRowId::SeeAll)
2235 );
2236 }
2237
2238 // --- the card fits the pane it is drawn into -----------------------
2239
2240 #[test]
2241 fn the_card_fits_every_pane_it_is_drawn_into() {
2242 // Both shapes: no MCP servers at all, and the twelve-server workspace
2243 // whose status block is the widest thing the card paints.
2244 for app in [
2245 app_with_recent(&["one", "two", "three", "four", "five"], 9),
2246 with_mcp(app_with_recent(&["one", "two", "three", "four", "five"], 9)),
2247 ] {
2248 for width in [0u16, 1, 2, 3, 8, 12, 20, 31, 32, 40, 44, 64, 80, 120, 200] {
2249 for height in 0u16..=30 {
2250 let state = launch_empty_state(&app, Rect::new(0, 0, width, height));
2251 assert!(
2252 state.lines.len() <= usize::from(height),
2253 "{width}x{height}: {} lines",
2254 state.lines.len(),
2255 );
2256 for line in &state.lines {
2257 let painted = text_display_width(&flatten(line));
2258 assert!(
2259 painted <= usize::from(width),
2260 "{width}x{height}: row of {painted} cells",
2261 );
2262 }
2263 for (id, row) in &state.rows {
2264 assert!(
2265 *row < state.lines.len(),
2266 "{width}x{height}: hitbox {id:?} has no row",
2267 );
2268 }
2269 if width > 0 && height > 0 {
2270 assert!(
2271 state
2272 .rows
2273 .iter()
2274 .any(|(id, _)| matches!(id, LaunchRowId::NewSession)),
2275 "{width}x{height}: nothing actionable painted",
2276 );
2277 }
2278 }
2279 }
2280 }
2281 }
2282
2283 #[test]
2284 fn startup_keeps_session_and_connector_details_behind_their_controls() {
2285 let mut app = with_mcp(app_with_recent(&["Private draft title"], 1));
2286 app.onboarding_needs_api_key = false;
2287 app.launch.recent_expanded = false;
2288 for (width, height) in [(40, 8), (80, 24), (140, 36)] {
2289 let area = Rect::new(0, 0, width, height);
2290 refresh_launch_row_hitboxes(&mut app, area);
2291 let ids = row_ids(&app);
2292 assert_eq!(
2293 ids,
2294 [
2295 LaunchRowId::NewSession,
2296 LaunchRowId::ShowRecent,
2297 LaunchRowId::McpManager,
2298 LaunchRowId::Skills,
2299 ]
2300 );
2301 assert_eq!(app.launch.menu_selected, None);
2302 let text = painted(&app, width, height).join("\n");
2303 assert!(text.contains("Recent") && text.contains("/mcp"), "{text}");
2304 assert!(
2305 text.contains("Skills") && text.contains("/skills"),
2306 "{text}"
2307 );
2308 assert_eq!(
2309 run_launch_card_row(&launch_rows_for_app(&app), Some(3)),
2310 LaunchAction::Skills
2311 );
2312 for hidden in [
2313 "Private draft title",
2314 "alibaba-cloud-ops",
2315 "authorization required",
2316 "/mcp login",
2317 ] {
2318 assert!(!text.contains(hidden), "{text}");
2319 }
2320 }
2321 let empty_inventory = painted(&app, 80, 24);
2322 app.cached_skills
2323 .push(("fixture-skill".into(), "Callable skill".into()));
2324 assert_eq!(painted(&app, 80, 24), empty_inventory);
2325 let server = app
2326 .mcp_snapshot
2327 .as_mut()
2328 .unwrap()
2329 .servers
2330 .iter_mut()
2331 .find(|server| server.name == "alibaba-cloud-ops")
2332 .unwrap();
2333 server.required = true;
2334 let text = painted(&app, 80, 24).join("\n");
2335 assert!(text.contains("Connectors · error (1)"), "{text}");
2336 assert!(!text.contains("alibaba-cloud-ops"), "{text}");
2337 }
2338
2339 #[test]
2340 fn build_stamp_uses_the_space_beside_the_whale() {
2341 let mut app = with_mcp(app_with_recent(&["one"], 1));
2342 app.onboarding_needs_api_key = false;
2343 app.launch.recent_expanded = false;
2344 let build = "0.10.5 (123456789abc)";
2345 for (width, height, full) in [(110, 36, true), (48, 8, true), (30, 8, false)] {
2346 let state = super::build_launch_card(&app, Rect::new(0, 0, width, height), build);
2347 let identity = state
2348 .lines
2349 .iter()
2350 .map(flatten)
2351 .find(|line| line.contains("codewhale v"))
2352 .expect("versioned identity");
2353 let version = if full {
2354 build
2355 } else {
2356 env!("CARGO_PKG_VERSION")
2357 };
2358 assert!(
2359 identity.ends_with(&format!("codewhale v{version}")),
2360 "{identity}"
2361 );
2362 assert!(
2363 text_display_width(&identity) <= usize::from(width),
2364 "{identity}"
2365 );
2366 if width == 110 && !crate::tui::color_compat::ascii_safe_enabled() {
2367 let rows_with_ink = state
2368 .lines
2369 .iter()
2370 .filter(|line| {
2371 line.spans.iter().any(|span| {
2372 span.content
2373 .chars()
2374 .any(|c| ('\u{2801}'..='\u{28ff}').contains(&c))
2375 })
2376 })
2377 .count();
2378 assert!(rows_with_ink > 10, "wide hero lost its largest pose");
2379 }
2380 }
2381 }
2382
2383 #[test]
2384 fn the_fit_ladder_never_sheds_the_one_actionable_row() {
2385 for height in 1usize..=16 {
2386 for recent in 0usize..=5 {
2387 for has_more in [false, true] {
2388 for (notice, whats_new) in [(false, 0), (true, 0), (false, 3), (true, 2)] {
2389 for mcp in 0usize..=4 {
2390 for setup in [false, true] {
2391 let fit = launch_fit(
2392 height,
2393 Some(recent),
2394 has_more,
2395 notice,
2396 whats_new,
2397 mcp,
2398 setup,
2399 );
2400 assert!(fit.rows() <= height.max(1), "{height} {recent}: {fit:?}");
2401 assert!(fit.shown <= recent);
2402 assert!(fit.extensions <= mcp);
2403 if fit.shown < recent {
2404 assert!(
2405 fit.see_all || fit.rows() >= height,
2406 "shed rows became unreachable: {fit:?}",
2407 );
2408 }
2409 if setup && !fit.setup {
2410 assert_eq!(
2411 (fit.shown, fit.extensions, fit.see_all),
2412 (0, 0, false),
2413 "the no-model line outlived other rows: {fit:?}",
2414 );
2415 }
2416 }
2417 }
2418 }
2419 }
2420 }
2421 }
2422 }
2423
2424 #[test]
2425 fn a_keyless_launch_says_no_model_is_connected_and_how_to_fix_it() {
2426 let mut app = app_with_recent(&["Fix the parser"], 1);
2427 app.onboarding_needs_api_key = true;
2428 refresh_launch_row_hitboxes(&mut app, Rect::new(0, 0, 100, 30));
2429 let ids = row_ids(&app);
2430 assert_eq!(ids.first(), Some(&LaunchRowId::ConnectModel), "{ids:?}");
2431 let lines = painted(&app, 100, 30).join("\n");
2432 assert!(lines.contains("Connect a model"), "{lines}");
2433 assert!(lines.contains("/connect"), "{lines}");
2434 let short = painted(&app, 100, 3).join("\n");
2435 assert!(short.contains("Connect a model"), "{short}");
2436
2437 app.onboarding_needs_api_key = false;
2438 refresh_launch_row_hitboxes(&mut app, Rect::new(0, 0, 100, 30));
2439 assert!(!row_ids(&app).contains(&LaunchRowId::ConnectModel));
2440 let lines = painted(&app, 100, 30).join("\n");
2441 assert!(!lines.contains("Connect a model"), "{lines}");
2442 }
2443
2444 #[test]
2445 fn empty_workspace_omits_recent_section_but_hidden_history_stays_reachable() {
2446 let app = app_with_recent(&[], 0);
2447 let text = painted(&app, 100, 24).join("\n");
2448 assert!(text.contains("New session"));
2449 assert!(!text.contains("Recent"));
2450 assert!(!text.contains("No recent sessions"));
2451 assert!(!launch_fit(24, Some(0), false, false, 0, 0, false).heading);
2452 assert!(launch_fit(24, Some(0), true, false, 0, 0, false).heading);
2453 assert!(launch_fit(24, Some(0), true, false, 0, 0, false).see_all);
2454 }
2455
2456 // --- the row reads as one object -----------------------------------
2457
2458 #[test]
2459 fn a_row_keeps_its_detail_beside_its_title() {
2460 let app = app_with_recent(&["Ship the launch card"], 1);
2461 let lines = painted(&app, 200, 24);
2462 let row = lines
2463 .iter()
2464 .find(|line| line.contains("Ship the launch card"))
2465 .expect("recent row painted");
2466 assert!(
2467 text_display_width(row.trim_start()) <= LAUNCH_CARD_MEASURE + 2,
2468 "row runs to the terminal edge: {row:?}",
2469 );
2470 let (entries, _) = launch_recent_entries(&app);
2471 assert!(
2472 row.contains(&entries[0].detail),
2473 "row lost its age: {row:?}"
2474 );
2475 assert!(
2476 !row.contains("msgs"),
2477 "message counts belong in session details: {row:?}"
2478 );
2479 }
2480
2481 #[test]
2482 fn narrow_recent_rows_keep_the_age_only_when_it_leaves_a_readable_title() {
2483 let short = "Ship the launch card";
2484 let long = "Ship the launch card with its full title through narrow terminals";
2485 let app = app_with_recent(&[short], 1);
2486 let row = recent_row_title(&app, 40, 24);
2487 let (entries, _) = launch_recent_entries(&app);
2488 assert!(row.starts_with(short), "{row:?}");
2489 assert!(row.ends_with(&entries[0].detail), "{row:?}");
2490
2491 let app = app_with_recent(&[long], 1);
2492 let row = recent_row_title(&app, 40, 24);
2493 let (entries, _) = launch_recent_entries(&app);
2494 assert!(!row.contains(&entries[0].detail), "{row:?}");
2495 let prefix = row.strip_suffix('…').expect("long title is truncated");
2496 assert!(
2497 prefix.starts_with(short) && long.starts_with(prefix),
2498 "{row:?}"
2499 );
2500 }
2501
2502 // --- scripts --------------------------------------------------------
2503
2504 #[test]
2505 fn titles_truncate_on_grapheme_boundaries_in_several_scripts() {
2506 // Not a claim about every script: these are the four shapes that break
2507 // char-indexed truncation — wide cells, RTL runs, ZWJ/skin-tone emoji,
2508 // and combining marks.
2509 let samples = [
2510 (
2511 "latin",
2512 "Ship the launch card and verify truncation behaviour",
2513 ),
2514 ("cjk", "部署新的会话启动卡片并验证宽字符截断行为"),
2515 ("arabic", "تهيئة بطاقة إطلاق الجلسة والتحقق من سلوك الاقتطاع"),
2516 ("hebrew", "הגדרת כרטיס פתיחת הפעלה ואימות התנהגות הקיצוץ"),
2517 ("emoji", "👩🏽‍🚀 crew 👨‍👩‍👧‍👦 families and flags 🇯🇵 shipping today"),
2518 (
2519 "combining",
2520 "cafe\u{301} de\u{301}ja\u{300} vu\u{308} with combining marks throughout",
2521 ),
2522 ];
2523 for (name, title) in samples {
2524 let app = app_with_recent(&[title], 1);
2525 for width in [8u16, 12, 20, 32, 40, 60, 80, 120, 200] {
2526 for line in painted(&app, width, 24) {
2527 assert!(
2528 text_display_width(&line) <= usize::from(width),
2529 "{name} at {width}: {line:?} overruns the pane",
2530 );
2531 }
2532 }
2533 // At these widths the detail has shed, so the row is the title
2534 // alone: what is painted must be whole graphemes off its front.
2535 for width in [12u16, 20, 32, 40] {
2536 let row = recent_row_title(&app, width, 24);
2537 let body = row.strip_suffix('…').unwrap_or(&row);
2538 assert!(
2539 is_grapheme_prefix(body, title),
2540 "{name} at {width}: {body:?} splits a grapheme of {title:?}",
2541 );
2542 }
2543 }
2544 }
2545
2546 // --- rhythm ---------------------------------------------------------
2547
2548 #[test]
2549 fn a_tall_pane_breathes_and_a_short_one_gives_the_rhythm_up_first() {
2550 // Measure the gap between the new-session entry and the heading.
2551 let app = app_with_recent(&["one", "two", "three", "four", "five"], 9);
2552
2553 let tall = painted(&app, 120, 30);
2554 let entry = tall
2555 .iter()
2556 .position(|line| line.contains("New session"))
2557 .expect("new-session row painted");
2558 assert!(
2559 !tall[entry + 1].contains("Recent"),
2560 "a tall pane should breathe: {tall:#?}",
2561 );
2562
2563 let tight = painted(&app, 120, 12);
2564 let entry = tight
2565 .iter()
2566 .position(|line| line.contains("New session"))
2567 .expect("new-session row painted");
2568 assert!(
2569 tight[entry + 1].contains("Recent"),
2570 "a tight pane kept rhythm it cannot afford: {tight:#?}",
2571 );
2572 }
2573
2574 /// Print the card as the renderer actually paints it, for the evidence
2575 /// fixture. Ignored by default; run with
2576 /// `cargo test -p codewhale-tui --lib render_launch_card_fixture -- --ignored --nocapture`.
2577 #[test]
2578 #[ignore = "fixture generator, not an assertion"]
2579 #[allow(clippy::print_stdout)] // the fixture's whole job is its stdout
2580 fn render_launch_card_fixture() {
2581 let app = with_mcp(app_with_recent(
2582 &[
2583 "Fix the diagnostic display",
2584 "Hunter has explicitly authorized setting up Codewhale",
2585 "部署新的会话启动卡片并验证宽字符截断行为",
2586 "👩🏽\u{200d}🚀 crew 👨\u{200d}👩\u{200d}👧\u{200d}👦 families and flags 🇯🇵",
2587 "תהיה כרטיס פתיחת הפעלה",
2588 ],
2589 9,
2590 ));
2591 for (width, height) in [(170u16, 24u16), (120, 24), (80, 24), (40, 12), (20, 8)] {
2592 println!("\n{width}x{height}");
2593 println!("+{}+", "-".repeat(usize::from(width)));
2594 for line in painted(&app, width, height) {
2595 let pad = usize::from(width).saturating_sub(text_display_width(&line));
2596 println!("|{line}{}|", " ".repeat(pad));
2597 }
2598 println!("+{}+", "-".repeat(usize::from(width)));
2599 }
2600 }
2601
2602 #[test]
2603 fn launch_healthy_mcp_and_recent_rows_have_visible_focus_in_their_click_lane() {
2604 let mut app = with_mcp(app_with_recent(&["Recent proof"], 1));
2605 app.mcp_snapshot
2606 .as_mut()
2607 .unwrap()
2608 .servers
2609 .retain(|s| s.connected);
2610 app.mcp_configured_count = 5;
2611 for (width, height) in [(40, 12), (60, 16), (80, 24), (100, 32), (140, 40)] {
2612 let area = Rect::new(3, 2, width, height);
2613 refresh_launch_row_hitboxes(&mut app, area);
2614 let rows = launch_rows_for_app(&app);
2615 let mcp = rows
2616 .iter()
2617 .position(|r| r.id == LaunchRowId::McpManager)
2618 .unwrap();
2619 assert_eq!(
2620 run_launch_card_row(&rows, Some(mcp)),
2621 LaunchAction::McpManager
2622 );
2623
2624 app.launch.menu_selected = None;
2625 app.launch.hovered_row = None;
2626 let rest = launch_empty_state(&app, area);
2627 let (_, first) = rest.rows[0];
2628 let line = rest.lines[first].to_string();
2629 assert!(line.contains(&rows[0].label), "{width}: {line}");
2630 assert!(line.contains("/connect"), "{width}: {line}");
2631 let hint = if crate::tui::color_compat::ascii_safe_enabled() {
2632 if width == 40 {
2633 "Up/Down"
2634 } else {
2635 "Up/Down move"
2636 }
2637 } else {
2638 "↑↓ move"
2639 };
2640 assert!(line.contains(hint), "{width}: {line}");
2641 let new_session = rows
2642 .iter()
2643 .position(|r| r.id == LaunchRowId::NewSession)
2644 .unwrap();
2645 let recent = rows
2646 .iter()
2647 .position(|r| matches!(r.id, LaunchRowId::Recent(_)))
2648 .unwrap();
2649 for index in [new_session, recent, mcp] {
2650 app.launch.menu_selected = None;
2651 app.launch.hovered_row = Some(index);
2652 let hovered = launch_empty_state(&app, area);
2653 let (_, y) = hovered.rows[index];
2654 let hit = app.launch.row_hitboxes[index].1;
2655 assert_eq!(hit.x, area.x + hovered.text_column.x);
2656 assert_eq!(hit.y, area.y + y as u16);
2657 assert!(hit.right() <= area.right());
2658 let text = hovered.lines[y].spans.last().unwrap();
2659 assert_eq!(text.style.bg, Some(app.ui_theme.elevated_bg));
2660 assert!(hovered.lines[y].spans.iter().any(|s| {
2661 s.style
2662 .add_modifier
2663 .contains(ratatui::style::Modifier::UNDERLINED)
2664 && s.content.contains(rows[index].label.as_str())
2665 }));
2666 assert_eq!(app.launch.menu_selected, None);
2667
2668 app.launch.menu_selected = Some(index);
2669 let selected = launch_empty_state(&app, area);
2670 if width >= 80 {
2671 assert!(selected.lines[y].to_string().contains("Enter open"));
2672 }
2673 assert_eq!(
2674 selected.lines[y].spans.last().unwrap().style,
2675 codewhale_tui_kit::menu_style::theme_selected_row_style(&app.ui_theme)
2676 );
2677 // Neither the whale nor the leading whitespace changes color.
2678 assert_eq!(selected.lines[y].spans[0].style.bg, None);
2679 }
2680 }
2681 }
2682
2683 #[test]
2684 fn narrow_return_keeps_its_shortcut_and_fits_localized_focus_cues() {
2685 let mut app = app_with_recent(&["Recent proof"], 1);
2686 app.launch.return_to_session = true;
2687 for locale in [Locale::En, Locale::Ja] {
2688 app.ui_locale = locale;
2689 let title = tr(locale, MessageId::HomeBackToConversation);
2690 for width in [34, 40, 60] {
2691 app.launch.menu_selected = Some(0);
2692 let state = launch_empty_state(&app, Rect::new(0, 0, width, 12));
2693 let (id, first) = &state.rows[0];
2694 assert_eq!(*id, LaunchRowId::ReturnToSession);
2695 let line = state.lines[*first].to_string();
2696 assert!(line.contains(title.as_ref()), "{width}: {line}");
2697 assert!(line.contains("Esc"), "{width}: {line}");
2698 if width >= 40 {
2699 assert!(line.contains("Enter"), "{width}: {line}");
2700 }
2701 if width >= 60 || locale == Locale::Ja {
2702 let open = tr(locale, MessageId::LaunchHintOpen);
2703 assert!(line.contains(&format!("Enter {open}")), "{width}: {line}");
2704 }
2705 }
2706 }
2707 }
2708
2709 /// The migration notice ends with the reassurance that nothing applies
2710 /// unapproved; a truncated notice drops exactly that half. The English
2711 /// line must fit the card measure whole at a wide terminal.
2712 #[test]
2713 fn claude_notice_is_never_truncated_on_a_wide_terminal() {
2714 let notice = codewhale_localization::tr(
2715 codewhale_localization::Locale::En,
2716 codewhale_localization::MessageId::LaunchNoticeClaude,
2717 );
2718 assert!(
2719 text_display_width(&notice) <= LAUNCH_CARD_MEASURE,
2720 "notice is {} cells; the card lane is {LAUNCH_CARD_MEASURE}: {notice:?}",
2721 text_display_width(&notice),
2722 );
2723 let mut app = app_with_recent(&["one"], 1);
2724 app.launch.claude_code_detected = true;
2725 let state = launch_empty_state(&app, Rect::new(0, 0, 160, 40));
2726 assert!(
2727 state
2728 .lines
2729 .iter()
2730 .any(|line| flatten(line).contains(notice.as_ref())),
2731 "the full notice must paint at 160 columns",
2732 );
2733 }
2734
2735 #[test]
2736 fn every_hitbox_points_at_the_row_that_painted() {
2737 let app = app_with_recent(&["one", "two", "three"], 9);
2738 for height in 1u16..=24 {
2739 let state = launch_empty_state(&app, Rect::new(0, 0, 120, height));
2740 for (id, row) in &state.rows {
2741 let text = flatten(&state.lines[*row]);
2742 assert!(
2743 !text.trim().is_empty(),
2744 "height {height}: hitbox for {id:?} points at a blank row",
2745 );
2746 }
2747 }
2748 }
2749
2750 #[test]
2751 fn whats_new_launch_lines_preserves_and_wraps_summary_at_narrow_width() {
2752 let mut app = app_with_recent(&["one"], 1);
2753 let mut notice = crate::whats_new::WhatsNewNotice::for_version(
2754 codewhale_localization::Locale::En,
2755 "0.10.5",
2756 );
2757 notice.summary = Some(
2758 "Faster startup, cleaner permission warnings, and reliable compaction cache reuse."
2759 .to_string(),
2760 );
2761 notice.counts = Some("2 features, 4 fixes".to_string());
2762 app.launch.whats_new = Some(notice);
2763
2764 let lines = super::whats_new_launch_lines(&app, 42);
2765 let joined = lines
2766 .iter()
2767 .map(|(line, _)| line.as_str())
2768 .collect::<Vec<_>>()
2769 .join(" ");
2770 assert!(
2771 joined.contains("Faster startup") && joined.contains("compaction cache reuse"),
2772 "narrow launch notice dropped release summary: {lines:?}"
2773 );
2774 assert!(
2775 !joined.contains("2 features, 4 fixes"),
2776 "narrow launch notice should wrap summary instead of falling back to counts: {lines:?}"
2777 );
2778 for (line, muted) in &lines {
2779 if !muted {
2780 assert!(
2781 text_display_width(line) <= 42,
2782 "wrapped summary line exceeds 42 cells: {line:?}"
2783 );
2784 }
2785 }
2786 }
2787 }
2788
2789 #[cfg(test)]
2790 mod empty_state_caption_tests {
2791 use super::{empty_state_caption, shorten_workspace};
2792 use unicode_width::UnicodeWidthStr;
2793
2794 const DEEP: &str = "/private/tmp/claude-501/-Volumes-WorkSSD-project-codewhale/34267917-11f4-4d15-911a-2a8acd5c49e1/scratchpad/surface/ws2";
2795
2796 #[test]
2797 fn caption_stays_narrow_enough_to_actually_centre() {
2798 // The caller centres this line with `(width - caption.width()) / 2`.
2799 // Building it at full length and truncating to `width` made that inset
2800 // zero, so the caption rendered flush-left and full-bleed straight
2801 // through the centred whale/wordmark/prompt composition.
2802 for width in [60usize, 80, 100, 120] {
2803 let caption = empty_state_caption(DEEP, "no git", "MCP", 0, width);
2804 assert!(
2805 caption.width() <= width,
2806 "width {width}: caption {caption:?} overflows the lane",
2807 );
2808 assert!(
2809 width.saturating_sub(caption.width()) / 2 > 0,
2810 "width {width}: caption {caption:?} would render flush-left",
2811 );
2812 }
2813 }
2814
2815 #[test]
2816 fn caption_keeps_the_folder_you_are_standing_in() {
2817 let long = "/a/very/deeply/nested/checkout/somewhere/far/away/myproject";
2818 for width in [40usize, 60, 80, 120] {
2819 let caption = empty_state_caption(long, "main", "MCP", 2, width);
2820 assert!(
2821 caption.contains("myproject"),
2822 "width {width}: {caption:?} dropped the current folder",
2823 );
2824 }
2825 }
2826
2827 #[test]
2828 fn caption_sheds_the_least_important_detail_first() {
2829 let ws = "~/code/app";
2830 let wide = empty_state_caption(ws, "main", "MCP", 3, 120);
2831 assert!(wide.contains("MCP 3") && wide.contains("main") && wide.contains(ws));
2832
2833 let mid = empty_state_caption(ws, "main", "MCP", 3, 24);
2834 assert!(
2835 !mid.contains("MCP"),
2836 "{mid:?} should shed the MCP count first"
2837 );
2838 assert!(mid.contains("main"), "{mid:?} should still name the branch");
2839
2840 let tight = empty_state_caption(ws, "main", "MCP", 3, 16);
2841 assert!(
2842 tight.contains("app"),
2843 "{tight:?} should still name the folder"
2844 );
2845 }
2846
2847 #[test]
2848 fn elision_lands_on_a_separator_not_mid_component() {
2849 // The old line ended in an ellipsis mid-directory
2850 // ("…/34267917-11f4-4d15-911a-"), which told the reader nothing.
2851 let caption = empty_state_caption(DEEP, "no git", "MCP", 0, 60);
2852 assert!(
2853 !caption.contains("2a8acd5c49e1"),
2854 "{caption:?} clipped mid-component"
2855 );
2856 if caption.starts_with('…') {
2857 assert!(
2858 caption.starts_with("…/"),
2859 "elision must land on a separator: {caption:?}",
2860 );
2861 }
2862 }
2863
2864 #[test]
2865 fn caption_margin_scales_so_it_is_always_visibly_a_caption() {
2866 // The flat four-column margin only looked like a margin at 60 columns.
2867 // At 119 it let a 114-column path through with an inset of two — a
2868 // full-bleed banner cutting the centred composition in half, which is
2869 // the exact failure the shedding ladder exists to prevent.
2870 for width in [40usize, 60, 80, 100, 119, 120, 200] {
2871 for workspace in [DEEP, "/a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/project"] {
2872 let caption = empty_state_caption(workspace, "main", "MCP", 2, width);
2873 let inset = width.saturating_sub(caption.width()) / 2;
2874 assert!(
2875 inset * 12 >= width,
2876 "width {width}: caption {caption:?} insets by only {inset}",
2877 );
2878 }
2879 }
2880 }
2881
2882 #[test]
2883 fn shorten_workspace_is_a_no_op_when_it_already_fits() {
2884 assert_eq!(shorten_workspace("~/code/app", 2), "~/code/app".to_string());
2885 assert_eq!(shorten_workspace("app", 2), "app".to_string());
2886 }
2887 }
2888
2889 // ---------------------------------------------------------------------------
2890 // Launch motion scheduling: the bounded mark reveal, a real dissolve, or
2891 // an active water field requests frames through the existing scheduler.
2892 // ---------------------------------------------------------------------------
2893
2894 /// Whether the launch screen has a visible transition or ambient scene.
2895 #[must_use]
2896 pub fn launch_motion_active(app: &App, obscured: bool, ambient_settled: bool) -> bool {
2897 if obscured
2898 || app.onboarding != OnboardingState::None
2899 || !app.view_stack.is_empty()
2900 || !app.motion_policy().allows_decorative()
2901 {
2902 return false;
2903 }
2904 let now = app.ambient_clock_ms;
2905 if !app.launch.visible {
2906 return app.launch.session_handoff_active(now, true)
2907 && crate::tui::widgets::should_render_empty_state(app);
2908 }
2909 let dissolving = app.launch.dissolve_started_ms.is_some()
2910 && app.launch.card_dissolve_progress(now, true) < 1.0;
2911 let water_alive = app.theme_id == codewhale_palette::ThemeId::Underwater && !ambient_settled;
2912 let revealing = !app.launch.return_to_session
2913 && !crate::tui::color_compat::ascii_safe_enabled()
2914 && app.launch.mark_reveal_started_at.is_some_and(|started| {
2915 started.elapsed() < codewhale_ratatui::whale_motion::arrival::DURATION
2916 });
2917 revealing || dissolving || water_alive
2918 }
2919
2920 #[cfg(test)]
2921 mod truncate_to_width_tests {
2922 use super::truncate_to_width;
2923
2924 #[test]
2925 fn truncate_to_width_keeps_graphemes_whole() {
2926 assert_eq!(truncate_to_width("日本語のテキスト", 8), "日本語…");
2927 assert_eq!(
2928 truncate_to_width("e\u{301}e\u{301}e\u{301}e\u{301}e\u{301}", 4),
2929 "e\u{301}e\u{301}e\u{301}…"
2930 );
2931 let family = "\u{1F468}\u{200D}\u{1F469}\u{200D}\u{1F467}\u{200D}\u{1F466}";
2932 assert_eq!(
2933 truncate_to_width(&family.repeat(3), 4),
2934 format!("{family}…")
2935 );
2936 }
2937 }
2938
2938 lines RUST