返回 CodeWhale
whales.rs
根目录 / crates / tui / src / tui / whales.rs
1 //! Whale Teams — the Signal Cut whale identities in the terminal.
2 //!
3 //! CWC's "Whale Teams / Signal Cut" identity (2026-08-15) gives each agent
4 //! role a species-led whale and every whale one of six runtime states. This
5 //! module carries that identity into the TUI as species badges and state
6 //! words. The hand-drawn portrait art that used to live here (the three-row
7 //! glyph renditions and the hand-drawn crown fluke) was deleted per the
8 //! 2026-08-29 founder directive; the only sanctioned terminal mark is the one
9 //! generated from the brand master path. Colors are Codewhale palette tokens
10 //! resolved through the live [`UiTheme`], so the whales follow Blue Stage
11 //! dark/light, the Terminal theme, and ANSI-16 adaptation like every other
12 //! surface.
13 //!
14 //! Contract:
15 //! - **Role → species is one table** ([`WhaleSpecies::for_role_id`]). Fleet
16 //! roles map onto the six species; roles without a species (`worker`,
17 //! `general`, `custom`, unknown) render the plain Codewhale whale.
18 //! - **State is evidence, never decoration.** [`WhaleState`] is derived only
19 //! from real runtime facts ([`WhaleState::for_subagent`],
20 //! [`WhaleState::for_shell_phase`]). *Working* is asserted only for a child
21 //! or turn that is actually running.
22 //! - **Every state pairs a glyph cue with a word** ([`WhaleState::word`]), so
23 //! state never depends on color alone (same rule as `menu_style`).
24 //! - **ASCII-safe by construction.** Every authored glyph has a
25 //! [`glyphs::ascii_fallback`] entry, and [`badge_ascii`] exposes the
26 //! narrowed badge for tests and text surfaces.
27 //!
28 //! Only the *signal-classic* colorway is represented. The three alternate CWC
29 //! colorways exist only as resting rasters upstream and are not modelled here.
30
31 use std::{borrow::Cow, sync::OnceLock};
32
33 use ratatui::style::{Color, Modifier, Style};
34 use ratatui::text::Span;
35
36 use crate::tui::motion::mode::MotionMode;
37 #[cfg(test)]
38 use crate::tui::underwater::ShellPhase;
39 use codewhale_agent_contract::role::FleetRole;
40 use codewhale_engine::tools::subagent::{AgentWorkerStatus, SubAgentResult, SubAgentStatus};
41 use codewhale_localization::{Locale, MessageId, tr};
42 use codewhale_palette::{self as palette, UiTheme};
43 use codewhale_ratatui::{whale::Grid, whale_motion::arrival};
44 use codewhale_tui_kit::glyphs;
45
46 type WhaleRows = Vec<Vec<(usize, String)>>;
47
48 pub(super) struct LaunchWhale {
49 pub width: usize,
50 poster: Grid,
51 frames: [OnceLock<WhaleRows>; arrival::FRAMES + 1],
52 }
53
54 impl LaunchWhale {
55 fn from_grid(poster: Grid) -> Self {
56 Self {
57 width: usize::from(poster.cols),
58 poster,
59 frames: std::array::from_fn(|_| OnceLock::new()),
60 }
61 }
62
63 pub fn rows(&self, elapsed: Option<std::time::Duration>) -> &WhaleRows {
64 let frame = elapsed.map_or(arrival::FRAMES, arrival::frame_index);
65 self.frames[frame].get_or_init(|| {
66 let arrival = arrival::frame(&self.poster, frame).expect("bounded launch mark");
67 let grid = arrival.grid;
68 let mut bands = Vec::with_capacity(usize::from(grid.rows));
69 for y in 0..grid.rows {
70 let mut runs: Vec<(usize, String)> = Vec::new();
71 for x in 0..grid.cols {
72 let dot = grid.char_at(x, y);
73 let tone = if dot == ' ' {
74 0
75 } else if y == 0 || grid.cell(x, y - 1) == 0 {
76 1
77 } else if y + 1 == grid.rows || grid.cell(x, y + 1) == 0 {
78 4
79 } else if x * 3 + y * 5 < grid.cols + grid.rows * 2 {
80 2
81 } else {
82 3
83 };
84 let rim = arrival.rim[usize::from(y) * self.width + usize::from(x)];
85 let ink = tone + 5 * usize::from(rim);
86 if let Some((last, glyphs)) = runs.last_mut()
87 && *last == ink
88 {
89 glyphs.push(dot);
90 } else {
91 runs.push((ink, dot.to_string()));
92 }
93 }
94 bands.push(runs);
95 }
96 bands
97 })
98 }
99
100 fn poster(cols: u16, rows: u16) -> Option<Self> {
101 let grid =
102 codewhale_ratatui::whale::frame(codewhale_ratatui::WhaleState::Rest, cols, rows)?;
103 let mut xs = (0..cols).filter(|&x| (0..rows).any(|y| grid.cell(x, y) != 0));
104 let mut ys = (0..rows).filter(|&y| (0..cols).any(|x| grid.cell(x, y) != 0));
105 let x0 = xs.clone().next()?;
106 let x1 = xs.next_back()?;
107 let y0 = ys.clone().next()?;
108 let y1 = ys.next_back()?;
109 let mut cells = Vec::new();
110 for y in y0..=y1 {
111 let row_start = usize::from(y) * usize::from(cols);
112 cells.extend_from_slice(
113 &grid.cells[row_start + usize::from(x0)..=row_start + usize::from(x1)],
114 );
115 }
116 Some(Self::from_grid(Grid {
117 cols: x1 - x0 + 1,
118 rows: y1 - y0 + 1,
119 cells,
120 }))
121 }
122
123 pub fn fitting(width: usize, height: usize) -> Option<&'static Self> {
124 use codewhale_tui_kit::mark::MarkSize;
125 static SIZES: OnceLock<Vec<LaunchWhale>> = OnceLock::new();
126 SIZES
127 .get_or_init(|| {
128 [(48, 24), (32, 16), (24, 12)]
129 .into_iter()
130 .filter_map(|(cols, rows)| Self::poster(cols, rows))
131 .chain(
132 [MarkSize::Large, MarkSize::Small, MarkSize::Tiny].map(|size| {
133 let (cols, rows) = size.cells();
134 let cells = size
135 .rows()
136 .iter()
137 .flat_map(|row| row.chars())
138 .map(|ch| (ch as u32).saturating_sub(0x2800) as u8)
139 .collect();
140 Self::from_grid(Grid { cols, rows, cells })
141 }),
142 )
143 .collect()
144 })
145 .iter()
146 .find(|mark| mark.width <= width && usize::from(mark.poster.rows) <= height)
147 }
148 }
149
150 /// Cells occupied by a badge (species mark + body).
151 #[cfg(test)]
152 const BADGE_WIDTH: usize = 2;
153 /// Working wake loop: four frames over 720 ms, as in the CWC GIFs.
154 pub const WORKING_FRAME_MS: u64 = 180;
155 pub const WORKING_FRAMES: usize = 4;
156
157 /// The six Signal Cut species plus the plain Codewhale whale for roles that
158 /// have no species of their own.
159 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
160 pub enum WhaleSpecies {
161 /// Beaked whale — research. The signature whale of the Signal Current mark.
162 Scout,
163 /// Harbor porpoise — coding.
164 Patch,
165 /// Humpback whale — coordination.
166 Harbor,
167 /// Pilot whale — communications.
168 Echo,
169 /// Sperm whale — operations.
170 Keel,
171 /// Orca — review.
172 Lantern,
173 /// The plain Codewhale whale: no species, no accent. Used for `worker`,
174 /// `general`, `custom`, and unknown roles rather than guessing.
175 Plain,
176 }
177
178 impl WhaleSpecies {
179 /// Every species, for exhaustive checks and the test gallery.
180 #[cfg(test)]
181 pub const ALL: [WhaleSpecies; 7] = [
182 Self::Scout,
183 Self::Patch,
184 Self::Harbor,
185 Self::Echo,
186 Self::Keel,
187 Self::Lantern,
188 Self::Plain,
189 ];
190
191 /// The single role → species table.
192 ///
193 /// Accepts Fleet profile ids / role hints (`manager`, `explore`,
194 /// `implement`, `reviewer`, `test`, `advisor`, `synthesizer`, `general`,
195 /// `custom`) and legacy compatibility aliases.
196 /// Anything else is [`WhaleSpecies::Plain`] — never a guess.
197 #[must_use]
198 pub fn for_role_id(role: &str) -> Self {
199 match role.trim().to_ascii_lowercase().as_str() {
200 "scout" | "explore" => Self::Scout,
201 "builder" | "implement" => Self::Patch,
202 "manager" | "planner" => Self::Harbor,
203 "reviewer" => Self::Lantern,
204 "verifier" | "test" => Self::Keel,
205 "consultant" | "advisor" | "synthesizer" => Self::Echo,
206 _ => Self::Plain,
207 }
208 }
209
210 /// Species for a runtime Fleet role.
211 #[must_use]
212 pub fn for_fleet_role(role: &FleetRole) -> Self {
213 Self::for_role_id(role.as_str())
214 }
215
216 /// Product name (a proper noun; not localized).
217 #[must_use]
218 pub const fn name(self) -> &'static str {
219 match self {
220 Self::Scout => "Scout",
221 Self::Patch => "Patch",
222 Self::Harbor => "Harbor",
223 Self::Echo => "Echo",
224 Self::Keel => "Keel",
225 Self::Lantern => "Lantern",
226 Self::Plain => "codewhale",
227 }
228 }
229
230 /// Localized species (animal) label.
231 #[must_use]
232 pub fn animal(self, locale: Locale) -> Cow<'static, str> {
233 tr(
234 locale,
235 match self {
236 Self::Scout => MessageId::WhaleAnimalScout,
237 Self::Patch => MessageId::WhaleAnimalPatch,
238 Self::Harbor => MessageId::WhaleAnimalHarbor,
239 Self::Echo => MessageId::WhaleAnimalEcho,
240 Self::Keel => MessageId::WhaleAnimalKeel,
241 Self::Lantern => MessageId::WhaleAnimalLantern,
242 Self::Plain => MessageId::WhaleAnimalPlain,
243 },
244 )
245 }
246
247 /// Localized job label.
248 #[must_use]
249 pub fn job(self, locale: Locale) -> Cow<'static, str> {
250 tr(
251 locale,
252 match self {
253 Self::Scout => MessageId::WhaleJobScout,
254 Self::Patch => MessageId::WhaleJobPatch,
255 Self::Harbor => MessageId::WhaleJobHarbor,
256 Self::Echo => MessageId::WhaleJobEcho,
257 Self::Keel => MessageId::WhaleJobKeel,
258 Self::Lantern => MessageId::WhaleJobLantern,
259 Self::Plain => MessageId::WhaleJobPlain,
260 },
261 )
262 }
263
264 /// Species-distinct 1-row mark: a feature glyph plus a body cell. Every
265 /// pair narrows to a distinct ASCII pair (`<#`, `#]`, `#\`, `:#`, `#-`,
266 /// `*#`, `.#`).
267 #[must_use]
268 pub const fn badge_glyphs(self) -> (&'static str, &'static str, bool) {
269 // (feature, body, feature_first)
270 match self {
271 Self::Scout => ("◂", "▰", true), // long beak
272 Self::Patch => ("]", "▰", false), // bracket patch
273 Self::Harbor => ("▚", "▰", false), // long winglike flipper
274 Self::Echo => (":", "▰", true), // sonar ticks
275 Self::Keel => ("━", "▰", false), // keel stripe
276 Self::Lantern => ("◇", "▰", true), // review lens (Reviewer charter glyph)
277 Self::Plain => ("·", "▰", true), // neutral dot
278 }
279 }
280 }
281
282 /// The six-state grammar. Priority (highest first) mirrors CWC:
283 /// waiting > blocked > working > thinking > offline > resting.
284 #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
285 pub enum WhaleState {
286 Resting,
287 Offline,
288 Thinking,
289 Working,
290 Blocked,
291 /// "Waiting for you": a human/parent action is required.
292 Waiting,
293 }
294
295 impl WhaleState {
296 /// Every state, for exhaustive checks and the test gallery.
297 #[cfg(test)]
298 pub const ALL: [WhaleState; 6] = [
299 Self::Resting,
300 Self::Thinking,
301 Self::Working,
302 Self::Waiting,
303 Self::Blocked,
304 Self::Offline,
305 ];
306
307 /// CWC state priority; higher wins when several facts apply. Public
308 /// contract for surfaces that fold several children into one whale.
309 #[cfg(test)]
310 #[must_use]
311 pub const fn priority(self) -> u8 {
312 match self {
313 Self::Waiting => 60,
314 Self::Blocked => 50,
315 Self::Working => 40,
316 Self::Thinking => 30,
317 Self::Offline => 20,
318 Self::Resting => 10,
319 }
320 }
321
322 /// Localized state word — always rendered next to the glyph cue.
323 #[must_use]
324 pub fn word(self, locale: Locale) -> Cow<'static, str> {
325 tr(
326 locale,
327 match self {
328 Self::Resting => MessageId::WhaleStateResting,
329 Self::Thinking => MessageId::WhaleStateThinking,
330 Self::Working => MessageId::WhaleStateWorking,
331 Self::Waiting => MessageId::WhaleStateWaiting,
332 Self::Blocked => MessageId::WhaleStateBlocked,
333 Self::Offline => MessageId::WhaleStateOffline,
334 },
335 )
336 }
337
338 /// State from a real child record. Evidence rules:
339 /// - a pending question for the parent/user → Waiting;
340 /// - the live worker status when present (`WaitingForUser` → Waiting,
341 /// `ModelWait`/`Queued`/`Starting` → Thinking, `Running`/`RunningTool`
342 /// → Working, `Failed` → Blocked, `Interrupted` → Waiting, `Cancelled`
343 /// → Offline, `Completed` → Resting);
344 /// - otherwise the durable status (`Running` → Working, `Completed` →
345 /// Resting, `Interrupted` → Waiting, `Failed`/`BudgetExhausted` →
346 /// Blocked, `Cancelled` → Offline).
347 ///
348 /// Working is therefore only ever asserted for a child the runtime says
349 /// is running — never inferred from timestamps.
350 #[must_use]
351 pub fn for_subagent(agent: &SubAgentResult) -> Self {
352 if agent.needs_input.is_some() {
353 return Self::Waiting;
354 }
355 if let Some(status) = agent.worker_status {
356 return match status {
357 AgentWorkerStatus::WaitingForUser | AgentWorkerStatus::Interrupted => Self::Waiting,
358 AgentWorkerStatus::Queued
359 | AgentWorkerStatus::Starting
360 | AgentWorkerStatus::ModelWait => Self::Thinking,
361 AgentWorkerStatus::Running | AgentWorkerStatus::RunningTool => Self::Working,
362 AgentWorkerStatus::Failed => Self::Blocked,
363 AgentWorkerStatus::Cancelled => Self::Offline,
364 AgentWorkerStatus::Completed => Self::Resting,
365 };
366 }
367 match agent.status {
368 SubAgentStatus::Running => Self::Working,
369 SubAgentStatus::Completed => Self::Resting,
370 SubAgentStatus::Interrupted(_) => Self::Waiting,
371 SubAgentStatus::Failed(_) | SubAgentStatus::BudgetExhausted => Self::Blocked,
372 SubAgentStatus::Cancelled => Self::Offline,
373 }
374 }
375
376 /// State from the operator session phase. Public contract for the shell
377 /// header / Fleet setup role pane (no consumer in this lane yet).
378 #[must_use]
379 #[cfg(test)]
380 pub const fn for_shell_phase(phase: ShellPhase) -> Self {
381 match phase {
382 ShellPhase::Idle | ShellPhase::Done => Self::Resting,
383 ShellPhase::Typing => Self::Thinking,
384 ShellPhase::Working | ShellPhase::Verifying => Self::Working,
385 ShellPhase::Waiting | ShellPhase::Approval => Self::Waiting,
386 ShellPhase::Failed => Self::Blocked,
387 }
388 }
389 }
390
391 /// Resolved inks for one theme. Accents are contrast-enforced against the
392 /// theme surface (≥ 3:1, the secondary-chrome floor) so a Blue Stage Light or
393 /// custom surface never swallows a role mark.
394 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
395 pub struct WhaleInk {
396 /// Signal Gold body (the theme's `accent_action` slot, as the idle mark).
397 pub body: Color,
398 /// Orca body: ink/white patches read as muted text ink, saddle stays gold.
399 pub lantern_body: Color,
400 /// Bounded cyan: thinking ticks and the working wake.
401 pub current: Color,
402 /// Waiting ring — Signal Gold, the human-attention role.
403 pub human: Color,
404 /// Blocked obstruction bar.
405 pub bar: Color,
406 /// Offline outline.
407 pub dim: Color,
408 pub scout: Color,
409 pub patch: Color,
410 pub harbor: Color,
411 pub echo: Color,
412 pub keel: Color,
413 pub lantern: Color,
414 }
415
416 impl WhaleInk {
417 #[must_use]
418 pub fn from_theme(theme: &UiTheme) -> Self {
419 let surface = theme.surface_bg;
420 let lift = |color: Color| {
421 palette::enforce_contrast(color, surface, palette::SECONDARY_CHROME_CONTRAST)
422 };
423 let rgb = |(r, g, b): (u8, u8, u8)| Color::Rgb(r, g, b);
424 Self {
425 body: lift(theme.accent_action),
426 lantern_body: lift(theme.text_muted),
427 current: lift(rgb(palette::WHALE_CYAN_RGB)),
428 human: lift(theme.accent_action),
429 bar: lift(theme.text_muted),
430 dim: theme.text_dim,
431 scout: lift(rgb(palette::WHALE_CYAN_RGB)),
432 patch: lift(theme.accent_secondary),
433 harbor: lift(rgb(palette::WHALE_BRAND_ORANGE_RGB)),
434 echo: lift(rgb(palette::WHALE_BRAND_MAGENTA_RGB)),
435 keel: lift(theme.warning),
436 lantern: lift(theme.mode_operate),
437 }
438 }
439
440 #[must_use]
441 pub const fn accent(&self, species: WhaleSpecies) -> Color {
442 match species {
443 WhaleSpecies::Scout => self.scout,
444 WhaleSpecies::Patch => self.patch,
445 WhaleSpecies::Harbor => self.harbor,
446 WhaleSpecies::Echo => self.echo,
447 WhaleSpecies::Keel => self.keel,
448 WhaleSpecies::Lantern => self.lantern,
449 WhaleSpecies::Plain => self.body,
450 }
451 }
452
453 #[must_use]
454 pub const fn body_for(&self, species: WhaleSpecies) -> Color {
455 match species {
456 WhaleSpecies::Lantern => self.lantern_body,
457 _ => self.body,
458 }
459 }
460 }
461
462 /// Which working frame to show now. Anything but [`MotionMode::Full`] holds
463 /// the frame-A poster; callers must also only pass `Some(Working)` for a
464 /// child that is really running.
465 #[must_use]
466 pub const fn working_frame(now_ms: u64, mode: MotionMode) -> usize {
467 match mode {
468 MotionMode::Full => ((now_ms / WORKING_FRAME_MS) % WORKING_FRAMES as u64) as usize,
469 MotionMode::Reduced | MotionMode::Still => 0,
470 }
471 }
472
473 /// Two-cell species badge: feature glyph in the role accent, body in Signal
474 /// Gold (Lantern's body in orca ink).
475 #[must_use]
476 pub fn badge(species: WhaleSpecies, theme: &UiTheme) -> Vec<Span<'static>> {
477 let ink = WhaleInk::from_theme(theme);
478 let (feature, body, feature_first) = species.badge_glyphs();
479 let feature_span = Span::styled(
480 feature,
481 Style::default()
482 .fg(ink.accent(species))
483 .add_modifier(Modifier::BOLD),
484 );
485 let body_span = Span::styled(body, Style::default().fg(ink.body_for(species)));
486 if feature_first {
487 vec![feature_span, body_span]
488 } else {
489 vec![body_span, feature_span]
490 }
491 }
492
493 /// Badge followed by the state word (glyph + word: never color alone). The
494 /// word takes the state's tone; when `state` is `None` only the badge renders.
495 #[cfg(test)]
496 #[must_use]
497 pub fn badge_with_state(
498 species: WhaleSpecies,
499 state: Option<WhaleState>,
500 theme: &UiTheme,
501 locale: Locale,
502 ) -> Vec<Span<'static>> {
503 badge_with_state_frame(species, state, 0, theme, locale)
504 }
505
506 /// [`badge_with_state`] with an explicit working-wake frame (see
507 /// [`working_frame`]); every non-working state ignores `frame`.
508 #[must_use]
509 pub fn badge_with_state_frame(
510 species: WhaleSpecies,
511 state: Option<WhaleState>,
512 frame: usize,
513 theme: &UiTheme,
514 locale: Locale,
515 ) -> Vec<Span<'static>> {
516 let mut spans = badge(species, theme);
517 if let Some(state) = state {
518 let ink = WhaleInk::from_theme(theme);
519 let (cue, tone) = state_cue(state, frame, &ink, theme);
520 spans.push(Span::raw(" "));
521 if !cue.is_empty() {
522 spans.push(Span::styled(format!("{cue} "), Style::default().fg(tone)));
523 }
524 spans.push(Span::styled(
525 state.word(locale).into_owned(),
526 Style::default().fg(tone),
527 ));
528 }
529 spans
530 }
531
532 /// One-cell state cue paired with its tone: the state grammar folded to a
533 /// single glyph for badge rows.
534 fn state_cue(
535 state: WhaleState,
536 frame: usize,
537 ink: &WhaleInk,
538 theme: &UiTheme,
539 ) -> (&'static str, Color) {
540 /// One-cell wake: the four-beat working loop, never blank.
541 const WAKE_CUE: [&str; WORKING_FRAMES] = ["·", "˚", "·", "˚"];
542 match state {
543 WhaleState::Resting => ("", theme.text_muted),
544 WhaleState::Thinking => ("˚", ink.current),
545 WhaleState::Working => (WAKE_CUE[frame % WORKING_FRAMES], ink.current),
546 WhaleState::Waiting => (glyphs::ATTENTION, ink.human),
547 WhaleState::Blocked => ("▌", ink.bar),
548 WhaleState::Offline => ("░", ink.dim),
549 }
550 }
551
552 /// The badge as ASCII text (`<#`, `#]`, ...), for tests and text surfaces.
553 #[cfg(test)]
554 #[must_use]
555 pub fn badge_ascii(species: WhaleSpecies) -> String {
556 let (feature, body, feature_first) = species.badge_glyphs();
557 let narrow = |glyph: &'static str| -> &'static str {
558 if glyph.is_ascii() {
559 glyph
560 } else {
561 glyphs::ascii_fallback(glyph).unwrap_or("?")
562 }
563 };
564 if feature_first {
565 format!("{}{}", narrow(feature), narrow(body))
566 } else {
567 format!("{}{}", narrow(body), narrow(feature))
568 }
569 }
570
571 #[cfg(test)]
572 mod tests {
573 use super::*;
574 use codewhale_palette::contrast_ratio;
575
576 #[test]
577 fn launch_whale_keeps_the_identity_columns_fixed_through_its_arrival() {
578 for (width, height) in [(48, 24), (26, 13), (19, 9), (14, 6), (7, 3), (5, 2)] {
579 let whale = LaunchWhale::fitting(width, height).unwrap();
580 let rest = whale.rows(None);
581 assert_eq!(rest, whale.rows(Some(arrival::DURATION)));
582 let moving = whale.rows(Some(std::time::Duration::from_millis(480)));
583 assert_eq!(moving.len(), rest.len());
584 assert!(moving.iter().flatten().any(|(ink, _)| *ink >= 5));
585 for row in moving {
586 let width: usize = row.iter().map(|(_, dots)| dots.chars().count()).sum();
587 assert_eq!(width, whale.width);
588 }
589 }
590 }
591
592 fn theme_dark() -> UiTheme {
593 palette::UI_THEME
594 }
595
596 #[test]
597 fn role_table_is_total_and_never_guesses() {
598 assert_eq!(WhaleSpecies::for_role_id("scout"), WhaleSpecies::Scout);
599 assert_eq!(WhaleSpecies::for_role_id("builder"), WhaleSpecies::Patch);
600 assert_eq!(WhaleSpecies::for_role_id("manager"), WhaleSpecies::Harbor);
601 assert_eq!(WhaleSpecies::for_role_id("planner"), WhaleSpecies::Harbor);
602 assert_eq!(WhaleSpecies::for_role_id("reviewer"), WhaleSpecies::Lantern);
603 assert_eq!(WhaleSpecies::for_role_id("verifier"), WhaleSpecies::Keel);
604 assert_eq!(WhaleSpecies::for_role_id("consultant"), WhaleSpecies::Echo);
605 assert_eq!(WhaleSpecies::for_role_id("synthesizer"), WhaleSpecies::Echo);
606 for plain in [
607 "worker",
608 "general",
609 "custom",
610 "",
611 "mystery-role",
612 "Scouting",
613 ] {
614 assert_eq!(
615 WhaleSpecies::for_role_id(plain),
616 WhaleSpecies::Plain,
617 "{plain}"
618 );
619 }
620 assert_eq!(
621 WhaleSpecies::for_role_id(" Reviewer "),
622 WhaleSpecies::Lantern
623 );
624 for role in [
625 FleetRole::Worker,
626 FleetRole::Scout,
627 FleetRole::Planner,
628 FleetRole::Reviewer,
629 FleetRole::Builder,
630 FleetRole::Verifier,
631 FleetRole::Consultant,
632 FleetRole::Custom,
633 ] {
634 // Every runtime role resolves without panicking.
635 let _ = WhaleSpecies::for_fleet_role(&role);
636 }
637 assert_eq!(
638 WhaleSpecies::for_fleet_role(&FleetRole::Custom),
639 WhaleSpecies::Plain
640 );
641 }
642
643 #[test]
644 fn state_priority_orders_attention_before_work() {
645 assert!(
646 WhaleState::Waiting.priority() > WhaleState::Working.priority()
647 && WhaleState::Working.priority() > WhaleState::Resting.priority()
648 );
649 }
650
651 #[test]
652 fn badge_glyphs_have_ascii_fallbacks_and_stay_distinct() {
653 for species in WhaleSpecies::ALL {
654 let badge = badge_ascii(species);
655 assert!(
656 badge.is_ascii() && badge.chars().count() == BADGE_WIDTH,
657 "{badge:?}"
658 );
659 }
660 // Distinct species read distinctly even without Unicode.
661 let mut badges: Vec<String> = WhaleSpecies::ALL.iter().map(|s| badge_ascii(*s)).collect();
662 badges.sort();
663 badges.dedup();
664 assert_eq!(badges.len(), WhaleSpecies::ALL.len(), "{badges:?}");
665 }
666
667 #[test]
668 fn working_wake_only_animates_under_full_motion() {
669 assert_eq!(working_frame(0, MotionMode::Full), 0);
670 assert_eq!(working_frame(180, MotionMode::Full), 1);
671 assert_eq!(working_frame(540, MotionMode::Full), 3);
672 assert_eq!(working_frame(720, MotionMode::Full), 0);
673 for now in [0, 180, 360, 540, 90_000] {
674 assert_eq!(working_frame(now, MotionMode::Reduced), 0);
675 assert_eq!(working_frame(now, MotionMode::Still), 0);
676 }
677 }
678
679 #[test]
680 fn every_state_pairs_a_cue_with_a_word_in_every_shipped_locale() {
681 let theme = theme_dark();
682 let ink = WhaleInk::from_theme(&theme);
683 for state in WhaleState::ALL {
684 for locale in Locale::shipped_complete() {
685 let word = state.word(*locale);
686 assert!(!word.trim().is_empty(), "{state:?} {locale:?}");
687 let spans = badge_with_state(WhaleSpecies::Scout, Some(state), &theme, *locale);
688 let text: String = spans.iter().map(|s| s.content.as_ref()).collect();
689 assert!(text.contains(word.as_ref()), "{state:?} {locale:?}: {text}");
690 }
691 let (cue, _) = state_cue(state, 0, &ink, &theme);
692 if state != WhaleState::Resting {
693 assert!(!cue.is_empty(), "{state:?} needs a glyph cue");
694 }
695 }
696 // Identity-only rows carry the badge and nothing that reads as state.
697 let spans = badge_with_state(WhaleSpecies::Patch, None, &theme, Locale::En);
698 assert_eq!(spans.len(), BADGE_WIDTH);
699 }
700
701 #[test]
702 fn subagent_state_is_derived_from_runtime_facts_only() {
703 let mut agent = SubAgentResult {
704 usage: None,
705 name: "child-1".into(),
706 agent_id: "child-1".into(),
707 context_mode: "fresh".into(),
708 fork_context: false,
709 workspace: None,
710 git_branch: None,
711 agent_type: FleetRole::Builder,
712 assignment: codewhale_engine::tools::subagent::SubAgentAssignment {
713 native_preset: None,
714 objective: "objective".into(),
715 role: None,
716 },
717 model: String::new(),
718 nickname: None,
719 status: SubAgentStatus::Running,
720 worker_status: None,
721 runtime_permissions: None,
722 parent_run_id: None,
723 spawn_depth: 0,
724 child_route: None,
725 result: None,
726 steps_taken: 0,
727 checkpoint: None,
728 needs_input: None,
729 duration_ms: 0,
730 started_at: None,
731 from_prior_session: false,
732 idle_ms: None,
733 heartbeat_timeout_ms: None,
734 };
735 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Working);
736 agent.status = SubAgentStatus::Completed;
737 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Resting);
738 agent.status = SubAgentStatus::Interrupted("parent".into());
739 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Waiting);
740 agent.status = SubAgentStatus::Failed("boom".into());
741 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Blocked);
742 agent.status = SubAgentStatus::BudgetExhausted;
743 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Blocked);
744 agent.status = SubAgentStatus::Cancelled;
745 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Offline);
746 // Live worker status refines the durable status.
747 agent.status = SubAgentStatus::Running;
748 agent.worker_status = Some(AgentWorkerStatus::ModelWait);
749 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Thinking);
750 agent.worker_status = Some(AgentWorkerStatus::RunningTool);
751 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Working);
752 agent.worker_status = Some(AgentWorkerStatus::WaitingForUser);
753 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Waiting);
754 // A pending question for the parent wins over everything.
755 agent.worker_status = Some(AgentWorkerStatus::Running);
756 agent.needs_input = Some(codewhale_engine::tools::subagent::SubAgentNeedsInput {
757 question: "which branch?".into(),
758 });
759 assert_eq!(WhaleState::for_subagent(&agent), WhaleState::Waiting);
760 // Priorities match CWC.
761 assert!(WhaleState::Waiting.priority() > WhaleState::Blocked.priority());
762 assert!(WhaleState::Blocked.priority() > WhaleState::Working.priority());
763 assert!(WhaleState::Working.priority() > WhaleState::Thinking.priority());
764 assert!(WhaleState::Thinking.priority() > WhaleState::Offline.priority());
765 assert!(WhaleState::Offline.priority() > WhaleState::Resting.priority());
766 }
767
768 #[test]
769 fn shell_phase_maps_without_inventing_work() {
770 assert_eq!(
771 WhaleState::for_shell_phase(ShellPhase::Idle),
772 WhaleState::Resting
773 );
774 assert_eq!(
775 WhaleState::for_shell_phase(ShellPhase::Done),
776 WhaleState::Resting
777 );
778 assert_eq!(
779 WhaleState::for_shell_phase(ShellPhase::Typing),
780 WhaleState::Thinking
781 );
782 assert_eq!(
783 WhaleState::for_shell_phase(ShellPhase::Working),
784 WhaleState::Working
785 );
786 assert_eq!(
787 WhaleState::for_shell_phase(ShellPhase::Verifying),
788 WhaleState::Working
789 );
790 assert_eq!(
791 WhaleState::for_shell_phase(ShellPhase::Waiting),
792 WhaleState::Waiting
793 );
794 assert_eq!(
795 WhaleState::for_shell_phase(ShellPhase::Approval),
796 WhaleState::Waiting
797 );
798 assert_eq!(
799 WhaleState::for_shell_phase(ShellPhase::Failed),
800 WhaleState::Blocked
801 );
802 }
803
804 #[test]
805 fn badge_accents_meet_secondary_chrome_contrast_on_dark_and_light() {
806 // Flat Whale shells are terminal-owned and therefore deliberately
807 // unresolvable. Contrast is enforced against the concrete colors the
808 // explicit Deepsea treatment paints behind these badges.
809 let mut dark = palette::UI_THEME;
810 dark.surface_bg = palette::WHALE_BG;
811 let mut light = palette::LIGHT_UI_THEME;
812 light.surface_bg = palette::LIGHT_SURFACE;
813 for theme in [dark, light] {
814 let ink = WhaleInk::from_theme(&theme);
815 for species in WhaleSpecies::ALL {
816 for color in [ink.accent(species), ink.body_for(species)] {
817 let ratio = contrast_ratio(color, theme.surface_bg)
818 .unwrap_or_else(|| panic!("{species:?} unresolvable on {}", theme.name));
819 assert!(
820 ratio >= palette::SECONDARY_CHROME_CONTRAST,
821 "{species:?} {color:?} on {} = {ratio:.2}",
822 theme.name
823 );
824 }
825 }
826 for color in [ink.current, ink.human, ink.bar] {
827 let ratio = contrast_ratio(color, theme.surface_bg).unwrap();
828 assert!(
829 ratio >= palette::SECONDARY_CHROME_CONTRAST,
830 "{color:?} {ratio:.2}"
831 );
832 }
833 }
834 // Terminal theme surfaces are terminal-owned; enforcement must pass
835 // named colors through untouched rather than inventing RGB.
836 let terminal = palette::TERMINAL_UI_THEME;
837 let ink = WhaleInk::from_theme(&terminal);
838 assert_eq!(ink.body, terminal.accent_action);
839 assert_eq!(ink.keel, terminal.warning);
840 }
841
842 #[test]
843 fn species_labels_are_localized_in_every_shipped_pack() {
844 for species in WhaleSpecies::ALL {
845 for locale in Locale::shipped_complete() {
846 assert!(!species.animal(*locale).trim().is_empty());
847 assert!(!species.job(*locale).trim().is_empty());
848 }
849 }
850 assert_eq!(WhaleSpecies::Scout.name(), "Scout");
851 assert_eq!(WhaleSpecies::Plain.name(), "codewhale");
852 }
853 }
854
854 lines RUST