| 1 | //! `/mode` picker: the conversation's mode first, then permissions. |
| 2 | |
| 3 | use std::cell::RefCell; |
| 4 | |
| 5 | use crossterm::event::{KeyCode, KeyEvent, MouseButton, MouseEvent, MouseEventKind}; |
| 6 | use ratatui::{ |
| 7 | buffer::Buffer, |
| 8 | layout::Rect, |
| 9 | style::{Modifier, Style}, |
| 10 | text::{Line, Span}, |
| 11 | widgets::{Padding, Paragraph, Widget}, |
| 12 | }; |
| 13 | use unicode_width::UnicodeWidthStr; |
| 14 | |
| 15 | use crate::tui::app::{App, AppModeUi}; |
| 16 | use crate::tui::conversation_mode as modes; |
| 17 | use crate::tui::views::{ |
| 18 | ActionHint, ModalKind, ModalView, SurfaceFrame, ViewAction, ViewEvent, centered_modal_area, |
| 19 | render_modal_footer, render_rounded_modal, |
| 20 | }; |
| 21 | use codewhale_config::AppMode; |
| 22 | use codewhale_engine::conversation_modes::ConversationModeTable; |
| 23 | use codewhale_localization::{Locale, MessageId, tr}; |
| 24 | use codewhale_palette as palette; |
| 25 | use codewhale_runtime::config::Config; |
| 26 | use codewhale_tui_kit::menu_style; |
| 27 | |
| 28 | const VISIBLE_MODES: [AppMode; 2] = [AppMode::Agent, AppMode::Plan]; |
| 29 | |
| 30 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 31 | struct ConversationRow { |
| 32 | id: String, |
| 33 | name: String, |
| 34 | description: String, |
| 35 | unavailable: Option<String>, |
| 36 | current: bool, |
| 37 | } |
| 38 | |
| 39 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 40 | enum Entry { |
| 41 | Conversation(usize), |
| 42 | Permission(AppMode), |
| 43 | } |
| 44 | |
| 45 | pub struct ModePickerView { |
| 46 | cursor: usize, |
| 47 | current_mode: AppMode, |
| 48 | locale: Locale, |
| 49 | rows: Vec<ConversationRow>, |
| 50 | locked: bool, |
| 51 | other_command: String, |
| 52 | row_hitboxes: RefCell<Vec<Rect>>, |
| 53 | } |
| 54 | |
| 55 | impl ModePickerView { |
| 56 | pub async fn for_app(app: &App, config: &Config) -> Self { |
| 57 | let table = modes::current_table(config).await; |
| 58 | Self::from_table( |
| 59 | app.mode, |
| 60 | app.ui_locale, |
| 61 | &table, |
| 62 | app.conversation_mode.as_deref(), |
| 63 | app.conversation_mode_locked(), |
| 64 | ) |
| 65 | } |
| 66 | |
| 67 | #[must_use] |
| 68 | pub fn from_table( |
| 69 | current: AppMode, |
| 70 | locale: Locale, |
| 71 | table: &ConversationModeTable, |
| 72 | conversation: Option<&str>, |
| 73 | locked: bool, |
| 74 | ) -> Self { |
| 75 | let current_id = codewhale_engine::conversation_modes::effective_id(conversation); |
| 76 | let rows = table |
| 77 | .modes |
| 78 | .iter() |
| 79 | .map(|mode| ConversationRow { |
| 80 | id: mode.id.clone(), |
| 81 | name: modes::display_name(locale, mode), |
| 82 | description: modes::display_description(locale, mode), |
| 83 | unavailable: (!mode.available) |
| 84 | .then(|| modes::display_reason(locale, mode.reason.as_deref())), |
| 85 | current: mode.id == current_id, |
| 86 | }) |
| 87 | .collect(); |
| 88 | let other_command = modes::new_command( |
| 89 | table |
| 90 | .modes |
| 91 | .iter() |
| 92 | .find(|mode| mode.id != current_id) |
| 93 | .map_or(codewhale_engine::conversation_modes::STANDARD, |mode| { |
| 94 | mode.id.as_str() |
| 95 | }), |
| 96 | ); |
| 97 | let mut view = Self { |
| 98 | cursor: 0, |
| 99 | current_mode: current, |
| 100 | locale, |
| 101 | rows, |
| 102 | locked, |
| 103 | other_command, |
| 104 | row_hitboxes: RefCell::new(Vec::new()), |
| 105 | }; |
| 106 | view.cursor = view |
| 107 | .entries() |
| 108 | .iter() |
| 109 | .position(|entry| *entry == Entry::Permission(current)) |
| 110 | .unwrap_or(0); |
| 111 | view |
| 112 | } |
| 113 | |
| 114 | fn entries(&self) -> Vec<Entry> { |
| 115 | let mut entries = Vec::new(); |
| 116 | if !self.locked { |
| 117 | entries.extend( |
| 118 | self.rows |
| 119 | .iter() |
| 120 | .enumerate() |
| 121 | .filter(|(_, row)| row.unavailable.is_none()) |
| 122 | .map(|(index, _)| Entry::Conversation(index)), |
| 123 | ); |
| 124 | } |
| 125 | entries.extend(VISIBLE_MODES.iter().copied().map(Entry::Permission)); |
| 126 | entries |
| 127 | } |
| 128 | |
| 129 | fn selected(&self) -> Option<Entry> { |
| 130 | self.entries().get(self.cursor).copied() |
| 131 | } |
| 132 | |
| 133 | fn event_for(&self, entry: Entry) -> ViewEvent { |
| 134 | match entry { |
| 135 | Entry::Conversation(index) => ViewEvent::ConversationModeSelected { |
| 136 | id: self.rows[index].id.clone(), |
| 137 | }, |
| 138 | Entry::Permission(mode) => ViewEvent::ModeSelected { mode }, |
| 139 | } |
| 140 | } |
| 141 | |
| 142 | fn apply_motion(&mut self, motion: codewhale_tui_kit::list_nav::Motion) -> bool { |
| 143 | let len = self.entries().len(); |
| 144 | let Some(next) = codewhale_tui_kit::list_nav::apply(self.cursor, len, len, motion) else { |
| 145 | return false; |
| 146 | }; |
| 147 | self.cursor = next; |
| 148 | true |
| 149 | } |
| 150 | |
| 151 | fn select_by_number(&mut self, number: char) -> Option<ViewAction> { |
| 152 | let entries = self.entries(); |
| 153 | let idx = entries.iter().position( |
| 154 | |entry| matches!(entry, Entry::Permission(mode) if mode.number() == number), |
| 155 | )?; |
| 156 | self.cursor = idx; |
| 157 | Some(ViewAction::EmitAndClose(self.event_for(entries[idx]))) |
| 158 | } |
| 159 | |
| 160 | fn line_count(&self) -> u16 { |
| 161 | let rows = u16::try_from(self.rows.len()).unwrap_or(u16::MAX); |
| 162 | let conversation = if self.rows.is_empty() { |
| 163 | 0 |
| 164 | } else { |
| 165 | 2 + rows + u16::from(self.locked) |
| 166 | }; |
| 167 | conversation + 1 + u16::try_from(VISIBLE_MODES.len()).unwrap_or(2) |
| 168 | } |
| 169 | } |
| 170 | |
| 171 | impl ModalView for ModePickerView { |
| 172 | fn kind(&self) -> ModalKind { |
| 173 | ModalKind::ModePicker |
| 174 | } |
| 175 | |
| 176 | fn as_any_mut(&mut self) -> &mut dyn std::any::Any { |
| 177 | self |
| 178 | } |
| 179 | |
| 180 | fn handle_key(&mut self, key: KeyEvent) -> ViewAction { |
| 181 | if let Some(motion) = codewhale_tui_kit::list_nav::motion(&key) |
| 182 | && self.apply_motion(motion) |
| 183 | { |
| 184 | return ViewAction::None; |
| 185 | } |
| 186 | match key.code { |
| 187 | KeyCode::Esc => ViewAction::Close, |
| 188 | KeyCode::Enter => match self.selected() { |
| 189 | Some(entry) => ViewAction::EmitAndClose(self.event_for(entry)), |
| 190 | None => ViewAction::None, |
| 191 | }, |
| 192 | KeyCode::Char(number) => self.select_by_number(number).unwrap_or(ViewAction::None), |
| 193 | _ => ViewAction::None, |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | fn handle_mouse(&mut self, mouse: MouseEvent) -> ViewAction { |
| 198 | match mouse.kind { |
| 199 | MouseEventKind::ScrollUp => { |
| 200 | self.apply_motion(codewhale_tui_kit::list_nav::Motion::Prev); |
| 201 | ViewAction::None |
| 202 | } |
| 203 | MouseEventKind::ScrollDown => { |
| 204 | self.apply_motion(codewhale_tui_kit::list_nav::Motion::Next); |
| 205 | ViewAction::None |
| 206 | } |
| 207 | MouseEventKind::Down(MouseButton::Left) => { |
| 208 | let clicked = self.row_hitboxes.borrow().iter().position(|rect| { |
| 209 | rect.contains(ratatui::layout::Position::new(mouse.column, mouse.row)) |
| 210 | }); |
| 211 | if let Some(index) = clicked { |
| 212 | self.cursor = index; |
| 213 | return self.handle_key(KeyEvent::new(KeyCode::Enter, mouse.modifiers)); |
| 214 | } |
| 215 | ViewAction::None |
| 216 | } |
| 217 | _ => ViewAction::None, |
| 218 | } |
| 219 | } |
| 220 | |
| 221 | fn render(&self, area: Rect, buf: &mut Buffer) { |
| 222 | let popup_height = self.line_count() + 7; |
| 223 | let popup_area = centered_modal_area(area, 68, popup_height, 44, 8); |
| 224 | |
| 225 | let (inner, _) = render_rounded_modal( |
| 226 | area, |
| 227 | popup_area, |
| 228 | buf, |
| 229 | SurfaceFrame::new(tr(self.locale, MessageId::ConversationModePickerTitle)) |
| 230 | .padding(Padding::uniform(1)), |
| 231 | ); |
| 232 | |
| 233 | let content = render_modal_footer( |
| 234 | inner, |
| 235 | buf, |
| 236 | &[ |
| 237 | ActionHint::new("↑/↓", "move"), |
| 238 | ActionHint::new("Enter", "select"), |
| 239 | ActionHint::new("Esc", "cancel"), |
| 240 | ], |
| 241 | ); |
| 242 | |
| 243 | self.row_hitboxes.borrow_mut().clear(); |
| 244 | |
| 245 | let entries = self.entries(); |
| 246 | let heading_style = Style::default() |
| 247 | .fg(palette::TEXT_MUTED) |
| 248 | .add_modifier(Modifier::BOLD); |
| 249 | let muted = Style::default().fg(palette::TEXT_MUTED); |
| 250 | let width = usize::from(content.width); |
| 251 | let mut lines: Vec<Line<'static>> = Vec::new(); |
| 252 | let mut row_line_indices: Vec<usize> = Vec::new(); |
| 253 | let mut selected_line_idx: Option<usize> = None; |
| 254 | |
| 255 | let mut push_row = |lines: &mut Vec<Line<'static>>, |
| 256 | entry: Option<Entry>, |
| 257 | pointer: String, |
| 258 | is_active: bool, |
| 259 | label: String, |
| 260 | text: String, |
| 261 | disabled: bool| { |
| 262 | let cursor_here = entry.is_some_and(|entry| entries.get(self.cursor) == Some(&entry)); |
| 263 | let row_style = if cursor_here { |
| 264 | menu_style::selected_row_style() |
| 265 | } else if disabled { |
| 266 | muted |
| 267 | } else { |
| 268 | Style::default().fg(palette::TEXT_PRIMARY) |
| 269 | }; |
| 270 | let active_style = if cursor_here { |
| 271 | menu_style::selected_row_style() |
| 272 | } else if is_active { |
| 273 | Style::default().fg(palette::STATUS_SUCCESS) |
| 274 | } else { |
| 275 | row_style |
| 276 | }; |
| 277 | let hint_style = if cursor_here { |
| 278 | menu_style::selected_row_bg_style().fg(palette::SELECTION_TEXT) |
| 279 | } else { |
| 280 | muted |
| 281 | }; |
| 282 | let check = if is_active { |
| 283 | codewhale_tui_kit::glyphs::CURRENT |
| 284 | } else { |
| 285 | " " |
| 286 | }; |
| 287 | let lead = format!("{pointer} "); |
| 288 | let body = format!(" {label}"); |
| 289 | let prefix_width = UnicodeWidthStr::width(lead.as_str()) |
| 290 | + UnicodeWidthStr::width(check) |
| 291 | + UnicodeWidthStr::width(body.as_str()); |
| 292 | let room = width.saturating_sub(prefix_width); |
| 293 | let text = codewhale_tui_kit::ui_text::semantic_truncate(&text, room); |
| 294 | let line_idx = lines.len(); |
| 295 | if entry.is_some() { |
| 296 | row_line_indices.push(line_idx); |
| 297 | } |
| 298 | if cursor_here { |
| 299 | selected_line_idx = Some(line_idx); |
| 300 | } |
| 301 | lines.push(Line::from(vec![ |
| 302 | Span::styled(lead, row_style), |
| 303 | Span::styled(check.to_string(), active_style), |
| 304 | Span::styled(body, row_style), |
| 305 | Span::styled(text, hint_style), |
| 306 | ])); |
| 307 | }; |
| 308 | |
| 309 | if !self.rows.is_empty() { |
| 310 | lines.push(Line::from(Span::styled( |
| 311 | tr(self.locale, MessageId::ConversationModeGroupConversation).into_owned(), |
| 312 | heading_style, |
| 313 | ))); |
| 314 | if self.locked { |
| 315 | lines.push(Line::from(Span::styled( |
| 316 | codewhale_tui_kit::ui_text::semantic_truncate( |
| 317 | tr(self.locale, MessageId::ConversationModeLockedNote) |
| 318 | .replace("{command}", &self.other_command) |
| 319 | .as_str(), |
| 320 | width, |
| 321 | ), |
| 322 | muted, |
| 323 | ))); |
| 324 | } |
| 325 | for (index, row) in self.rows.iter().enumerate() { |
| 326 | let selectable = !self.locked && row.unavailable.is_none(); |
| 327 | let entry = selectable.then_some(Entry::Conversation(index)); |
| 328 | let cursor_here = |
| 329 | entry.is_some_and(|entry| entries.get(self.cursor) == Some(&entry)); |
| 330 | let pointer = if cursor_here { |
| 331 | codewhale_tui_kit::glyphs::selection_marker(true).to_string() |
| 332 | } else { |
| 333 | " ".to_string() |
| 334 | }; |
| 335 | let pad = |
| 336 | " ".repeat(16usize.saturating_sub(UnicodeWidthStr::width(row.name.as_str()))); |
| 337 | let label = format!("{}{pad}", row.name); |
| 338 | let text = row |
| 339 | .unavailable |
| 340 | .clone() |
| 341 | .unwrap_or_else(|| row.description.clone()); |
| 342 | push_row( |
| 343 | &mut lines, |
| 344 | entry, |
| 345 | pointer, |
| 346 | row.current, |
| 347 | label, |
| 348 | text, |
| 349 | row.unavailable.is_some() || self.locked, |
| 350 | ); |
| 351 | } |
| 352 | lines.push(Line::default()); |
| 353 | } |
| 354 | lines.push(Line::from(Span::styled( |
| 355 | tr(self.locale, MessageId::ConversationModeGroupPermissions).into_owned(), |
| 356 | heading_style, |
| 357 | ))); |
| 358 | for mode in VISIBLE_MODES { |
| 359 | let entry = Entry::Permission(mode); |
| 360 | let cursor_here = entries.get(self.cursor) == Some(&entry); |
| 361 | let pointer = codewhale_tui_kit::glyphs::selection_marker(cursor_here).to_string(); |
| 362 | let name = mode.display_name_localized(self.locale); |
| 363 | let hint = mode.picker_hint_localized(self.locale); |
| 364 | let pad = " ".repeat(8usize.saturating_sub(UnicodeWidthStr::width(&*name))); |
| 365 | let label = format!("{}. {name}{pad}", mode.number()); |
| 366 | push_row( |
| 367 | &mut lines, |
| 368 | Some(entry), |
| 369 | pointer, |
| 370 | mode == self.current_mode, |
| 371 | label, |
| 372 | hint.into_owned(), |
| 373 | false, |
| 374 | ); |
| 375 | } |
| 376 | |
| 377 | let visible_height = usize::from(content.height).max(1); |
| 378 | let max_scroll = lines.len().saturating_sub(visible_height); |
| 379 | let scroll = selected_line_idx.map_or(0, |idx| { |
| 380 | idx.saturating_add(1) |
| 381 | .saturating_sub(visible_height) |
| 382 | .min(max_scroll) |
| 383 | }); |
| 384 | let mut hitboxes = self.row_hitboxes.borrow_mut(); |
| 385 | for line_idx in row_line_indices { |
| 386 | if line_idx >= scroll && line_idx < scroll.saturating_add(visible_height) { |
| 387 | let y = content |
| 388 | .y |
| 389 | .saturating_add(u16::try_from(line_idx - scroll).unwrap_or(u16::MAX)); |
| 390 | hitboxes.push(Rect::new(content.x, y, content.width, 1)); |
| 391 | } else { |
| 392 | hitboxes.push(Rect::ZERO); |
| 393 | } |
| 394 | } |
| 395 | drop(hitboxes); |
| 396 | |
| 397 | if let Some(idx) = selected_line_idx |
| 398 | && idx >= scroll |
| 399 | && idx < scroll.saturating_add(visible_height) |
| 400 | { |
| 401 | let y = content |
| 402 | .y |
| 403 | .saturating_add(u16::try_from(idx - scroll).unwrap_or(u16::MAX)); |
| 404 | if y < content.bottom() { |
| 405 | buf.set_style( |
| 406 | Rect::new(content.x, y, content.width, 1), |
| 407 | menu_style::selected_row_bg_style(), |
| 408 | ); |
| 409 | } |
| 410 | } |
| 411 | Paragraph::new(lines) |
| 412 | .scroll((u16::try_from(scroll).unwrap_or(u16::MAX), 0)) |
| 413 | .render(content, buf); |
| 414 | } |
| 415 | } |
| 416 | |
| 417 | #[cfg(test)] |
| 418 | mod tests { |
| 419 | use super::*; |
| 420 | use codewhale_engine::conversation_modes::{ |
| 421 | self, CREATOR_KEY_OFF_REASON, CreatorAvailabilityGuard, |
| 422 | }; |
| 423 | use crossterm::event::KeyModifiers; |
| 424 | use ratatui::{Terminal, backend::TestBackend}; |
| 425 | |
| 426 | fn picker(current: AppMode, conversation: Option<&str>, locked: bool) -> ModePickerView { |
| 427 | ModePickerView::from_table( |
| 428 | current, |
| 429 | Locale::En, |
| 430 | &conversation_modes::table(Some(CREATOR_KEY_OFF_REASON.to_string())), |
| 431 | conversation, |
| 432 | locked, |
| 433 | ) |
| 434 | } |
| 435 | |
| 436 | #[test] |
| 437 | fn opens_on_current_mode() { |
| 438 | let view = picker(AppMode::Plan, None, false); |
| 439 | assert_eq!(view.selected(), Some(Entry::Permission(AppMode::Plan))); |
| 440 | } |
| 441 | |
| 442 | #[test] |
| 443 | fn enter_emits_selected_mode() { |
| 444 | let mut view = picker(AppMode::Agent, None, false); |
| 445 | view.handle_key(KeyEvent::new(KeyCode::Down, KeyModifiers::NONE)); |
| 446 | let action = view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); |
| 447 | match action { |
| 448 | ViewAction::EmitAndClose(ViewEvent::ModeSelected { mode }) => { |
| 449 | assert_eq!(mode, AppMode::Plan); |
| 450 | } |
| 451 | other => panic!("expected ModeSelected, got {other:?}"), |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | const BLOCKER_SIZES: [(u16, u16); 4] = [(80, 24), (100, 30), (120, 32), (160, 40)]; |
| 456 | |
| 457 | fn render_view(view: ModePickerView, width: u16, height: u16) -> (Buffer, Rect) { |
| 458 | use crate::tui::views::ViewStack; |
| 459 | let area = Rect::new(0, 0, width, height); |
| 460 | let mut buf = Buffer::empty(area); |
| 461 | for y in 0..height { |
| 462 | for x in 0..width { |
| 463 | buf[(x, y)].set_symbol("X"); |
| 464 | } |
| 465 | } |
| 466 | let mut stack = ViewStack::new(); |
| 467 | stack.push(view); |
| 468 | stack.render(area, &mut buf); |
| 469 | (buf, area) |
| 470 | } |
| 471 | |
| 472 | fn render_at(width: u16, height: u16) -> (Buffer, Rect) { |
| 473 | render_view(picker(AppMode::Agent, None, false), width, height) |
| 474 | } |
| 475 | |
| 476 | fn rows(buf: &Buffer, area: Rect) -> Vec<String> { |
| 477 | (0..area.height) |
| 478 | .map(|y| { |
| 479 | (0..area.width) |
| 480 | .map(|x| buf[(x, y)].symbol().to_string()) |
| 481 | .collect::<String>() |
| 482 | }) |
| 483 | .collect() |
| 484 | } |
| 485 | |
| 486 | fn frame_text(buf: &Buffer, area: Rect) -> String { |
| 487 | rows(buf, area) |
| 488 | .iter() |
| 489 | .map(|row| row.trim_end().to_string()) |
| 490 | .filter(|row| !row.is_empty()) |
| 491 | .collect::<Vec<_>>() |
| 492 | .join("\n") |
| 493 | } |
| 494 | |
| 495 | #[test] |
| 496 | fn mode_picker_is_usable_and_opaque_at_blocker_sizes() { |
| 497 | for (w, h) in BLOCKER_SIZES { |
| 498 | for view in [ |
| 499 | picker(AppMode::Agent, None, false), |
| 500 | picker(AppMode::Plan, Some("creator"), true), |
| 501 | ] { |
| 502 | let (buf, area) = render_view(view, w, h); |
| 503 | let text = rows(&buf, area).join("\n"); |
| 504 | |
| 505 | assert!(text.contains("move"), "{w}x{h}: missing 'move' hint"); |
| 506 | assert!(text.contains("select"), "{w}x{h}: missing 'select' hint"); |
| 507 | assert!(text.contains("cancel"), "{w}x{h}: missing 'cancel' hint"); |
| 508 | assert!( |
| 509 | text.contains("Conversation mode") && text.contains("Permissions"), |
| 510 | "{w}x{h}: both groups are labelled" |
| 511 | ); |
| 512 | assert!( |
| 513 | text.contains(codewhale_tui_kit::glyphs::SELECTION), |
| 514 | "{w}x{h}: missing charter selection pointer" |
| 515 | ); |
| 516 | assert!( |
| 517 | !text.contains('X'), |
| 518 | "{w}x{h}: background bleed-through into modal surface" |
| 519 | ); |
| 520 | let lines = rows(&buf, area); |
| 521 | let heading_row = lines |
| 522 | .iter() |
| 523 | .position(|row| row.contains("Conversation mode")) |
| 524 | .expect("heading row"); |
| 525 | let heading_byte = lines[heading_row] |
| 526 | .find("Conversation mode") |
| 527 | .expect("heading column"); |
| 528 | let heading_x = lines[heading_row][..heading_byte].chars().count(); |
| 529 | let padding = &buf[( |
| 530 | u16::try_from(heading_x + "Conversation mode".len() + 3).unwrap(), |
| 531 | u16::try_from(heading_row).unwrap(), |
| 532 | )]; |
| 533 | assert_eq!( |
| 534 | padding.bg, |
| 535 | palette::WHALE_BG, |
| 536 | "{w}x{h}: modal interior must be opaque" |
| 537 | ); |
| 538 | for (y, row) in rows(&buf, area).iter().enumerate() { |
| 539 | assert!( |
| 540 | UnicodeWidthStr::width(row.trim_end()) <= w as usize, |
| 541 | "{w}x{h}: row {y} overflows width: {row:?}" |
| 542 | ); |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | |
| 548 | #[test] |
| 549 | fn operate_is_not_advertised_as_a_visible_mode() { |
| 550 | let (buf, area) = render_at(80, 24); |
| 551 | let text = rows(&buf, area).join("\n"); |
| 552 | assert!(!text.contains("Operate"), "{text}"); |
| 553 | } |
| 554 | |
| 555 | #[test] |
| 556 | fn number_keys_select_modes() { |
| 557 | let mut view = picker(AppMode::Agent, None, false); |
| 558 | let action = view.handle_key(KeyEvent::new(KeyCode::Char('2'), KeyModifiers::NONE)); |
| 559 | assert!(matches!( |
| 560 | action, |
| 561 | ViewAction::EmitAndClose(ViewEvent::ModeSelected { |
| 562 | mode: AppMode::Plan |
| 563 | }) |
| 564 | )); |
| 565 | |
| 566 | for key in ['3', '4', '5'] { |
| 567 | let mut view = picker(AppMode::Agent, None, false); |
| 568 | let action = view.handle_key(KeyEvent::new(KeyCode::Char(key), KeyModifiers::NONE)); |
| 569 | assert!(matches!(action, ViewAction::None), "{key}"); |
| 570 | } |
| 571 | } |
| 572 | |
| 573 | #[test] |
| 574 | fn mouse_click_renders_and_selects_mode_row() { |
| 575 | let mut view = picker(AppMode::Agent, None, false); |
| 576 | let mut terminal = Terminal::new(TestBackend::new(100, 30)).expect("test terminal"); |
| 577 | terminal |
| 578 | .draw(|frame| view.render(frame.area(), frame.buffer_mut())) |
| 579 | .expect("render mode picker"); |
| 580 | let rect = view.row_hitboxes.borrow()[2]; |
| 581 | let action = view.handle_mouse(MouseEvent { |
| 582 | kind: MouseEventKind::Down(MouseButton::Left), |
| 583 | column: rect.x, |
| 584 | row: rect.y, |
| 585 | modifiers: KeyModifiers::NONE, |
| 586 | }); |
| 587 | assert!(matches!( |
| 588 | action, |
| 589 | ViewAction::EmitAndClose(ViewEvent::ModeSelected { |
| 590 | mode: AppMode::Plan |
| 591 | }) |
| 592 | )); |
| 593 | } |
| 594 | |
| 595 | #[tokio::test] |
| 596 | #[allow(clippy::await_holding_lock)] |
| 597 | async fn mode_picker_lists_conversation_modes_first_and_locks_after_first_message() { |
| 598 | let _available = CreatorAvailabilityGuard::set(None); |
| 599 | let table = conversation_modes::current_table(Default::default(), true).await; |
| 600 | for (w, h) in [(80, 24), (120, 32)] { |
| 601 | let open = ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, false); |
| 602 | let (buf, area) = render_view(open, w, h); |
| 603 | let text = frame_text(&buf, area); |
| 604 | let order = |needle: &str| { |
| 605 | text.find(needle) |
| 606 | .unwrap_or_else(|| panic!("{needle}: {text}")) |
| 607 | }; |
| 608 | assert!(order("Conversation mode") < order("Standard mode")); |
| 609 | assert!(order("Standard mode") < order("Creator mode")); |
| 610 | assert!(order("Creator mode") < order("Permissions")); |
| 611 | assert!(order("Permissions") < order("1. Work")); |
| 612 | assert!(!text.contains("Fixed after the first message")); |
| 613 | |
| 614 | let mut open = |
| 615 | ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, false); |
| 616 | open.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); |
| 617 | open.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); |
| 618 | assert!(matches!( |
| 619 | open.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 620 | ViewAction::EmitAndClose(ViewEvent::ConversationModeSelected { ref id }) if id == "standard" |
| 621 | )); |
| 622 | |
| 623 | let locked_standard = |
| 624 | ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, true); |
| 625 | let (buf, area) = render_view(locked_standard, w, h); |
| 626 | let text = frame_text(&buf, area); |
| 627 | assert!( |
| 628 | text.contains("Fixed after the first message. Start another with /new creator."), |
| 629 | "{text}" |
| 630 | ); |
| 631 | assert!(text.contains("Standard mode"), "{text}"); |
| 632 | |
| 633 | let locked = ModePickerView::from_table( |
| 634 | AppMode::Agent, |
| 635 | Locale::En, |
| 636 | &table, |
| 637 | Some("creator"), |
| 638 | true, |
| 639 | ); |
| 640 | let (buf, area) = render_view(locked, w, h); |
| 641 | let text = frame_text(&buf, area); |
| 642 | assert!( |
| 643 | text.contains("Fixed after the first message. Start another with /new."), |
| 644 | "{text}" |
| 645 | ); |
| 646 | assert!(text.contains("Creator mode"), "{text}"); |
| 647 | } |
| 648 | let mut locked = |
| 649 | ModePickerView::from_table(AppMode::Agent, Locale::En, &table, Some("creator"), true); |
| 650 | assert_eq!( |
| 651 | locked.entries().len(), |
| 652 | 2, |
| 653 | "only the permission rows stay selectable" |
| 654 | ); |
| 655 | for key in [KeyCode::Up, KeyCode::Up, KeyCode::Home] { |
| 656 | locked.handle_key(KeyEvent::new(key, KeyModifiers::NONE)); |
| 657 | assert!(matches!(locked.selected(), Some(Entry::Permission(_)))); |
| 658 | } |
| 659 | for number in ['1', '2'] { |
| 660 | let mut locked = |
| 661 | ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, true); |
| 662 | assert!(matches!( |
| 663 | locked.handle_key(KeyEvent::new(KeyCode::Char(number), KeyModifiers::NONE)), |
| 664 | ViewAction::EmitAndClose(ViewEvent::ModeSelected { .. }) |
| 665 | )); |
| 666 | } |
| 667 | } |
| 668 | |
| 669 | #[tokio::test] |
| 670 | #[allow(clippy::await_holding_lock)] |
| 671 | async fn creator_row_is_listed_disabled_with_its_reason_while_unavailable() { |
| 672 | let runtime_missing = |
| 673 | "Creator mode needs a plugin runtime (Node.js or Bun), and none was found."; |
| 674 | for reason in [CREATOR_KEY_OFF_REASON, runtime_missing] { |
| 675 | let _guard = CreatorAvailabilityGuard::set(Some(reason)); |
| 676 | let table = conversation_modes::current_table(Default::default(), true).await; |
| 677 | let view = ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, false); |
| 678 | let (buf, area) = render_view(view, 100, 30); |
| 679 | let text = frame_text(&buf, area); |
| 680 | assert!( |
| 681 | text.contains("Creator mode"), |
| 682 | "listed, never hidden: {text}" |
| 683 | ); |
| 684 | let shown = if reason == CREATOR_KEY_OFF_REASON { |
| 685 | "Plugin creator is off in [features]" |
| 686 | } else { |
| 687 | "Creator mode needs a plugin runtime" |
| 688 | }; |
| 689 | assert!(text.contains(shown), "{text}"); |
| 690 | let mut view = |
| 691 | ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, false); |
| 692 | assert_eq!(view.entries().len(), 3); |
| 693 | for key in [ |
| 694 | KeyCode::Up, |
| 695 | KeyCode::Up, |
| 696 | KeyCode::Up, |
| 697 | KeyCode::Home, |
| 698 | KeyCode::End, |
| 699 | ] { |
| 700 | let action = view.handle_key(KeyEvent::new(key, KeyModifiers::NONE)); |
| 701 | assert!(matches!(action, ViewAction::None)); |
| 702 | } |
| 703 | let mut view = |
| 704 | ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, false); |
| 705 | view.handle_key(KeyEvent::new(KeyCode::Home, KeyModifiers::NONE)); |
| 706 | let action = view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)); |
| 707 | assert!( |
| 708 | !matches!(action, ViewAction::EmitAndClose(ViewEvent::ConversationModeSelected { ref id }) if id == "creator"), |
| 709 | "an unavailable mode is never selectable" |
| 710 | ); |
| 711 | } |
| 712 | let _guard = CreatorAvailabilityGuard::set(None); |
| 713 | let table = conversation_modes::current_table(Default::default(), true).await; |
| 714 | let mut view = ModePickerView::from_table(AppMode::Agent, Locale::En, &table, None, false); |
| 715 | view.handle_key(KeyEvent::new(KeyCode::Up, KeyModifiers::NONE)); |
| 716 | assert!(matches!( |
| 717 | view.handle_key(KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE)), |
| 718 | ViewAction::EmitAndClose(ViewEvent::ConversationModeSelected { ref id }) if id == "creator" |
| 719 | )); |
| 720 | } |
| 721 | |
| 722 | #[test] |
| 723 | fn unavailable_mode_without_reason_uses_localized_default() { |
| 724 | let table = ConversationModeTable { |
| 725 | default: conversation_modes::STANDARD, |
| 726 | modes: vec![conversation_modes::ConversationMode { |
| 727 | id: "unavailable-id".to_string(), |
| 728 | name: "Unavailable".to_string(), |
| 729 | description: "Unavailable mode".to_string(), |
| 730 | source: "builtin", |
| 731 | available: false, |
| 732 | reason: None, |
| 733 | }], |
| 734 | }; |
| 735 | let view = ModePickerView::from_table(AppMode::Agent, Locale::ZhHans, &table, None, false); |
| 736 | let expected = tr( |
| 737 | Locale::ZhHans, |
| 738 | MessageId::ConversationModeUnavailableDefault, |
| 739 | ); |
| 740 | assert_eq!(view.rows[0].unavailable.as_deref(), Some(expected.as_ref())); |
| 741 | } |
| 742 | |
| 743 | #[test] |
| 744 | fn short_terminal_scrolls_to_keep_selected_row_visible_and_clickable() { |
| 745 | let mut view = picker(AppMode::Agent, None, false); |
| 746 | let last_idx = view.entries().len() - 1; |
| 747 | view.cursor = last_idx; |
| 748 | |
| 749 | let area = Rect::new(0, 0, 68, 12); |
| 750 | let mut buf = Buffer::empty(area); |
| 751 | view.render(area, &mut buf); |
| 752 | let rendered: String = buf.content().iter().map(|cell| cell.symbol()).collect(); |
| 753 | let last_label = VISIBLE_MODES |
| 754 | .last() |
| 755 | .unwrap() |
| 756 | .display_name_localized(Locale::En); |
| 757 | assert!( |
| 758 | rendered.contains(last_label.as_ref()), |
| 759 | "expected selected row `{last_label}` in short viewport: {rendered}" |
| 760 | ); |
| 761 | |
| 762 | let rect = view.row_hitboxes.borrow()[last_idx]; |
| 763 | assert!(rect.width > 0 && rect.height == 1, "{rect:?}"); |
| 764 | let action = view.handle_mouse(MouseEvent { |
| 765 | kind: MouseEventKind::Down(MouseButton::Left), |
| 766 | column: rect.x + 1, |
| 767 | row: rect.y, |
| 768 | modifiers: KeyModifiers::NONE, |
| 769 | }); |
| 770 | assert!(matches!( |
| 771 | action, |
| 772 | ViewAction::EmitAndClose(ViewEvent::ModeSelected { .. }) |
| 773 | )); |
| 774 | } |
| 775 | } |
| 776 |