| 1 | //! Full viewport ownership uses the existing modal stack. Hidden composer, |
| 2 | //! history, selection and active Engine state are untouched. Escape returns |
| 3 | //! to the whale backdrop and the real composer when the whale view is on. |
| 4 | use super::Control; |
| 5 | use crate::tui::{ |
| 6 | shell_key_routing::{self, Focus, ShellBindingId as Id}, |
| 7 | views::{CommandPaletteAction, ModalKind, ModalView, ViewAction, ViewEvent}, |
| 8 | }; |
| 9 | use crossterm::event::{KeyEvent, MouseButton, MouseEvent, MouseEventKind}; |
| 10 | use ratatui::{ |
| 11 | buffer::Buffer, |
| 12 | layout::{Position, Rect}, |
| 13 | }; |
| 14 | use std::sync::{Arc, Mutex}; |
| 15 | pub struct Habitat { |
| 16 | controls: Arc<Mutex<Vec<Control>>>, |
| 17 | selection: Arc<Mutex<Option<String>>>, |
| 18 | copy_area: Arc<Mutex<Option<Rect>>>, |
| 19 | } |
| 20 | impl Habitat { |
| 21 | pub fn new( |
| 22 | controls: Arc<Mutex<Vec<Control>>>, |
| 23 | selection: Arc<Mutex<Option<String>>>, |
| 24 | copy_area: Arc<Mutex<Option<Rect>>>, |
| 25 | ) -> Self { |
| 26 | Self { |
| 27 | controls, |
| 28 | selection, |
| 29 | copy_area, |
| 30 | } |
| 31 | } |
| 32 | } |
| 33 | fn copy_reply() -> ViewAction { |
| 34 | // Keep completion authority, Markdown, recovery and clipboard acknowledgements |
| 35 | // with /copy. This deliberately copies the last finished reply during a stream. |
| 36 | ViewAction::Emit(ViewEvent::CommandPaletteSelected { |
| 37 | action: CommandPaletteAction::ExecuteCommand { |
| 38 | command: "/copy".into(), |
| 39 | }, |
| 40 | }) |
| 41 | } |
| 42 | impl ModalView for Habitat { |
| 43 | fn kind(&self) -> ModalKind { |
| 44 | ModalKind::PetHabitat |
| 45 | } |
| 46 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 47 | let action = match shell_key_routing::route(Focus::Modal(self.kind()), &key) { |
| 48 | Some(Id::PetResultUp) => Some(Control::Scroll(-1)), |
| 49 | Some(Id::PetResultDown) => Some(Control::Scroll(1)), |
| 50 | Some(Id::PetResultPageUp) => Some(Control::Scroll(-10)), |
| 51 | Some(Id::PetResultPageDown) => Some(Control::Scroll(10)), |
| 52 | Some(Id::PetBack) => return ViewAction::Close, |
| 53 | Some(Id::PetCopyReply) => return copy_reply(), |
| 54 | Some(Id::PetFocusAgents) => Some(Control::FocusAgents), |
| 55 | Some(Id::PetResultStart) => Some(Control::ScrollEnd(false)), |
| 56 | Some(Id::PetResultEnd) => Some(Control::ScrollEnd(true)), |
| 57 | Some(Id::PetOpenAgent) => { |
| 58 | if let Some(agent_id) = self.selection.lock().ok().and_then(|s| s.clone()) { |
| 59 | return ViewAction::EmitAndClose(ViewEvent::OpenAgentTranscript { agent_id }); |
| 60 | } |
| 61 | None |
| 62 | } |
| 63 | _ => None, |
| 64 | }; |
| 65 | if let Some(action) = action |
| 66 | && let Ok(mut queue) = self.controls.lock() |
| 67 | && queue.len() < 16 |
| 68 | { |
| 69 | queue.push(action); |
| 70 | } |
| 71 | ViewAction::None |
| 72 | } |
| 73 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 74 | if mouse.kind == MouseEventKind::Down(MouseButton::Left) |
| 75 | && self |
| 76 | .copy_area |
| 77 | .lock() |
| 78 | .ok() |
| 79 | .and_then(|area| *area) |
| 80 | .is_some_and(|area| area.contains(Position::new(mouse.column, mouse.row))) |
| 81 | { |
| 82 | return copy_reply(); |
| 83 | } |
| 84 | if let Ok(mut queue) = self.controls.lock() |
| 85 | && queue.len() < 16 |
| 86 | { |
| 87 | queue.push(Control::Mouse(mouse)); |
| 88 | } |
| 89 | ViewAction::None |
| 90 | } |
| 91 | fn render(&self, _area: Rect, _buf: &mut Buffer) {} |
| 92 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 93 | self |
| 94 | } |
| 95 | } |
| 96 | #[cfg(test)] |
| 97 | mod tests { |
| 98 | use super::*; |
| 99 | use crossterm::event::{KeyCode, KeyModifiers}; |
| 100 | #[test] |
| 101 | fn enter_opens_only_the_painted_worker_through_the_existing_event_and_closes_pet_focus() { |
| 102 | let controls = Arc::new(Mutex::new(Vec::new())); |
| 103 | let selection = Arc::new(Mutex::new(None)); |
| 104 | let mut view = Habitat::new(controls, selection.clone(), Arc::new(Mutex::new(None))); |
| 105 | let enter = KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE); |
| 106 | assert!(matches!(view.handle_key(enter), ViewAction::None)); |
| 107 | *selection.lock().unwrap() = Some("worker-id".into()); |
| 108 | assert!( |
| 109 | matches!(view.handle_key(enter), ViewAction::EmitAndClose(ViewEvent::OpenAgentTranscript { agent_id }) if agent_id == "worker-id") |
| 110 | ); |
| 111 | } |
| 112 | #[test] |
| 113 | fn pet_habitat_full_view_preserves_composer_history_and_session_on_escape() { |
| 114 | let mut app = crate::tui::test_support::test_app_with_options( |
| 115 | crate::tui::test_support::test_tui_options("."), |
| 116 | ); |
| 117 | app.input = "unfinished composer".into(); |
| 118 | app.add_message(crate::tui::history::HistoryCell::System { |
| 119 | content: "retained transcript".into(), |
| 120 | }); |
| 121 | let history = app.history.len(); |
| 122 | let session = app.current_session_id.clone(); |
| 123 | // Push the actual focus owner without starting a network client. |
| 124 | let controls = Arc::new(Mutex::new(Vec::new())); |
| 125 | app.view_stack.push(Habitat::new( |
| 126 | controls.clone(), |
| 127 | Arc::new(Mutex::new(None)), |
| 128 | Arc::new(Mutex::new(None)), |
| 129 | )); |
| 130 | assert_eq!(app.focus(), Focus::Modal(ModalKind::PetHabitat)); |
| 131 | assert_eq!( |
| 132 | shell_key_routing::route( |
| 133 | Focus::Composer, |
| 134 | &KeyEvent::new(KeyCode::F(5), KeyModifiers::NONE) |
| 135 | ), |
| 136 | Some(Id::PetInspect) |
| 137 | ); |
| 138 | app.view_stack |
| 139 | .handle_key(KeyEvent::new(KeyCode::Tab, KeyModifiers::NONE)); |
| 140 | assert!(matches!( |
| 141 | controls.lock().unwrap().as_slice(), |
| 142 | [Control::FocusAgents] |
| 143 | )); |
| 144 | app.view_stack |
| 145 | .handle_key(KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE)); |
| 146 | app.view_stack |
| 147 | .handle_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE)); |
| 148 | assert!(app.view_stack.is_empty()); |
| 149 | assert_eq!(app.input, "unfinished composer"); |
| 150 | assert_eq!(app.history.len(), history); |
| 151 | assert_eq!(app.current_session_id, session); |
| 152 | } |
| 153 | #[test] |
| 154 | fn pet_copy_keyboard_and_mouse_share_the_finished_reply_receipt_without_closing_or_editing() { |
| 155 | let _env = crate::test_support::lock_test_env(); |
| 156 | let tmp = tempfile::TempDir::new().unwrap(); |
| 157 | let _home = crate::test_support::EnvVarGuard::set("HOME", tmp.path()); |
| 158 | let _state = crate::test_support::EnvVarGuard::set("CODEWHALE_HOME", tmp.path()); |
| 159 | let mut app = crate::tui::test_support::test_app_with_options( |
| 160 | crate::tui::test_support::test_tui_options("."), |
| 161 | ); |
| 162 | app.clipboard = crate::tui::clipboard::ClipboardHandler::for_test(false, false); |
| 163 | app.input = "unfinished draft".into(); |
| 164 | let answer = "Finished **Markdown**\n```rust\nlet x = 1;\n```"; |
| 165 | let index = app.history.len(); |
| 166 | app.add_message(crate::tui::history::HistoryCell::Assistant { |
| 167 | content: answer.into(), |
| 168 | streaming: false, |
| 169 | }); |
| 170 | app.record_completed_assistant_output(index, answer); |
| 171 | app.add_message(crate::tui::history::HistoryCell::Assistant { |
| 172 | content: "partial new answer".into(), |
| 173 | streaming: true, |
| 174 | }); |
| 175 | let copy_area = Arc::new(Mutex::new(Some(Rect::new(2, 8, 24, 1)))); |
| 176 | let mut view = Habitat::new( |
| 177 | Arc::new(Mutex::new(Vec::new())), |
| 178 | Arc::new(Mutex::new(None)), |
| 179 | copy_area.clone(), |
| 180 | ); |
| 181 | let key = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::NONE); |
| 182 | assert_eq!(shell_key_routing::route(Focus::Composer, &key), None); |
| 183 | let actions = [ |
| 184 | view.handle_key(key), |
| 185 | view.handle_mouse(MouseEvent { |
| 186 | kind: MouseEventKind::Down(MouseButton::Left), |
| 187 | column: 3, |
| 188 | row: 8, |
| 189 | modifiers: KeyModifiers::NONE, |
| 190 | }), |
| 191 | ]; |
| 192 | for action in actions { |
| 193 | let ViewAction::Emit(ViewEvent::CommandPaletteSelected { |
| 194 | action: CommandPaletteAction::ExecuteCommand { command }, |
| 195 | }) = action |
| 196 | else { |
| 197 | panic!("copy must emit without closing the inspector") |
| 198 | }; |
| 199 | assert_eq!(command, "/copy"); |
| 200 | let result = crate::commands::execute(&command, &mut app); |
| 201 | assert!(!result.is_error, "{:?}", result.message); |
| 202 | let toast = app |
| 203 | .active_status_toast(crate::tui::underwater::ShellPhase::Done) |
| 204 | .expect("manual copy feedback must survive the completed phase"); |
| 205 | assert_eq!(toast.text, result.message.unwrap()); |
| 206 | assert_eq!(toast.level, crate::tui::app::StatusToastLevel::Info); |
| 207 | assert_eq!(toast.ttl_ms, Some(8_000)); |
| 208 | assert_eq!( |
| 209 | std::fs::read_to_string(tmp.path().join("exports/last-copy.md")).unwrap(), |
| 210 | answer |
| 211 | ); |
| 212 | assert_eq!(app.input, "unfinished draft"); |
| 213 | } |
| 214 | *copy_area.lock().unwrap() = None; |
| 215 | assert!( |
| 216 | matches!( |
| 217 | view.handle_mouse(MouseEvent { |
| 218 | kind: MouseEventKind::Down(MouseButton::Left), |
| 219 | column: 3, |
| 220 | row: 8, |
| 221 | modifiers: KeyModifiers::NONE |
| 222 | }), |
| 223 | ViewAction::None |
| 224 | ), |
| 225 | "hidden copy targets must not remain active" |
| 226 | ); |
| 227 | } |
| 228 | } |
| 229 |