//! Key routing and composer-adjacent UI interaction for `ChatWidget`. use super::clipboard::PendingCopy; use super::*; use crate::activation_key_guard::ActivationKeySuppression; 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 { text_fallback: Option, context: ClipboardPasteContext, }, } impl ChatWidget { pub(crate) fn current_patch_approval(&self) -> Option<(ThreadId, &str)> { let patch = self.bottom_pane.current_patch_approval()?; Some((patch.thread_id, &patch.id)) } pub(crate) fn clear_composer_selection(&mut self) { self.bottom_pane.clear_composer_selection(); } pub(crate) fn end_composer_drag(&mut self) { self.bottom_pane.end_composer_drag(); } pub(crate) fn cancel_composer_primary(&mut self) { self.bottom_pane.cancel_composer_primary(); } 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 copy_composer_selection_on_release( &mut self, event: crossterm::event::MouseEvent, selection_copy: crate::tui::SelectionCopy, copy: impl FnOnce(&str, crate::tui::SelectionCopy) -> (CopyResult, Option>), ) -> Option<(usize, Option)> { self.bottom_pane .copy_composer_selection_on_release(event, selection_copy, copy) } pub(crate) fn set_composer_cursor(&mut self, cursor: usize) { self.bottom_pane.set_composer_cursor(cursor); } pub(crate) fn handle_composer_mouse(&mut self, event: crossterm::event::MouseEvent) -> bool { self.bottom_pane.handle_composer_mouse(event) } /// Snapshot the paste target without changing pending submissions. Unlike mouse paste, /// a keyboard paste may replace a composer selection or complete an active popup. pub(crate) fn clipboard_paste_target( &self, shortcut: Option, ) -> Option { if self.blocks_direct_input { return None; } self.bottom_pane.clipboard_paste_target(shortcut) } pub(crate) fn prepare_composer_mouse(&mut self, event: crossterm::event::MouseEvent) -> bool { self.bottom_pane.prepare_composer_mouse(event) } 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 { let contexts = self.bottom_pane.keymap_contexts(); if self.visible_new_backend_control().is_some() { contexts.with_backend_cycling() } else { contexts } } pub(crate) fn take_key_chord_reset(&mut self) -> bool { std::mem::take(&mut self.bottom_pane.key_chord_reset_requested) } pub(crate) fn suppress_current_view_key_until_release( &mut self, key: KeyBinding, activated_at: Instant, suppression: ActivationKeySuppression, ) { self.bottom_pane .suppress_current_view_key_until_release(key, activated_at, suppression); } /// Held keys belong to the terminal input stream across conversation switches. pub(crate) fn inherit_view_transition_key_guard(&mut self, previous: &mut Self) { if let Some(guard) = previous.bottom_pane.view_transition_key_guard.take() { self.bottom_pane.view_transition_key_guard = Some(guard); } } pub(crate) fn consume_view_transition_key_event(&mut self, key_event: KeyEvent) -> bool { self.bottom_pane .consume_view_transition_key_event(key_event) } #[cfg(test)] pub(crate) fn handle_key_event(&mut self, key_event: KeyEvent) -> KeyEventAction { self.handle_key_event_with_activation_key(key_event, /*activation_key*/ None) } pub(crate) fn set_new_backend_control(&mut self, label: Option) { if self.new_backend_label != label { self.new_backend_label = label; self.request_redraw(); } } pub(crate) fn can_choose_new_backend(&self) -> bool { !self.blocks_direct_input && !self.is_user_turn_pending_or_running() && self.last_turn_id().is_none() && !self.input_queue.has_queued_follow_up_messages() && self.input_queue.startup_submission.is_none() && self.initial_user_message.is_none() } pub(super) fn visible_new_backend_control(&self) -> Option<&str> { let label = self.new_backend_label.as_deref()?; (self.can_choose_new_backend() && self.bottom_pane.no_modal_or_popup_active() && !self.fork_in_progress && !self.shortcut_overlay_visible() && !self.quick_dial_menu && self.safety_recourse.is_none() && !self.has_provider_error() && matches!(self.external_editor_state, ExternalEditorState::Closed)) .then_some(label) } pub(crate) fn handle_key_event_with_activation_key( &mut self, key_event: KeyEvent, activation_key: Option, ) -> KeyEventAction { if self.handle_quick_dial_menu(key_event) { return KeyEventAction::None; } 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 == 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_with_activation_key(key_event, activation_key); 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; } let keymap = self.bottom_pane.keymap(); if keymap.app.change_host.is_pressed(key_event) && self.visible_new_backend_control().is_some() { self.app_event_tx .send(AppEvent::CycleNewConversationBackend); return KeyEventAction::None; } if self.shortcut_overlay_visible() && key_hint::plain(KeyCode::Esc).is_press(key_event) { self.bottom_pane .handle_key_event_with_activation_key(key_event, activation_key); return KeyEventAction::None; } if key_event.kind == KeyEventKind::Press && self.chat_keymap.open_presets.is_pressed(key_event) && self.bottom_pane.no_modal_or_popup_active() { self.open_quick_dial_menu(); 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; } key if Self::is_ctrl_d_press(key) => { 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; } _ => { if let Some(action) = self.image_paste_key_action(key_event, ClipboardPasteContext::Composer) { return action; } if key_event.kind == KeyEventKind::Press { self.bottom_pane.clear_quit_shortcut_hint(); self.quit_shortcut_expires_at = None; self.quit_shortcut_key = None; } } } 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_with_activation_key(key_event, activation_key); 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, deferring model validation while the draft awaits its destination. /// /// Ordinary paste still checks the active model. Handoff only retains the attachment locally; /// submission validates the destination model and backend before admission. pub(crate) fn attach_image(&mut self, path: PathBuf, context: ClipboardPasteContext) { if context == ClipboardPasteContext::Composer && !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:?}"); if context == ClipboardPasteContext::DraftHandoff && !self.has_active_view() { self.bottom_pane.settle_before_handoff_image(); } 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>) { self.quick_dial_menu = false; 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 dismiss_provider_view(&mut self, id: &'static str) { self.bottom_pane.dismiss_view_by_id(id); } 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 completion_can_yield_focus(&self) -> bool { self.bottom_pane.completion_can_yield_focus() } 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) { self.cancel_quick_dial_menu(); if (self.external_writer_view || self.has_provider_error()) && !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(); } pub(crate) fn is_in_paste_burst(&self) -> bool { self.bottom_pane.is_in_paste_burst() } // 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 { let flushed = self.bottom_pane.flush_paste_burst_if_due(); self.finish_paste_burst_tick(frame_requester, flushed) } pub(crate) fn handle_handoff_paste_tick(&mut self, frame_requester: FrameRequester) -> bool { let flushed = self.bottom_pane.flush_handoff_paste_if_due(); self.finish_paste_burst_tick(frame_requester, flushed) } fn finish_paste_burst_tick(&mut self, frame_requester: FrameRequester, flushed: bool) -> bool { if flushed { self.refresh_startup_recovery(); // A paste just flushed; request an immediate redraw and skip this frame. self.request_redraw(); true } else if self.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(); } } pub(super) fn is_ctrl_d_press(key: KeyEvent) -> bool { matches!( key, KeyEvent { code: KeyCode::Char(c), modifiers, kind: KeyEventKind::Press, .. } if modifiers.contains(KeyModifiers::CONTROL) && c.eq_ignore_ascii_case(&'d') ) } /// 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. pub(super) 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, }); } }