//! Key routing and composer-adjacent UI interaction for `ChatWidget`. use super::clipboard::PendingCopy; use super::*; use crate::bottom_pane::BottomPaneView; use crate::clipboard_copy::CopyStatus; use crate::clipboard_copy::worker::CopyResult; /// An input action the app must finish before processing the next key. #[derive(Debug)] pub(crate) enum KeyEventAction { None, CopyLastResponse(Arc), PasteImage, } impl ChatWidget { pub(crate) fn end_composer_drag(&mut self) { self.bottom_pane.end_composer_drag(); } pub(crate) fn copy_composer_selection( &mut self, event: &crate::tui::TuiEvent, copy: impl FnOnce(&str) -> Result, ) -> Option<(usize, Result)> { self.bottom_pane.copy_composer_selection(event, copy) } pub(crate) fn handle_composer_mouse(&mut self, event: crossterm::event::MouseEvent) -> bool { self.bottom_pane.handle_composer_mouse(event) } /// Snapshot only the editable paste target, without changing pending submissions. pub(crate) fn right_click_paste_target(&self) -> Option<(String, usize)> { self.bottom_pane.can_paste_on_right_click().then(|| { ( self.bottom_pane.composer_text(), self.bottom_pane.composer_cursor(), ) }) } pub(crate) fn prepare_composer_mouse(&mut self, event: crossterm::event::MouseEvent) -> bool { self.bottom_pane.prepare_composer_mouse(event) } pub(crate) fn set_agents_navigation_enabled(&mut self, enabled: bool) { self.bottom_pane.set_agents_navigation_enabled(enabled); } pub(crate) fn agents_navigation_key_available(&self) -> bool { self.bottom_pane.agents_navigation_key_available() } pub(crate) fn keymap_contexts(&self) -> crate::keymap::KeymapContextSet { self.bottom_pane.keymap_contexts() } pub(crate) fn handle_key_event(&mut self, key_event: KeyEvent) -> KeyEventAction { if self.handle_startup_submission_key(key_event) { return KeyEventAction::None; } if self.handle_question_key(key_event) { return KeyEventAction::None; } if self.bottom_pane.has_active_view() && !matches!( key_event, KeyEvent { code: KeyCode::Char(c), modifiers, kind: KeyEventKind::Press, .. } if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'c') ) && (self.bottom_pane.warnings_active() || (!key_hint::ctrl(KeyCode::Char('r')).is_press(key_event) && !key_hint::ctrl(KeyCode::Char('u')).is_press(key_event))) { let should_pause_active_goal = self .bottom_pane .active_view_will_interrupt_turn_on_key_event(key_event); self.bottom_pane.handle_key_event(key_event); if should_pause_active_goal { self.pause_active_goal_for_interrupt(); } if self.bottom_pane.no_modal_or_popup_active() { self.on_modal_or_popup_closed(); } return KeyEventAction::None; } if self.shortcut_overlay_visible() && key_hint::plain(KeyCode::Esc).is_press(key_event) { self.bottom_pane.handle_key_event(key_event); return KeyEventAction::None; } if (self.chat_keymap.interrupt_turn.is_pressed(key_event) || key_hint::ctrl(KeyCode::Char('c')).is_press(key_event)) && self.bottom_pane.no_modal_or_popup_active() && !self.should_handle_vim_insert_escape(key_event) && self.pending_image_submission.is_some() { if self.is_cancellable_work_active() { self.requeue_image_submission(); self.input_queue.recovered_queue = true; if self.submit_op(AppCommand::interrupt()) { self.pause_active_goal_for_interrupt(); } } else { self.cancel_image_submission(); } return KeyEventAction::None; } if self.handle_reasoning_shortcut(key_event) || self.handle_permission_shortcut(key_event) { self.bottom_pane.clear_quit_shortcut_hint(); self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; return KeyEventAction::None; } if key_event.kind == KeyEventKind::Press && self.copy_last_response_binding.is_pressed(key_event) { self.bottom_pane.clear_quit_shortcut_hint(); self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; return self.prepare_last_response_copy(); } match key_event { KeyEvent { code: KeyCode::Char(c), modifiers, kind: KeyEventKind::Press, .. } if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'c') => { self.on_ctrl_c(); return KeyEventAction::None; } KeyEvent { code: KeyCode::Char(c), modifiers, kind: KeyEventKind::Press, .. } if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'d') => { if self.on_ctrl_d() { return KeyEventAction::None; } self.bottom_pane.clear_quit_shortcut_hint(); self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; } KeyEvent { code: KeyCode::Char(c), modifiers, kind: KeyEventKind::Press, .. } if modifiers.intersects(KeyModifiers::CONTROL | KeyModifiers::ALT) && c.eq_ignore_ascii_case(&'v') => { if Instant::now() < self.suppress_image_paste_until { self.suppress_image_paste_until = Instant::now() + clipboard::IMAGE_PASTE_REPEAT_WINDOW; return KeyEventAction::None; } self.suppress_image_paste_until = Instant::now() + clipboard::IMAGE_PASTE_REPEAT_WINDOW; return KeyEventAction::PasteImage; } other if other.kind == KeyEventKind::Press => { self.suppress_image_paste_until = Instant::now(); self.bottom_pane.clear_quit_shortcut_hint(); self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; } other if other.kind == KeyEventKind::Release => { self.suppress_image_paste_until = Instant::now(); } _ => {} } if key_event.kind == KeyEventKind::Press && self.chat_keymap.edit_queued_message.is_pressed(key_event) && (self.has_queued_follow_up_messages() || self.pending_image_submission.is_some()) && self.bottom_pane.no_modal_or_popup_active() { if let Some(composer) = self.pop_latest_queued_composer_state() { self.restore_composer_state(composer); self.refresh_startup_recovery(); self.refresh_pending_input_preview(); self.request_redraw(); } else { self.cancel_image_submission(); } return KeyEventAction::None; } const REVIEW_STEER_UNAVAILABLE_MESSAGE: &str = "Steer messages aren't supported during /review. Press Ctrl+C now to cancel the review."; if self.chat_keymap.interrupt_turn.is_pressed(key_event) && self.review.is_review_mode && (!self.input_queue.pending_steers.is_empty() || !self.input_queue.rejected_steers_queue.is_empty()) && self.bottom_pane.is_task_running() && self.bottom_pane.no_modal_or_popup_active() && !self.should_handle_vim_insert_escape(key_event) { self.add_warning_message(REVIEW_STEER_UNAVAILABLE_MESSAGE.to_string()); return KeyEventAction::None; } if self.chat_keymap.interrupt_turn.is_pressed(key_event) && !self.input_queue.pending_steers.is_empty() && self.bottom_pane.is_task_running() && self.bottom_pane.no_modal_or_popup_active() && !self.should_handle_vim_insert_escape(key_event) { self.input_queue.submit_pending_steers_after_interrupt = true; if self.submit_op(AppCommand::interrupt()) { self.pause_active_goal_for_interrupt(); } else { self.input_queue.submit_pending_steers_after_interrupt = false; } return KeyEventAction::None; } if self.handle_plugins_popup_key_event(key_event) { return KeyEventAction::None; } match key_event { KeyEvent { code: KeyCode::BackTab, kind: KeyEventKind::Press, .. } if self.collaboration_modes_enabled() && !self.bottom_pane.is_task_running() && self.bottom_pane.no_modal_or_popup_active() => { if self.blocks_direct_input { self.add_error_message(PARENT_OWNED_INPUT_MESSAGE.to_string()); } else { self.cycle_collaboration_mode(); } } _ => { let had_modal_or_popup = !self.bottom_pane.no_modal_or_popup_active(); let should_pause_active_goal = self.bottom_pane.should_interrupt_running_task(key_event); let input_result = self.bottom_pane.handle_key_event(key_event); if matches!( input_result, InputResult::None | InputResult::ParentOwnedInputBlocked ) { self.refresh_startup_recovery(); } crate::startup_recovery::submitted(&input_result); self.sync_backend_banner_view(); if should_pause_active_goal { self.pause_active_goal_for_interrupt(); } self.handle_composer_input_result(input_result, had_modal_or_popup); } } KeyEventAction::None } /// Attach a local image to the composer when the active model supports image inputs. /// /// When the model does not advertise image support, we keep the draft unchanged and surface a /// warning event so users can switch models or remove attachments. pub(crate) fn attach_image(&mut self, path: PathBuf) { if !self.current_model_supports_images() { self.add_to_history(history_cell::new_warning_event( self.image_inputs_not_supported_message(), )); self.request_redraw(); return; } tracing::info!("attach_image path={path:?}"); self.bottom_pane.attach_image(path); self.refresh_startup_recovery(); self.request_redraw(); } pub(crate) fn composer_text_with_pending(&self) -> String { self.bottom_pane.composer_text_with_pending() } pub(crate) fn apply_external_edit(&mut self, text: String) { self.bottom_pane.apply_external_edit(text); self.refresh_startup_recovery(); self.request_redraw(); } pub(crate) fn external_editor_state(&self) -> ExternalEditorState { self.external_editor_state } pub(crate) fn set_external_editor_state(&mut self, state: ExternalEditorState) { self.external_editor_state = state; } pub(crate) fn set_footer_hint_override(&mut self, items: Option>) { if items.is_some() { // Active input instructions supersede transient feedback from a previous action. self.bottom_pane .show_footer_flash(Line::default(), Duration::ZERO); } self.bottom_pane.set_footer_hint_override(items); } pub(crate) fn show_selection_view(&mut self, params: SelectionViewParams) { self.bottom_pane.show_selection_view(params); self.request_redraw(); } pub(crate) fn show_bottom_pane_view(&mut self, view: Box) { self.bottom_pane.show_view(view); self.request_redraw(); } pub(crate) fn replace_bottom_pane_view_if_present( &mut self, view_id: &'static str, view: Box, ) { self.bottom_pane.replace_view_if_present(view_id, view); } pub(crate) fn selected_index_for_present_view(&self, view_id: &'static str) -> Option { self.bottom_pane.selected_index_for_present_view(view_id) } pub(crate) fn selected_index_for_active_view(&self, view_id: &'static str) -> Option { self.bottom_pane.selected_index_for_active_view(view_id) } pub(crate) fn replace_selection_view_if_present( &mut self, view_id: &'static str, params: SelectionViewParams, ) -> bool { self.bottom_pane .replace_selection_view_if_present(view_id, params) } pub(crate) fn shortcut_overlay_visible(&self) -> bool { self.bottom_pane.shortcut_overlay_visible() } pub(crate) fn no_modal_or_popup_active(&self) -> bool { self.bottom_pane.no_modal_or_popup_active() } pub(crate) fn can_launch_external_editor(&self) -> bool { !self.external_writer_view && self.bottom_pane.can_launch_external_editor() } pub(crate) fn can_run_ctrl_l_clear_now(&mut self) -> bool { // Ctrl+L is not a slash command, but it follows /clear's current rule: // block while a task is running. if !self.bottom_pane.is_task_running() { return true; } let message = "Ctrl+L is disabled while a task is in progress.".to_string(); self.add_to_history(history_cell::new_error_event(message)); self.request_redraw(); false } /// Capture the last response for the app to copy before processing another key. pub(super) fn prepare_last_response_copy(&mut self) -> KeyEventAction { self.app_event_tx.send(AppEvent::FollowTranscript); let action = match self.transcript.last_agent_markdown.as_deref() { Some(markdown) if !markdown.is_empty() => { KeyEventAction::CopyLastResponse(markdown.into()) } _ => { self.add_error_message("No agent response to copy".into()); KeyEventAction::None } }; self.request_redraw(); action } /// Report a selection copy in the footer without adding history. pub(crate) fn show_selection_copy_result(&mut self, result: CopyResult) { if let Ok(CopyStatus::Pending(id)) = result { self.pending_clipboard = Some(PendingCopy::Selection(id)); } self.show_clipboard_flash(&result); } pub(crate) fn show_copy_result(&mut self, label: &str, result: CopyResult) { if let Ok(CopyStatus::Pending(id)) = result { self.pending_clipboard = Some(PendingCopy::Message(id, label.into())); } match result { Ok(status) => self.add_info_message(status.message(label), /*hint*/ None), Err(error) => self.add_error_message(format!("Copy failed: {error}")), } self.request_redraw(); } #[cfg(test)] pub(crate) fn last_agent_markdown_text(&self) -> Option<&str> { self.transcript.last_agent_markdown.as_deref() } pub(super) fn show_rename_prompt(&mut self) { if !self.ensure_thread_rename_allowed() { return; } let tx = self.app_event_tx.clone(); let existing_name = self.thread_name.as_deref().filter(|name| !name.is_empty()); let title = if existing_name.is_some() { "Rename thread" } else { "Name thread" }; let suggestion_request = self .thread_id .map(|thread_id| (thread_id, uuid::Uuid::new_v4())); let mut view = CustomPromptView::new( title.to_string(), "Type a name and press Enter".to_string(), /*initial_text*/ existing_name.unwrap_or_default().to_string(), /*context_label*/ None, Box::new(move |name: String| { let Some(name) = normalize_thread_name(&name) else { tx.send(AppEvent::InsertHistoryCell(Box::new( history_cell::new_error_event("Thread name cannot be empty.".to_string()), ))); return; }; tx.set_thread_name(name); }), ); if let Some((_, request_id)) = suggestion_request { view = view.with_text_suggestion( request_id, "Generating a title suggestion…".to_string(), "Suggested from this conversation".to_string(), ); } self.bottom_pane.show_text_prompt(view); if let Some((thread_id, request_id)) = suggestion_request { self.app_event_tx.send(AppEvent::SuggestThreadName { thread_id, request_id, }); } } pub(crate) fn apply_thread_name_suggestion( &mut self, thread_id: ThreadId, request_id: uuid::Uuid, suggestion: Option<&str>, ) { if self.thread_id == Some(thread_id) { self.bottom_pane .apply_text_suggestion(request_id, suggestion); } } pub(super) fn ensure_thread_rename_allowed(&mut self) -> bool { match self.thread_rename_block_message.clone() { Some(message) => { self.add_error_message(message); false } None => true, } } pub(crate) fn handle_paste(&mut self, text: String) { if self.external_writer_view && !self.bottom_pane.has_active_view() { return; } if !self.startup_submission_has_protected_input() { self.cancel_startup_submission(); } self.bottom_pane.handle_paste(text); self.refresh_startup_recovery(); } // Returns true if caller should skip rendering this frame (a future frame is scheduled). pub(crate) fn handle_paste_burst_tick(&mut self, frame_requester: FrameRequester) -> bool { if self.bottom_pane.flush_paste_burst_if_due() { self.refresh_startup_recovery(); // A paste just flushed; request an immediate redraw and skip this frame. self.request_redraw(); true } else if self.bottom_pane.is_in_paste_burst() { // While capturing a burst, schedule a follow-up tick and skip this frame // to avoid redundant renders between ticks. frame_requester.schedule_frame_in( crate::bottom_pane::ChatComposer::recommended_paste_flush_delay(), ); true } else { false } } /// Handles a Ctrl+C press at the chat-widget layer. /// /// The first press arms a time-bounded quit shortcut and shows a footer hint via the bottom /// pane. If cancellable work is active, Ctrl+C also submits `Op::Interrupt` after the shortcut /// is armed. /// /// When the double-press quit shortcut is enabled, pressing the same shortcut again before /// expiry requests a shutdown-first quit. pub(super) fn on_ctrl_c(&mut self) { let key = key_hint::ctrl(KeyCode::Char('c')); let modal_or_popup_active = !self.bottom_pane.no_modal_or_popup_active(); let should_pause_active_goal = self .bottom_pane .active_view_will_interrupt_turn_on_key_event(KeyEvent::new( KeyCode::Char('c'), KeyModifiers::CONTROL, )); if self.bottom_pane.on_ctrl_c() == CancellationEvent::Handled { self.refresh_startup_recovery(); if DOUBLE_PRESS_QUIT_SHORTCUT_ENABLED { if modal_or_popup_active { self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; self.bottom_pane.clear_quit_shortcut_hint(); } else { self.arm_quit_shortcut(key); } } if should_pause_active_goal { self.pause_active_goal_for_interrupt(); } if modal_or_popup_active && self.bottom_pane.no_modal_or_popup_active() { self.on_modal_or_popup_closed(); } return; } if self .bottom_pane .selected_index_for_active_view(crate::app::AGENTS_OVERVIEW_VIEW_ID) .is_some() { self.request_quit_without_confirmation(); return; } if !DOUBLE_PRESS_QUIT_SHORTCUT_ENABLED { if self.is_cancellable_work_active() { self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; self.bottom_pane.clear_quit_shortcut_hint(); if self.submit_op(AppCommand::interrupt()) { self.pause_active_goal_for_interrupt(); } } else { self.request_quit_without_confirmation(); } return; } if self.quit_shortcut_active_for(key) { self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; self.request_quit_without_confirmation(); return; } self.arm_quit_shortcut(key); if self.is_cancellable_work_active() && self.submit_op(AppCommand::interrupt()) { self.pause_active_goal_for_interrupt(); } } /// Handles a Ctrl+D press at the chat-widget layer. /// /// Ctrl-D only participates in quit when the composer is empty and no modal/popup is active. /// Otherwise it should be routed to the active view and not attempt to quit. fn on_ctrl_d(&mut self) -> bool { let key = key_hint::ctrl(KeyCode::Char('d')); if !DOUBLE_PRESS_QUIT_SHORTCUT_ENABLED { if !self.bottom_pane.composer_is_empty() || !self.bottom_pane.no_modal_or_popup_active() { return false; } self.request_quit_without_confirmation(); return true; } if self.quit_shortcut_active_for(key) { self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; self.request_quit_without_confirmation(); return true; } if !self.bottom_pane.composer_is_empty() || !self.bottom_pane.no_modal_or_popup_active() { return false; } self.arm_quit_shortcut(key); true } /// True if `key` matches the armed quit shortcut and the window has not expired. fn quit_shortcut_active_for(&self, key: KeyBinding) -> bool { self.quit_shortcut_key == Some(key) && self .quit_shortcut_expires_at .is_some_and(|expires_at| Instant::now() < expires_at) } /// Arm the double-press quit shortcut and show the footer hint. /// /// This keeps the state machine (`quit_shortcut_*`) in `ChatWidget`, since /// it is the component that interprets Ctrl+C vs Ctrl+D and decides whether /// quitting is currently allowed, while delegating rendering to `BottomPane`. pub(super) fn arm_quit_shortcut(&mut self, key: KeyBinding) { self.quit_shortcut_expires_at = Instant::now() .checked_add(QUIT_SHORTCUT_TIMEOUT) .or_else(|| Some(Instant::now())); self.quit_shortcut_key = Some(key); self.bottom_pane.show_quit_shortcut_hint(key); } // Review mode counts as cancellable work so Ctrl+C interrupts instead of quitting. fn is_cancellable_work_active(&self) -> bool { self.bottom_pane.is_task_running() || self.review.is_review_mode } pub(crate) fn is_agent_turn_running(&self) -> bool { self.turn_lifecycle.agent_turn_running } pub(crate) fn is_active_goal_turn_running(&self) -> bool { self.turn_lifecycle.agent_turn_running && self .current_goal_status .as_ref() .is_some_and(GoalStatusState::is_active) } pub(crate) fn pause_active_goal_for_interrupt(&self) { if !self.is_active_goal_turn_running() { return; } let Some(thread_id) = self.thread_id else { return; }; self.app_event_tx.send(AppEvent::SetThreadGoalStatus { thread_id, status: AppThreadGoalStatus::Paused, }); } }