| 1 | //! The `/whale` surface over the foreground Engine session. No prompt, worker |
| 2 | //! or execution authority lives here. |
| 3 | use super::PetWatch; |
| 4 | use crate::tui::{ |
| 5 | app::App, |
| 6 | history::HistoryCell, |
| 7 | shell_key_routing::{self, ShellBindingId as Id}, |
| 8 | underwater::ShellPhase, |
| 9 | }; |
| 10 | use codewhale_engine::{ |
| 11 | agent_roster::{AgentRosterRow, RosterState}, |
| 12 | tools::subagent::AgentWorkerStatus, |
| 13 | }; |
| 14 | use codewhale_localization::{Locale, MessageId, tr}; |
| 15 | use codewhale_ratatui::{ |
| 16 | AgentCard, Caps, DotWhale, MotionMode, PetMode, PetModeAreas, PetStyle, State, StatusMark, |
| 17 | Subagent, SubagentControls, SubagentUsage, SubagentViewWords, Theme, WhalePet, |
| 18 | whale_motion::{Context, Inputs, Presence}, |
| 19 | }; |
| 20 | use ratatui::{Frame, layout::Rect, text::Line}; |
| 21 | use std::{ |
| 22 | borrow::Cow, |
| 23 | time::{Duration, Instant}, |
| 24 | }; |
| 25 | |
| 26 | fn needs( |
| 27 | watch: &PetWatch, |
| 28 | theme: &Theme, |
| 29 | locale: Locale, |
| 30 | ) -> Option<(Cow<'static, str>, Cow<'static, str>)> { |
| 31 | if theme.ascii() { |
| 32 | Some(( |
| 33 | tr(locale, MessageId::PetNeedsUnicode), |
| 34 | tr(locale, MessageId::PetWords), |
| 35 | )) |
| 36 | } else if watch.dots.as_ref().is_some_and(|dots| dots.failed()) { |
| 37 | Some(( |
| 38 | tr(locale, MessageId::PetNeedsDots), |
| 39 | tr(locale, MessageId::PetFallbackWhale), |
| 40 | )) |
| 41 | } else { |
| 42 | None |
| 43 | } |
| 44 | } |
| 45 | pub(super) fn theme(app: &App) -> Theme { |
| 46 | let mut caps = Caps::detect(); |
| 47 | if let Some(appearance) = |
| 48 | codewhale_ratatui::detect::appearance_for_background(app.ui_theme.surface_bg) |
| 49 | { |
| 50 | caps.appearance = appearance; |
| 51 | } |
| 52 | let theme = Theme::new(caps); |
| 53 | codewhale_ratatui::TuiPalette::ALL |
| 54 | .into_iter() |
| 55 | .find(|palette| palette.name() == app.ui_theme.name) |
| 56 | .map_or(theme, |palette| theme.tui_palette(palette)) |
| 57 | } |
| 58 | |
| 59 | fn live_rows(app: &App) -> Vec<AgentRosterRow> { |
| 60 | use crate::tui::subagent_routing::{subagent_is_parked, worker_status_for_terminal_projection}; |
| 61 | let mut rows = app.current_agent_roster().to_vec(); |
| 62 | let name = |id: &str| app.agent_label_map.get(id).cloned(); |
| 63 | let blank = |id: &str, display_name: String| AgentRosterRow { |
| 64 | worker_id: id.to_string(), |
| 65 | display_name, |
| 66 | model: String::new(), |
| 67 | state: RosterState::Running, |
| 68 | status: AgentWorkerStatus::Running, |
| 69 | activity: None, |
| 70 | outcome: None, |
| 71 | millis: None, |
| 72 | input_tokens: None, |
| 73 | output_tokens: None, |
| 74 | cost_microusd: None, |
| 75 | steps_taken: 0, |
| 76 | parent_run_id: None, |
| 77 | run_id: id.to_string(), |
| 78 | }; |
| 79 | for agent in &app.subagent_cache { |
| 80 | let index = rows |
| 81 | .iter() |
| 82 | .position(|row| row.worker_id == agent.agent_id) |
| 83 | .unwrap_or_else(|| { |
| 84 | let display_name = name(&agent.agent_id) |
| 85 | .or_else(|| agent.nickname.clone()) |
| 86 | .unwrap_or_else(|| agent.name.clone()); |
| 87 | let usage = agent.usage.as_ref(); |
| 88 | rows.push(AgentRosterRow { |
| 89 | model: agent.model.clone(), |
| 90 | millis: Some(agent.duration_ms), |
| 91 | input_tokens: usage.and_then(|usage| usage.input_tokens), |
| 92 | output_tokens: usage.and_then(|usage| usage.output_tokens), |
| 93 | cost_microusd: usage.and_then(|usage| usage.cost_microusd), |
| 94 | steps_taken: agent.steps_taken, |
| 95 | parent_run_id: agent.parent_run_id.clone(), |
| 96 | ..blank(&agent.agent_id, display_name) |
| 97 | }); |
| 98 | rows.len() - 1 |
| 99 | }); |
| 100 | let row = &mut rows[index]; |
| 101 | row.status = agent |
| 102 | .worker_status |
| 103 | .unwrap_or_else(|| worker_status_for_terminal_projection(&agent.status)); |
| 104 | row.state = if subagent_is_parked(agent) { |
| 105 | RosterState::Parked |
| 106 | } else { |
| 107 | RosterState::from_worker(row.status) |
| 108 | }; |
| 109 | if row.state == RosterState::Running |
| 110 | && let Some(started) = agent.started_at |
| 111 | { |
| 112 | row.millis = Some(u64::try_from(started.elapsed().as_millis()).unwrap_or(u64::MAX)); |
| 113 | } |
| 114 | } |
| 115 | for (id, progress) in &app.agent_progress { |
| 116 | match rows.iter_mut().find(|row| &row.worker_id == id) { |
| 117 | Some(row) => row.activity = Some(progress.clone()), |
| 118 | None => rows.push(AgentRosterRow { |
| 119 | activity: Some(progress.clone()), |
| 120 | ..blank(id, name(id).unwrap_or_else(|| id.clone())) |
| 121 | }), |
| 122 | } |
| 123 | } |
| 124 | rows |
| 125 | } |
| 126 | |
| 127 | pub(super) fn agents(app: &App) -> Vec<Subagent<'static>> { |
| 128 | live_rows(app) |
| 129 | .iter() |
| 130 | .map(|row| { |
| 131 | let (state, label) = match row.state { |
| 132 | RosterState::Running if row.status == AgentWorkerStatus::Queued => { |
| 133 | (State::Ready, MessageId::AgentRailQueuedCount) |
| 134 | } |
| 135 | RosterState::Running => (State::Working, MessageId::SubagentsStatusRunning), |
| 136 | RosterState::Waiting => (State::NeedsYou, MessageId::PhaseWaitingOnYou), |
| 137 | RosterState::Parked => (State::Stopped, MessageId::AgentStatusParked), |
| 138 | RosterState::Done => (State::Done, MessageId::SubagentsStatusCompleted), |
| 139 | RosterState::Failed => (State::Failed, MessageId::SubagentsStatusFailed), |
| 140 | RosterState::Cancelled => (State::Stopped, MessageId::SubagentsStatusCancelled), |
| 141 | }; |
| 142 | let mut card = AgentCard::new(row.display_name.clone(), state) |
| 143 | .status_word(tr(app.ui_locale, label).replace("{count}", "1")) |
| 144 | .task(row.activity.clone().unwrap_or_default()); |
| 145 | if !row.model.trim().is_empty() { |
| 146 | card = card.route(row.model.clone()); |
| 147 | } |
| 148 | let mut agent = Subagent::new(row.worker_id.clone(), card); |
| 149 | agent.elapsed = row.millis.map(Duration::from_millis); |
| 150 | agent.usage = Some(SubagentUsage { |
| 151 | input_tokens: row.input_tokens, |
| 152 | output_tokens: row.output_tokens, |
| 153 | cost_microusd: row.cost_microusd, |
| 154 | }); |
| 155 | agent.steps = Some(row.steps_taken); |
| 156 | // This pane is the retained roster. Enter opens the existing full |
| 157 | // agent transcript, so long outcomes are not cloned on animation frames. |
| 158 | agent.controls = SubagentControls { |
| 159 | open: true, |
| 160 | ..Default::default() |
| 161 | }; |
| 162 | agent |
| 163 | }) |
| 164 | .collect() |
| 165 | } |
| 166 | fn inputs(app: &App) -> Inputs { |
| 167 | let presence = match ShellPhase::from_app(app) { |
| 168 | ShellPhase::Working | ShellPhase::Verifying => Presence::Working, |
| 169 | ShellPhase::Waiting | ShellPhase::Approval => Presence::NeedsYou, |
| 170 | ShellPhase::Typing => Presence::Listening, |
| 171 | ShellPhase::Done => Presence::Done, |
| 172 | ShellPhase::Idle | ShellPhase::Failed => Presence::Idle, |
| 173 | }; |
| 174 | Inputs { |
| 175 | presence, |
| 176 | activity: None, |
| 177 | context: Context { |
| 178 | turn_id: app.runtime_turn_id.clone(), |
| 179 | status: app.runtime_turn_status.clone(), |
| 180 | ..Default::default() |
| 181 | }, |
| 182 | } |
| 183 | } |
| 184 | pub(super) fn motion(app: &App) -> MotionMode { |
| 185 | // The habitat owns the viewport through the modal stack. The ordinary |
| 186 | // shell's ambient helper intentionally stops under every modal, so using |
| 187 | // it here would freeze the pet simply because its own view is open. |
| 188 | if app.pet_watch.still() { |
| 189 | return MotionMode::Still; |
| 190 | } |
| 191 | match app.motion_policy().mode() { |
| 192 | crate::tui::motion::MotionMode::Still => MotionMode::Still, |
| 193 | crate::tui::motion::MotionMode::Reduced => MotionMode::Reduced, |
| 194 | crate::tui::motion::MotionMode::Full |
| 195 | if matches!( |
| 196 | ShellPhase::from_app(app), |
| 197 | ShellPhase::Approval | ShellPhase::Waiting |
| 198 | ) => |
| 199 | { |
| 200 | MotionMode::Reduced |
| 201 | } |
| 202 | crate::tui::motion::MotionMode::Full => MotionMode::Full, |
| 203 | } |
| 204 | } |
| 205 | pub(super) fn tick(app: &mut App, visible: bool, now: Instant) { |
| 206 | app.pet_watch.full.set_visible(visible); |
| 207 | if !visible { |
| 208 | app.pet_watch.full_next = None; |
| 209 | return; |
| 210 | } |
| 211 | let agents = agents(app); |
| 212 | // Revalidate the painted identity against the current session before the |
| 213 | // modal can return an open intent. A removed/ambiguous worker never turns |
| 214 | // into the new fallback selection before it has actually been painted. |
| 215 | if let Ok(mut selected) = app.pet_watch.selection.lock() |
| 216 | && selected.as_deref().is_some_and(|id| { |
| 217 | agents |
| 218 | .iter() |
| 219 | .filter(|agent| agent.id == id && agent.controls.open) |
| 220 | .count() |
| 221 | != 1 |
| 222 | }) |
| 223 | { |
| 224 | *selected = None; |
| 225 | } |
| 226 | let inputs = inputs(app); |
| 227 | let changed = app.pet_watch.full_inputs.as_ref().is_none_or(|old| { |
| 228 | old.presence != inputs.presence |
| 229 | || old.context.turn_id != inputs.context.turn_id |
| 230 | || old.context.status != inputs.context.status |
| 231 | }); |
| 232 | let motion = motion(app); |
| 233 | let theme = theme(app); |
| 234 | let painted_local = app.pet_watch.dots_frame.is_some() && app.pet_watch.dots_area.is_some(); |
| 235 | let local = app |
| 236 | .pet_watch |
| 237 | .dots_frame |
| 238 | .as_ref() |
| 239 | .filter(|_| painted_local && motion.animates()) |
| 240 | .map(|f| Duration::from_millis(if f.busy { 66 } else { 250 })); |
| 241 | let state = &mut app.pet_watch; |
| 242 | state.full.update( |
| 243 | app.current_session_id.as_deref(), |
| 244 | inputs.clone(), |
| 245 | &agents, |
| 246 | now, |
| 247 | motion, |
| 248 | ); |
| 249 | state.full_inputs = Some(inputs); |
| 250 | if changed { |
| 251 | state.full_next = None; |
| 252 | app.needs_redraw = true; |
| 253 | } |
| 254 | let stage = state.full.next_frame_in(&agents, &theme).map(|s| { |
| 255 | if painted_local { |
| 256 | s.max(Duration::from_millis(200)) |
| 257 | } else { |
| 258 | s |
| 259 | } |
| 260 | }); |
| 261 | if let Some(interval) = [local, stage].into_iter().flatten().min() { |
| 262 | if state.full_next.is_none_or(|deadline| now >= deadline) { |
| 263 | state.full_next = now.checked_add(interval); |
| 264 | app.needs_redraw |= stage.is_some(); |
| 265 | } |
| 266 | } else { |
| 267 | state.full_next = None; |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | pub fn render_full(frame: &mut Frame, app: &mut App) { |
| 272 | render(frame, frame.area(), app, true); |
| 273 | } |
| 274 | /// The same stage becomes the shell backdrop. Inspection is opt-in so streamed |
| 275 | /// replies and a retained roster never displace the whale or the composer. |
| 276 | pub fn render_main(frame: &mut Frame, area: Rect, app: &mut App) { |
| 277 | render(frame, area, app, false); |
| 278 | } |
| 279 | fn render(frame: &mut Frame, area: Rect, app: &mut App, inspect: bool) { |
| 280 | if inspect { |
| 281 | app.resync_history_revisions(); |
| 282 | } |
| 283 | let agents = agents(app); |
| 284 | let theme = theme(app); |
| 285 | let phase = ShellPhase::from_app(app); |
| 286 | let notice = app.active_status_toast(phase).map(|toast| { |
| 287 | Line::styled( |
| 288 | toast.text, |
| 289 | codewhale_palette::chrome_style(&app.ui_theme, toast.level.ink()), |
| 290 | ) |
| 291 | }); |
| 292 | let words = phase.label(app.ui_locale); |
| 293 | let mark = StatusMark::new(match phase { |
| 294 | ShellPhase::Working | ShellPhase::Verifying => State::Working, |
| 295 | ShellPhase::Approval | ShellPhase::Waiting => State::NeedsYou, |
| 296 | ShellPhase::Done => State::Done, |
| 297 | ShellPhase::Failed => State::Failed, |
| 298 | ShellPhase::Idle | ShellPhase::Typing => State::Ready, |
| 299 | }) |
| 300 | .word(words.clone().into_owned()); |
| 301 | // ActiveCell is the same live transcript the normal shell reads. Include |
| 302 | // streamed replies and terminal errors, without waiting for a successful turn. |
| 303 | let response_index = inspect |
| 304 | .then(|| { |
| 305 | (app.pet_watch.work_history_start..app.virtual_cell_count()).rfind(|&index| { |
| 306 | matches!( |
| 307 | app.cell_at_virtual_index(index), |
| 308 | Some(HistoryCell::Assistant { .. } | HistoryCell::Error { .. }) |
| 309 | ) |
| 310 | }) |
| 311 | }) |
| 312 | .flatten(); |
| 313 | let active = app.active_cell.as_ref(); |
| 314 | let response = response_index.and_then(|index| { |
| 315 | if index < app.history.len() { |
| 316 | app.history.get(index) |
| 317 | } else { |
| 318 | active.and_then(|cell| cell.entries().get(index - app.history.len())) |
| 319 | } |
| 320 | }); |
| 321 | let plan = PetModeAreas::new( |
| 322 | area, |
| 323 | inspect && !agents.is_empty(), |
| 324 | response.is_some(), |
| 325 | app.pet_watch.full.focus_agents, |
| 326 | ); |
| 327 | let owner = inputs(app); |
| 328 | let motion = motion(app); |
| 329 | let tinted = app |
| 330 | .pet_watch |
| 331 | .color() |
| 332 | .zip(app.pet_watch.dots_frame.as_ref()) |
| 333 | .map(|(color, f)| tint(&f.materials, color)); |
| 334 | let dot_whale = app.pet_watch.dots_frame.as_ref().map(|f| { |
| 335 | DotWhale::new(&f.points, tinted.as_deref().unwrap_or(&f.materials)) |
| 336 | .caption(&words) |
| 337 | .hollow(f.hollow) |
| 338 | }); |
| 339 | let missing = (!plan.pet.is_empty() && dot_whale.is_none()) |
| 340 | .then(|| needs(&app.pet_watch, &theme, app.ui_locale)) |
| 341 | .flatten() |
| 342 | .map(|(requirement, shown)| { |
| 343 | Line::styled( |
| 344 | tr(app.ui_locale, MessageId::PetViewNeeds) |
| 345 | .replace("{view}", "whale") |
| 346 | .replace("{requirement}", requirement.as_ref()) |
| 347 | .replace("{shown}", shown.as_ref()), |
| 348 | codewhale_palette::chrome_style( |
| 349 | &app.ui_theme, |
| 350 | crate::tui::app::StatusToastLevel::Info.ink(), |
| 351 | ), |
| 352 | ) |
| 353 | }); |
| 354 | // Revisions invalidate the selected cell inside the existing incremental |
| 355 | // cache. Only source replacement or a destructive history change discards |
| 356 | // its parser; streaming chunks and ambient frames keep the stable prefix. |
| 357 | let key = response_index.map(|index| { |
| 358 | ( |
| 359 | app.transcript_identity_epoch, |
| 360 | index, |
| 361 | index >= app.history.len(), |
| 362 | ) |
| 363 | }); |
| 364 | let title = app.pet_watch.name().unwrap_or("Codewhale").to_owned(); |
| 365 | if inspect && app.pet_watch.full_response_key != key { |
| 366 | app.pet_watch.full_response = None; |
| 367 | app.pet_watch.full_response_key = key; |
| 368 | } |
| 369 | let mut options = app.transcript_render_options(); |
| 370 | options.low_motion = true; |
| 371 | options.motion_mode = crate::tui::motion::MotionMode::Reduced; |
| 372 | let chord = |id| shell_key_routing::display_chord(shell_key_routing::binding(id).footer_chord); |
| 373 | let copy_hint = (inspect && app.completed_assistant_output_receipt().is_some()).then(|| { |
| 374 | tr(app.ui_locale, MessageId::PetModeCopyHint).replace( |
| 375 | "{copy}", |
| 376 | shell_key_routing::binding(Id::PetCopyReply).footer_chord, |
| 377 | ) |
| 378 | }); |
| 379 | let lines = if inspect { |
| 380 | let revision = response_index.map_or(0, |index| { |
| 381 | if index < app.history.len() { |
| 382 | app.history_revisions[index] |
| 383 | } else { |
| 384 | active.map_or(0, |cell| cell.revision()) |
| 385 | } |
| 386 | }); |
| 387 | let revisions = [revision]; |
| 388 | let cache = app |
| 389 | .pet_watch |
| 390 | .full_response |
| 391 | .get_or_insert_with(crate::tui::transcript::TranscriptViewCache::new); |
| 392 | cache.set_streaming_source_receipt( |
| 393 | app.streaming_source_receipt |
| 394 | .filter(|receipt| Some(receipt.cell_index) == response_index), |
| 395 | ); |
| 396 | cache.ensure_split( |
| 397 | &[response.map_or(&[], std::slice::from_ref)], |
| 398 | if response.is_some() { &revisions } else { &[] }, |
| 399 | plan.output.width.max(1), |
| 400 | options, |
| 401 | &std::collections::HashMap::new(), |
| 402 | response_index.as_ref().map(std::slice::from_ref), |
| 403 | None, |
| 404 | ); |
| 405 | if let Some(receipt) = app.streaming_source_receipt.as_mut() |
| 406 | && Some(receipt.cell_index) == response_index |
| 407 | { |
| 408 | receipt.from_revision = receipt.to_revision; |
| 409 | } |
| 410 | cache.lines() |
| 411 | } else { |
| 412 | &[] |
| 413 | }; |
| 414 | let has_output = !lines.is_empty(); |
| 415 | let mut hints = tr(app.ui_locale, MessageId::PetModeMessageHint).replace( |
| 416 | "{back}", |
| 417 | shell_key_routing::binding(Id::PetBack).footer_chord, |
| 418 | ); |
| 419 | if !agents.is_empty() { |
| 420 | hints.push_str(&format!( |
| 421 | " · {}", |
| 422 | tr(app.ui_locale, MessageId::PetModePaneHint).replace( |
| 423 | "{switch}", |
| 424 | shell_key_routing::binding(Id::PetFocusAgents).footer_chord, |
| 425 | ) |
| 426 | )); |
| 427 | } |
| 428 | let arrows = format!( |
| 429 | "{}{}", |
| 430 | shell_key_routing::binding(Id::PetResultUp).footer_chord, |
| 431 | shell_key_routing::binding(Id::PetResultDown).footer_chord, |
| 432 | ); |
| 433 | let mut pane_hints = if app.pet_watch.full.focus_agents && !agents.is_empty() { |
| 434 | tr(app.ui_locale, MessageId::PetModeAgentHints) |
| 435 | .replace("{select}", &arrows) |
| 436 | .replace( |
| 437 | "{open}", |
| 438 | shell_key_routing::binding(Id::PetOpenAgent).footer_chord, |
| 439 | ) |
| 440 | } else if !lines.is_empty() { |
| 441 | tr(app.ui_locale, MessageId::PetModeReplyHints) |
| 442 | .replace("{scroll}", &arrows) |
| 443 | .replace( |
| 444 | "{latest}", |
| 445 | shell_key_routing::binding(Id::PetResultEnd).footer_chord, |
| 446 | ) |
| 447 | } else { |
| 448 | String::new() |
| 449 | }; |
| 450 | if let Some(copy_hint) = ©_hint { |
| 451 | pane_hints = if pane_hints.is_empty() { |
| 452 | copy_hint.clone() |
| 453 | } else { |
| 454 | format!("{copy_hint} · {pane_hints}") |
| 455 | }; |
| 456 | } |
| 457 | let mut view = PetMode::new(&theme, mark); |
| 458 | view.style = PetStyle::Color; |
| 459 | view.cove = false; |
| 460 | view.dot_whale = dot_whale; |
| 461 | view.notice = notice.or(missing); |
| 462 | view.title = title.into(); |
| 463 | view.agents = if inspect { &agents } else { &[] }; |
| 464 | view.agent_words = SubagentViewWords { |
| 465 | title: tr(app.ui_locale, MessageId::ConfigChoiceRailAgents), |
| 466 | empty: tr( |
| 467 | app.ui_locale, |
| 468 | MessageId::SubagentsNoCurrentSessionFleetWorkers, |
| 469 | ), |
| 470 | activity: tr(app.ui_locale, MessageId::AutomationStatusLabel), |
| 471 | output: tr(app.ui_locale, MessageId::AgentFocusResult), |
| 472 | // The retained roster supplies no event log or copied outcome. |
| 473 | // Enter opens those through the existing localized transcript view. |
| 474 | toggle_output: "".into(), |
| 475 | no_events: "".into(), |
| 476 | hints: "".into(), |
| 477 | open: "".into(), |
| 478 | message: "".into(), |
| 479 | stop: "".into(), |
| 480 | summary: Some( |
| 481 | tr(app.ui_locale, MessageId::SubagentsSummaryItem) |
| 482 | .replace( |
| 483 | "{label}", |
| 484 | tr(app.ui_locale, MessageId::CtxInspTotal).as_ref(), |
| 485 | ) |
| 486 | .replace("{count}", &agents.len().to_string()) |
| 487 | .into(), |
| 488 | ), |
| 489 | steps_label: Some(tr(app.ui_locale, MessageId::SessionMetricsSteps)), |
| 490 | }; |
| 491 | view.output = lines; |
| 492 | view.output_title = tr( |
| 493 | app.ui_locale, |
| 494 | match response { |
| 495 | Some(HistoryCell::Error { .. }) => MessageId::ExtensionsStateError, |
| 496 | _ => MessageId::PetModeReplyTitle, |
| 497 | }, |
| 498 | ); |
| 499 | let inspect_hint = tr(app.ui_locale, MessageId::PetModeInspectHint) |
| 500 | .replace("{inspect}", &chord(Id::PetInspect)); |
| 501 | view.pane_hints = if inspect { |
| 502 | pane_hints.into() |
| 503 | } else { |
| 504 | Cow::Borrowed("") |
| 505 | }; |
| 506 | view.hints = if inspect { |
| 507 | hints.into() |
| 508 | } else { |
| 509 | inspect_hint.clone().into() |
| 510 | }; |
| 511 | app.pet_watch |
| 512 | .full |
| 513 | .set_visible(inspect || app.view_stack.is_empty()); |
| 514 | app.pet_watch.full.update( |
| 515 | app.current_session_id.as_deref(), |
| 516 | owner, |
| 517 | &agents, |
| 518 | Instant::now(), |
| 519 | motion, |
| 520 | ); |
| 521 | frame.render_stateful_widget(view, area, &mut app.pet_watch.full); |
| 522 | let painted = area.intersection(frame.area()); |
| 523 | let pet = PetModeAreas::new( |
| 524 | painted, |
| 525 | inspect && !agents.is_empty(), |
| 526 | has_output, |
| 527 | app.pet_watch.full.focus_agents, |
| 528 | ) |
| 529 | .pet; |
| 530 | let art = WhalePet::art_area(pet); |
| 531 | app.pet_watch.dots_area = (!painted.is_empty() |
| 532 | && (inspect || app.view_stack.is_empty()) |
| 533 | && !theme.ascii() |
| 534 | && art.width >= 16 |
| 535 | && art.height >= 8) |
| 536 | .then_some(pet); |
| 537 | if let Ok(mut copy_area) = app.pet_watch.copy_area.lock() { |
| 538 | *copy_area = copy_hint.as_ref().and_then(|hint| { |
| 539 | let width = codewhale_ratatui::text::width(hint); |
| 540 | // Match the actual second-row truncation; a hidden/truncated label |
| 541 | // never leaves a clickable target behind. |
| 542 | (plan.footer.height > 1 && width + 4 <= usize::from(plan.footer.width)) |
| 543 | .then(|| Rect::new(plan.footer.x, plan.footer.y + 1, width as u16, 1)) |
| 544 | }); |
| 545 | } |
| 546 | if let Ok(mut selection) = app.pet_watch.selection.lock() { |
| 547 | *selection = inspect |
| 548 | .then(|| app.pet_watch.full.selected_agent_id().map(str::to_owned)) |
| 549 | .flatten(); |
| 550 | } |
| 551 | app.pet_watch.inspect_area = (!inspect).then(|| { |
| 552 | Rect::new( |
| 553 | plan.footer.x, |
| 554 | plan.footer.y, |
| 555 | (codewhale_ratatui::text::width(inspect_hint.split(" · ").next().unwrap_or_default()) |
| 556 | as u16) |
| 557 | .min(plan.footer.width), |
| 558 | plan.footer.height.min(1), |
| 559 | ) |
| 560 | }); |
| 561 | app.pet_watch.area = Some(plan.pet); |
| 562 | } |
| 563 | fn tint(materials: &[[f64; 4]], color: [u8; 3]) -> Vec<[f64; 4]> { |
| 564 | let [r, g, b] = color.map(f64::from); |
| 565 | let peak = r.max(g).max(b); |
| 566 | let hue = if peak > 0.0 { |
| 567 | [r / peak, g / peak, b / peak] |
| 568 | } else { |
| 569 | [1.0; 3] |
| 570 | }; |
| 571 | materials |
| 572 | .iter() |
| 573 | .map(|m| { |
| 574 | let value = m[0].max(m[1]).max(m[2]); |
| 575 | [hue[0] * value, hue[1] * value, hue[2] * value, m[3]] |
| 576 | }) |
| 577 | .collect() |
| 578 | } |
| 579 | |
| 580 | #[cfg(test)] |
| 581 | mod tests { |
| 582 | use super::*; |
| 583 | use crate::tui::{active_cell::ActiveCell, app::OnboardingState}; |
| 584 | fn app() -> App { |
| 585 | let mut app = crate::tui::test_support::test_app_with_options( |
| 586 | crate::tui::test_support::test_tui_options("."), |
| 587 | ); |
| 588 | app.onboarding = OnboardingState::None; |
| 589 | app.redaction_gate = false; |
| 590 | app.pet_watch.session = app.current_session_id.clone(); |
| 591 | app.pet_watch.detach_for_test(); |
| 592 | app |
| 593 | } |
| 594 | fn paint(app: &mut App, width: u16, height: u16) -> String { |
| 595 | let mut terminal = |
| 596 | ratatui::Terminal::new(ratatui::backend::TestBackend::new(width, height)).unwrap(); |
| 597 | terminal.draw(|frame| render_full(frame, app)).unwrap(); |
| 598 | terminal |
| 599 | .backend() |
| 600 | .buffer() |
| 601 | .content |
| 602 | .iter() |
| 603 | .map(|cell| cell.symbol()) |
| 604 | .collect() |
| 605 | } |
| 606 | #[test] |
| 607 | fn native_main_stage_wakes_the_existing_idle_loop_and_stops_when_hidden() { |
| 608 | let mut app = app(); |
| 609 | app.low_motion = false; |
| 610 | app.fancy_animations = true; |
| 611 | app.pet_watch.enabled = true; |
| 612 | let mut terminal = |
| 613 | ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 32)).unwrap(); |
| 614 | terminal |
| 615 | .draw(|frame| render_main(frame, frame.area(), &mut app)) |
| 616 | .unwrap(); |
| 617 | let now = Instant::now(); |
| 618 | super::super::tick(&mut app, now); |
| 619 | assert!(app.pet_watch.next_frame_in(now).is_some()); |
| 620 | app.view_stack |
| 621 | .push(crate::tui::views::HelpView::new_for_locale(app.ui_locale)); |
| 622 | super::super::tick(&mut app, now + Duration::from_secs(2)); |
| 623 | assert!( |
| 624 | app.pet_watch |
| 625 | .next_frame_in(now + Duration::from_secs(2)) |
| 626 | .is_none() |
| 627 | ); |
| 628 | } |
| 629 | #[test] |
| 630 | fn full_mode_animates_under_its_own_modal_and_respects_motion_preferences() { |
| 631 | let mut app = app(); |
| 632 | app.is_loading = true; |
| 633 | app.low_motion = false; |
| 634 | app.fancy_animations = true; |
| 635 | super::super::open_habitat(&mut app); |
| 636 | assert!(super::super::is_open(&app)); |
| 637 | assert_eq!(motion(&app), MotionMode::Full); |
| 638 | paint(&mut app, 100, 32); |
| 639 | tick(&mut app, true, Instant::now()); |
| 640 | assert!(app.pet_watch.full_next.is_some()); |
| 641 | app.low_motion = true; |
| 642 | tick(&mut app, true, Instant::now()); |
| 643 | assert!(app.pet_watch.full_next.is_none()); |
| 644 | app.low_motion = false; |
| 645 | app.fancy_animations = false; |
| 646 | assert_eq!(motion(&app), MotionMode::Still); |
| 647 | } |
| 648 | #[test] |
| 649 | fn a_terminal_draws_its_own_dot_whale_from_its_own_session() { |
| 650 | let projector = super::super::dots::Projector::new().expect("committed bundle loads"); |
| 651 | assert!(projector.observe( |
| 652 | r#"[{"event":"turn_started","turn_id":"t"}, |
| 653 | {"event":"operation_activity_started","span_id":"s","activity_kind":"editing"}]"#, |
| 654 | 0.0 |
| 655 | )); |
| 656 | let frame = projector |
| 657 | .frame(100.0, false, false) |
| 658 | .unwrap() |
| 659 | .expect("a moving frame"); |
| 660 | assert_eq!(frame.points.len(), 980); |
| 661 | assert_eq!(frame.materials.len(), 980); |
| 662 | assert!(!frame.hollow); |
| 663 | let still = projector |
| 664 | .frame(3000.0, true, false) |
| 665 | .unwrap() |
| 666 | .expect("a still frame"); |
| 667 | assert_eq!(still.points.len(), 980); |
| 668 | assert_eq!(projector.frame(3100.0, true, false), Ok(None)); |
| 669 | assert!(projector.reset()); |
| 670 | let rest = projector |
| 671 | .frame(3200.0, true, false) |
| 672 | .unwrap() |
| 673 | .expect("a still rest frame"); |
| 674 | assert!(rest.hollow); |
| 675 | assert_ne!(rest.points, still.points, "editing reshapes the dots"); |
| 676 | |
| 677 | let mut app = app(); |
| 678 | assert!(!paint(&mut app, 100, 32).contains(" needs ")); |
| 679 | app.pet_watch.dots_frame = Some(frame); |
| 680 | app.pet_watch.set_name(Some("Moby".into())); |
| 681 | let painted = paint(&mut app, 100, 32); |
| 682 | assert!(!painted.contains(" needs "), "{painted}"); |
| 683 | assert!(painted.contains("Moby"), "{painted}"); |
| 684 | assert!( |
| 685 | painted |
| 686 | .chars() |
| 687 | .any(|c| ('\u{2801}'..='\u{28FF}').contains(&c)) |
| 688 | ); |
| 689 | } |
| 690 | #[test] |
| 691 | fn hold_still_stops_the_stage_and_a_colour_keeps_each_dot_s_brightness() { |
| 692 | let mut app = app(); |
| 693 | app.low_motion = false; |
| 694 | app.fancy_animations = true; |
| 695 | assert_eq!(motion(&app), MotionMode::Full); |
| 696 | app.pet_watch.set_still(true); |
| 697 | assert_eq!(motion(&app), MotionMode::Still); |
| 698 | |
| 699 | let tinted = tint( |
| 700 | &[[40.0, 80.0, 120.0, 0.5], [120.0, 200.0, 240.0, 0.9]], |
| 701 | [255, 0, 0], |
| 702 | ); |
| 703 | assert_eq!(tinted, [[120.0, 0.0, 0.0, 0.5], [240.0, 0.0, 0.0, 0.9]]); |
| 704 | assert_eq!( |
| 705 | tint(&[[10.0, 20.0, 30.0, 1.0]], [0, 0, 0])[0][..3], |
| 706 | [30.0; 3] |
| 707 | ); |
| 708 | } |
| 709 | #[test] |
| 710 | fn a_dot_whale_that_cannot_start_falls_back_to_the_block_whale_and_says_so() { |
| 711 | let mut starting = app(); |
| 712 | starting.pet_watch.dots = Some(super::super::dots::Dots::start()); |
| 713 | assert!(!paint(&mut starting, 100, 32).contains(" needs ")); |
| 714 | |
| 715 | let dots = super::super::dots::failing_for_test(); |
| 716 | let deadline = Instant::now() + Duration::from_secs(60); |
| 717 | while !dots.failed() && Instant::now() < deadline { |
| 718 | std::thread::sleep(Duration::from_millis(20)); |
| 719 | } |
| 720 | assert!(dots.failed()); |
| 721 | let mut app = app(); |
| 722 | app.pet_watch.enabled = true; |
| 723 | app.pet_watch.dots = Some(dots); |
| 724 | app.pet_watch.dots_frame = Some(super::super::dots::Frame { |
| 725 | points: vec![[0.0, 0.0]; 980], |
| 726 | materials: vec![[100.0, 150.0, 200.0, 0.9]; 980], |
| 727 | hollow: false, |
| 728 | busy: false, |
| 729 | }); |
| 730 | super::super::tick(&mut app, Instant::now()); |
| 731 | assert!(app.pet_watch.dots_frame.is_none()); |
| 732 | assert!(paint(&mut app, 100, 32).contains(" needs ")); |
| 733 | app.pet_watch.enabled = false; |
| 734 | super::super::tick(&mut app, Instant::now()); |
| 735 | assert!( |
| 736 | app.pet_watch.dots.is_none(), |
| 737 | "pet off with no habitat drops the thread" |
| 738 | ); |
| 739 | } |
| 740 | #[test] |
| 741 | fn roster_scope_and_missing_vs_zero_receipts_come_from_the_existing_owner_guard() { |
| 742 | let mut app = app(); |
| 743 | app.current_session_id = Some("foreground".into()); |
| 744 | app.agent_roster_session_id = Some("other-session".into()); |
| 745 | app.agent_roster = vec![codewhale_engine::agent_roster::AgentRosterRow { |
| 746 | worker_id: "retained-worker".into(), |
| 747 | display_name: "Retained worker".into(), |
| 748 | model: "reported-model".into(), |
| 749 | state: RosterState::Waiting, |
| 750 | status: AgentWorkerStatus::WaitingForUser, |
| 751 | activity: Some("Owner activity".into()), |
| 752 | outcome: None, |
| 753 | millis: None, |
| 754 | input_tokens: Some(0), |
| 755 | output_tokens: None, |
| 756 | cost_microusd: Some(1), |
| 757 | steps_taken: 0, |
| 758 | parent_run_id: None, |
| 759 | run_id: "actual-run".into(), |
| 760 | }]; |
| 761 | assert!(agents(&app).is_empty()); |
| 762 | *app.pet_watch.selection.lock().unwrap() = Some("retained-worker".into()); |
| 763 | tick(&mut app, true, Instant::now()); |
| 764 | assert!(app.pet_watch.selection.lock().unwrap().is_none()); |
| 765 | app.agent_roster_session_id = app.current_session_id.clone(); |
| 766 | let rows = agents(&app); |
| 767 | assert_eq!(rows.len(), 1); |
| 768 | assert_eq!(rows[0].id, "retained-worker"); |
| 769 | assert_eq!(rows[0].card.status.state, State::NeedsYou); |
| 770 | assert_eq!(rows[0].usage.unwrap().input_tokens, Some(0)); |
| 771 | assert_eq!(rows[0].usage.unwrap().output_tokens, None); |
| 772 | assert_eq!(rows[0].usage.unwrap().cost_microusd, Some(1)); |
| 773 | assert_eq!(rows[0].elapsed, None); |
| 774 | app.agent_roster[0].state = RosterState::Parked; |
| 775 | assert_eq!( |
| 776 | agents(&app)[0].card.status.word, |
| 777 | tr(app.ui_locale, MessageId::AgentStatusParked) |
| 778 | ); |
| 779 | app.ui_locale = codewhale_localization::Locale::Fr; |
| 780 | app.pet_watch.full.focus_agents = true; |
| 781 | let detail = paint(&mut app, 95, 40); |
| 782 | assert!(detail.contains(tr(app.ui_locale, MessageId::AutomationStatusLabel).as_ref())); |
| 783 | assert!(!detail.contains("No events reported")); |
| 784 | assert!(!detail.contains("Activity")); |
| 785 | } |
| 786 | #[test] |
| 787 | fn pet_reply_reuses_incremental_markdown_and_rejects_unproven_edits() { |
| 788 | let mut app = app(); |
| 789 | app.is_loading = true; |
| 790 | let index = crate::tui::ui::ensure_streaming_assistant_history_cell(&mut app); |
| 791 | let initial: String = (0..120) |
| 792 | .map(|row| format!("Cached row {row}\n\n")) |
| 793 | .collect(); |
| 794 | crate::tui::ui::append_streaming_text(&mut app, index, &initial); |
| 795 | paint(&mut app, 80, 24); |
| 796 | let work = |app: &App| { |
| 797 | app.pet_watch |
| 798 | .full_response |
| 799 | .as_ref() |
| 800 | .unwrap() |
| 801 | .streaming_render_work(0) |
| 802 | .unwrap() |
| 803 | }; |
| 804 | assert_eq!(work(&app).invalidations, 1); |
| 805 | for row in 0..20 { |
| 806 | let before = work(&app); |
| 807 | let tail = format!("APPENDED_ROW_{row}"); |
| 808 | crate::tui::ui::append_streaming_text(&mut app, index, &format!("{tail}\n\n")); |
| 809 | assert!(paint(&mut app, 80, 24).contains(&tail)); |
| 810 | let after = work(&app); |
| 811 | assert_eq!(after.invalidations, 1); |
| 812 | assert!(after.classified_lines - before.classified_lines <= 2); |
| 813 | let receipt = app.streaming_source_receipt.unwrap(); |
| 814 | assert_eq!(receipt.from_revision, receipt.to_revision); |
| 815 | } |
| 816 | // Returning to the main view must preserve the inspector's parser. |
| 817 | let before = work(&app); |
| 818 | let mut terminal = |
| 819 | ratatui::Terminal::new(ratatui::backend::TestBackend::new(80, 24)).unwrap(); |
| 820 | terminal |
| 821 | .draw(|frame| render_main(frame, frame.area(), &mut app)) |
| 822 | .unwrap(); |
| 823 | assert_eq!(work(&app), before); |
| 824 | paint(&mut app, 80, 24); |
| 825 | assert_eq!(work(&app), before); |
| 826 | |
| 827 | let HistoryCell::Assistant { content, .. } = &mut app.history[index] else { |
| 828 | panic!("expected the real streaming history cell"); |
| 829 | }; |
| 830 | content.insert_str(0, "REWRITTEN_PREFIX\n\n"); |
| 831 | app.bump_history_cell(index); |
| 832 | assert!(app.streaming_source_receipt.is_none()); |
| 833 | paint(&mut app, 80, 24); |
| 834 | assert_eq!(work(&app).invalidations, 2); |
| 835 | assert!( |
| 836 | app.pet_watch |
| 837 | .full_response |
| 838 | .as_ref() |
| 839 | .unwrap() |
| 840 | .lines() |
| 841 | .iter() |
| 842 | .any(|line| line.to_string().contains("REWRITTEN_PREFIX")) |
| 843 | ); |
| 844 | crate::tui::ui::append_streaming_text(&mut app, index, "AFTER_REWRITE\n\n"); |
| 845 | assert!(paint(&mut app, 80, 24).contains("AFTER_REWRITE")); |
| 846 | assert_eq!(work(&app).invalidations, 2); |
| 847 | |
| 848 | let mut options = app.transcript_render_options(); |
| 849 | options.low_motion = true; |
| 850 | options.motion_mode = crate::tui::motion::MotionMode::Reduced; |
| 851 | let width = PetModeAreas::new(Rect::new(0, 0, 80, 24), false, true, false) |
| 852 | .output |
| 853 | .width; |
| 854 | let mut cold = crate::tui::transcript::TranscriptViewCache::new(); |
| 855 | cold.ensure( |
| 856 | &app.history[index..=index], |
| 857 | &[app.history_revisions[index]], |
| 858 | width, |
| 859 | options, |
| 860 | ); |
| 861 | assert_eq!( |
| 862 | app.pet_watch.full_response.as_ref().unwrap().lines(), |
| 863 | cold.lines() |
| 864 | ); |
| 865 | } |
| 866 | #[test] |
| 867 | fn streamed_tail_follows_until_the_reader_scrolls_back() { |
| 868 | let mut app = app(); |
| 869 | app.is_loading = true; |
| 870 | app.runtime_turn_id = Some("streamed-turn".into()); |
| 871 | let mut active = ActiveCell::new(); |
| 872 | active.push_untracked(HistoryCell::Assistant { |
| 873 | content: (0..30).map(|n| format!("Stream row {n}\n\n")).collect(), |
| 874 | streaming: true, |
| 875 | }); |
| 876 | app.active_cell = Some(active); |
| 877 | assert!(paint(&mut app, 40, 12).contains("Stream row 29")); |
| 878 | app.pet_watch.full.scroll(&[], -3); |
| 879 | let top = app.pet_watch.full.output_scroll; |
| 880 | let Some(HistoryCell::Assistant { content, .. }) = |
| 881 | app.active_cell.as_mut().unwrap().entry_mut(0) |
| 882 | else { |
| 883 | panic!("expected the live assistant response"); |
| 884 | }; |
| 885 | content.push_str("Appended streamed tail\n\n"); |
| 886 | assert!(!paint(&mut app, 40, 12).contains("Appended streamed tail")); |
| 887 | assert_eq!(app.pet_watch.full.output_scroll, top); |
| 888 | app.pet_watch.full.scroll_end(&[], true); |
| 889 | assert!(paint(&mut app, 40, 12).contains("Appended streamed tail")); |
| 890 | } |
| 891 | #[test] |
| 892 | fn full_mode_reads_streaming_response_then_failure_and_preserves_the_session() { |
| 893 | let mut app = app(); |
| 894 | app.is_loading = true; |
| 895 | app.input = "retained draft".into(); |
| 896 | let session = app.current_session_id.clone(); |
| 897 | let mut active = ActiveCell::new(); |
| 898 | active.push_untracked(HistoryCell::Assistant { |
| 899 | content: "Streaming response from this session".into(), |
| 900 | streaming: true, |
| 901 | }); |
| 902 | app.active_cell = Some(active); |
| 903 | assert!(paint(&mut app, 80, 24).contains("Streaming response from this session")); |
| 904 | app.active_cell = None; |
| 905 | app.is_loading = false; |
| 906 | app.runtime_turn_status = Some("failed".into()); |
| 907 | app.add_message(HistoryCell::Error { |
| 908 | message: "Actual failure receipt".into(), |
| 909 | severity: codewhale_error_taxonomy::ErrorSeverity::Error, |
| 910 | code: None, |
| 911 | }); |
| 912 | assert!(paint(&mut app, 40, 12).contains("Actual failure receipt")); |
| 913 | assert_eq!(app.input, "retained draft"); |
| 914 | assert_eq!(app.current_session_id, session); |
| 915 | } |
| 916 | #[test] |
| 917 | fn reduced_completed_view_reuses_the_response_and_does_not_schedule_paints() { |
| 918 | let mut app = app(); |
| 919 | app.runtime_turn_status = Some("completed".into()); |
| 920 | app.add_message(HistoryCell::Assistant { |
| 921 | content: "Finished answer".into(), |
| 922 | streaming: false, |
| 923 | }); |
| 924 | let first = paint(&mut app, 100, 32); |
| 925 | let lines = app |
| 926 | .pet_watch |
| 927 | .full_response |
| 928 | .as_ref() |
| 929 | .unwrap() |
| 930 | .lines() |
| 931 | .as_ptr(); |
| 932 | assert_eq!(paint(&mut app, 100, 32), first); |
| 933 | assert_eq!( |
| 934 | app.pet_watch |
| 935 | .full_response |
| 936 | .as_ref() |
| 937 | .unwrap() |
| 938 | .lines() |
| 939 | .as_ptr(), |
| 940 | lines |
| 941 | ); |
| 942 | tick(&mut app, true, Instant::now() + Duration::from_secs(2)); |
| 943 | assert!(app.pet_watch.full_next.is_none()); |
| 944 | tick(&mut app, false, Instant::now() + Duration::from_secs(3)); |
| 945 | assert!(app.pet_watch.full_next.is_none()); |
| 946 | } |
| 947 | #[test] |
| 948 | fn pet_copy_footer_tracks_completed_output_and_only_keeps_fully_painted_hitboxes() { |
| 949 | let mut app = app(); |
| 950 | assert!(!paint(&mut app, 100, 32).contains("copy finished reply")); |
| 951 | assert!(app.pet_watch.copy_area.lock().unwrap().is_none()); |
| 952 | let index = app.history.len(); |
| 953 | app.add_message(HistoryCell::Assistant { |
| 954 | content: "finished answer".into(), |
| 955 | streaming: false, |
| 956 | }); |
| 957 | app.record_completed_assistant_output(index, "finished answer"); |
| 958 | app.add_message(HistoryCell::Assistant { |
| 959 | content: "current partial reply".into(), |
| 960 | streaming: true, |
| 961 | }); |
| 962 | assert!(paint(&mut app, 100, 32).contains("c copy finished reply")); |
| 963 | assert!(app.pet_watch.copy_area.lock().unwrap().is_some()); |
| 964 | paint(&mut app, 16, 8); |
| 965 | assert!( |
| 966 | app.pet_watch.copy_area.lock().unwrap().is_none(), |
| 967 | "truncated labels have no invisible click area" |
| 968 | ); |
| 969 | paint(&mut app, 100, 32); |
| 970 | app.pet_watch.prepare_frame(); |
| 971 | assert!( |
| 972 | app.pet_watch.copy_area.lock().unwrap().is_none(), |
| 973 | "another focus owner clears old targets before painting" |
| 974 | ); |
| 975 | paint(&mut app, 100, 32); |
| 976 | let mut terminal = |
| 977 | ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 32)).unwrap(); |
| 978 | terminal |
| 979 | .draw(|frame| render_main(frame, frame.area(), &mut app)) |
| 980 | .unwrap(); |
| 981 | assert!( |
| 982 | app.pet_watch.copy_area.lock().unwrap().is_none(), |
| 983 | "the composer backdrop does not expose an inspector action" |
| 984 | ); |
| 985 | } |
| 986 | } |
| 987 |