| 1 | //! The whale view of one terminal. Engine events from this terminal's own |
| 2 | //! session are projected here once and drawn locally as the dot whale; no |
| 3 | //! other process takes part. |
| 4 | //! |
| 5 | //! Known limits: hold-still lasts until this terminal closes. The name and |
| 6 | //! colour live in settings.toml beside `pet_mode`; a change another process |
| 7 | //! makes is picked up within two seconds while the whale is kept. |
| 8 | use crate::tui::{app::App, underwater::ShellPhase, views::ModalKind}; |
| 9 | use codewhale_engine::core::events::{Event, TurnOutcomeStatus}; |
| 10 | use ratatui::layout::Rect; |
| 11 | use serde_json::json; |
| 12 | use std::{ |
| 13 | sync::{Arc, Mutex}, |
| 14 | time::{Duration, Instant, SystemTime}, |
| 15 | }; |
| 16 | const IDENTITY_POLL: Duration = Duration::from_secs(2); |
| 17 | type IdentityStamp = Option<(SystemTime, u64)>; |
| 18 | type DiskIdentity = (Option<String>, Option<String>); |
| 19 | mod dots; |
| 20 | mod full; |
| 21 | mod habitat; |
| 22 | pub use full::{render_full, render_main}; |
| 23 | #[derive(Clone, Copy)] |
| 24 | pub enum Control { |
| 25 | Scroll(i16), |
| 26 | FocusAgents, |
| 27 | ScrollEnd(bool), |
| 28 | Mouse(crossterm::event::MouseEvent), |
| 29 | } |
| 30 | #[derive(Default)] |
| 31 | pub struct PetWatch { |
| 32 | session: Option<String>, |
| 33 | active_turn_id: Option<String>, |
| 34 | pub(crate) area: Option<Rect>, |
| 35 | pub(crate) inspect_area: Option<Rect>, |
| 36 | copy_area: Arc<Mutex<Option<Rect>>>, |
| 37 | dots: Option<dots::Dots>, |
| 38 | dots_frame: Option<dots::Frame>, |
| 39 | dots_area: Option<Rect>, |
| 40 | controls: Arc<Mutex<Vec<Control>>>, |
| 41 | /// `/whale`: the whale replaces the ordinary shell backdrop. |
| 42 | pub(crate) enabled: bool, |
| 43 | still: bool, |
| 44 | name: Option<String>, |
| 45 | color: Option<[u8; 3]>, |
| 46 | identity_checked: Option<Instant>, |
| 47 | identity_poll: Arc<Mutex<(IdentityStamp, Option<DiskIdentity>, bool)>>, |
| 48 | work_history_start: usize, |
| 49 | full: codewhale_ratatui::PetModeState, |
| 50 | full_next: Option<Instant>, |
| 51 | full_response: Option<crate::tui::transcript::TranscriptViewCache>, |
| 52 | full_response_key: Option<(u64, usize, bool)>, |
| 53 | full_inputs: Option<codewhale_ratatui::whale_motion::Inputs>, |
| 54 | selection: Arc<Mutex<Option<String>>>, |
| 55 | #[cfg(test)] |
| 56 | detached: bool, |
| 57 | } |
| 58 | impl PetWatch { |
| 59 | pub fn still(&self) -> bool { |
| 60 | self.still |
| 61 | } |
| 62 | pub fn set_still(&mut self, still: bool) { |
| 63 | self.still = still; |
| 64 | } |
| 65 | pub fn name(&self) -> Option<&str> { |
| 66 | self.name.as_deref() |
| 67 | } |
| 68 | pub fn set_name(&mut self, name: Option<String>) { |
| 69 | self.name = name; |
| 70 | self.identity_checked = Some(Instant::now()); |
| 71 | } |
| 72 | pub fn color(&self) -> Option<[u8; 3]> { |
| 73 | self.color |
| 74 | } |
| 75 | pub fn set_color(&mut self, color: Option<&str>) { |
| 76 | self.color = color.and_then(codewhale_command_contract::whale_identity::whale_color_rgb); |
| 77 | self.identity_checked = Some(Instant::now()); |
| 78 | } |
| 79 | pub fn apply_identity(&mut self, name: Option<&str>, color: Option<&str>) { |
| 80 | self.name = name.map(str::to_owned); |
| 81 | self.color = color.and_then(codewhale_command_contract::whale_identity::whale_color_rgb); |
| 82 | } |
| 83 | fn refresh_identity(&mut self, now: Instant) -> bool { |
| 84 | let pending = self |
| 85 | .identity_poll |
| 86 | .lock() |
| 87 | .ok() |
| 88 | .and_then(|mut poll| poll.1.take()); |
| 89 | let applied = pending.is_some_and(|(name, color)| { |
| 90 | let changed = self.name != name |
| 91 | || self.color |
| 92 | != color |
| 93 | .as_deref() |
| 94 | .and_then(codewhale_command_contract::whale_identity::whale_color_rgb); |
| 95 | self.apply_identity(name.as_deref(), color.as_deref()); |
| 96 | changed |
| 97 | }); |
| 98 | let due = self |
| 99 | .identity_checked |
| 100 | .is_none_or(|at| now.saturating_duration_since(at) >= IDENTITY_POLL); |
| 101 | if due && tokio::runtime::Handle::try_current().is_ok() { |
| 102 | self.identity_checked = Some(now); |
| 103 | let poll = Arc::clone(&self.identity_poll); |
| 104 | if poll |
| 105 | .lock() |
| 106 | .is_ok_and(|mut state| !std::mem::replace(&mut state.2, true)) |
| 107 | { |
| 108 | start_identity_read(poll); |
| 109 | } |
| 110 | } |
| 111 | applied |
| 112 | } |
| 113 | fn reset(&mut self, session: Option<String>) { |
| 114 | self.session = session; |
| 115 | self.active_turn_id = None; |
| 116 | if let Some(dots) = &self.dots { |
| 117 | dots.reset(); |
| 118 | } |
| 119 | self.dots_frame = None; |
| 120 | self.work_history_start = 0; |
| 121 | self.full = codewhale_ratatui::PetModeState::default(); |
| 122 | self.full_next = None; |
| 123 | self.full_response = None; |
| 124 | self.full_response_key = None; |
| 125 | self.full_inputs = None; |
| 126 | if let Ok(mut selection) = self.selection.lock() { |
| 127 | *selection = None; |
| 128 | } |
| 129 | } |
| 130 | fn start_dots(&mut self) { |
| 131 | #[cfg(test)] |
| 132 | if self.detached { |
| 133 | return; |
| 134 | } |
| 135 | self.dots = Some(dots::Dots::start()); |
| 136 | } |
| 137 | /// Tests drive the shell without the dot whale's thread. |
| 138 | #[cfg(test)] |
| 139 | pub(crate) fn detach_for_test(&mut self) { |
| 140 | self.dots = None; |
| 141 | self.detached = true; |
| 142 | } |
| 143 | pub fn observe(&mut self, event: &Event, session: Option<&str>) { |
| 144 | if self.session.as_deref() != session { |
| 145 | self.reset(session.map(str::to_owned)); |
| 146 | } |
| 147 | if let Event::TurnStarted { turn_id, .. } = event { |
| 148 | self.active_turn_id = Some(turn_id.clone()); |
| 149 | } |
| 150 | if let Some(text) = metadata(event, self.active_turn_id.as_deref()) |
| 151 | && let Some(dots) = &self.dots |
| 152 | { |
| 153 | dots.observe(text); |
| 154 | } |
| 155 | if matches!(event, Event::TurnComplete { .. }) { |
| 156 | self.active_turn_id = None; |
| 157 | } |
| 158 | } |
| 159 | /// Wake the existing terminal loop for the native stage, even at idle. |
| 160 | /// Hidden and reduced/still stages clear this deadline in `full::tick`. |
| 161 | pub fn next_frame_in(&self, now: Instant) -> Option<Duration> { |
| 162 | self.full_next |
| 163 | .map(|deadline| deadline.saturating_duration_since(now)) |
| 164 | } |
| 165 | pub fn prepare_frame(&mut self) { |
| 166 | self.inspect_area = None; |
| 167 | if let Ok(mut area) = self.copy_area.lock() { |
| 168 | *area = None; |
| 169 | } |
| 170 | } |
| 171 | } |
| 172 | fn start_identity_read(poll: Arc<Mutex<(IdentityStamp, Option<DiskIdentity>, bool)>>) { |
| 173 | codewhale_util::utils::spawn_blocking_supervised("whale-identity", move || { |
| 174 | use codewhale_runtime::settings::Settings; |
| 175 | let stamp = Settings::path() |
| 176 | .ok() |
| 177 | .and_then(|path| std::fs::metadata(path).ok()) |
| 178 | .and_then(|meta| Some((meta.modified().ok()?, meta.len()))); |
| 179 | let seen = poll.lock().map(|state| state.0).unwrap_or(None); |
| 180 | let identity = (stamp != seen) |
| 181 | .then(Settings::load_persisted) |
| 182 | .and_then(Result::ok) |
| 183 | .map(|settings| (settings.whale_name, settings.whale_color)); |
| 184 | if let Ok(mut state) = poll.lock() { |
| 185 | if identity.is_some() { |
| 186 | state.0 = stamp; |
| 187 | state.1 = identity; |
| 188 | } |
| 189 | state.2 = false; |
| 190 | } |
| 191 | }); |
| 192 | } |
| 193 | /// Existing protocol projection defines the variant names. This allowlist |
| 194 | /// removes payloads before the dot whale's bounded queue; no model text escapes. |
| 195 | fn metadata(event: &Event, turn_id: Option<&str>) -> Option<String> { |
| 196 | let mut value = match event { |
| 197 | Event::TurnStarted { turn_id, .. } => json!({"event":"turn_started","turn_id":turn_id}), |
| 198 | Event::TurnComplete { status, .. } => { |
| 199 | let mut value = json!({ |
| 200 | "event":"turn_complete", |
| 201 | "turn_outcome":match status { |
| 202 | TurnOutcomeStatus::Completed => "completed", |
| 203 | TurnOutcomeStatus::Interrupted => "interrupted", |
| 204 | TurnOutcomeStatus::Failed => "failed", |
| 205 | } |
| 206 | }); |
| 207 | // An untracked turn omits the id; the reducer rejects `null`, and |
| 208 | // without an id a completed turn cannot claim Done. |
| 209 | if let Some(turn_id) = turn_id { |
| 210 | value["turn_id"] = json!(turn_id); |
| 211 | } |
| 212 | value |
| 213 | } |
| 214 | Event::MessageStarted { index } => json!({"event":"message_started","index":index}), |
| 215 | Event::MessageDelta { index, .. } => { |
| 216 | json!({"event":"response_delta","index":index,"channel":"text"}) |
| 217 | } |
| 218 | Event::MessageComplete { index } => json!({"event":"message_complete","index":index}), |
| 219 | Event::ThinkingStarted { index } => json!({"event":"thinking_started","index":index}), |
| 220 | Event::ThinkingDelta { index, .. } => { |
| 221 | json!({"event":"response_delta","index":index,"channel":"reasoning"}) |
| 222 | } |
| 223 | Event::ThinkingComplete { index } => json!({"event":"thinking_complete","index":index}), |
| 224 | Event::OperationActivityStarted { |
| 225 | span_id, |
| 226 | activity_kind, |
| 227 | action_id, |
| 228 | } => json!({ |
| 229 | "event":"operation_activity_started", |
| 230 | "span_id":span_id, |
| 231 | "action_id":action_id, |
| 232 | "activity_kind":activity_kind |
| 233 | }), |
| 234 | Event::OperationActivityCompleted { |
| 235 | span_id, |
| 236 | activity_kind, |
| 237 | action_id, |
| 238 | outcome, |
| 239 | } => json!({ |
| 240 | "event":"operation_activity_completed", |
| 241 | "span_id":span_id, |
| 242 | "action_id":action_id, |
| 243 | "activity_kind":activity_kind, |
| 244 | "outcome":outcome |
| 245 | }), |
| 246 | Event::ToolCallHeartbeat => json!({"event":"tool_call_heartbeat"}), |
| 247 | // A denied (by a human or by policy) or cancelled call ends any wait |
| 248 | // on it. Only the Engine call id and typed outcome cross; the tool |
| 249 | // name and error text stay in the transcript. Approvals that run are |
| 250 | // cleared by their operation start and by the shell's typed |
| 251 | // `waiting` flag on every tick. |
| 252 | Event::ToolCallComplete { |
| 253 | id, |
| 254 | result: Err(codewhale_engine::tools::spec::ToolError::PermissionDenied { .. }), |
| 255 | .. |
| 256 | } => json!({ |
| 257 | "event":"approval_resolved","id":id,"outcome":"denied" |
| 258 | }), |
| 259 | Event::ToolCallComplete { |
| 260 | id, |
| 261 | result: Err(codewhale_engine::tools::spec::ToolError::Cancelled { .. }), |
| 262 | .. |
| 263 | } => json!({ |
| 264 | "event":"approval_resolved","id":id,"outcome":"cancelled" |
| 265 | }), |
| 266 | Event::UserInputClosed { id, outcome } => json!({ |
| 267 | "event":"approval_resolved", "id":id, |
| 268 | "outcome":if matches!(outcome, codewhale_engine::core::events::UserInputClosedOutcome::Answered) { "approved" } else { "cancelled" } |
| 269 | }), |
| 270 | Event::AgentSpawned { id, .. } => json!({"event":"agent_spawned","id":id}), |
| 271 | Event::AgentProgress { id, activity, .. } => json!({ |
| 272 | "event":"agent_progress", |
| 273 | "id":id, |
| 274 | "worker_status":codewhale_engine::core::protocol_parity::worker_status_str(activity.worker_status) |
| 275 | }), |
| 276 | Event::AgentComplete { id, .. } => json!({"event":"agent_complete","id":id}), |
| 277 | Event::ApprovalRequired { id, .. } | Event::UserInputRequired { id, .. } => json!({ |
| 278 | "event":if matches!(event, Event::ApprovalRequired { .. }) {"approval_required"} else {"user_input_required"}, |
| 279 | "id":id |
| 280 | }), |
| 281 | _ => return None, |
| 282 | }; |
| 283 | if value |
| 284 | .get("action_id") |
| 285 | .is_some_and(serde_json::Value::is_null) |
| 286 | { |
| 287 | value.as_object_mut()?.remove("action_id"); |
| 288 | } |
| 289 | let json = serde_json::to_string(&value).ok()?; |
| 290 | (json.len() <= 16_384).then_some(json) |
| 291 | } |
| 292 | |
| 293 | pub fn command(app: &mut App, control: Control) -> bool { |
| 294 | let agents = full::agents(app); |
| 295 | let state = &mut app.pet_watch; |
| 296 | match control { |
| 297 | Control::Scroll(delta) => state.full.scroll(&agents, delta), |
| 298 | Control::FocusAgents => state.full.toggle_agents(&agents), |
| 299 | Control::ScrollEnd(end) => state.full.scroll_end(&agents, end), |
| 300 | Control::Mouse(mouse) => { |
| 301 | state.full.handle_mouse(&agents, mouse); |
| 302 | } |
| 303 | } |
| 304 | app.needs_redraw = true; |
| 305 | true |
| 306 | } |
| 307 | pub fn open_habitat(app: &mut App) { |
| 308 | if app.view_stack.top_kind() != Some(ModalKind::PetHabitat) { |
| 309 | app.view_stack.push(habitat::Habitat::new( |
| 310 | app.pet_watch.controls.clone(), |
| 311 | app.pet_watch.selection.clone(), |
| 312 | app.pet_watch.copy_area.clone(), |
| 313 | )); |
| 314 | } |
| 315 | app.needs_redraw = true; |
| 316 | } |
| 317 | /// Explicit tools and focused workers remain available on demand. |
| 318 | pub fn main_view(app: &App) -> bool { |
| 319 | app.pet_watch.enabled |
| 320 | && app.agent_focus.is_none() |
| 321 | && !app.work_surface.focused |
| 322 | && app.file_tree.is_none() |
| 323 | } |
| 324 | pub fn is_open(app: &App) -> bool { |
| 325 | app.view_stack.top_kind() == Some(ModalKind::PetHabitat) |
| 326 | || (main_view(app) && app.view_stack.is_empty()) |
| 327 | } |
| 328 | /// `/whale` selects the shell backdrop without taking composer focus. |
| 329 | /// Drafts, history, selection and the active Engine turn retain their owners. |
| 330 | pub fn set_enabled(app: &mut App, enabled: bool) { |
| 331 | app.pet_watch.enabled = enabled; |
| 332 | if app.view_stack.top_kind() == Some(ModalKind::PetHabitat) { |
| 333 | app.view_stack.pop(); |
| 334 | } |
| 335 | if enabled { |
| 336 | crate::tui::work_surface::release_focus(app); |
| 337 | app.launch.visible = false; |
| 338 | crate::tui::agent_focus::exit_focus(app); |
| 339 | app.file_tree = None; |
| 340 | app.file_tree_visible = false; |
| 341 | } else { |
| 342 | let session = app.pet_watch.session.clone(); |
| 343 | app.pet_watch.reset(session); |
| 344 | app.pet_watch.dots = None; |
| 345 | app.pet_watch.dots_frame = None; |
| 346 | } |
| 347 | app.needs_redraw = true; |
| 348 | } |
| 349 | /// F5 enters the existing modal stack. Printable keys, paste, submit and |
| 350 | /// editing remain with the normal composer on the main view. |
| 351 | pub fn handle_key(app: &mut App, key: &crossterm::event::KeyEvent) -> bool { |
| 352 | use crate::tui::shell_key_routing::{self, ShellBindingId as Id}; |
| 353 | if !app.pet_watch.enabled { |
| 354 | return false; |
| 355 | } |
| 356 | if shell_key_routing::route(app.focus(), key) != Some(Id::PetInspect) { |
| 357 | return false; |
| 358 | } |
| 359 | open_habitat(app); |
| 360 | true |
| 361 | } |
| 362 | /// The existing Engine determines work boundaries. Only the shell reads the |
| 363 | /// answer; no conversation text enters the whale's projection. |
| 364 | pub fn observe(app: &mut App, event: &Event) { |
| 365 | app.pet_watch |
| 366 | .observe(event, app.current_session_id.as_deref()); |
| 367 | if matches!(event, Event::TurnStarted { .. }) { |
| 368 | app.pet_watch.work_history_start = app.history.len(); |
| 369 | app.pet_watch.full.reset_output(); |
| 370 | } else if matches!(event, Event::TurnComplete { .. }) { |
| 371 | app.needs_redraw = true; |
| 372 | } |
| 373 | } |
| 374 | pub fn tick(app: &mut App, now: Instant) { |
| 375 | // Only the visible native backdrop or its inspector advances the stage. |
| 376 | // Other modal owners pause it; the existing composer never becomes a modal. |
| 377 | let visible = !app.redaction_gate |
| 378 | && app.onboarding == crate::tui::app::OnboardingState::None |
| 379 | && is_open(app); |
| 380 | let motion = visible && full::motion(app).animates(); |
| 381 | let waiting = matches!( |
| 382 | ShellPhase::from_app(app), |
| 383 | ShellPhase::Waiting | ShellPhase::Approval |
| 384 | ); |
| 385 | let keep_dots = app.pet_watch.enabled || app.view_stack.contains_kind(ModalKind::PetHabitat); |
| 386 | let controls = app |
| 387 | .pet_watch |
| 388 | .controls |
| 389 | .lock() |
| 390 | .map(|mut c| std::mem::take(&mut *c)) |
| 391 | .unwrap_or_default(); |
| 392 | for control in controls { |
| 393 | command(app, control); |
| 394 | } |
| 395 | let state = &mut app.pet_watch; |
| 396 | if keep_dots && state.refresh_identity(now) { |
| 397 | app.needs_redraw = true; |
| 398 | } |
| 399 | let state = &mut app.pet_watch; |
| 400 | if state.session != app.current_session_id { |
| 401 | state.reset(app.current_session_id.clone()); |
| 402 | } |
| 403 | let want = visible && state.dots_area.is_some(); |
| 404 | if !keep_dots { |
| 405 | state.dots = None; |
| 406 | state.dots_frame = None; |
| 407 | } else if want && state.dots.is_none() { |
| 408 | state.start_dots(); |
| 409 | } |
| 410 | if let Some(dots) = &state.dots { |
| 411 | dots.set_view(want, motion, waiting); |
| 412 | if dots.failed() { |
| 413 | state.dots_frame = None; |
| 414 | } else if let Some(frame) = dots.take() { |
| 415 | state.dots_frame = Some(frame); |
| 416 | if visible { |
| 417 | app.needs_redraw = true; |
| 418 | } |
| 419 | } |
| 420 | } |
| 421 | full::tick(app, visible, now); |
| 422 | } |
| 423 | |
| 424 | #[cfg(test)] |
| 425 | mod tests { |
| 426 | use super::*; |
| 427 | use serde_json::Value; |
| 428 | |
| 429 | fn app() -> App { |
| 430 | let mut app = crate::tui::test_support::test_app_with_options( |
| 431 | crate::tui::test_support::test_tui_options("."), |
| 432 | ); |
| 433 | app.onboarding = crate::tui::app::OnboardingState::None; |
| 434 | app.redaction_gate = false; |
| 435 | app.pet_watch.session = app.current_session_id.clone(); |
| 436 | app.pet_watch.detach_for_test(); |
| 437 | app |
| 438 | } |
| 439 | fn turn_started(turn_id: &str) -> Event { |
| 440 | Event::TurnStarted { |
| 441 | previous_source: None, |
| 442 | turn_id: turn_id.into(), |
| 443 | created_at: chrono::Utc::now(), |
| 444 | route: None, |
| 445 | submission_id: None, |
| 446 | } |
| 447 | } |
| 448 | fn turn_completed() -> Event { |
| 449 | Event::TurnComplete { |
| 450 | source_accounting: false, |
| 451 | |
| 452 | turn_id: None, |
| 453 | submission_id: None, |
| 454 | compaction_id: None, |
| 455 | usage: Default::default(), |
| 456 | parent_route_usage: Default::default(), |
| 457 | routed_usage_dropped_records: 0, |
| 458 | status: TurnOutcomeStatus::Completed, |
| 459 | error: None, |
| 460 | tool_catalog: None, |
| 461 | base_url: None, |
| 462 | } |
| 463 | } |
| 464 | |
| 465 | #[test] |
| 466 | fn work_completion_reveals_existing_answer_and_keeps_the_draft() { |
| 467 | let mut app = app(); |
| 468 | assert!(app.view_stack.is_empty()); |
| 469 | app.input = "retained draft".into(); |
| 470 | app.pet_watch.enabled = true; |
| 471 | observe(&mut app, &turn_started("preview-turn")); |
| 472 | tick(&mut app, Instant::now()); |
| 473 | assert!( |
| 474 | app.view_stack.is_empty(), |
| 475 | "accepted work keeps the composer focused" |
| 476 | ); |
| 477 | assert!(main_view(&app)); |
| 478 | app.add_message(crate::tui::history::HistoryCell::Assistant { |
| 479 | content: "Prepared result stays in the transcript".into(), |
| 480 | streaming: false, |
| 481 | }); |
| 482 | observe(&mut app, &turn_completed()); |
| 483 | let mut terminal = |
| 484 | ratatui::Terminal::new(ratatui::backend::TestBackend::new(100, 40)).unwrap(); |
| 485 | terminal.draw(|frame| render_full(frame, &mut app)).unwrap(); |
| 486 | let text = terminal |
| 487 | .backend() |
| 488 | .buffer() |
| 489 | .content |
| 490 | .iter() |
| 491 | .map(|cell| cell.symbol()) |
| 492 | .collect::<String>(); |
| 493 | assert!(text.contains("Prepared result stays in the transcript")); |
| 494 | assert_eq!(app.input, "retained draft"); |
| 495 | } |
| 496 | |
| 497 | #[test] |
| 498 | fn the_whale_view_draws_from_this_terminal_and_the_inspector_needs_no_other_process() { |
| 499 | let mut app = app(); |
| 500 | set_enabled(&mut app, true); |
| 501 | assert!(is_open(&app)); |
| 502 | assert!(command(&mut app, Control::FocusAgents)); |
| 503 | open_habitat(&mut app); |
| 504 | assert_eq!(app.view_stack.top_kind(), Some(ModalKind::PetHabitat)); |
| 505 | assert!(is_open(&app)); |
| 506 | tick(&mut app, Instant::now()); |
| 507 | assert!( |
| 508 | app.pet_watch.dots.is_none(), |
| 509 | "detached tests start no thread" |
| 510 | ); |
| 511 | set_enabled(&mut app, false); |
| 512 | assert!(app.view_stack.is_empty()); |
| 513 | assert!(!is_open(&app)); |
| 514 | } |
| 515 | |
| 516 | #[test] |
| 517 | fn whale_off_restores_the_shell_and_keeps_the_draft() { |
| 518 | let mut app = app(); |
| 519 | app.input = "kept draft".into(); |
| 520 | app.pet_watch.enabled = true; |
| 521 | observe(&mut app, &turn_started("turn")); |
| 522 | assert!(main_view(&app)); |
| 523 | assert!(app.view_stack.is_empty()); |
| 524 | set_enabled(&mut app, false); |
| 525 | tick(&mut app, Instant::now()); |
| 526 | assert!(!app.pet_watch.enabled); |
| 527 | assert!(app.view_stack.is_empty()); |
| 528 | assert_eq!(app.input, "kept draft"); |
| 529 | assert!(app.pet_watch.dots.is_none()); |
| 530 | } |
| 531 | |
| 532 | #[test] |
| 533 | fn name_colour_and_stillness_survive_a_session_switch() { |
| 534 | let mut watch = PetWatch::default(); |
| 535 | watch.detach_for_test(); |
| 536 | watch.set_name(Some("Moby".into())); |
| 537 | watch.set_color(Some("#0a141e")); |
| 538 | watch.set_still(true); |
| 539 | watch.observe(&turn_started("turn"), Some("another-session")); |
| 540 | assert_eq!(watch.name(), Some("Moby")); |
| 541 | assert_eq!(watch.color(), Some([10, 20, 30])); |
| 542 | assert!(watch.still()); |
| 543 | } |
| 544 | |
| 545 | #[test] |
| 546 | fn session_switch_resets_the_view_and_tracks_the_switching_turn() { |
| 547 | let mut watch = PetWatch::default(); |
| 548 | watch.detach_for_test(); |
| 549 | watch.session = Some("session-a".into()); |
| 550 | watch.active_turn_id = Some("turn-a".into()); |
| 551 | watch.full.output_scroll = 100; |
| 552 | watch.work_history_start = 50; |
| 553 | |
| 554 | watch.observe(&turn_started("turn-b"), Some("session-b")); |
| 555 | assert_eq!(watch.session.as_deref(), Some("session-b")); |
| 556 | // The event that switched sessions is not dropped: its turn is the |
| 557 | // one a later `turn_complete` must carry to claim Done. |
| 558 | assert_eq!(watch.active_turn_id.as_deref(), Some("turn-b")); |
| 559 | assert_eq!(watch.full.output_scroll, 0); |
| 560 | assert_eq!(watch.work_history_start, 0); |
| 561 | |
| 562 | let done = metadata(&turn_completed(), watch.active_turn_id.as_deref()).unwrap(); |
| 563 | assert_eq!( |
| 564 | serde_json::from_str::<Value>(&done).unwrap(), |
| 565 | json!({"event":"turn_complete","turn_id":"turn-b","turn_outcome":"completed"}) |
| 566 | ); |
| 567 | } |
| 568 | |
| 569 | #[test] |
| 570 | fn foreground_projection_forwards_only_typed_owner_metadata() { |
| 571 | let call = metadata( |
| 572 | &Event::ToolCallStarted { |
| 573 | model_call: None, |
| 574 | id: "call-a".into(), |
| 575 | name: "exec_command".into(), |
| 576 | input: json!({"command":"PRIVATE TOOL INPUT"}), |
| 577 | }, |
| 578 | Some("turn-a"), |
| 579 | ); |
| 580 | assert!( |
| 581 | call.is_none(), |
| 582 | "tool names and inputs are not activity facts" |
| 583 | ); |
| 584 | |
| 585 | let thought = metadata( |
| 586 | &Event::ThinkingDelta { |
| 587 | index: 2, |
| 588 | content: "PRIVATE REASONING".into(), |
| 589 | }, |
| 590 | None, |
| 591 | ) |
| 592 | .unwrap(); |
| 593 | assert_eq!( |
| 594 | serde_json::from_str::<Value>(&thought).unwrap(), |
| 595 | json!({"event":"response_delta","index":2,"channel":"reasoning"}) |
| 596 | ); |
| 597 | let message = metadata( |
| 598 | &Event::MessageDelta { |
| 599 | index: 3, |
| 600 | content: "PRIVATE MESSAGE".into(), |
| 601 | }, |
| 602 | None, |
| 603 | ) |
| 604 | .unwrap(); |
| 605 | |
| 606 | let operation = metadata( |
| 607 | &Event::OperationActivityStarted { |
| 608 | span_id: "private-internal-span".into(), |
| 609 | activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind::Computer, |
| 610 | action_id: Some("mcp_computer_use_click".into()), |
| 611 | }, |
| 612 | None, |
| 613 | ) |
| 614 | .unwrap(); |
| 615 | assert_eq!( |
| 616 | serde_json::from_str::<Value>(&operation).unwrap(), |
| 617 | json!({ |
| 618 | "event":"operation_activity_started", |
| 619 | "span_id":"private-internal-span", |
| 620 | "activity_kind":"computer", |
| 621 | "action_id":"mcp_computer_use_click" |
| 622 | }) |
| 623 | ); |
| 624 | let completed = metadata( |
| 625 | &Event::OperationActivityCompleted { |
| 626 | span_id: "private-internal-span".into(), |
| 627 | activity_kind: codewhale_protocol::engine_owner::OwnerActivityKind::Editing, |
| 628 | action_id: Some("edit_file".into()), |
| 629 | outcome: codewhale_protocol::engine_owner::OwnerOperationOutcome::Denied, |
| 630 | }, |
| 631 | None, |
| 632 | ) |
| 633 | .unwrap(); |
| 634 | assert_eq!( |
| 635 | serde_json::from_str::<Value>(&completed).unwrap(), |
| 636 | json!({ |
| 637 | "event":"operation_activity_completed", |
| 638 | "span_id":"private-internal-span", |
| 639 | "activity_kind":"editing", |
| 640 | "action_id":"edit_file", |
| 641 | "outcome":"denied" |
| 642 | }) |
| 643 | ); |
| 644 | |
| 645 | let turn = metadata( |
| 646 | &Event::TurnComplete { |
| 647 | source_accounting: false, |
| 648 | |
| 649 | turn_id: None, |
| 650 | submission_id: None, |
| 651 | compaction_id: None, |
| 652 | usage: Default::default(), |
| 653 | parent_route_usage: Default::default(), |
| 654 | routed_usage_dropped_records: 0, |
| 655 | status: TurnOutcomeStatus::Completed, |
| 656 | error: None, |
| 657 | tool_catalog: None, |
| 658 | base_url: None, |
| 659 | }, |
| 660 | Some("stable-turn-a"), |
| 661 | ) |
| 662 | .unwrap(); |
| 663 | assert_eq!( |
| 664 | serde_json::from_str::<Value>(&turn).unwrap(), |
| 665 | json!({ |
| 666 | "event":"turn_complete", |
| 667 | "turn_id":"stable-turn-a", |
| 668 | "turn_outcome":"completed" |
| 669 | }) |
| 670 | ); |
| 671 | |
| 672 | assert!(!message.contains("PRIVATE")); |
| 673 | assert!(call.is_none()); |
| 674 | assert!(!thought.contains("PRIVATE")); |
| 675 | assert!(!operation.contains("tool_name")); |
| 676 | assert!(!operation.contains("PRIVATE")); |
| 677 | } |
| 678 | |
| 679 | /// The pet's multi-agent count is derived on the JS side from |
| 680 | /// `agent:`-prefixed spans, keyed by the `id` this projection forwards |
| 681 | /// (app-side issue #12). The counting itself is proven in |
| 682 | /// `pet/tests/pet-engine.test.mjs`; the handoff is the half that fails |
| 683 | /// silently — a trimmed allowlist or a dropped id zeroes `parallel` with |
| 684 | /// no error and no log line, and nothing else here covers agent events. |
| 685 | /// Pin the wire shape the JS dispatches on, and keep child text off it. |
| 686 | #[test] |
| 687 | fn agent_events_forward_span_identity_without_child_text() { |
| 688 | use codewhale_engine::core::events::AgentProgressEventMeta; |
| 689 | use codewhale_engine::tools::subagent::{AgentWorkerStatus, SubAgentStatus}; |
| 690 | |
| 691 | let spawned = metadata( |
| 692 | &Event::AgentSpawned { |
| 693 | display_name: None, |
| 694 | owner_session_id: "session-a".into(), |
| 695 | id: "agent-1".into(), |
| 696 | prompt: "PRIVATE CHILD PROMPT".into(), |
| 697 | worker_status: Some(AgentWorkerStatus::Running), |
| 698 | parent_run_id: Some("run-9".into()), |
| 699 | spawn_depth: 2, |
| 700 | model: "PRIVATE CHILD MODEL".into(), |
| 701 | route_source: Some("task.model".into()), |
| 702 | }, |
| 703 | None, |
| 704 | ) |
| 705 | .expect("agent spawns are observed"); |
| 706 | assert_eq!( |
| 707 | serde_json::from_str::<Value>(&spawned).unwrap(), |
| 708 | // A spawn opens the span; the reducer reads no status from it. |
| 709 | json!({"event":"agent_spawned","id":"agent-1"}) |
| 710 | ); |
| 711 | |
| 712 | // The JS finishes a span when progress reports a terminal status. |
| 713 | let progress = metadata( |
| 714 | &Event::AgentProgress { |
| 715 | owner_session_id: "session-a".into(), |
| 716 | id: "agent-1".into(), |
| 717 | status: "PRIVATE PROGRESS TEXT".into(), |
| 718 | activity: AgentProgressEventMeta { |
| 719 | worker_status: AgentWorkerStatus::Completed, |
| 720 | step: Some(3), |
| 721 | tool_name: Some("exec_command".into()), |
| 722 | routine_wait: false, |
| 723 | approval_id: None, |
| 724 | }, |
| 725 | parent_run_id: Some("run-9".into()), |
| 726 | spawn_depth: 2, |
| 727 | }, |
| 728 | None, |
| 729 | ) |
| 730 | .expect("agent progress is observed"); |
| 731 | assert_eq!( |
| 732 | serde_json::from_str::<Value>(&progress).unwrap(), |
| 733 | json!({"event":"agent_progress","id":"agent-1","worker_status":"completed"}) |
| 734 | ); |
| 735 | |
| 736 | let complete = metadata( |
| 737 | &Event::AgentComplete { |
| 738 | limit_kind: None, |
| 739 | display_name: None, |
| 740 | owner_session_id: "session-a".into(), |
| 741 | id: "agent-1".into(), |
| 742 | result: "PRIVATE CHILD RESULT".into(), |
| 743 | outcome: Some(SubAgentStatus::Completed), |
| 744 | parent_run_id: Some("run-9".into()), |
| 745 | spawn_depth: Some(2), |
| 746 | continuable: Some(false), |
| 747 | usage: None, |
| 748 | }, |
| 749 | None, |
| 750 | ) |
| 751 | .expect("agent completions are observed"); |
| 752 | assert_eq!( |
| 753 | serde_json::from_str::<Value>(&complete).unwrap(), |
| 754 | json!({"event":"agent_complete","id":"agent-1"}) |
| 755 | ); |
| 756 | |
| 757 | for (label, payload) in [ |
| 758 | ("spawned", &spawned), |
| 759 | ("progress", &progress), |
| 760 | ("complete", &complete), |
| 761 | ] { |
| 762 | assert!( |
| 763 | !payload.contains("PRIVATE"), |
| 764 | "{label} leaked child text: {payload}" |
| 765 | ); |
| 766 | } |
| 767 | } |
| 768 | } |
| 769 |