diff --git a/harness/src/runtime/input.rs b/harness/src/runtime/input.rs index 494825f27..d3917ac53 100644 --- a/harness/src/runtime/input.rs +++ b/harness/src/runtime/input.rs @@ -1,3 +1,5 @@ +mod keyboard; + use super::*; use crate::ui::keymap::{KeyAction, KeyMap}; use crossterm::event::KeyEvent; @@ -721,1698 +723,140 @@ pub(super) async fn handle_app_event( }, AppEvent::Tui(ev) => match ev { TuiEvent::Key(key) => { - *needs_redraw = true; - app_state.lock().await.mark_user_activity(); - let is_ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL); - let is_cmd = key.modifiers.contains(event::KeyModifiers::SUPER); - - if is_ctrl && key.code == KeyCode::Char(' ') && !app_state.lock().await.modal_open() - { - let snapshot = { - let state = app_state.lock().await; - ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( - &state, - )) - }; - transcript_state - .selection - .begin_keyboard_with_snapshot(snapshot, transcript_state.scroll_rows()); - return Ok(InputFlow::ContinueIteration); - } - if transcript_state.panel_selection_area.is_none() - && transcript_state.selection.is_keyboard_mode() - { - if is_keyboard_range_key(key) { - transcript_state.selection.move_keyboard(key.code); - return Ok(InputFlow::ContinueIteration); + return keyboard::handle_key( + key, + InputContext { + terminal_runtime, + app_state, + client, + current_cancel_token, + needs_redraw, + frame_requester, + terminal_focused, + transcript_state, + app_event_sender, + agent_ui_event_sender, + composer, + demo_state, + }, + ) + .await; + } + TuiEvent::Mouse(mouse) => { + match mouse.kind { + // The return-to-bottom control owns its rectangle only while + // it is painted, so a hidden control can never swallow this + // click (#1595). + event::MouseEventKind::Down(event::MouseButton::Left) + if transcript_state + .follow_control() + .area() + .is_some_and(|area| { + area.contains(ratatui::layout::Position::new( + mouse.column, + mouse.row, + )) + }) => + { + transcript_state.jump_to_latest(); + frame_requester.schedule_frame(); } - } - - // Ctrl+C runs before selection handlers so the chord can copy - // and retain its double-press exit behavior. Cmd+C is copy-only. - if is_copy_or_exit_chord(key) { - return Ok(handle_copy_or_exit_chord(&app_state, transcript_state).await); - } - if is_cmd_copy_chord(key) { - return Ok(handle_cmd_copy_chord(&app_state, transcript_state).await); - } - - if selection_owns_key(transcript_state, key) { - let selection = if transcript_state.panel_selection_area.is_some() { - &mut transcript_state.panel_selection - } else { - &mut transcript_state.selection - }; - selection.clear(); - return Ok(InputFlow::ContinueIteration); - } - - // Composer selection owns Esc (#1493, #1566). The copy chord is - // already handled above so it can also arm the exit. - if key.code == KeyCode::Esc && app_state.lock().await.has_composer_selection() { - app_state.lock().await.clear_composer_selection(); - return Ok(InputFlow::ContinueIteration); - } - - let transcript_navigation = is_transcript_navigation(key); - clear_selection_for_composer_key(transcript_state, key); - - { - let mut s = app_state.lock().await; - s.clear_ctrl_c_exit_arming(); - } - - if (is_ctrl || is_cmd) - && (key.code == KeyCode::Char('k') || key.code == KeyCode::Char('K')) - { - let mut s = app_state.lock().await; - s.request_clear_screen(); - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - if is_ctrl && (key.code == KeyCode::Char('l') || key.code == KeyCode::Char('L')) { - let mut s = app_state.lock().await; - s.request_clear_screen(); - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - - { - let selected = { - let state = app_state.lock().await; - state - .show_update_prompt - .then_some(state.update_prompt_index) - }; - if let Some(selected) = selected { - match key.code { - KeyCode::Up => { - let mut state = app_state.lock().await; - state.update_prompt_index = - state.update_prompt_index.saturating_sub(1); - } - KeyCode::Down => { - let mut state = app_state.lock().await; - state.update_prompt_index = (state.update_prompt_index + 1).min(2); - } - KeyCode::Enter => { - let decision = match selected { - 0 => UpdateDecision::UpdateNow, - 1 => UpdateDecision::Skip, - _ => UpdateDecision::SkipUntilNextVersion, - }; - let _ = app_event_sender.send(AppEvent::UpdateDecision(decision)); - } - KeyCode::Esc => { - let _ = app_event_sender - .send(AppEvent::UpdateDecision(UpdateDecision::Skip)); + // A panel's `esc` hint and its list rows act like the + // keys they stand for, so the panel needs no second path. + event::MouseEventKind::Down(event::MouseButton::Left) + if transcript_state + .panel_target_at(mouse.column, mouse.row) + .is_some() => + { + let keys = match transcript_state + .panel_target_at(mouse.column, mouse.row) + .expect("checked") + { + ui::PanelTarget::Escape => vec![KeyCode::Esc], + ui::PanelTarget::ListRow(rows) => { + let step = if rows < 0 { KeyCode::Up } else { KeyCode::Down }; + let mut keys = vec![step; rows.unsigned_abs()]; + keys.push(KeyCode::Enter); + keys } - _ => {} + }; + for key in keys { + let _ = app_event_sender.send(AppEvent::Tui(TuiEvent::Key( + event::KeyEvent::new(key, event::KeyModifiers::NONE), + ))); } return Ok(InputFlow::ContinueIteration); } - } - - { - let selected = { - let s = app_state.lock().await; - (s.status == AppStatus::AwaitingToolConfirmation && !s.user_overlay_open()) - .then(|| { - let prefix = s - .pending_tool_confirmation - .as_ref() - .filter(|items| { - items.len() == 1 && items[0].rememberable_prefix.is_some() - || items.len() == 1 - && items[0].forbidden_prefix.is_some() - }) - .and_then(|items| items[0].rememberable_prefix.clone()); - let forbidden_prefix = s - .pending_tool_confirmation - .as_ref() - .filter(|items| items.len() == 1) - .and_then(|items| items[0].forbidden_prefix.clone()); - (s.tool_confirmation_selected, prefix, forbidden_prefix) - }) - }; - if let Some((selected, prefix, forbidden_prefix)) = selected { - if let Some(event) = ui::approval_event_for_key( - key, - selected, - prefix.as_deref(), - forbidden_prefix.as_deref(), - ) { - let _ = app_event_sender.send(event); - } else { - if is_shift_tab(key) { - let mut s = app_state.lock().await; - s.overlays().toggle_auto_confirm(); - s.record_auto_confirm(); - } else { - match key.code { - KeyCode::Tab => { - let mut s = app_state.lock().await; - s.overlays().toggle_auto_confirm(); - s.record_auto_confirm(); - } - KeyCode::Up => { - let mut s = app_state.lock().await; - s.overlays().move_approval_selection(-1); - } - KeyCode::Down => { - let mut s = app_state.lock().await; - s.overlays().move_approval_selection(1); - } - _ => {} - } - } + // Pointer motion only moves the hover; a frame is drawn + // when it reaches or leaves a tool block. + event::MouseEventKind::Moved => { + if transcript_state.hover_at(mouse.column, mouse.row) { + frame_requester.schedule_frame(); } return Ok(InputFlow::ContinueIteration); } - } - - { - // A device asks to share this session. Plain keys answer - // it so a stray keystroke cannot leak into the composer - // while the terminal decides; chords keep working. - let share_open = app_state.lock().await.pending_share_prompt.is_some(); - if share_open { - if key.modifiers.intersects( - KeyModifiers::CONTROL | KeyModifiers::SUPER | KeyModifiers::ALT, - ) { - // Fall through to normal handling below. - } else { - match key.code { - KeyCode::Char('y') | KeyCode::Char('Y') => { - app_state.lock().await.share_decision = Some(true); - } - KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => { - app_state.lock().await.share_decision = Some(false); - } - _ => {} - } - return Ok(InputFlow::ContinueIteration); - } - } - } - - { - let s = app_state.lock().await; - if s.status == AppStatus::AwaitingQuestion && !s.user_overlay_open() { - let typing = s - .pending_question - .as_ref() - .map(|q| q.custom_input.is_some()) - .unwrap_or(false); - drop(s); - - if typing { - let action = match key.code { - KeyCode::Tab => { - app_state.lock().await.focus_question(1); - QuestionEditAction::Handled - } - KeyCode::BackTab => { - app_state.lock().await.focus_question(-1); - QuestionEditAction::Handled - } - KeyCode::Esc => { - let mut s = app_state.lock().await; - if let Some(q) = s.pending_question.as_mut() { - q.custom_input = None; - q.custom_cursor = 0; - q.custom_draft.clear(); - } - QuestionEditAction::Handled - } - _ => { - let mut s = app_state.lock().await; - s.pending_question - .as_mut() - .map_or(QuestionEditAction::Handled, |q| { - handle_question_custom_key(q, key) - }) - } - }; - match action { - QuestionEditAction::Submit => { - let answer_event = { - let s = app_state.lock().await; - s.pending_question - .as_ref() - .map(ui::question_custom_answer_event) - }; - if let Some(answer_event) = answer_event { - let _ = app_event_sender.send(answer_event); - } - } - QuestionEditAction::Paste => { - if let Some(text) = - rustcode::clipboard::read_text_from_clipboard() - { - let mut s = app_state.lock().await; - if let Some(q) = s.pending_question.as_mut() { - insert_question_answer_text(q, &text); - } - } - } - QuestionEditAction::Handled => {} - } - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - - match key.code { - KeyCode::Up => { - let mut s = app_state.lock().await; - if let Some(q) = s.pending_question.as_mut() { - q.selected = q.selected.saturating_sub(1); - } - } - KeyCode::Down => { - let mut s = app_state.lock().await; - if let Some(q) = s.pending_question.as_mut() { - let last = q.options.len(); - q.selected = (q.selected + 1).min(last); - if q.selected == last { - q.activate_custom_input(); - } - } - } - KeyCode::Tab => { - let mut s = app_state.lock().await; - s.focus_question(1); - } - KeyCode::BackTab => { - let mut s = app_state.lock().await; - s.focus_question(-1); - } - KeyCode::Char(' ') => { - let mut s = app_state.lock().await; - if let Some(q) = s.pending_question.as_mut() { - if q.selected == q.options.len() { - q.activate_custom_input(); - } else if q.is_multi_select - && let Some(c) = q.chosen.get_mut(q.selected) - { - *c = !*c; - } - } - } - KeyCode::Char(d @ '1'..='9') => { - let idx = (d as usize) - ('1' as usize); - let mut s = app_state.lock().await; - if let Some(q) = s.pending_question.as_mut() - && idx < q.options.len() - { - q.selected = idx; - if q.is_multi_select { - if let Some(c) = q.chosen.get_mut(idx) { - *c = !*c; - } - } else { - let answer_event = ui::question_answer_event(q); - if let Some(answer_event) = answer_event { - let _ = app_event_sender.send(answer_event); - } - } - } - } - KeyCode::Char(c) => { - let mut s = app_state.lock().await; - if let Some(q) = s.pending_question.as_mut() { - if q.selected == q.options.len() { - q.activate_custom_input(); - q.insert_char(c); - } - } - } - KeyCode::Enter => { - let mut s = app_state.lock().await; - let is_custom_slot = s - .pending_question - .as_ref() - .map(|q| q.selected == q.options.len()) - .unwrap_or(false); - if is_custom_slot { - if let Some(q) = s.pending_question.as_mut() { - q.activate_custom_input(); - } - } else if let Some(q) = s.pending_question.as_ref() - && let Some(answer_event) = ui::question_answer_event(q) - { - let _ = app_event_sender.send(answer_event); - } - } - KeyCode::Esc => { - let _ = app_event_sender.send(ui::question_cancel_event()); - } - _ => {} + // The footer's task counter opens the tasks panel. + event::MouseEventKind::Down(event::MouseButton::Left) + if transcript_state.tasks_chip_at(mouse.column, mouse.row) => + { + let mut state = app_state.lock().await; + if !state.modal_open() { + rustcode::controller::show_tasks_panel(&mut state); } *needs_redraw = true; return Ok(InputFlow::ContinueIteration); } - } - - { - let s = app_state.lock().await; - if s.settings_picker == Some(rustcode::controller::SettingsPicker::ScrollSpeed) + // The composer's posture token cycles ask -> auto-approve -> plan. + event::MouseEventKind::Down(event::MouseButton::Left) + if transcript_state.posture_chip_at(mouse.column, mouse.row) => { - drop(s); - let mut s = app_state.lock().await; - if let Some(lines) = scroll_speed_picker_key(&mut s, key.code) { - s.config.scroll_lines = Some(lines); - rustcode::controller::save_config(&s.config); - s.close_modal_status(); - s.set_transient_notice(rustcode::controller::scroll_speed_notice( - lines, - )); + let mut state = app_state.lock().await; + if !state.modal_open() { + super::composer::cycle_permission_posture(&mut state); } *needs_redraw = true; return Ok(InputFlow::ContinueIteration); } - - if s.settings_picker == Some(rustcode::controller::SettingsPicker::Verbosity) { - drop(s); - match key.code { - KeyCode::Up => { - let mut s = app_state.lock().await; - s.modal_picker_index = s.modal_picker_index.saturating_sub(1); - } - KeyCode::Down => { - let mut s = app_state.lock().await; - s.modal_picker_index = s - .modal_picker_index - .saturating_add(1) - .min(Verbosity::ALL.len() - 1); - } - KeyCode::Enter => { - let mut s = app_state.lock().await; - let new_verbosity = Verbosity::ALL - .get(s.modal_picker_index) - .cloned() - .unwrap_or_default(); - s.verbosity = new_verbosity.clone(); - s.config.verbosity = new_verbosity; - rustcode::controller::save_config(&s.config); - s.close_modal_status(); - } - KeyCode::Esc => { - let mut s = app_state.lock().await; - s.close_modal_status(); - } - _ => {} - } - return Ok(InputFlow::ContinueIteration); + // The wheel moves the tasks panel's selection, or scrolls + // its log, instead of the transcript behind it. + event::MouseEventKind::ScrollUp | event::MouseEventKind::ScrollDown + if app_state.lock().await.tasks_panel.is_some() => + { + let input = if mouse.kind == event::MouseEventKind::ScrollUp { + rustcode::controller::TasksPanelInput::Up + } else { + rustcode::controller::TasksPanelInput::Down + }; + let mut state = app_state.lock().await; + rustcode::controller::tasks_panel_input(&mut state, input); + *needs_redraw = true; } - - if s.settings_picker == Some(rustcode::controller::SettingsPicker::Thinking) { - drop(s); - match key.code { - KeyCode::Up => { - let mut s = app_state.lock().await; - s.modal_picker_index = s.modal_picker_index.saturating_sub(1); - } - KeyCode::Down => { - let mut s = app_state.lock().await; - s.modal_picker_index = - s.modal_picker_index.saturating_add(1).min(2); // 0 on, 1 off, 2 default - } - KeyCode::Enter => { - let mut s = app_state.lock().await; - let value = match s.modal_picker_index { - 0 => Some(true), - 1 => Some(false), - _ => None, - }; - if let Some(profile) = s.active_model_profile_mut() { - profile.enable_thinking = value; - } - rustcode::controller::save_config(&s.config); - s.close_modal_status(); - } - KeyCode::Esc => { - let mut s = app_state.lock().await; - s.close_modal_status(); - } - _ => {} - } - return Ok(InputFlow::ContinueIteration); + event::MouseEventKind::ScrollUp + if transcript_state.panel_selection_area.is_some() => + { + let mut state = app_state.lock().await; + scroll_panel_selection(transcript_state, &mut state.modal_scroll_row, -1); + frame_requester.schedule_frame(); } - - if s.settings_picker == Some(rustcode::controller::SettingsPicker::Effort) { - drop(s); - match key.code { - KeyCode::Up => { - let mut s = app_state.lock().await; - s.modal_picker_index = s.modal_picker_index.saturating_sub(1); - } - KeyCode::Down => { - let mut s = app_state.lock().await; - let last = rustcode::controller::effort_choices( - s.active_model_profile().as_ref(), - ) - .len() - .saturating_sub(1); - s.modal_picker_index = - s.modal_picker_index.saturating_add(1).min(last); - } - KeyCode::Enter => { - let mut s = app_state.lock().await; - let choices = rustcode::controller::effort_choices( - s.active_model_profile().as_ref(), - ); - let value = choices.get(s.modal_picker_index).cloned().flatten(); - s.set_active_reasoning_effort(value); - s.close_modal_status(); - } - KeyCode::Esc => { - let mut s = app_state.lock().await; - s.close_modal_status(); - } - _ => {} - } - return Ok(InputFlow::ContinueIteration); + event::MouseEventKind::ScrollDown + if transcript_state.panel_selection_area.is_some() => + { + let mut state = app_state.lock().await; + scroll_panel_selection(transcript_state, &mut state.modal_scroll_row, 1); + frame_requester.schedule_frame(); } - - if s.settings_picker == Some(rustcode::controller::SettingsPicker::Protocol) { - drop(s); - match key.code { - KeyCode::Up => { - let mut s = app_state.lock().await; - s.modal_picker_index = s.modal_picker_index.saturating_sub(1); - } - KeyCode::Down => { - let mut s = app_state.lock().await; - s.modal_picker_index = - s.modal_picker_index.saturating_add(1).min(2); // 0 json, 1 native, 2 apinative - } - KeyCode::Enter => { - let mut s = app_state.lock().await; - let (protocol, label) = match s.modal_picker_index { - 0 => (rustcode::config::ToolProtocol::Json, "JSON (```tool)"), - 1 => ( - rustcode::config::ToolProtocol::Native, - "Native ([TOOL_CALLS])", - ), - _ => ( - rustcode::config::ToolProtocol::ApiNative, - "ApiNative (schema in request `tools`, structured `tool_calls` back)", - ), - }; - let url = s.api_base_url.clone(); - let scoped = s - .config - .models - .iter_mut() - .find(|profile| profile.url == url); - if let Some(profile) = scoped { - profile.tool_protocol = Some(protocol); - } else { - s.config.tool_protocol = protocol; - } - rustcode::controller::save_config(&s.config); - let active_model = s.model_name.clone(); - s.set_transient_notice(format!( - "Switched tool protocol to {label} for model '{active_model}'." - )); - s.close_modal_status(); - } - KeyCode::Esc => { - let mut s = app_state.lock().await; - s.close_modal_status(); - } - _ => {} - } - return Ok(InputFlow::ContinueIteration); + event::MouseEventKind::ScrollUp if transcript_state.selection.is_active() => { + transcript_state + .selection + .queue_scroll(-1, ui::wheel_scroll_lines()); } - - if s.settings_picker == Some(rustcode::controller::SettingsPicker::Yolo) { - drop(s); - match key.code { - KeyCode::Up => { - let mut s = app_state.lock().await; - s.modal_picker_index = s.modal_picker_index.saturating_sub(1); - } - KeyCode::Down => { - let mut s = app_state.lock().await; - s.modal_picker_index = - s.modal_picker_index.saturating_add(1).min(1); // 0 on, 1 off - } - KeyCode::Enter => { - let mut s = app_state.lock().await; - let enable = s.modal_picker_index == 0; - s.set_auto_confirm(enable); - let status = if enable { "enabled" } else { "disabled" }; - s.set_transient_notice(format!("YOLO mode {status}")); - s.close_modal_status(); - } - KeyCode::Esc => { - let mut s = app_state.lock().await; - s.close_modal_status(); - } - _ => {} - } - return Ok(InputFlow::ContinueIteration); + event::MouseEventKind::ScrollDown if transcript_state.selection.is_active() => { + transcript_state + .selection + .queue_scroll(1, ui::wheel_scroll_lines()); } - } - - let mut s = app_state.lock().await; - if s.show_subagent_picker { - let total = s.subagents.len() + 1; - match subagent_picker_action(key.code) { - Some(SubagentPickerAction::Close) => { - s.show_subagent_picker = false; - } - Some(SubagentPickerAction::MoveUp) => { - s.subagent_picker_index = picker_selection_for_key( - s.subagent_picker_index, - total, - KeyCode::Up, - ) - .unwrap_or(s.subagent_picker_index); - } - Some(SubagentPickerAction::MoveDown) => { - s.subagent_picker_index = picker_selection_for_key( - s.subagent_picker_index, - total, - KeyCode::Down, - ) - .unwrap_or(s.subagent_picker_index); - } - Some(SubagentPickerAction::Select) => { - let selected = s.subagent_picker_index.min(total.saturating_sub(1)); - let id = if selected == 0 { - 0 - } else { - s.subagents[selected - 1].id - }; - s.show_subagent_picker = false; - drop(s); - let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); - return Ok(InputFlow::ContinueIteration); - } - None => {} - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.tasks_panel.is_some() { - if let Some(input) = tasks_panel_input_for_key(key.code) { - rustcode::controller::tasks_panel_input(&mut s, input); - } - return Ok(InputFlow::ContinueIteration); - } - if s.command_panel.is_some() { - match key.code { - KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') => { - s.command_panel = None; - } - KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown => { - let delta = match key.code { - KeyCode::Up => -1, - KeyCode::Down => 1, - KeyCode::PageUp => -10, - _ => 10, - }; - scroll_command_panel( - &mut s.modal_scroll_row, - transcript_state.panel_max_scroll_row, - delta, - ); - } - _ => {} - } - return Ok(InputFlow::ContinueIteration); - } - if s.show_context_modal { - match key.code { - KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') => { - s.show_context_modal = false; - } - _ => {} - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.show_status_modal { - if matches!( - key.code, - KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') - ) { - s.show_status_modal = false; - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.show_stats_modal { - if matches!( - key.code, - KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') - ) { - s.show_stats_modal = false; - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.show_session_modal { - if matches!( - key.code, - KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') - ) { - s.show_session_modal = false; - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.show_history_picker { - // Ctrl+D triggers delete confirmation overlay - if key.modifiers.contains(event::KeyModifiers::CONTROL) - && key.code == KeyCode::Char('d') - { - let idx = s - .history_picker_index - .min(s.history_picker_sessions.len().saturating_sub(1)); - s.pending_delete_session_idx = Some(idx); - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - // Confirmation overlay for delete - if let Some(del_idx) = s.pending_delete_session_idx { - match key.code { - KeyCode::Char('y') | KeyCode::Enter => { - let action = s - .history_picker_sessions - .get(del_idx) - .and_then( - rustcode::app::session_controller::session_id_from_meta, - ) - .map(rustcode::app::events::SessionAction::Id); - s.pending_delete_session_idx = None; - if let Some(action) = action { - let _ = app_event_sender.send(AppEvent::DeleteSession(action)); - } - } - KeyCode::Esc | KeyCode::Char('n') => { - s.pending_delete_session_idx = None; - } - _ => {} - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - match key.code { - KeyCode::Esc => { - s.show_history_picker = false; - } - KeyCode::Up => { - let len = s.history_picker_sessions.len(); - s.history_picker_index = - picker_selection_for_key(s.history_picker_index, len, key.code) - .unwrap_or(s.history_picker_index); - } - KeyCode::Down => { - let len = s.history_picker_sessions.len(); - s.history_picker_index = - picker_selection_for_key(s.history_picker_index, len, key.code) - .unwrap_or(s.history_picker_index); - } - KeyCode::Enter => { - let idx = s - .history_picker_index - .min(s.history_picker_sessions.len().saturating_sub(1)); - if let Some(action) = s - .history_picker_sessions - .get(idx) - .and_then(rustcode::app::session_controller::session_id_from_meta) - .map(rustcode::app::events::SessionAction::Id) - { - let _ = app_event_sender.send(AppEvent::ResumeSession(action)); - } - } - _ => {} - } - - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if let Some(panel) = s.skills_panel.as_mut() { - match key.code { - KeyCode::Esc => s.skills_panel = None, - KeyCode::Up | KeyCode::Down => { - let next = picker_selection_for_key( - panel.selected, - panel.entries.len(), - key.code, - ) - .unwrap_or(panel.selected); - panel.select(next); - panel.notice = None; - } - KeyCode::Enter | KeyCode::Char(' ') => { - // Keep the in-memory config in step so a later - // full save cannot write the old list back. - if let Some(disabled) = panel.toggle_selected() { - s.config.disabled_skills = disabled; - } - } - _ => {} - } - drop(s); - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - - if s.show_mcp_config { - let (existing_mcp_always_include, existing_mcp_client_id, existing_mcp_timeout) = - s.mcp_edit_state - .as_ref() - .and_then(|edit_state| edit_state.edit_index) - .and_then(|idx| s.config.mcp_servers.get(idx)) - .map(|server| { - ( - server.always_include, - server.client_id.clone(), - server.timeout_secs, - ) - }) - .unwrap_or_default(); - if let Some(ref mut edit_state) = s.mcp_edit_state { - if crate::ui::keymap::KeyMap::from_environment().resolve(key) - == crate::ui::keymap::KeyAction::Paste - { - // Text only: an image marker has no place in a - // server name or command. - if let Some(text) = rustcode::clipboard::read_text_from_clipboard() { - edit_state.insert_str(&text); - } - drop(s); - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - match key.code { - KeyCode::Esc => { - s.mcp_edit_state = None; - } - KeyCode::Up => { - let prev = if edit_state.active_field == 0 { - 2 - } else { - edit_state.active_field - 1 - }; - edit_state.set_active_field(prev); - } - KeyCode::Down | KeyCode::Tab => { - let next = (edit_state.active_field + 1) % 3; - edit_state.set_active_field(next); - } - KeyCode::Enter => { - let name = edit_state.name_input.trim().to_string(); - let command = edit_state.command_input.trim().to_string(); - let args = edit_state - .args_input - .split_whitespace() - .map(|s| s.to_string()) - .collect::>(); - - // An http(s) value in the command field declares a - // remote Streamable HTTP server; anything else is - // spawned over stdio. - let remote = command.starts_with("http://") - || command.starts_with("https://"); - if !name.is_empty() && !command.is_empty() { - let url = remote.then(|| command.clone()); - let new_srv = rustcode::config::McpServerConfig { - name: name.clone(), - command: if remote { String::new() } else { command }, - // Arguments only apply to stdio servers. - args: if remote { Vec::new() } else { args }, - env: std::collections::HashMap::new(), - url, - headers: std::collections::HashMap::new(), - client_id: existing_mcp_client_id, - enabled: true, - always_include: existing_mcp_always_include, - timeout_secs: existing_mcp_timeout, - }; - - if edit_state.is_add { - s.config.mcp_servers.push(new_srv); - } else if let Some(idx) = edit_state.edit_index - && idx < s.config.mcp_servers.len() - { - let old_name = s.config.mcp_servers[idx].name.clone(); - s.config.mcp_servers[idx] = new_srv; - if old_name != name { - rustcode::mcp::shutdown_server(&old_name).await; - } - } - - rustcode::controller::save_config(&s.config); - - let name_clone = name.clone(); - tokio::spawn(async move { - let _ = - rustcode::mcp::start_server_by_name(&name_clone).await; - }); - - s.mcp_edit_state = None; - } - } - // Everything else edits the active field with - // the keys every other text field uses. - _ => { - let action = - crate::ui::keymap::KeyMap::from_environment().resolve(key); - if let Some(edit) = action.text_edit(&mut [0; 4]) { - edit_state.edit(edit); - } - } - } - } else { - match key.code { - KeyCode::Esc => { - s.show_mcp_config = false; - } - KeyCode::Up => { - let len = s.config.mcp_servers.len(); - s.mcp_picker_index = - picker_selection_for_key(s.mcp_picker_index, len, key.code) - .unwrap_or(s.mcp_picker_index); - } - KeyCode::Down => { - let len = s.config.mcp_servers.len(); - s.mcp_picker_index = - picker_selection_for_key(s.mcp_picker_index, len, key.code) - .unwrap_or(s.mcp_picker_index); - } - KeyCode::Char('a') | KeyCode::Char('A') => { - s.mcp_edit_state = Some(rustcode::app::McpEditState { - is_add: true, - edit_index: None, - name_input: String::new(), - command_input: String::new(), - args_input: String::new(), - active_field: 0, - cursor_pos: 0, - }); - } - KeyCode::Char('e') | KeyCode::Char('E') => { - let idx = s.mcp_picker_index; - if let Some(srv) = s.config.mcp_servers.get(idx) { - s.mcp_edit_state = Some(rustcode::app::McpEditState { - is_add: false, - edit_index: Some(idx), - name_input: srv.name.clone(), - command_input: if srv.is_remote() { - srv.url.clone().unwrap_or_default() - } else { - srv.command.clone() - }, - args_input: srv.args.join(" "), - active_field: 0, - cursor_pos: srv.name.len(), - }); - } - } - KeyCode::Char('d') | KeyCode::Char('D') => { - let idx = s.mcp_picker_index; - if idx < s.config.mcp_servers.len() { - let removed = s.config.mcp_servers.remove(idx); - rustcode::controller::save_config(&s.config); - let name_clone = removed.name.clone(); - tokio::spawn(async move { - rustcode::mcp::shutdown_server(&name_clone).await; - }); - if s.mcp_picker_index >= s.config.mcp_servers.len() - && s.mcp_picker_index > 0 - { - s.mcp_picker_index -= 1; - } - } - } - KeyCode::Enter => { - let idx = s.mcp_picker_index; - if let Some(srv) = s.config.mcp_servers.get_mut(idx) { - srv.enabled = !srv.enabled; - let name_clone = srv.name.clone(); - let enabled = srv.enabled; - rustcode::controller::save_config(&s.config); - tokio::spawn(async move { - rustcode::controller::apply_mcp_toggle( - &name_clone, - enabled, - ) - .await; - }); - } - } - _ => {} - } - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.show_model_picker { - if crate::ui::keymap::KeyMap::from_environment().resolve(key) - == crate::ui::keymap::KeyAction::Paste - { - if let Some(payload) = clipboard_paste_payload() { - insert_picker_search_text(&mut s, PickerSearchTarget::Model, &payload); - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - match key.code { - KeyCode::Esc => { - s.show_model_picker = false; - } - KeyCode::Up => { - let len = rustcode::app::get_picker_items_count(&s); - s.model_picker_index = - picker_selection_for_key(s.model_picker_index, len, key.code) - .unwrap_or(s.model_picker_index); - } - KeyCode::Down => { - let len = rustcode::app::get_picker_items_count(&s); - s.model_picker_index = - picker_selection_for_key(s.model_picker_index, len, key.code) - .unwrap_or(s.model_picker_index); - } - KeyCode::Enter => { - rustcode::app::select_picker_model(&mut s); - s.show_model_picker = false; - rustcode::app::spawn_context_window_detection( - Arc::clone(&app_state), - client.clone(), - ); - } - _ => { - handle_picker_search_key(&mut s, PickerSearchTarget::Model, key); - } - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.show_theme_picker { - let themes = crate::ui::theme::load_available_themes(); - let len = themes.len(); - match key.code { - KeyCode::Esc => { - s.config.theme = s.theme_picker_initial.clone(); - s.show_theme_picker = false; - } - KeyCode::Up | KeyCode::Char('k') => { - s.theme_picker_index = - move_picker_selection(s.theme_picker_index, len, false); - if len > 0 { - s.config.theme = themes[s.theme_picker_index].name.clone(); - } - } - KeyCode::Down | KeyCode::Char('j') => { - s.theme_picker_index = - move_picker_selection(s.theme_picker_index, len, true); - if len > 0 { - s.config.theme = themes[s.theme_picker_index].name.clone(); - } - } - KeyCode::Enter => { - let selected = themes[s.theme_picker_index.min(len.saturating_sub(1))] - .name - .clone(); - s.config.theme = selected.clone(); - s.show_theme_picker = false; - rustcode::controller::save_config(&s.config); - s.set_transient_notice(format!("Theme set to '{}'", selected)); - } - _ => {} - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - if s.show_command_picker { - let filtered_items = filtered_command_picker_items(&s.command_picker_search); - - if crate::ui::keymap::KeyMap::from_environment().resolve(key) - == crate::ui::keymap::KeyAction::Paste - { - if let Some(payload) = clipboard_paste_payload() { - insert_picker_search_text( - &mut s, - PickerSearchTarget::Command, - &payload, - ); - } - drop(s); - return Ok(InputFlow::ContinueIteration); - } - - let mut exit_flag = false; - match key.code { - KeyCode::Esc => { - s.show_command_picker = false; - } - KeyCode::Up => { - let len = filtered_items.len(); - s.command_picker_index = - picker_selection_for_key(s.command_picker_index, len, key.code) - .unwrap_or(s.command_picker_index); - } - KeyCode::Down => { - let len = filtered_items.len(); - s.command_picker_index = - picker_selection_for_key(s.command_picker_index, len, key.code) - .unwrap_or(s.command_picker_index); - } - KeyCode::Enter => { - let idx = s - .command_picker_index - .min(filtered_items.len().saturating_sub(1)); - if !filtered_items.is_empty() { - let item = filtered_items[idx]; - s.show_command_picker = false; - if item.shortcut == "ctrl+c" { - exit_flag = true; - } else { - // Palette commands share slash dispatch, including panel - // presentation, arguments and immediate actions. - s.input_buffer = item.shortcut.to_owned(); - s.cursor_position = s.input_buffer.len(); - drop(s); - if open_demo_if_requested(app_state, demo_state).await { - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - let should_exit = rustcode::app::handle_enter_with_ui_events( - app_state, - client, - current_cancel_token, - agent_ui_event_sender.clone(), - &|| { - crate::ui::theme::load_available_themes() - .into_iter() - .map(|theme| theme.name) - .collect() - }, - ) - .await; - *needs_redraw = true; - return Ok(if should_exit { - InputFlow::Exit { update: false } - } else { - InputFlow::ContinueIteration - }); - } - } else { - s.show_command_picker = false; - } - } - _ => { - handle_picker_search_key(&mut s, PickerSearchTarget::Command, key); - } - } - drop(s); - if exit_flag { - return Ok(InputFlow::Exit { update: false }); - } - return Ok(InputFlow::ContinueIteration); - } - drop(s); - if transcript_navigation { - let page = terminal_runtime.terminal().area().height.saturating_sub(4) as usize; - // Keep every intermediate row visible while a mouse range is growing. - let page = if transcript_state.selection.is_dragging() { - 1 - } else { - page.max(1) - }; - if transcript_state.selection.is_active() { - let direction = if matches!(key.code, KeyCode::PageUp | KeyCode::Up) { - -1 - } else { - 1 - }; - transcript_state.selection.queue_scroll(direction, page); - frame_requester.schedule_frame(); - } else if matches!(key.code, KeyCode::PageUp | KeyCode::Up) { - transcript_state.scroll_up(page); - } else { - transcript_state.scroll_down(page); - } - return Ok(InputFlow::ContinueIteration); - } - // Escape closes transcript browsing without discarding a draft. - if return_to_latest_for_key(transcript_state, key.code) { - return Ok(InputFlow::ContinueIteration); - } - if key.code == KeyCode::Enter - && !key.modifiers.intersects( - event::KeyModifiers::SHIFT - | event::KeyModifiers::CONTROL - | event::KeyModifiers::ALT, - ) - && open_demo_if_requested(app_state, demo_state).await - { - return Ok(InputFlow::ContinueIteration); - } - match { - let mut state = app_state.lock().await; - composer.handle_key(&mut state, key) - } { - ui::ComposerAction::Handled => { - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - ui::ComposerAction::Submit => { - if rustcode::app::handle_enter_with_ui_events( - &app_state, - &client, - current_cancel_token, - agent_ui_event_sender.clone(), - &|| { - crate::ui::theme::load_available_themes() - .into_iter() - .map(|t| t.name) - .collect() - }, - ) - .await - { - return Ok(InputFlow::Exit { update: false }); - } - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - ui::ComposerAction::ClearScreen => { - terminal_runtime.terminal().clear()?; - return Ok(InputFlow::ContinueIteration); - } - ui::ComposerAction::Paste => { - if let Some(payload) = clipboard_paste_payload() { - let mut state = app_state.lock().await; - insert_clipboard_paste(composer, &mut state, &payload); - } - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - ui::ComposerAction::BackgroundCommand => { - let mut state = app_state.lock().await; - let moved = rustcode::tools::move_foreground_commands_to_background( - &state.active_session_id, - ); - state.set_transient_notice(match moved { - 0 => "No running command to move to the background", - 1 => "Moved the running command to the background", - _ => "Moved the running commands to the background", - }); - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - action @ (ui::ComposerAction::ToggleExpandAll - | ui::ComposerAction::ToggleExpandStep) => { - let step = matches!(action, ui::ComposerAction::ToggleExpandStep); - let mut state = app_state.lock().await; - let width = terminal_runtime.terminal().area().width; - toggle_tool_expansion(&mut state, width, step); - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - ui::ComposerAction::ToggleExpandEdits => { - let mut state = app_state.lock().await; - let width = terminal_runtime.terminal().area().width; - toggle_edit_expansion(&mut state, width); - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - ui::ComposerAction::Unhandled => {} - } - - match key.code { - KeyCode::Esc => { - let mut s = app_state.lock().await; - if s.dismiss_completion() { - // Popup dismissal keeps the draft intact. Typing or moving - // to another token makes completion eligible again. - } else if s.sel_start.is_some() || s.sel_end.is_some() { - s.clear_selection(); - } else if !s.input_buffer.is_empty() - && matches!(s.status, AppStatus::Idle) - && s.running_tools.is_empty() - { - s.input_buffer.clear(); - s.cursor_position = 0; - } else { - drop(s); - rustcode::app::handle_escape(&app_state, current_cancel_token).await; - } - *needs_redraw = true; - } - KeyCode::Up => { - let mut s = app_state.lock().await; - let completion_len = s.completion_len(); - if s.active_suggestion_index.is_some() && completion_len > 0 { - let current = s.active_suggestion_index.unwrap_or(0); - s.active_suggestion_index = Some(if current == 0 { - completion_len - 1 - } else { - current - 1 - }); - } else { - s.active_suggestion_index = None; - if s.input_buffer.is_empty() || s.history_index.is_some() { - // With an empty buffer, Up first pulls the most - // recent queued prompt back for editing; only - // when nothing is queued does it recall history. - // Once recall has started, keep walking it — - // without this, the recalled text made the buffer - // non-empty and the next Up fell through to - // cursor movement, pinning recall on the most - // recent entry. - let pulled = s.history_index.is_none() && s.pop_queued_prompt(); - if !pulled { - s.history_up(); - } - } else { - s.move_cursor_line_up(); - } - } - } - KeyCode::Down => { - let mut s = app_state.lock().await; - let completion_len = s.completion_len(); - if s.active_suggestion_index.is_some() && completion_len > 0 { - let current = s.active_suggestion_index.unwrap_or(0); - s.active_suggestion_index = Some(if current + 1 >= completion_len { - 0 - } else { - current + 1 - }); - } else { - s.active_suggestion_index = None; - if s.history_index.is_some() { - s.history_down(); - } else { - s.move_cursor_line_down(); - } - } - } - KeyCode::Left => { - let mut s = app_state.lock().await; - // An empty composer has no cursor to move, so Left opens - // the agent contexts the way Codex opens its agents overview. - if key.modifiers.is_empty() - && s.input_buffer.is_empty() - && !s.subagents.is_empty() - { - open_overlay(&mut s, rustcode::app::events::Overlay::Subagents); - return Ok(InputFlow::ContinueIteration); - } - let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); - let alt = key.modifiers.contains(event::KeyModifiers::ALT) - || key.modifiers.contains(event::KeyModifiers::META); - // Word motion wins whenever there is a draft; only an - // empty composer gives Alt+arrows to agent switching. - if alt - && !shift - && s.input_buffer.is_empty() - && let Some(id) = sessions::adjacent_context_id(&s, false) - { - drop(s); - let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); - return Ok(InputFlow::ContinueIteration); - } - if shift && s.composer_selection_anchor.is_none() { - s.composer_selection_anchor = Some(s.cursor_position); - } - if alt { - s.move_cursor_word_left(); - } else { - s.move_cursor_left(); - } - if !shift { - s.composer_selection_anchor = None; - } else if s.composer_selection_anchor == Some(s.cursor_position) { - s.composer_selection_anchor = None; - } - } - KeyCode::Right => { - let mut s = app_state.lock().await; - if key.modifiers.is_empty() - && let Some(id) = agent_context_return_target(&s, key.code) - { - drop(s); - let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); - return Ok(InputFlow::ContinueIteration); - } - let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); - let alt = key.modifiers.contains(event::KeyModifiers::ALT) - || key.modifiers.contains(event::KeyModifiers::META); - // Word motion wins whenever there is a draft; only an - // empty composer gives Alt+arrows to agent switching. - if alt - && !shift - && s.input_buffer.is_empty() - && let Some(id) = sessions::adjacent_context_id(&s, true) - { - drop(s); - let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); - return Ok(InputFlow::ContinueIteration); - } - if shift && s.composer_selection_anchor.is_none() { - s.composer_selection_anchor = Some(s.cursor_position); - } - if alt { - s.move_cursor_word_right(); - } else { - s.move_cursor_right(); - } - if !shift { - s.composer_selection_anchor = None; - } else if s.composer_selection_anchor == Some(s.cursor_position) { - s.composer_selection_anchor = None; - } - } - KeyCode::Home => { - let mut s = app_state.lock().await; - let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); - if shift && s.composer_selection_anchor.is_none() { - s.composer_selection_anchor = Some(s.cursor_position); - } - s.move_cursor_to_start(); - if !shift { - s.composer_selection_anchor = None; - } else if s.composer_selection_anchor == Some(s.cursor_position) { - s.composer_selection_anchor = None; - } - } - KeyCode::End => { - let mut s = app_state.lock().await; - let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); - if shift && s.composer_selection_anchor.is_none() { - s.composer_selection_anchor = Some(s.cursor_position); - } - s.move_cursor_to_end(); - if !shift { - s.composer_selection_anchor = None; - } else if s.composer_selection_anchor == Some(s.cursor_position) { - s.composer_selection_anchor = None; - } - } - KeyCode::Char('l') if key.modifiers.contains(event::KeyModifiers::CONTROL) => { - terminal_runtime.terminal().clear()?; - } - KeyCode::Enter => { - let modifiers = key.modifiers; - if modifiers.contains(event::KeyModifiers::SHIFT) - || modifiers.contains(event::KeyModifiers::CONTROL) - || modifiers.contains(event::KeyModifiers::ALT) - { - let mut s = app_state.lock().await; - s.insert_char('\n'); - s.reset_suggestion_cycle(); - } else { - if open_demo_if_requested(app_state, demo_state).await { - return Ok(InputFlow::ContinueIteration); - } - if rustcode::app::handle_enter_with_ui_events( - &app_state, - &client, - current_cancel_token, - agent_ui_event_sender.clone(), - &|| { - crate::ui::theme::load_available_themes() - .into_iter() - .map(|t| t.name) - .collect() - }, - ) - .await - { - return Ok(InputFlow::Exit { update: false }); - } - } - } - KeyCode::Char('v') | KeyCode::Char('V') - if key.modifiers.contains(event::KeyModifiers::CONTROL) - || key.modifiers.contains(event::KeyModifiers::SUPER) - || key.modifiers.contains(event::KeyModifiers::META) => - { - // Terminals without bracketed paste deliver Ctrl/Cmd+V - // as a key. Route it through the same helper the keymap - // paste uses so the large-paste marker cannot drift - // between the two (#1527). - if let Some(payload) = clipboard_paste_payload() { - let mut s = app_state.lock().await; - insert_clipboard_paste(composer, &mut s, &payload); - } - } - KeyCode::Char('p') | KeyCode::Char('n') - if key.modifiers.contains(event::KeyModifiers::CONTROL) => - { - let mut s = app_state.lock().await; - let completion_len = s.completion_len(); - if s.active_suggestion_index.is_some() && completion_len > 0 { - let current = s.active_suggestion_index.unwrap_or(0); - s.active_suggestion_index = Some(if key.code == KeyCode::Char('p') { - if current == 0 { - completion_len - 1 - } else { - current - 1 - } - } else if current + 1 >= completion_len { - 0 - } else { - current + 1 - }); - } else if key.code == KeyCode::Char('p') { - s.show_command_picker = true; - s.command_picker_index = 0; - s.command_picker_search.clear(); - } - } - - KeyCode::Char(c) => { - let mut s = app_state.lock().await; - let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL); - let alt = key.modifiers.contains(event::KeyModifiers::ALT) - || key.modifiers.contains(event::KeyModifiers::META); - let cmd = key.modifiers.contains(event::KeyModifiers::SUPER); - - if c == '\x7f' || c == '\x08' || c == '\x17' { - // Option+Backspace, Ctrl+W, or raw DEL on Mac - if alt || cmd || c == '\x17' { - s.delete_word_backspace(); - } else { - s.delete_char_backspace(); - } - s.reset_suggestion_cycle(); - } else if cmd { - if c == 'u' { - s.kill_line_to_start(); - s.reset_suggestion_cycle(); - } - } else if (alt && c == 'b') || c == '∫' { - // Terminals without enhanced key reporting send - // Option+Left/Right as these word-motion keys. - if s.input_buffer.is_empty() - && let Some(id) = sessions::adjacent_context_id(&s, false) - { - drop(s); - let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); - return Ok(InputFlow::ContinueIteration); - } - s.move_cursor_word_left(); - } else if (alt && c == 'f') || c == 'ƒ' { - if s.input_buffer.is_empty() - && let Some(id) = sessions::adjacent_context_id(&s, true) - { - drop(s); - let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); - return Ok(InputFlow::ContinueIteration); - } - s.move_cursor_word_right(); - } else if (alt && c == 'd') || c == '∂' { - s.delete_word_forward(); - s.reset_suggestion_cycle(); - } else if ctrl && c == 'j' { - s.insert_char('\n'); - s.reset_suggestion_cycle(); - } else if ctrl && c == 'a' { - s.move_cursor_to_start(); - } else if ctrl && c == 'e' { - s.move_cursor_to_end(); - } else if ctrl && c == 'u' { - s.kill_line_to_start(); - s.reset_suggestion_cycle(); - } else if ctrl && c == 'w' { - s.delete_word_backspace(); - s.reset_suggestion_cycle(); - } else if c == '?' && !ctrl && !alt && !cmd && s.input_buffer.is_empty() { - s.show_command_panel("Help", rustcode::app::build_help_text()); - s.request_redraw(); - } else if !ctrl && !alt && !c.is_control() { - s.insert_char(c); - s.reset_suggestion_cycle(); - } - } - KeyCode::Backspace => { - let mut s = app_state.lock().await; - let alt = key.modifiers.contains(event::KeyModifiers::ALT) - || key.modifiers.contains(event::KeyModifiers::META); - let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL); - let cmd = key.modifiers.contains(event::KeyModifiers::SUPER); - if cmd { - s.kill_line_to_start(); - } else if alt || ctrl { - s.delete_word_backspace(); - } else { - s.delete_char_backspace(); - } - s.reset_suggestion_cycle(); - } - KeyCode::Delete => { - let mut s = app_state.lock().await; - let alt = key.modifiers.contains(event::KeyModifiers::ALT) - || key.modifiers.contains(event::KeyModifiers::META); - let cmd = key.modifiers.contains(event::KeyModifiers::SUPER); - if cmd { - s.kill_line_to_start(); - } else if alt { - s.delete_word_forward(); - } else { - s.delete_char_delete(); - } - s.reset_suggestion_cycle(); - } - _ => {} - } - } - TuiEvent::Mouse(mouse) => { - match mouse.kind { - // The return-to-bottom control owns its rectangle only while - // it is painted, so a hidden control can never swallow this - // click (#1595). - event::MouseEventKind::Down(event::MouseButton::Left) - if transcript_state - .follow_control() - .area() - .is_some_and(|area| { - area.contains(ratatui::layout::Position::new( - mouse.column, - mouse.row, - )) - }) => - { - transcript_state.jump_to_latest(); - frame_requester.schedule_frame(); - } - // A panel's `esc` hint and its list rows act like the - // keys they stand for, so the panel needs no second path. - event::MouseEventKind::Down(event::MouseButton::Left) - if transcript_state - .panel_target_at(mouse.column, mouse.row) - .is_some() => - { - let keys = match transcript_state - .panel_target_at(mouse.column, mouse.row) - .expect("checked") - { - ui::PanelTarget::Escape => vec![KeyCode::Esc], - ui::PanelTarget::ListRow(rows) => { - let step = if rows < 0 { KeyCode::Up } else { KeyCode::Down }; - let mut keys = vec![step; rows.unsigned_abs()]; - keys.push(KeyCode::Enter); - keys - } - }; - for key in keys { - let _ = app_event_sender.send(AppEvent::Tui(TuiEvent::Key( - event::KeyEvent::new(key, event::KeyModifiers::NONE), - ))); - } - return Ok(InputFlow::ContinueIteration); - } - // Pointer motion only moves the hover; a frame is drawn - // when it reaches or leaves a tool block. - event::MouseEventKind::Moved => { - if transcript_state.hover_at(mouse.column, mouse.row) { - frame_requester.schedule_frame(); - } - return Ok(InputFlow::ContinueIteration); - } - // The footer's task counter opens the tasks panel. - event::MouseEventKind::Down(event::MouseButton::Left) - if transcript_state.tasks_chip_at(mouse.column, mouse.row) => - { - let mut state = app_state.lock().await; - if !state.modal_open() { - rustcode::controller::show_tasks_panel(&mut state); - } - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - // The composer's posture token cycles ask -> auto-approve -> plan. - event::MouseEventKind::Down(event::MouseButton::Left) - if transcript_state.posture_chip_at(mouse.column, mouse.row) => - { - let mut state = app_state.lock().await; - if !state.modal_open() { - super::composer::cycle_permission_posture(&mut state); - } - *needs_redraw = true; - return Ok(InputFlow::ContinueIteration); - } - // The wheel moves the tasks panel's selection, or scrolls - // its log, instead of the transcript behind it. - event::MouseEventKind::ScrollUp | event::MouseEventKind::ScrollDown - if app_state.lock().await.tasks_panel.is_some() => - { - let input = if mouse.kind == event::MouseEventKind::ScrollUp { - rustcode::controller::TasksPanelInput::Up - } else { - rustcode::controller::TasksPanelInput::Down - }; - let mut state = app_state.lock().await; - rustcode::controller::tasks_panel_input(&mut state, input); - *needs_redraw = true; - } - event::MouseEventKind::ScrollUp - if transcript_state.panel_selection_area.is_some() => - { - let mut state = app_state.lock().await; - scroll_panel_selection(transcript_state, &mut state.modal_scroll_row, -1); - frame_requester.schedule_frame(); - } - event::MouseEventKind::ScrollDown - if transcript_state.panel_selection_area.is_some() => - { - let mut state = app_state.lock().await; - scroll_panel_selection(transcript_state, &mut state.modal_scroll_row, 1); - frame_requester.schedule_frame(); - } - event::MouseEventKind::ScrollUp if transcript_state.selection.is_active() => { - transcript_state - .selection - .queue_scroll(-1, ui::wheel_scroll_lines()); - } - event::MouseEventKind::ScrollDown if transcript_state.selection.is_active() => { - transcript_state - .selection - .queue_scroll(1, ui::wheel_scroll_lines()); - } - event::MouseEventKind::ScrollUp => { - transcript_state.scroll_up(ui::wheel_scroll_lines()); + event::MouseEventKind::ScrollUp => { + transcript_state.scroll_up(ui::wheel_scroll_lines()); } event::MouseEventKind::ScrollDown => { transcript_state.scroll_down(ui::wheel_scroll_lines()); @@ -2802,1039 +1246,4 @@ pub(super) async fn handle_app_event( } #[cfg(test)] -mod tests { - use super::{ - InputFlow, PickerSearchTarget, QuestionEditAction, SubagentPickerAction, - agent_context_return_target, clear_selection_for_composer_key, - filtered_command_picker_items, handle_cmd_copy_chord, handle_cmd_copy_chord_with, - handle_copy_or_exit_chord, handle_picker_search_key, handle_question_custom_key, - insert_clipboard_paste, insert_question_answer_text, is_cmd_copy_chord, - is_copy_or_exit_chord, is_keyboard_range_key, is_shift_tab, is_transcript_navigation, - open_demo_if_requested, picker_selection_for_key, report_selection_copy, - return_to_latest_for_key, scroll_command_panel, scroll_panel_selection, selection_owns_key, - subagent_picker_action, - }; - use crate::ui::{Composer, TranscriptState}; - use crossterm::event::{ - KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind, - }; - use ratatui::{buffer::Buffer, layout::Rect}; - use rustcode::app::AppState; - use rustcode::clipboard::ClipboardCopyStatus; - use rustcode::controller::PendingQuestion; - use std::sync::Arc; - use tokio::sync::Mutex; - - #[test] - fn clicking_a_tool_block_opens_then_closes_only_that_block() { - use rustcode::app::{ChatMessage, ToolCallRef, ToolResultRecord}; - - let mut state = AppState::new(); - for round in 0..2 { - let id = format!("call-{round}"); - state.history.push( - ChatMessage::new("assistant", format!("round {round}")).with_tool_calls(vec![ - ToolCallRef { - id: id.clone(), - name: "run_command".to_owned(), - arguments: r#"{"command":"cargo test"}"#.to_owned(), - }, - ]), - ); - state.history.push( - ChatMessage::new("tool", "run_command: exit code: 0\nok") - .answering(Some(id)) - .with_tool_result(ToolResultRecord { - tool_name: "run_command".to_owned(), - success: true, - ..Default::default() - }), - ); - } - - // The second block is history index 3. - super::toggle_tool_block(&mut state, 80, (3, 4)); - assert!(state.expanded_thoughts.contains(&3)); - assert!(!state.expanded_thoughts.contains(&1)); - - super::toggle_tool_block(&mut state, 80, (3, 4)); - assert!(state.expanded_thoughts.is_empty()); - } - - #[test] - fn clicking_a_folded_run_opens_and_folds_it() { - let mut state = AppState::new(); - state.verbosity = rustcode::app::Verbosity::Low; - // A summary row stands for the calls from history index 1 up to 4. - super::toggle_tool_block(&mut state, 80, (1, 4)); - assert!(state.expanded_tool_runs.contains(&1)); - assert!(state.expanded_thoughts.is_empty(), "no call body opens"); - super::toggle_tool_block(&mut state, 80, (1, 4)); - assert!(state.expanded_tool_runs.is_empty()); - } - - #[test] - fn ask_question_editor_matches_composer_modified_enter_and_word_navigation() { - let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); - question.activate_custom_input(); - question.insert_str("café tools"); - - assert_eq!( - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Left, KeyModifiers::CONTROL) - ), - QuestionEditAction::Handled - ); - assert_eq!(question.custom_cursor, "café ".len()); - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Char('X'), KeyModifiers::NONE), - ); - assert_eq!(question.custom_input.as_deref(), Some("café Xtools")); - - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT), - ); - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL), - ); - assert_eq!(question.custom_input.as_deref(), Some("café X\n\ntools")); - assert_eq!( - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE) - ), - QuestionEditAction::Submit - ); - } - - #[test] - fn ask_question_editor_supports_forward_word_delete_and_line_kill() { - let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); - question.activate_custom_input(); - question.insert_str("one two three"); - question.custom_cursor = "one ".len(); - - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Char('d'), KeyModifiers::ALT), - ); - // Forward word delete removes the word and leaves the space after it. - assert_eq!(question.custom_input.as_deref(), Some("one three")); - assert_eq!(question.custom_cursor, "one ".len()); - - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Backspace, KeyModifiers::SUPER), - ); - assert_eq!(question.custom_input.as_deref(), Some(" three")); - assert_eq!(question.custom_cursor, 0); - } - - #[test] - fn ask_question_paste_preserves_normalized_newlines_and_unicode() { - let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); - question.activate_custom_input(); - insert_question_answer_text(&mut question, "først\r\n二つ\rslutt"); - - assert_eq!(question.custom_input.as_deref(), Some("først\n二つ\nslutt")); - assert_eq!(question.custom_cursor, "først\n二つ\nslutt".len()); - } - - #[test] - fn ask_question_up_from_first_answer_line_returns_to_options_with_draft() { - let up = KeyEvent::new(KeyCode::Up, KeyModifiers::NONE); - let mut question = PendingQuestion::new( - "Question?".to_owned(), - vec!["One".to_owned(), "Two".to_owned()], - false, - ); - question.selected = 2; - question.activate_custom_input(); - question.insert_str("first\nsecond"); - - // Up on the second line moves within the answer. - handle_question_custom_key(&mut question, up); - assert!(question.custom_input.is_some()); - assert!(question.custom_cursor_on_first_line()); - - // Up on the first line returns to the last option and keeps the text. - handle_question_custom_key(&mut question, up); - assert!(question.custom_input.is_none()); - assert_eq!(question.selected, 1); - assert_eq!(question.custom_draft, "first\nsecond"); - - question.activate_custom_input(); - assert_eq!(question.custom_input.as_deref(), Some("first\nsecond")); - assert_eq!(question.custom_cursor, "first\nsecond".len()); - } - - #[test] - fn scroll_speed_picker_steps_within_range_and_saves_on_enter() { - let mut state = AppState::new(); - state.settings_picker = Some(rustcode::controller::SettingsPicker::ScrollSpeed); - state.modal_picker_index = 1; - - assert_eq!( - super::scroll_speed_picker_key(&mut state, KeyCode::Left), - None - ); - assert_eq!(state.modal_picker_index, 1, "never below one line"); - super::scroll_speed_picker_key(&mut state, KeyCode::Right); - super::scroll_speed_picker_key(&mut state, KeyCode::Up); - assert_eq!(state.modal_picker_index, 3); - super::scroll_speed_picker_key(&mut state, KeyCode::End); - super::scroll_speed_picker_key(&mut state, KeyCode::Right); - assert_eq!(state.modal_picker_index, 20, "never above the range"); - super::scroll_speed_picker_key(&mut state, KeyCode::Char('5')); - assert_eq!( - super::scroll_speed_picker_key(&mut state, KeyCode::Enter), - Some(5) - ); - - assert_eq!( - super::scroll_speed_picker_key(&mut state, KeyCode::Esc), - None - ); - assert!(state.settings_picker.is_none(), "esc closes without saving"); - } - - #[test] - fn ask_question_up_without_options_stays_in_the_answer() { - let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); - question.activate_custom_input(); - question.insert_str("text"); - handle_question_custom_key( - &mut question, - KeyEvent::new(KeyCode::Up, KeyModifiers::NONE), - ); - assert_eq!(question.custom_input.as_deref(), Some("text")); - } - - #[tokio::test] - async fn opening_demo_consumes_only_the_command_and_preserves_live_session() { - let mut state = AppState::new(); - state.active_session_id = "live-session".to_owned(); - state - .history - .push(rustcode::app::ChatMessage::new("user", "existing history")); - state.input_buffer = "/test".to_owned(); - state.cursor_position = state.input_buffer.len(); - let expected_history = state.history.snapshot(); - let app_state = Arc::new(Mutex::new(state)); - let mut demo_state = None; - - assert!(open_demo_if_requested(&app_state, &mut demo_state).await); - let live = app_state.lock().await; - assert_eq!(live.active_session_id, "live-session"); - assert_eq!(live.history.snapshot(), expected_history); - assert!(live.input_buffer.is_empty()); - let demo = demo_state.expect("demo view is separate from the live session"); - assert_eq!(demo.render_state().active_session_id, "static-visual-demo"); - assert_eq!(demo.render_state().history.len(), 4); - } - - #[tokio::test] - async fn demo_command_does_not_match_a_prompt_with_arguments() { - let mut state = AppState::new(); - state.input_buffer = "/test please".to_owned(); - let app_state = Arc::new(Mutex::new(state)); - let mut demo_state = None; - - assert!(!open_demo_if_requested(&app_state, &mut demo_state).await); - assert!(demo_state.is_none()); - assert_eq!(app_state.lock().await.input_buffer, "/test please"); - } - - #[test] - fn picker_navigation_stops_at_both_ends_and_reaches_long_list_tail() { - let last = 127; - let mut selected = 0; - assert_eq!( - picker_selection_for_key(selected, last + 1, KeyCode::Up), - Some(0) - ); - for _ in 0..last { - selected = picker_selection_for_key(selected, last + 1, KeyCode::Down).unwrap(); - } - assert_eq!(selected, last); - assert_eq!( - picker_selection_for_key(selected, last + 1, KeyCode::Down), - Some(last) - ); - assert_eq!( - picker_selection_for_key(selected, last + 1, KeyCode::Up), - Some(last - 1) - ); - assert_eq!(picker_selection_for_key(0, 0, KeyCode::Down), Some(0)); - } - - #[test] - fn subagent_picker_left_selects_and_right_returns() { - assert_eq!( - subagent_picker_action(KeyCode::Left), - Some(SubagentPickerAction::Select) - ); - assert_eq!( - subagent_picker_action(KeyCode::Right), - Some(SubagentPickerAction::Close) - ); - assert_eq!( - subagent_picker_action(KeyCode::Enter), - Some(SubagentPickerAction::Select) - ); - } - - #[test] - fn tasks_panel_owns_navigation_log_stop_and_close_keys() { - use rustcode::controller::TasksPanelInput; - for (key, expected) in [ - (KeyCode::Up, Some(TasksPanelInput::Up)), - (KeyCode::Down, Some(TasksPanelInput::Down)), - (KeyCode::Enter, Some(TasksPanelInput::Open)), - (KeyCode::Esc, Some(TasksPanelInput::Back)), - (KeyCode::Char('x'), Some(TasksPanelInput::Stop)), - (KeyCode::Char('q'), Some(TasksPanelInput::Close)), - (KeyCode::Char('a'), None), - (KeyCode::Backspace, None), - ] { - assert_eq!(super::tasks_panel_input_for_key(key), expected, "{key:?}"); - } - } - - #[test] - fn right_from_an_empty_child_composer_returns_to_its_parent() { - let mut state = AppState::new(); - let child = rustcode::app::SubagentController - .spawn( - &mut state, - "child", - None, - None, - false, - Vec::new(), - None, - None, - ) - .raw(); - state.selected_subagent_id = Some(child); - assert_eq!(agent_context_return_target(&state, KeyCode::Right), Some(0)); - - state.input_buffer = "draft".to_owned(); - assert_eq!(agent_context_return_target(&state, KeyCode::Right), None); - } - - #[test] - fn command_picker_filter_includes_visible_fuzzy_group_matches() { - let expected = crate::ui::PALETTE_ITEMS - .iter() - .find(|item| item.group == "System") - .expect("palette has a System group"); - assert!( - filtered_command_picker_items("system") - .iter() - .any(|item| item.name == expected.name) - ); - } - - #[test] - fn picker_search_supports_composer_cursor_editing_without_splitting_unicode() { - let mut state = AppState::new(); - state.command_picker_search = "café tools".to_owned(); - state.command_picker_search_cursor = state.command_picker_search.len(); - state.command_picker_index = 7; - let key = |code, modifiers| KeyEvent::new(code, modifiers); - - assert!(handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Left, KeyModifiers::NONE) - )); - assert_eq!( - state.command_picker_index, 7, - "cursor motion keeps selection" - ); - assert!(handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Left, KeyModifiers::ALT) - )); - assert_eq!( - &state.command_picker_search[..state.command_picker_search_cursor], - "café " - ); - assert!(handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Char('X'), KeyModifiers::NONE) - )); - assert_eq!(state.command_picker_search, "café Xtools"); - assert_eq!( - state.command_picker_index, 0, - "query changes reset selection" - ); - assert!(handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Left, KeyModifiers::NONE) - )); - assert!(handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Delete, KeyModifiers::ALT) - )); - assert_eq!(state.command_picker_search, "café "); - assert_eq!(state.command_picker_search_cursor, "café ".len()); - assert!(handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Home, KeyModifiers::NONE) - )); - assert!(handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Char('a'), KeyModifiers::CONTROL) - )); - assert_eq!(state.command_picker_search_cursor, 0); - assert!(!handle_picker_search_key( - &mut state, - PickerSearchTarget::Command, - key(KeyCode::Up, KeyModifiers::NONE) - )); - } - - #[test] - fn mcp_editor_paste_uses_active_utf8_cursor_for_key_and_bracketed_paste() { - use crate::ui::keymap::{KeyAction, KeyMap}; - - let keymap = KeyMap::from_environment(); - for modifiers in [ - KeyModifiers::CONTROL, - KeyModifiers::SUPER, - KeyModifiers::META, - ] { - assert_eq!( - keymap.resolve(KeyEvent::new(KeyCode::Char('v'), modifiers)), - KeyAction::Paste - ); - } - - let mut edit_state = rustcode::app::McpEditState { - is_add: true, - edit_index: None, - name_input: "café".to_owned(), - command_input: String::new(), - args_input: String::new(), - active_field: 0, - cursor_pos: "caf".len(), - }; - // A pasted line break becomes a space: the field holds one line. - edit_state.insert_str("X\r\nY"); - assert_eq!(edit_state.name_input, "cafX Yé"); - assert_eq!(edit_state.cursor_pos, "cafX Y".len()); - } - - #[tokio::test] - async fn selection_copy_feedback_reports_backend_result_without_chat_message() { - let state = Arc::new(Mutex::new(AppState::new())); - for (result, expected) in [ - ( - ClipboardCopyStatus::Confirmed, - "Copied selection to clipboard", - ), - ( - ClipboardCopyStatus::Requested, - "Copy sent to terminal; paste to verify", - ), - (ClipboardCopyStatus::Failed, "Copy failed; try again"), - ] { - report_selection_copy(&state, "selected text", |text| { - assert_eq!(text, "selected text"); - result - }) - .await; - let state = state.lock().await; - assert_eq!(state.active_transient_notice(), Some(expected)); - assert!(state.history.is_empty()); - } - } - - #[test] - fn shift_tab_is_normalized_from_supported_terminal_events() { - assert!(is_shift_tab(KeyEvent::new( - KeyCode::BackTab, - KeyModifiers::NONE - ))); - assert!(is_shift_tab(KeyEvent::new( - KeyCode::Tab, - KeyModifiers::SHIFT - ))); - assert!(!is_shift_tab(KeyEvent::new( - KeyCode::Tab, - KeyModifiers::NONE - ))); - } - - #[test] - fn keyboard_range_only_owns_unmodified_or_shifted_arrows() { - assert!(is_keyboard_range_key(KeyEvent::new( - KeyCode::Left, - KeyModifiers::NONE - ))); - assert!(is_keyboard_range_key(KeyEvent::new( - KeyCode::Down, - KeyModifiers::SHIFT - ))); - assert!(!is_keyboard_range_key(KeyEvent::new( - KeyCode::Left, - KeyModifiers::ALT - ))); - assert!(!is_keyboard_range_key(KeyEvent::new( - KeyCode::Char('x'), - KeyModifiers::NONE - ))); - } - - #[test] - fn ordinary_composer_key_exits_keyboard_range_mode() { - let mut transcript = TranscriptState::default(); - let area = Rect::new(0, 0, 8, 1); - transcript - .selection - .refresh(area, &Buffer::empty(area), &[false]); - transcript.selection.begin_keyboard_with_snapshot( - crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( - &AppState::new(), - )), - 0, - ); - assert!(transcript.selection.is_keyboard_mode()); - assert!(selection_owns_key( - &transcript, - KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE) - )); - assert!(!selection_owns_key( - &transcript, - KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL) - )); - // Ctrl+C stays out of the selection's hands so it can arm the exit; - // Cmd+C stays out too, but takes the copy-only path. - assert!(is_copy_or_exit_chord(KeyEvent::new( - KeyCode::Char('c'), - KeyModifiers::CONTROL - ))); - assert!(is_cmd_copy_chord(KeyEvent::new( - KeyCode::Char('C'), - KeyModifiers::SUPER - ))); - assert!(!selection_owns_key( - &transcript, - KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE) - )); - clear_selection_for_composer_key( - &mut transcript, - KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE), - ); - assert!(!transcript.selection.is_keyboard_mode()); - assert!(!transcript.selection.is_active()); - } - - /// The advertised copy binding reaches the selection handler for both - /// mouse and keyboard selections, and `ctrl+c` without a selection falls - /// through to interrupt/exit (#1566). - #[test] - fn ctrl_c_copies_every_selection_and_still_reaches_the_exit_arm() { - use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; - - // The hint and the handler share this definition: the footer promises - // exactly the chord the handler owns. - assert_eq!(rustcode::controller::copy_selection_binding(), "ctrl+c"); - let copy = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL); - assert!(is_copy_or_exit_chord(copy)); - // Cmd+C is handled as copy-only; Control takes precedence when both - // modifiers arrive in the same event. - let cmd_copy = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::SUPER); - assert!(!is_copy_or_exit_chord(cmd_copy)); - assert!(is_cmd_copy_chord(cmd_copy)); - let mixed_copy = KeyEvent::new( - KeyCode::Char('c'), - KeyModifiers::SUPER | KeyModifiers::CONTROL, - ); - assert!(is_copy_or_exit_chord(mixed_copy)); - assert!(!is_cmd_copy_chord(mixed_copy)); - assert!(!is_copy_or_exit_chord(KeyEvent::new( - KeyCode::Char('c'), - KeyModifiers::NONE - ))); - - // A live selection does not take the chord away from the exit path, so - // copying and arming happen together. - let area = Rect::new(0, 0, 8, 1); - let mut buffer = Buffer::empty(area); - buffer.set_string(0, 0, "hello", ratatui::style::Style::default()); - - // Mouse selection. - let mut mouse = TranscriptState::default(); - mouse.selection.refresh(area, &buffer, &[false]); - let down = MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: 0, - row: 0, - modifiers: KeyModifiers::NONE, - }; - mouse.selection.mouse(down); - mouse.selection.mouse(MouseEvent { - kind: MouseEventKind::Drag(MouseButton::Left), - column: 3, - row: 0, - modifiers: KeyModifiers::NONE, - }); - mouse.selection.mouse(MouseEvent { - kind: MouseEventKind::Up(MouseButton::Left), - column: 3, - row: 0, - modifiers: KeyModifiers::NONE, - }); - assert!(mouse.selection.has_selection()); - assert!(!mouse.selection.is_keyboard_mode()); - assert_eq!(mouse.selection.selected_text().as_deref(), Some("hell")); - - // Keyboard selection offers the same copyable text. - let mut keyboard = TranscriptState::default(); - keyboard.selection.refresh(area, &buffer, &[false]); - keyboard.selection.begin_keyboard_with_snapshot( - crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( - &AppState::new(), - )), - 0, - ); - keyboard.selection.move_keyboard(KeyCode::Right); - assert!(keyboard.selection.has_selection()); - - // Esc is the only key the selection owns outright; the chord is handled - // before it so the double-press exit stays reachable. - assert!(!selection_owns_key(&mouse, copy)); - assert!(selection_owns_key( - &mouse, - KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE) - )); - - // No selection: the key is not owned, so the caller falls through to - // the existing interruption/exit behavior. - let idle = TranscriptState::default(); - assert!(!idle.selection.has_selection()); - assert!(!selection_owns_key( - &idle, - KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE) - )); - } - - /// Two presses of the chord must exit even while a selection is live. - /// - /// The selection handlers used to sit above the exit check and returned - /// early, so any selection made the double-press unreachable — and a - /// pinned selection survives a whole turn. - #[tokio::test] - async fn two_ctrl_c_presses_exit_while_a_selection_is_live() { - use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; - - let area = Rect::new(0, 0, 8, 1); - let mut buffer = Buffer::empty(area); - buffer.set_string(0, 0, "hello", ratatui::style::Style::default()); - - let mut transcript = TranscriptState::default(); - transcript.selection.refresh(area, &buffer, &[false]); - for event in [ - MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: 0, - row: 0, - modifiers: KeyModifiers::NONE, - }, - MouseEvent { - kind: MouseEventKind::Drag(MouseButton::Left), - column: 3, - row: 0, - modifiers: KeyModifiers::NONE, - }, - MouseEvent { - kind: MouseEventKind::Up(MouseButton::Left), - column: 3, - row: 0, - modifiers: KeyModifiers::NONE, - }, - ] { - transcript.selection.mouse(event); - } - assert!(transcript.selection.has_selection()); - - let app_state = Arc::new(Mutex::new(AppState::new())); - - // First press: copies and arms, without exiting. - assert!(matches!( - handle_copy_or_exit_chord(&app_state, &transcript).await, - InputFlow::ContinueIteration - )); - assert!(app_state.lock().await.ctrl_c_exit_armed()); - - // Second press inside the window exits. - assert!(matches!( - handle_copy_or_exit_chord(&app_state, &transcript).await, - InputFlow::Exit { update: false } - )); - } - - #[tokio::test] - async fn repeated_cmd_c_copies_selection_without_arming_exit() { - use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; - - let area = Rect::new(0, 0, 8, 1); - let mut buffer = Buffer::empty(area); - buffer.set_string(0, 0, "hello", ratatui::style::Style::default()); - let mut transcript = TranscriptState::default(); - // `/session` displays a fixed session panel whose selection is stored - // separately from the main transcript selection. - transcript.panel_selection_area = Some(area); - transcript.panel_selection_scrollable = false; - transcript.panel_selection.refresh(area, &buffer, &[false]); - for event in [ - MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: 0, - row: 0, - modifiers: KeyModifiers::NONE, - }, - MouseEvent { - kind: MouseEventKind::Drag(MouseButton::Left), - column: 3, - row: 0, - modifiers: KeyModifiers::NONE, - }, - MouseEvent { - kind: MouseEventKind::Up(MouseButton::Left), - column: 3, - row: 0, - modifiers: KeyModifiers::NONE, - }, - ] { - transcript.panel_selection.mouse(event); - } - assert_eq!( - transcript.panel_selection.selected_text().as_deref(), - Some("hell") - ); - - let app_state = Arc::new(Mutex::new(AppState::new())); - for _ in 0..2 { - let copied = std::sync::Arc::new(std::sync::Mutex::new(None)); - let copied_by_backend = copied.clone(); - assert!(matches!( - handle_cmd_copy_chord_with(&app_state, &transcript, move |text| { - *copied_by_backend.lock().unwrap() = Some(text.to_owned()); - rustcode::clipboard::ClipboardCopyStatus::Confirmed - }) - .await, - InputFlow::ContinueIteration - )); - assert_eq!(copied.lock().unwrap().as_deref(), Some("hell")); - assert!(!app_state.lock().await.ctrl_c_exit_armed()); - } - } - - #[tokio::test] - async fn cmd_c_copies_a_composer_selection_without_hanging() { - let app_state = Arc::new(Mutex::new(AppState::new())); - { - let mut state = app_state.lock().await; - state.input_buffer = "see ![image](file:///tmp/a.png) here".to_owned(); - state.composer_selection_anchor = Some(0); - state.cursor_position = 3; - } - let copied = std::sync::Arc::new(std::sync::Mutex::new(None)); - let copied_by_backend = copied.clone(); - let flow = tokio::time::timeout( - std::time::Duration::from_secs(2), - handle_cmd_copy_chord_with(&app_state, &TranscriptState::default(), move |text| { - *copied_by_backend.lock().unwrap() = Some(text.to_owned()); - rustcode::clipboard::ClipboardCopyStatus::Confirmed - }), - ) - .await - .expect("copying a composer selection must not deadlock on the state lock"); - assert!(matches!(flow, InputFlow::ContinueIteration)); - assert_eq!(copied.lock().unwrap().as_deref(), Some("see")); - } - - #[tokio::test] - async fn cmd_c_without_app_selection_never_arms_exit() { - let app_state = Arc::new(Mutex::new(AppState::new())); - let transcript = TranscriptState::default(); - // Cmd+C also breaks a pending Ctrl+C confirmation. A later Ctrl+C - // starts a fresh sequence instead of exiting unexpectedly. - assert!(!rustcode::app::handle_ctrl_c(&app_state).await); - assert!(app_state.lock().await.ctrl_c_exit_armed()); - for _ in 0..2 { - assert!(matches!( - handle_cmd_copy_chord(&app_state, &transcript).await, - InputFlow::ContinueIteration - )); - assert!(!app_state.lock().await.ctrl_c_exit_armed()); - } - assert!(!rustcode::app::handle_ctrl_c(&app_state).await); - assert!(app_state.lock().await.ctrl_c_exit_armed()); - } - - /// With no selection the chord is purely the exit affordance. - #[tokio::test] - async fn two_ctrl_c_presses_exit_with_no_selection() { - let transcript = TranscriptState::default(); - let app_state = Arc::new(Mutex::new(AppState::new())); - - assert!(matches!( - handle_copy_or_exit_chord(&app_state, &transcript).await, - InputFlow::ContinueIteration - )); - assert!(app_state.lock().await.ctrl_c_exit_armed()); - assert!(matches!( - handle_copy_or_exit_chord(&app_state, &transcript).await, - InputFlow::Exit { update: false } - )); - } - - /// Keyboard-select mode owns the chord with a collapsed caret: nothing to - /// copy, but it must still report progress and arm the exit. - #[tokio::test] - async fn collapsed_keyboard_selection_reports_instead_of_failing_silently() { - let mut transcript = TranscriptState::default(); - let area = Rect::new(0, 0, 8, 1); - transcript - .selection - .refresh(area, &Buffer::empty(area), &[false]); - transcript.selection.begin_keyboard_with_snapshot( - crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( - &AppState::new(), - )), - 0, - ); - assert!(transcript.selection.is_keyboard_mode()); - assert_eq!(transcript.selection.selected_text(), None); - - let app_state = Arc::new(Mutex::new(AppState::new())); - assert!(matches!( - handle_copy_or_exit_chord(&app_state, &transcript).await, - InputFlow::ContinueIteration - )); - assert!(app_state.lock().await.ctrl_c_exit_armed()); - } - - #[test] - fn command_panel_wheel_stops_at_bottom_and_reverses_immediately() { - let mut transcript = TranscriptState::default(); - transcript.panel_selection_area = Some(Rect::new(0, 0, 40, 10)); - transcript.panel_selection_scrollable = true; - transcript.panel_max_scroll_row = 7; - let mut row = 0; - scroll_panel_selection(&mut transcript, &mut row, 1); - assert_eq!(row, 1, "each wheel event moves one row"); - for _ in 0..100 { - scroll_panel_selection(&mut transcript, &mut row, 1); - } - assert_eq!(row, 7); - scroll_panel_selection(&mut transcript, &mut row, -1); - assert_eq!(row, 6, "no invisible scroll debt at the bottom"); - transcript.panel_max_scroll_row = 0; - scroll_panel_selection(&mut transcript, &mut row, 1); - assert_eq!(row, 0, "short or empty replacement content cannot scroll"); - } - - #[test] - fn command_panel_key_steps_clamp_before_and_after_movement() { - for step in [1, 10] { - let mut row = 0; - for _ in 0..100 { - scroll_command_panel(&mut row, 23, step); - } - assert_eq!(row, 23); - scroll_command_panel(&mut row, 23, -step); - assert_eq!(row, 23 - step as u16); - row = u16::MAX; - scroll_command_panel(&mut row, 15, -step); - assert_eq!(row, 15 - step as u16, "resize clamps before moving up"); - scroll_command_panel(&mut row, 0, step); - assert_eq!(row, 0); - } - } - - #[test] - fn informational_panel_selection_keeps_its_range_across_wheel_scroll() { - let area = Rect::new(0, 0, 12, 1); - let mut buffer = Buffer::empty(area); - buffer.set_string(0, 0, "panel text", ratatui::style::Style::default()); - - let mut transcript = TranscriptState::default(); - transcript.selection.refresh(area, &buffer, &[false]); - transcript.selection.mouse(MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: 0, - row: 0, - modifiers: KeyModifiers::NONE, - }); - transcript.selection.mouse(MouseEvent { - kind: MouseEventKind::Drag(MouseButton::Left), - column: 2, - row: 0, - modifiers: KeyModifiers::NONE, - }); - transcript.selection.mouse(MouseEvent { - kind: MouseEventKind::Up(MouseButton::Left), - column: 2, - row: 0, - modifiers: KeyModifiers::NONE, - }); - let transcript_text = transcript.selection.selected_text(); - - transcript.panel_selection_area = Some(area); - transcript.panel_selection.refresh(area, &buffer, &[false]); - transcript.panel_selection.mouse(MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: 6, - row: 0, - modifiers: KeyModifiers::NONE, - }); - transcript.panel_selection.mouse(MouseEvent { - kind: MouseEventKind::Drag(MouseButton::Left), - column: 9, - row: 0, - modifiers: KeyModifiers::NONE, - }); - transcript.panel_selection.mouse(MouseEvent { - kind: MouseEventKind::Up(MouseButton::Left), - column: 9, - row: 0, - modifiers: KeyModifiers::NONE, - }); - - assert_eq!( - transcript.panel_selection.selected_text().as_deref(), - Some("text") - ); - assert_eq!(transcript.selection.selected_text(), transcript_text); - let mut modal_scroll_row = 0; - assert!(scroll_panel_selection( - &mut transcript, - &mut modal_scroll_row, - 1, - )); - assert_eq!(modal_scroll_row, 0); - assert_eq!( - transcript.panel_selection.selected_text().as_deref(), - Some("text"), - "wheel input over a fixed info panel preserves the copyable range" - ); - clear_selection_for_composer_key( - &mut transcript, - KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE), - ); - assert!(!transcript.panel_selection.has_selection()); - assert_eq!(transcript.selection.selected_text(), transcript_text); - } - - #[test] - fn composer_keys_keep_reading_position_and_escape_returns_to_latest() { - let mut transcript = TranscriptState::default(); - transcript.scroll_up(3); - assert!(!return_to_latest_for_key( - &mut transcript, - KeyCode::Char('x') - )); - assert_eq!(transcript.scroll_rows(), 3); - - transcript.scroll_up(2); - assert!(return_to_latest_for_key(&mut transcript, KeyCode::Esc)); - assert_eq!(transcript.scroll_rows(), 0); - } - - #[test] - fn typing_and_submission_end_pinned_selection_while_transcript_navigation_keeps_it() { - let mut transcript = TranscriptState::default(); - let area = Rect::new(0, 0, 8, 2); - let buffer = Buffer::empty(area); - transcript.selection.refresh(area, &buffer, &[false, false]); - let down = MouseEvent { - kind: MouseEventKind::Down(MouseButton::Left), - column: 0, - row: 0, - modifiers: KeyModifiers::NONE, - }; - let begin = |transcript: &mut TranscriptState| { - transcript.selection.begin_with_snapshot( - down, - crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( - &AppState::new(), - )), - transcript.scroll_rows(), - ); - assert!(transcript.selection.is_active()); - }; - begin(&mut transcript); - assert!(is_transcript_navigation(KeyEvent::new( - KeyCode::PageUp, - KeyModifiers::NONE - ))); - clear_selection_for_composer_key( - &mut transcript, - KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE), - ); - assert!(transcript.selection.is_active()); - clear_selection_for_composer_key( - &mut transcript, - KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE), - ); - assert!(!transcript.selection.is_active()); - begin(&mut transcript); - clear_selection_for_composer_key( - &mut transcript, - KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), - ); - assert!(!transcript.selection.is_active()); - } - - /// The Ctrl/Cmd+V fallback and the keymap paste share one insert helper, - /// so both land the same buffer for the same clipboard text at and just - /// below the large-paste threshold (#1527). - #[test] - fn clipboard_paste_paths_agree_on_threshold_and_newlines() { - let composer = Composer::default(); - for payload in [ - "y".repeat(299), - "z".repeat(300), - "one\r\ntwo\rthree".to_owned(), - ] { - let mut fallback = AppState::new(); - insert_clipboard_paste(&composer, &mut fallback, &payload); - - let mut keymap = AppState::new(); - composer.handle_paste(&mut keymap, &payload); - - assert_eq!( - fallback.input_buffer, keymap.input_buffer, - "fallback and keymap paste must insert the same buffer for {payload:?}" - ); - } - } - - #[test] - fn clipboard_paste_below_threshold_inserts_verbatim() { - let mut state = AppState::new(); - insert_clipboard_paste(&Composer::default(), &mut state, &"y".repeat(299)); - assert_eq!(state.input_buffer, "y".repeat(299)); - - let mut large = AppState::new(); - insert_clipboard_paste(&Composer::default(), &mut large, &"y".repeat(300)); - assert!(large.input_buffer.starts_with("")); - } -} +mod tests; diff --git a/harness/src/runtime/input/keyboard.rs b/harness/src/runtime/input/keyboard.rs new file mode 100644 index 000000000..7988e6798 --- /dev/null +++ b/harness/src/runtime/input/keyboard.rs @@ -0,0 +1,1545 @@ +use super::*; + +pub(super) async fn handle_key( + key: KeyEvent, + ctx: InputContext<'_>, +) -> Result> { + let InputContext { + terminal_runtime, + app_state, + client, + current_cancel_token, + needs_redraw, + frame_requester, + transcript_state, + app_event_sender, + agent_ui_event_sender, + composer, + demo_state, + .. + } = ctx; + *needs_redraw = true; + app_state.lock().await.mark_user_activity(); + let is_ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL); + let is_cmd = key.modifiers.contains(event::KeyModifiers::SUPER); + + if is_ctrl && key.code == KeyCode::Char(' ') && !app_state.lock().await.modal_open() { + let snapshot = { + let state = app_state.lock().await; + ui::render_snapshot::render_snapshot(&rustcode::controller::render_state(&state)) + }; + transcript_state + .selection + .begin_keyboard_with_snapshot(snapshot, transcript_state.scroll_rows()); + return Ok(InputFlow::ContinueIteration); + } + if transcript_state.panel_selection_area.is_none() + && transcript_state.selection.is_keyboard_mode() + { + if is_keyboard_range_key(key) { + transcript_state.selection.move_keyboard(key.code); + return Ok(InputFlow::ContinueIteration); + } + } + + // Ctrl+C runs before selection handlers so the chord can copy + // and retain its double-press exit behavior. Cmd+C is copy-only. + if is_copy_or_exit_chord(key) { + return Ok(handle_copy_or_exit_chord(&app_state, transcript_state).await); + } + if is_cmd_copy_chord(key) { + return Ok(handle_cmd_copy_chord(&app_state, transcript_state).await); + } + + if selection_owns_key(transcript_state, key) { + let selection = if transcript_state.panel_selection_area.is_some() { + &mut transcript_state.panel_selection + } else { + &mut transcript_state.selection + }; + selection.clear(); + return Ok(InputFlow::ContinueIteration); + } + + // Composer selection owns Esc (#1493, #1566). The copy chord is + // already handled above so it can also arm the exit. + if key.code == KeyCode::Esc && app_state.lock().await.has_composer_selection() { + app_state.lock().await.clear_composer_selection(); + return Ok(InputFlow::ContinueIteration); + } + + let transcript_navigation = is_transcript_navigation(key); + clear_selection_for_composer_key(transcript_state, key); + + { + let mut s = app_state.lock().await; + s.clear_ctrl_c_exit_arming(); + } + + if (is_ctrl || is_cmd) && (key.code == KeyCode::Char('k') || key.code == KeyCode::Char('K')) { + let mut s = app_state.lock().await; + s.request_clear_screen(); + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + if is_ctrl && (key.code == KeyCode::Char('l') || key.code == KeyCode::Char('L')) { + let mut s = app_state.lock().await; + s.request_clear_screen(); + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + + { + let selected = { + let state = app_state.lock().await; + state + .show_update_prompt + .then_some(state.update_prompt_index) + }; + if let Some(selected) = selected { + match key.code { + KeyCode::Up => { + let mut state = app_state.lock().await; + state.update_prompt_index = state.update_prompt_index.saturating_sub(1); + } + KeyCode::Down => { + let mut state = app_state.lock().await; + state.update_prompt_index = (state.update_prompt_index + 1).min(2); + } + KeyCode::Enter => { + let decision = match selected { + 0 => UpdateDecision::UpdateNow, + 1 => UpdateDecision::Skip, + _ => UpdateDecision::SkipUntilNextVersion, + }; + let _ = app_event_sender.send(AppEvent::UpdateDecision(decision)); + } + KeyCode::Esc => { + let _ = app_event_sender.send(AppEvent::UpdateDecision(UpdateDecision::Skip)); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + } + + { + let selected = { + let s = app_state.lock().await; + (s.status == AppStatus::AwaitingToolConfirmation && !s.user_overlay_open()).then(|| { + let prefix = s + .pending_tool_confirmation + .as_ref() + .filter(|items| { + items.len() == 1 && items[0].rememberable_prefix.is_some() + || items.len() == 1 && items[0].forbidden_prefix.is_some() + }) + .and_then(|items| items[0].rememberable_prefix.clone()); + let forbidden_prefix = s + .pending_tool_confirmation + .as_ref() + .filter(|items| items.len() == 1) + .and_then(|items| items[0].forbidden_prefix.clone()); + (s.tool_confirmation_selected, prefix, forbidden_prefix) + }) + }; + if let Some((selected, prefix, forbidden_prefix)) = selected { + if let Some(event) = ui::approval_event_for_key( + key, + selected, + prefix.as_deref(), + forbidden_prefix.as_deref(), + ) { + let _ = app_event_sender.send(event); + } else { + if is_shift_tab(key) { + let mut s = app_state.lock().await; + s.overlays().toggle_auto_confirm(); + s.record_auto_confirm(); + } else { + match key.code { + KeyCode::Tab => { + let mut s = app_state.lock().await; + s.overlays().toggle_auto_confirm(); + s.record_auto_confirm(); + } + KeyCode::Up => { + let mut s = app_state.lock().await; + s.overlays().move_approval_selection(-1); + } + KeyCode::Down => { + let mut s = app_state.lock().await; + s.overlays().move_approval_selection(1); + } + _ => {} + } + } + } + return Ok(InputFlow::ContinueIteration); + } + } + + { + // A device asks to share this session. Plain keys answer + // it so a stray keystroke cannot leak into the composer + // while the terminal decides; chords keep working. + let share_open = app_state.lock().await.pending_share_prompt.is_some(); + if share_open { + if key + .modifiers + .intersects(KeyModifiers::CONTROL | KeyModifiers::SUPER | KeyModifiers::ALT) + { + // Fall through to normal handling below. + } else { + match key.code { + KeyCode::Char('y') | KeyCode::Char('Y') => { + app_state.lock().await.share_decision = Some(true); + } + KeyCode::Char('n') | KeyCode::Char('N') | KeyCode::Esc => { + app_state.lock().await.share_decision = Some(false); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + } + } + + { + let s = app_state.lock().await; + if s.status == AppStatus::AwaitingQuestion && !s.user_overlay_open() { + let typing = s + .pending_question + .as_ref() + .map(|q| q.custom_input.is_some()) + .unwrap_or(false); + drop(s); + + if typing { + let action = match key.code { + KeyCode::Tab => { + app_state.lock().await.focus_question(1); + QuestionEditAction::Handled + } + KeyCode::BackTab => { + app_state.lock().await.focus_question(-1); + QuestionEditAction::Handled + } + KeyCode::Esc => { + let mut s = app_state.lock().await; + if let Some(q) = s.pending_question.as_mut() { + q.custom_input = None; + q.custom_cursor = 0; + q.custom_draft.clear(); + } + QuestionEditAction::Handled + } + _ => { + let mut s = app_state.lock().await; + s.pending_question + .as_mut() + .map_or(QuestionEditAction::Handled, |q| { + handle_question_custom_key(q, key) + }) + } + }; + match action { + QuestionEditAction::Submit => { + let answer_event = { + let s = app_state.lock().await; + s.pending_question + .as_ref() + .map(ui::question_custom_answer_event) + }; + if let Some(answer_event) = answer_event { + let _ = app_event_sender.send(answer_event); + } + } + QuestionEditAction::Paste => { + if let Some(text) = rustcode::clipboard::read_text_from_clipboard() { + let mut s = app_state.lock().await; + if let Some(q) = s.pending_question.as_mut() { + insert_question_answer_text(q, &text); + } + } + } + QuestionEditAction::Handled => {} + } + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + + match key.code { + KeyCode::Up => { + let mut s = app_state.lock().await; + if let Some(q) = s.pending_question.as_mut() { + q.selected = q.selected.saturating_sub(1); + } + } + KeyCode::Down => { + let mut s = app_state.lock().await; + if let Some(q) = s.pending_question.as_mut() { + let last = q.options.len(); + q.selected = (q.selected + 1).min(last); + if q.selected == last { + q.activate_custom_input(); + } + } + } + KeyCode::Tab => { + let mut s = app_state.lock().await; + s.focus_question(1); + } + KeyCode::BackTab => { + let mut s = app_state.lock().await; + s.focus_question(-1); + } + KeyCode::Char(' ') => { + let mut s = app_state.lock().await; + if let Some(q) = s.pending_question.as_mut() { + if q.selected == q.options.len() { + q.activate_custom_input(); + } else if q.is_multi_select + && let Some(c) = q.chosen.get_mut(q.selected) + { + *c = !*c; + } + } + } + KeyCode::Char(d @ '1'..='9') => { + let idx = (d as usize) - ('1' as usize); + let mut s = app_state.lock().await; + if let Some(q) = s.pending_question.as_mut() + && idx < q.options.len() + { + q.selected = idx; + if q.is_multi_select { + if let Some(c) = q.chosen.get_mut(idx) { + *c = !*c; + } + } else { + let answer_event = ui::question_answer_event(q); + if let Some(answer_event) = answer_event { + let _ = app_event_sender.send(answer_event); + } + } + } + } + KeyCode::Char(c) => { + let mut s = app_state.lock().await; + if let Some(q) = s.pending_question.as_mut() { + if q.selected == q.options.len() { + q.activate_custom_input(); + q.insert_char(c); + } + } + } + KeyCode::Enter => { + let mut s = app_state.lock().await; + let is_custom_slot = s + .pending_question + .as_ref() + .map(|q| q.selected == q.options.len()) + .unwrap_or(false); + if is_custom_slot { + if let Some(q) = s.pending_question.as_mut() { + q.activate_custom_input(); + } + } else if let Some(q) = s.pending_question.as_ref() + && let Some(answer_event) = ui::question_answer_event(q) + { + let _ = app_event_sender.send(answer_event); + } + } + KeyCode::Esc => { + let _ = app_event_sender.send(ui::question_cancel_event()); + } + _ => {} + } + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + } + + { + let s = app_state.lock().await; + if s.settings_picker == Some(rustcode::controller::SettingsPicker::ScrollSpeed) { + drop(s); + let mut s = app_state.lock().await; + if let Some(lines) = scroll_speed_picker_key(&mut s, key.code) { + s.config.scroll_lines = Some(lines); + rustcode::controller::save_config(&s.config); + s.close_modal_status(); + s.set_transient_notice(rustcode::controller::scroll_speed_notice(lines)); + } + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + + if s.settings_picker == Some(rustcode::controller::SettingsPicker::Verbosity) { + drop(s); + match key.code { + KeyCode::Up => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_sub(1); + } + KeyCode::Down => { + let mut s = app_state.lock().await; + s.modal_picker_index = s + .modal_picker_index + .saturating_add(1) + .min(Verbosity::ALL.len() - 1); + } + KeyCode::Enter => { + let mut s = app_state.lock().await; + let new_verbosity = Verbosity::ALL + .get(s.modal_picker_index) + .cloned() + .unwrap_or_default(); + s.verbosity = new_verbosity.clone(); + s.config.verbosity = new_verbosity; + rustcode::controller::save_config(&s.config); + s.close_modal_status(); + } + KeyCode::Esc => { + let mut s = app_state.lock().await; + s.close_modal_status(); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + + if s.settings_picker == Some(rustcode::controller::SettingsPicker::Thinking) { + drop(s); + match key.code { + KeyCode::Up => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_sub(1); + } + KeyCode::Down => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_add(1).min(2); // 0 on, 1 off, 2 default + } + KeyCode::Enter => { + let mut s = app_state.lock().await; + let value = match s.modal_picker_index { + 0 => Some(true), + 1 => Some(false), + _ => None, + }; + if let Some(profile) = s.active_model_profile_mut() { + profile.enable_thinking = value; + } + rustcode::controller::save_config(&s.config); + s.close_modal_status(); + } + KeyCode::Esc => { + let mut s = app_state.lock().await; + s.close_modal_status(); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + + if s.settings_picker == Some(rustcode::controller::SettingsPicker::Effort) { + drop(s); + match key.code { + KeyCode::Up => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_sub(1); + } + KeyCode::Down => { + let mut s = app_state.lock().await; + let last = + rustcode::controller::effort_choices(s.active_model_profile().as_ref()) + .len() + .saturating_sub(1); + s.modal_picker_index = s.modal_picker_index.saturating_add(1).min(last); + } + KeyCode::Enter => { + let mut s = app_state.lock().await; + let choices = + rustcode::controller::effort_choices(s.active_model_profile().as_ref()); + let value = choices.get(s.modal_picker_index).cloned().flatten(); + s.set_active_reasoning_effort(value); + s.close_modal_status(); + } + KeyCode::Esc => { + let mut s = app_state.lock().await; + s.close_modal_status(); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + + if s.settings_picker == Some(rustcode::controller::SettingsPicker::Protocol) { + drop(s); + match key.code { + KeyCode::Up => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_sub(1); + } + KeyCode::Down => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_add(1).min(2); // 0 json, 1 native, 2 apinative + } + KeyCode::Enter => { + let mut s = app_state.lock().await; + let (protocol, label) = match s.modal_picker_index { + 0 => (rustcode::config::ToolProtocol::Json, "JSON (```tool)"), + 1 => ( + rustcode::config::ToolProtocol::Native, + "Native ([TOOL_CALLS])", + ), + _ => ( + rustcode::config::ToolProtocol::ApiNative, + "ApiNative (schema in request `tools`, structured `tool_calls` back)", + ), + }; + let url = s.api_base_url.clone(); + let scoped = s + .config + .models + .iter_mut() + .find(|profile| profile.url == url); + if let Some(profile) = scoped { + profile.tool_protocol = Some(protocol); + } else { + s.config.tool_protocol = protocol; + } + rustcode::controller::save_config(&s.config); + let active_model = s.model_name.clone(); + s.set_transient_notice(format!( + "Switched tool protocol to {label} for model '{active_model}'." + )); + s.close_modal_status(); + } + KeyCode::Esc => { + let mut s = app_state.lock().await; + s.close_modal_status(); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + + if s.settings_picker == Some(rustcode::controller::SettingsPicker::Yolo) { + drop(s); + match key.code { + KeyCode::Up => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_sub(1); + } + KeyCode::Down => { + let mut s = app_state.lock().await; + s.modal_picker_index = s.modal_picker_index.saturating_add(1).min(1); // 0 on, 1 off + } + KeyCode::Enter => { + let mut s = app_state.lock().await; + let enable = s.modal_picker_index == 0; + s.set_auto_confirm(enable); + let status = if enable { "enabled" } else { "disabled" }; + s.set_transient_notice(format!("YOLO mode {status}")); + s.close_modal_status(); + } + KeyCode::Esc => { + let mut s = app_state.lock().await; + s.close_modal_status(); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + } + + let mut s = app_state.lock().await; + if s.show_subagent_picker { + let total = s.subagents.len() + 1; + match subagent_picker_action(key.code) { + Some(SubagentPickerAction::Close) => { + s.show_subagent_picker = false; + } + Some(SubagentPickerAction::MoveUp) => { + s.subagent_picker_index = + picker_selection_for_key(s.subagent_picker_index, total, KeyCode::Up) + .unwrap_or(s.subagent_picker_index); + } + Some(SubagentPickerAction::MoveDown) => { + s.subagent_picker_index = + picker_selection_for_key(s.subagent_picker_index, total, KeyCode::Down) + .unwrap_or(s.subagent_picker_index); + } + Some(SubagentPickerAction::Select) => { + let selected = s.subagent_picker_index.min(total.saturating_sub(1)); + let id = if selected == 0 { + 0 + } else { + s.subagents[selected - 1].id + }; + s.show_subagent_picker = false; + drop(s); + let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); + return Ok(InputFlow::ContinueIteration); + } + None => {} + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.tasks_panel.is_some() { + if let Some(input) = tasks_panel_input_for_key(key.code) { + rustcode::controller::tasks_panel_input(&mut s, input); + } + return Ok(InputFlow::ContinueIteration); + } + if s.command_panel.is_some() { + match key.code { + KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') => { + s.command_panel = None; + } + KeyCode::Up | KeyCode::Down | KeyCode::PageUp | KeyCode::PageDown => { + let delta = match key.code { + KeyCode::Up => -1, + KeyCode::Down => 1, + KeyCode::PageUp => -10, + _ => 10, + }; + scroll_command_panel( + &mut s.modal_scroll_row, + transcript_state.panel_max_scroll_row, + delta, + ); + } + _ => {} + } + return Ok(InputFlow::ContinueIteration); + } + if s.show_context_modal { + match key.code { + KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') => { + s.show_context_modal = false; + } + _ => {} + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.show_status_modal { + if matches!( + key.code, + KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') + ) { + s.show_status_modal = false; + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.show_stats_modal { + if matches!( + key.code, + KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') + ) { + s.show_stats_modal = false; + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.show_session_modal { + if matches!( + key.code, + KeyCode::Esc | KeyCode::Enter | KeyCode::Char('q') | KeyCode::Char('Q') + ) { + s.show_session_modal = false; + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.show_history_picker { + // Ctrl+D triggers delete confirmation overlay + if key.modifiers.contains(event::KeyModifiers::CONTROL) && key.code == KeyCode::Char('d') { + let idx = s + .history_picker_index + .min(s.history_picker_sessions.len().saturating_sub(1)); + s.pending_delete_session_idx = Some(idx); + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + // Confirmation overlay for delete + if let Some(del_idx) = s.pending_delete_session_idx { + match key.code { + KeyCode::Char('y') | KeyCode::Enter => { + let action = s + .history_picker_sessions + .get(del_idx) + .and_then(rustcode::app::session_controller::session_id_from_meta) + .map(rustcode::app::events::SessionAction::Id); + s.pending_delete_session_idx = None; + if let Some(action) = action { + let _ = app_event_sender.send(AppEvent::DeleteSession(action)); + } + } + KeyCode::Esc | KeyCode::Char('n') => { + s.pending_delete_session_idx = None; + } + _ => {} + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + match key.code { + KeyCode::Esc => { + s.show_history_picker = false; + } + KeyCode::Up => { + let len = s.history_picker_sessions.len(); + s.history_picker_index = + picker_selection_for_key(s.history_picker_index, len, key.code) + .unwrap_or(s.history_picker_index); + } + KeyCode::Down => { + let len = s.history_picker_sessions.len(); + s.history_picker_index = + picker_selection_for_key(s.history_picker_index, len, key.code) + .unwrap_or(s.history_picker_index); + } + KeyCode::Enter => { + let idx = s + .history_picker_index + .min(s.history_picker_sessions.len().saturating_sub(1)); + if let Some(action) = s + .history_picker_sessions + .get(idx) + .and_then(rustcode::app::session_controller::session_id_from_meta) + .map(rustcode::app::events::SessionAction::Id) + { + let _ = app_event_sender.send(AppEvent::ResumeSession(action)); + } + } + _ => {} + } + + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if let Some(panel) = s.skills_panel.as_mut() { + match key.code { + KeyCode::Esc => s.skills_panel = None, + KeyCode::Up | KeyCode::Down => { + let next = picker_selection_for_key(panel.selected, panel.entries.len(), key.code) + .unwrap_or(panel.selected); + panel.select(next); + panel.notice = None; + } + KeyCode::Enter | KeyCode::Char(' ') => { + // Keep the in-memory config in step so a later + // full save cannot write the old list back. + if let Some(disabled) = panel.toggle_selected() { + s.config.disabled_skills = disabled; + } + } + _ => {} + } + drop(s); + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + + if s.show_mcp_config { + let (existing_mcp_always_include, existing_mcp_client_id, existing_mcp_timeout) = s + .mcp_edit_state + .as_ref() + .and_then(|edit_state| edit_state.edit_index) + .and_then(|idx| s.config.mcp_servers.get(idx)) + .map(|server| { + ( + server.always_include, + server.client_id.clone(), + server.timeout_secs, + ) + }) + .unwrap_or_default(); + if let Some(ref mut edit_state) = s.mcp_edit_state { + if crate::ui::keymap::KeyMap::from_environment().resolve(key) + == crate::ui::keymap::KeyAction::Paste + { + // Text only: an image marker has no place in a + // server name or command. + if let Some(text) = rustcode::clipboard::read_text_from_clipboard() { + edit_state.insert_str(&text); + } + drop(s); + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + match key.code { + KeyCode::Esc => { + s.mcp_edit_state = None; + } + KeyCode::Up => { + let prev = if edit_state.active_field == 0 { + 2 + } else { + edit_state.active_field - 1 + }; + edit_state.set_active_field(prev); + } + KeyCode::Down | KeyCode::Tab => { + let next = (edit_state.active_field + 1) % 3; + edit_state.set_active_field(next); + } + KeyCode::Enter => { + let name = edit_state.name_input.trim().to_string(); + let command = edit_state.command_input.trim().to_string(); + let args = edit_state + .args_input + .split_whitespace() + .map(|s| s.to_string()) + .collect::>(); + + // An http(s) value in the command field declares a + // remote Streamable HTTP server; anything else is + // spawned over stdio. + let remote = command.starts_with("http://") || command.starts_with("https://"); + if !name.is_empty() && !command.is_empty() { + let url = remote.then(|| command.clone()); + let new_srv = rustcode::config::McpServerConfig { + name: name.clone(), + command: if remote { String::new() } else { command }, + // Arguments only apply to stdio servers. + args: if remote { Vec::new() } else { args }, + env: std::collections::HashMap::new(), + url, + headers: std::collections::HashMap::new(), + client_id: existing_mcp_client_id, + enabled: true, + always_include: existing_mcp_always_include, + timeout_secs: existing_mcp_timeout, + }; + + if edit_state.is_add { + s.config.mcp_servers.push(new_srv); + } else if let Some(idx) = edit_state.edit_index + && idx < s.config.mcp_servers.len() + { + let old_name = s.config.mcp_servers[idx].name.clone(); + s.config.mcp_servers[idx] = new_srv; + if old_name != name { + rustcode::mcp::shutdown_server(&old_name).await; + } + } + + rustcode::controller::save_config(&s.config); + + let name_clone = name.clone(); + tokio::spawn(async move { + let _ = rustcode::mcp::start_server_by_name(&name_clone).await; + }); + + s.mcp_edit_state = None; + } + } + // Everything else edits the active field with + // the keys every other text field uses. + _ => { + let action = crate::ui::keymap::KeyMap::from_environment().resolve(key); + if let Some(edit) = action.text_edit(&mut [0; 4]) { + edit_state.edit(edit); + } + } + } + } else { + match key.code { + KeyCode::Esc => { + s.show_mcp_config = false; + } + KeyCode::Up => { + let len = s.config.mcp_servers.len(); + s.mcp_picker_index = + picker_selection_for_key(s.mcp_picker_index, len, key.code) + .unwrap_or(s.mcp_picker_index); + } + KeyCode::Down => { + let len = s.config.mcp_servers.len(); + s.mcp_picker_index = + picker_selection_for_key(s.mcp_picker_index, len, key.code) + .unwrap_or(s.mcp_picker_index); + } + KeyCode::Char('a') | KeyCode::Char('A') => { + s.mcp_edit_state = Some(rustcode::app::McpEditState { + is_add: true, + edit_index: None, + name_input: String::new(), + command_input: String::new(), + args_input: String::new(), + active_field: 0, + cursor_pos: 0, + }); + } + KeyCode::Char('e') | KeyCode::Char('E') => { + let idx = s.mcp_picker_index; + if let Some(srv) = s.config.mcp_servers.get(idx) { + s.mcp_edit_state = Some(rustcode::app::McpEditState { + is_add: false, + edit_index: Some(idx), + name_input: srv.name.clone(), + command_input: if srv.is_remote() { + srv.url.clone().unwrap_or_default() + } else { + srv.command.clone() + }, + args_input: srv.args.join(" "), + active_field: 0, + cursor_pos: srv.name.len(), + }); + } + } + KeyCode::Char('d') | KeyCode::Char('D') => { + let idx = s.mcp_picker_index; + if idx < s.config.mcp_servers.len() { + let removed = s.config.mcp_servers.remove(idx); + rustcode::controller::save_config(&s.config); + let name_clone = removed.name.clone(); + tokio::spawn(async move { + rustcode::mcp::shutdown_server(&name_clone).await; + }); + if s.mcp_picker_index >= s.config.mcp_servers.len() + && s.mcp_picker_index > 0 + { + s.mcp_picker_index -= 1; + } + } + } + KeyCode::Enter => { + let idx = s.mcp_picker_index; + if let Some(srv) = s.config.mcp_servers.get_mut(idx) { + srv.enabled = !srv.enabled; + let name_clone = srv.name.clone(); + let enabled = srv.enabled; + rustcode::controller::save_config(&s.config); + tokio::spawn(async move { + rustcode::controller::apply_mcp_toggle(&name_clone, enabled).await; + }); + } + } + _ => {} + } + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.show_model_picker { + if crate::ui::keymap::KeyMap::from_environment().resolve(key) + == crate::ui::keymap::KeyAction::Paste + { + if let Some(payload) = clipboard_paste_payload() { + insert_picker_search_text(&mut s, PickerSearchTarget::Model, &payload); + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + match key.code { + KeyCode::Esc => { + s.show_model_picker = false; + } + KeyCode::Up => { + let len = rustcode::app::get_picker_items_count(&s); + s.model_picker_index = + picker_selection_for_key(s.model_picker_index, len, key.code) + .unwrap_or(s.model_picker_index); + } + KeyCode::Down => { + let len = rustcode::app::get_picker_items_count(&s); + s.model_picker_index = + picker_selection_for_key(s.model_picker_index, len, key.code) + .unwrap_or(s.model_picker_index); + } + KeyCode::Enter => { + rustcode::app::select_picker_model(&mut s); + s.show_model_picker = false; + rustcode::app::spawn_context_window_detection( + Arc::clone(&app_state), + client.clone(), + ); + } + _ => { + handle_picker_search_key(&mut s, PickerSearchTarget::Model, key); + } + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.show_theme_picker { + let themes = crate::ui::theme::load_available_themes(); + let len = themes.len(); + match key.code { + KeyCode::Esc => { + s.config.theme = s.theme_picker_initial.clone(); + s.show_theme_picker = false; + } + KeyCode::Up | KeyCode::Char('k') => { + s.theme_picker_index = move_picker_selection(s.theme_picker_index, len, false); + if len > 0 { + s.config.theme = themes[s.theme_picker_index].name.clone(); + } + } + KeyCode::Down | KeyCode::Char('j') => { + s.theme_picker_index = move_picker_selection(s.theme_picker_index, len, true); + if len > 0 { + s.config.theme = themes[s.theme_picker_index].name.clone(); + } + } + KeyCode::Enter => { + let selected = themes[s.theme_picker_index.min(len.saturating_sub(1))] + .name + .clone(); + s.config.theme = selected.clone(); + s.show_theme_picker = false; + rustcode::controller::save_config(&s.config); + s.set_transient_notice(format!("Theme set to '{}'", selected)); + } + _ => {} + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + if s.show_command_picker { + let filtered_items = filtered_command_picker_items(&s.command_picker_search); + + if crate::ui::keymap::KeyMap::from_environment().resolve(key) + == crate::ui::keymap::KeyAction::Paste + { + if let Some(payload) = clipboard_paste_payload() { + insert_picker_search_text(&mut s, PickerSearchTarget::Command, &payload); + } + drop(s); + return Ok(InputFlow::ContinueIteration); + } + + let mut exit_flag = false; + match key.code { + KeyCode::Esc => { + s.show_command_picker = false; + } + KeyCode::Up => { + let len = filtered_items.len(); + s.command_picker_index = + picker_selection_for_key(s.command_picker_index, len, key.code) + .unwrap_or(s.command_picker_index); + } + KeyCode::Down => { + let len = filtered_items.len(); + s.command_picker_index = + picker_selection_for_key(s.command_picker_index, len, key.code) + .unwrap_or(s.command_picker_index); + } + KeyCode::Enter => { + let idx = s + .command_picker_index + .min(filtered_items.len().saturating_sub(1)); + if !filtered_items.is_empty() { + let item = filtered_items[idx]; + s.show_command_picker = false; + if item.shortcut == "ctrl+c" { + exit_flag = true; + } else { + // Palette commands share slash dispatch, including panel + // presentation, arguments and immediate actions. + s.input_buffer = item.shortcut.to_owned(); + s.cursor_position = s.input_buffer.len(); + drop(s); + if open_demo_if_requested(app_state, demo_state).await { + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + let should_exit = rustcode::app::handle_enter_with_ui_events( + app_state, + client, + current_cancel_token, + agent_ui_event_sender.clone(), + &|| { + crate::ui::theme::load_available_themes() + .into_iter() + .map(|theme| theme.name) + .collect() + }, + ) + .await; + *needs_redraw = true; + return Ok(if should_exit { + InputFlow::Exit { update: false } + } else { + InputFlow::ContinueIteration + }); + } + } else { + s.show_command_picker = false; + } + } + _ => { + handle_picker_search_key(&mut s, PickerSearchTarget::Command, key); + } + } + drop(s); + if exit_flag { + return Ok(InputFlow::Exit { update: false }); + } + return Ok(InputFlow::ContinueIteration); + } + drop(s); + if transcript_navigation { + let page = terminal_runtime.terminal().area().height.saturating_sub(4) as usize; + // Keep every intermediate row visible while a mouse range is growing. + let page = if transcript_state.selection.is_dragging() { + 1 + } else { + page.max(1) + }; + if transcript_state.selection.is_active() { + let direction = if matches!(key.code, KeyCode::PageUp | KeyCode::Up) { + -1 + } else { + 1 + }; + transcript_state.selection.queue_scroll(direction, page); + frame_requester.schedule_frame(); + } else if matches!(key.code, KeyCode::PageUp | KeyCode::Up) { + transcript_state.scroll_up(page); + } else { + transcript_state.scroll_down(page); + } + return Ok(InputFlow::ContinueIteration); + } + // Escape closes transcript browsing without discarding a draft. + if return_to_latest_for_key(transcript_state, key.code) { + return Ok(InputFlow::ContinueIteration); + } + if key.code == KeyCode::Enter + && !key.modifiers.intersects( + event::KeyModifiers::SHIFT | event::KeyModifiers::CONTROL | event::KeyModifiers::ALT, + ) + && open_demo_if_requested(app_state, demo_state).await + { + return Ok(InputFlow::ContinueIteration); + } + match { + let mut state = app_state.lock().await; + composer.handle_key(&mut state, key) + } { + ui::ComposerAction::Handled => { + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + ui::ComposerAction::Submit => { + if rustcode::app::handle_enter_with_ui_events( + &app_state, + &client, + current_cancel_token, + agent_ui_event_sender.clone(), + &|| { + crate::ui::theme::load_available_themes() + .into_iter() + .map(|t| t.name) + .collect() + }, + ) + .await + { + return Ok(InputFlow::Exit { update: false }); + } + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + ui::ComposerAction::ClearScreen => { + terminal_runtime.terminal().clear()?; + return Ok(InputFlow::ContinueIteration); + } + ui::ComposerAction::Paste => { + if let Some(payload) = clipboard_paste_payload() { + let mut state = app_state.lock().await; + insert_clipboard_paste(composer, &mut state, &payload); + } + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + ui::ComposerAction::BackgroundCommand => { + let mut state = app_state.lock().await; + let moved = + rustcode::tools::move_foreground_commands_to_background(&state.active_session_id); + state.set_transient_notice(match moved { + 0 => "No running command to move to the background", + 1 => "Moved the running command to the background", + _ => "Moved the running commands to the background", + }); + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + action @ (ui::ComposerAction::ToggleExpandAll | ui::ComposerAction::ToggleExpandStep) => { + let step = matches!(action, ui::ComposerAction::ToggleExpandStep); + let mut state = app_state.lock().await; + let width = terminal_runtime.terminal().area().width; + toggle_tool_expansion(&mut state, width, step); + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + ui::ComposerAction::ToggleExpandEdits => { + let mut state = app_state.lock().await; + let width = terminal_runtime.terminal().area().width; + toggle_edit_expansion(&mut state, width); + *needs_redraw = true; + return Ok(InputFlow::ContinueIteration); + } + ui::ComposerAction::Unhandled => {} + } + + match key.code { + KeyCode::Esc => { + let mut s = app_state.lock().await; + if s.dismiss_completion() { + // Popup dismissal keeps the draft intact. Typing or moving + // to another token makes completion eligible again. + } else if s.sel_start.is_some() || s.sel_end.is_some() { + s.clear_selection(); + } else if !s.input_buffer.is_empty() + && matches!(s.status, AppStatus::Idle) + && s.running_tools.is_empty() + { + s.input_buffer.clear(); + s.cursor_position = 0; + } else { + drop(s); + rustcode::app::handle_escape(&app_state, current_cancel_token).await; + } + *needs_redraw = true; + } + KeyCode::Up => { + let mut s = app_state.lock().await; + let completion_len = s.completion_len(); + if s.active_suggestion_index.is_some() && completion_len > 0 { + let current = s.active_suggestion_index.unwrap_or(0); + s.active_suggestion_index = Some(if current == 0 { + completion_len - 1 + } else { + current - 1 + }); + } else { + s.active_suggestion_index = None; + if s.input_buffer.is_empty() || s.history_index.is_some() { + // With an empty buffer, Up first pulls the most + // recent queued prompt back for editing; only + // when nothing is queued does it recall history. + // Once recall has started, keep walking it — + // without this, the recalled text made the buffer + // non-empty and the next Up fell through to + // cursor movement, pinning recall on the most + // recent entry. + let pulled = s.history_index.is_none() && s.pop_queued_prompt(); + if !pulled { + s.history_up(); + } + } else { + s.move_cursor_line_up(); + } + } + } + KeyCode::Down => { + let mut s = app_state.lock().await; + let completion_len = s.completion_len(); + if s.active_suggestion_index.is_some() && completion_len > 0 { + let current = s.active_suggestion_index.unwrap_or(0); + s.active_suggestion_index = Some(if current + 1 >= completion_len { + 0 + } else { + current + 1 + }); + } else { + s.active_suggestion_index = None; + if s.history_index.is_some() { + s.history_down(); + } else { + s.move_cursor_line_down(); + } + } + } + KeyCode::Left => { + let mut s = app_state.lock().await; + // An empty composer has no cursor to move, so Left opens + // the agent contexts the way Codex opens its agents overview. + if key.modifiers.is_empty() && s.input_buffer.is_empty() && !s.subagents.is_empty() { + open_overlay(&mut s, rustcode::app::events::Overlay::Subagents); + return Ok(InputFlow::ContinueIteration); + } + let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); + let alt = key.modifiers.contains(event::KeyModifiers::ALT) + || key.modifiers.contains(event::KeyModifiers::META); + // Word motion wins whenever there is a draft; only an + // empty composer gives Alt+arrows to agent switching. + if alt + && !shift + && s.input_buffer.is_empty() + && let Some(id) = sessions::adjacent_context_id(&s, false) + { + drop(s); + let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); + return Ok(InputFlow::ContinueIteration); + } + if shift && s.composer_selection_anchor.is_none() { + s.composer_selection_anchor = Some(s.cursor_position); + } + if alt { + s.move_cursor_word_left(); + } else { + s.move_cursor_left(); + } + if !shift { + s.composer_selection_anchor = None; + } else if s.composer_selection_anchor == Some(s.cursor_position) { + s.composer_selection_anchor = None; + } + } + KeyCode::Right => { + let mut s = app_state.lock().await; + if key.modifiers.is_empty() + && let Some(id) = agent_context_return_target(&s, key.code) + { + drop(s); + let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); + return Ok(InputFlow::ContinueIteration); + } + let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); + let alt = key.modifiers.contains(event::KeyModifiers::ALT) + || key.modifiers.contains(event::KeyModifiers::META); + // Word motion wins whenever there is a draft; only an + // empty composer gives Alt+arrows to agent switching. + if alt + && !shift + && s.input_buffer.is_empty() + && let Some(id) = sessions::adjacent_context_id(&s, true) + { + drop(s); + let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); + return Ok(InputFlow::ContinueIteration); + } + if shift && s.composer_selection_anchor.is_none() { + s.composer_selection_anchor = Some(s.cursor_position); + } + if alt { + s.move_cursor_word_right(); + } else { + s.move_cursor_right(); + } + if !shift { + s.composer_selection_anchor = None; + } else if s.composer_selection_anchor == Some(s.cursor_position) { + s.composer_selection_anchor = None; + } + } + KeyCode::Home => { + let mut s = app_state.lock().await; + let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); + if shift && s.composer_selection_anchor.is_none() { + s.composer_selection_anchor = Some(s.cursor_position); + } + s.move_cursor_to_start(); + if !shift { + s.composer_selection_anchor = None; + } else if s.composer_selection_anchor == Some(s.cursor_position) { + s.composer_selection_anchor = None; + } + } + KeyCode::End => { + let mut s = app_state.lock().await; + let shift = key.modifiers.contains(event::KeyModifiers::SHIFT); + if shift && s.composer_selection_anchor.is_none() { + s.composer_selection_anchor = Some(s.cursor_position); + } + s.move_cursor_to_end(); + if !shift { + s.composer_selection_anchor = None; + } else if s.composer_selection_anchor == Some(s.cursor_position) { + s.composer_selection_anchor = None; + } + } + KeyCode::Char('l') if key.modifiers.contains(event::KeyModifiers::CONTROL) => { + terminal_runtime.terminal().clear()?; + } + KeyCode::Enter => { + let modifiers = key.modifiers; + if modifiers.contains(event::KeyModifiers::SHIFT) + || modifiers.contains(event::KeyModifiers::CONTROL) + || modifiers.contains(event::KeyModifiers::ALT) + { + let mut s = app_state.lock().await; + s.insert_char('\n'); + s.reset_suggestion_cycle(); + } else { + if open_demo_if_requested(app_state, demo_state).await { + return Ok(InputFlow::ContinueIteration); + } + if rustcode::app::handle_enter_with_ui_events( + &app_state, + &client, + current_cancel_token, + agent_ui_event_sender.clone(), + &|| { + crate::ui::theme::load_available_themes() + .into_iter() + .map(|t| t.name) + .collect() + }, + ) + .await + { + return Ok(InputFlow::Exit { update: false }); + } + } + } + KeyCode::Char('v') | KeyCode::Char('V') + if key.modifiers.contains(event::KeyModifiers::CONTROL) + || key.modifiers.contains(event::KeyModifiers::SUPER) + || key.modifiers.contains(event::KeyModifiers::META) => + { + // Terminals without bracketed paste deliver Ctrl/Cmd+V + // as a key. Route it through the same helper the keymap + // paste uses so the large-paste marker cannot drift + // between the two (#1527). + if let Some(payload) = clipboard_paste_payload() { + let mut s = app_state.lock().await; + insert_clipboard_paste(composer, &mut s, &payload); + } + } + KeyCode::Char('p') | KeyCode::Char('n') + if key.modifiers.contains(event::KeyModifiers::CONTROL) => + { + let mut s = app_state.lock().await; + let completion_len = s.completion_len(); + if s.active_suggestion_index.is_some() && completion_len > 0 { + let current = s.active_suggestion_index.unwrap_or(0); + s.active_suggestion_index = Some(if key.code == KeyCode::Char('p') { + if current == 0 { + completion_len - 1 + } else { + current - 1 + } + } else if current + 1 >= completion_len { + 0 + } else { + current + 1 + }); + } else if key.code == KeyCode::Char('p') { + s.show_command_picker = true; + s.command_picker_index = 0; + s.command_picker_search.clear(); + } + } + + KeyCode::Char(c) => { + let mut s = app_state.lock().await; + let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL); + let alt = key.modifiers.contains(event::KeyModifiers::ALT) + || key.modifiers.contains(event::KeyModifiers::META); + let cmd = key.modifiers.contains(event::KeyModifiers::SUPER); + + if c == '\x7f' || c == '\x08' || c == '\x17' { + // Option+Backspace, Ctrl+W, or raw DEL on Mac + if alt || cmd || c == '\x17' { + s.delete_word_backspace(); + } else { + s.delete_char_backspace(); + } + s.reset_suggestion_cycle(); + } else if cmd { + if c == 'u' { + s.kill_line_to_start(); + s.reset_suggestion_cycle(); + } + } else if (alt && c == 'b') || c == '∫' { + // Terminals without enhanced key reporting send + // Option+Left/Right as these word-motion keys. + if s.input_buffer.is_empty() + && let Some(id) = sessions::adjacent_context_id(&s, false) + { + drop(s); + let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); + return Ok(InputFlow::ContinueIteration); + } + s.move_cursor_word_left(); + } else if (alt && c == 'f') || c == 'ƒ' { + if s.input_buffer.is_empty() + && let Some(id) = sessions::adjacent_context_id(&s, true) + { + drop(s); + let _ = app_event_sender.send(AppEvent::SelectSubagent(id)); + return Ok(InputFlow::ContinueIteration); + } + s.move_cursor_word_right(); + } else if (alt && c == 'd') || c == '∂' { + s.delete_word_forward(); + s.reset_suggestion_cycle(); + } else if ctrl && c == 'j' { + s.insert_char('\n'); + s.reset_suggestion_cycle(); + } else if ctrl && c == 'a' { + s.move_cursor_to_start(); + } else if ctrl && c == 'e' { + s.move_cursor_to_end(); + } else if ctrl && c == 'u' { + s.kill_line_to_start(); + s.reset_suggestion_cycle(); + } else if ctrl && c == 'w' { + s.delete_word_backspace(); + s.reset_suggestion_cycle(); + } else if c == '?' && !ctrl && !alt && !cmd && s.input_buffer.is_empty() { + s.show_command_panel("Help", rustcode::app::build_help_text()); + s.request_redraw(); + } else if !ctrl && !alt && !c.is_control() { + s.insert_char(c); + s.reset_suggestion_cycle(); + } + } + KeyCode::Backspace => { + let mut s = app_state.lock().await; + let alt = key.modifiers.contains(event::KeyModifiers::ALT) + || key.modifiers.contains(event::KeyModifiers::META); + let ctrl = key.modifiers.contains(event::KeyModifiers::CONTROL); + let cmd = key.modifiers.contains(event::KeyModifiers::SUPER); + if cmd { + s.kill_line_to_start(); + } else if alt || ctrl { + s.delete_word_backspace(); + } else { + s.delete_char_backspace(); + } + s.reset_suggestion_cycle(); + } + KeyCode::Delete => { + let mut s = app_state.lock().await; + let alt = key.modifiers.contains(event::KeyModifiers::ALT) + || key.modifiers.contains(event::KeyModifiers::META); + let cmd = key.modifiers.contains(event::KeyModifiers::SUPER); + if cmd { + s.kill_line_to_start(); + } else if alt { + s.delete_word_forward(); + } else { + s.delete_char_delete(); + } + s.reset_suggestion_cycle(); + } + _ => {} + } + Ok(InputFlow::ContinueLoop) +} diff --git a/harness/src/runtime/input/tests.rs b/harness/src/runtime/input/tests.rs new file mode 100644 index 000000000..15c319d38 --- /dev/null +++ b/harness/src/runtime/input/tests.rs @@ -0,0 +1,1031 @@ +use super::{ + InputFlow, PickerSearchTarget, QuestionEditAction, SubagentPickerAction, + agent_context_return_target, clear_selection_for_composer_key, filtered_command_picker_items, + handle_cmd_copy_chord, handle_cmd_copy_chord_with, handle_copy_or_exit_chord, + handle_picker_search_key, handle_question_custom_key, insert_clipboard_paste, + insert_question_answer_text, is_cmd_copy_chord, is_copy_or_exit_chord, is_keyboard_range_key, + is_shift_tab, is_transcript_navigation, open_demo_if_requested, picker_selection_for_key, + report_selection_copy, return_to_latest_for_key, scroll_command_panel, scroll_panel_selection, + selection_owns_key, subagent_picker_action, +}; +use crate::ui::{Composer, TranscriptState}; +use crossterm::event::{KeyCode, KeyEvent, KeyModifiers, MouseButton, MouseEvent, MouseEventKind}; +use ratatui::{buffer::Buffer, layout::Rect}; +use rustcode::app::AppState; +use rustcode::clipboard::ClipboardCopyStatus; +use rustcode::controller::PendingQuestion; +use std::sync::Arc; +use tokio::sync::Mutex; + +#[test] +fn clicking_a_tool_block_opens_then_closes_only_that_block() { + use rustcode::app::{ChatMessage, ToolCallRef, ToolResultRecord}; + + let mut state = AppState::new(); + for round in 0..2 { + let id = format!("call-{round}"); + state.history.push( + ChatMessage::new("assistant", format!("round {round}")).with_tool_calls(vec![ + ToolCallRef { + id: id.clone(), + name: "run_command".to_owned(), + arguments: r#"{"command":"cargo test"}"#.to_owned(), + }, + ]), + ); + state.history.push( + ChatMessage::new("tool", "run_command: exit code: 0\nok") + .answering(Some(id)) + .with_tool_result(ToolResultRecord { + tool_name: "run_command".to_owned(), + success: true, + ..Default::default() + }), + ); + } + + // The second block is history index 3. + super::toggle_tool_block(&mut state, 80, (3, 4)); + assert!(state.expanded_thoughts.contains(&3)); + assert!(!state.expanded_thoughts.contains(&1)); + + super::toggle_tool_block(&mut state, 80, (3, 4)); + assert!(state.expanded_thoughts.is_empty()); +} + +#[test] +fn clicking_a_folded_run_opens_and_folds_it() { + let mut state = AppState::new(); + state.verbosity = rustcode::app::Verbosity::Low; + // A summary row stands for the calls from history index 1 up to 4. + super::toggle_tool_block(&mut state, 80, (1, 4)); + assert!(state.expanded_tool_runs.contains(&1)); + assert!(state.expanded_thoughts.is_empty(), "no call body opens"); + super::toggle_tool_block(&mut state, 80, (1, 4)); + assert!(state.expanded_tool_runs.is_empty()); +} + +#[test] +fn ask_question_editor_matches_composer_modified_enter_and_word_navigation() { + let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); + question.activate_custom_input(); + question.insert_str("café tools"); + + assert_eq!( + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Left, KeyModifiers::CONTROL) + ), + QuestionEditAction::Handled + ); + assert_eq!(question.custom_cursor, "café ".len()); + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Char('X'), KeyModifiers::NONE), + ); + assert_eq!(question.custom_input.as_deref(), Some("café Xtools")); + + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Enter, KeyModifiers::SHIFT), + ); + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Char('j'), KeyModifiers::CONTROL), + ); + assert_eq!(question.custom_input.as_deref(), Some("café X\n\ntools")); + assert_eq!( + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE) + ), + QuestionEditAction::Submit + ); +} + +#[test] +fn ask_question_editor_supports_forward_word_delete_and_line_kill() { + let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); + question.activate_custom_input(); + question.insert_str("one two three"); + question.custom_cursor = "one ".len(); + + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Char('d'), KeyModifiers::ALT), + ); + // Forward word delete removes the word and leaves the space after it. + assert_eq!(question.custom_input.as_deref(), Some("one three")); + assert_eq!(question.custom_cursor, "one ".len()); + + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Backspace, KeyModifiers::SUPER), + ); + assert_eq!(question.custom_input.as_deref(), Some(" three")); + assert_eq!(question.custom_cursor, 0); +} + +#[test] +fn ask_question_paste_preserves_normalized_newlines_and_unicode() { + let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); + question.activate_custom_input(); + insert_question_answer_text(&mut question, "først\r\n二つ\rslutt"); + + assert_eq!(question.custom_input.as_deref(), Some("først\n二つ\nslutt")); + assert_eq!(question.custom_cursor, "først\n二つ\nslutt".len()); +} + +#[test] +fn ask_question_up_from_first_answer_line_returns_to_options_with_draft() { + let up = KeyEvent::new(KeyCode::Up, KeyModifiers::NONE); + let mut question = PendingQuestion::new( + "Question?".to_owned(), + vec!["One".to_owned(), "Two".to_owned()], + false, + ); + question.selected = 2; + question.activate_custom_input(); + question.insert_str("first\nsecond"); + + // Up on the second line moves within the answer. + handle_question_custom_key(&mut question, up); + assert!(question.custom_input.is_some()); + assert!(question.custom_cursor_on_first_line()); + + // Up on the first line returns to the last option and keeps the text. + handle_question_custom_key(&mut question, up); + assert!(question.custom_input.is_none()); + assert_eq!(question.selected, 1); + assert_eq!(question.custom_draft, "first\nsecond"); + + question.activate_custom_input(); + assert_eq!(question.custom_input.as_deref(), Some("first\nsecond")); + assert_eq!(question.custom_cursor, "first\nsecond".len()); +} + +#[test] +fn scroll_speed_picker_steps_within_range_and_saves_on_enter() { + let mut state = AppState::new(); + state.settings_picker = Some(rustcode::controller::SettingsPicker::ScrollSpeed); + state.modal_picker_index = 1; + + assert_eq!( + super::scroll_speed_picker_key(&mut state, KeyCode::Left), + None + ); + assert_eq!(state.modal_picker_index, 1, "never below one line"); + super::scroll_speed_picker_key(&mut state, KeyCode::Right); + super::scroll_speed_picker_key(&mut state, KeyCode::Up); + assert_eq!(state.modal_picker_index, 3); + super::scroll_speed_picker_key(&mut state, KeyCode::End); + super::scroll_speed_picker_key(&mut state, KeyCode::Right); + assert_eq!(state.modal_picker_index, 20, "never above the range"); + super::scroll_speed_picker_key(&mut state, KeyCode::Char('5')); + assert_eq!( + super::scroll_speed_picker_key(&mut state, KeyCode::Enter), + Some(5) + ); + + assert_eq!( + super::scroll_speed_picker_key(&mut state, KeyCode::Esc), + None + ); + assert!(state.settings_picker.is_none(), "esc closes without saving"); +} + +#[test] +fn ask_question_up_without_options_stays_in_the_answer() { + let mut question = PendingQuestion::new("Question?".to_owned(), vec![], false); + question.activate_custom_input(); + question.insert_str("text"); + handle_question_custom_key( + &mut question, + KeyEvent::new(KeyCode::Up, KeyModifiers::NONE), + ); + assert_eq!(question.custom_input.as_deref(), Some("text")); +} + +#[tokio::test] +async fn opening_demo_consumes_only_the_command_and_preserves_live_session() { + let mut state = AppState::new(); + state.active_session_id = "live-session".to_owned(); + state + .history + .push(rustcode::app::ChatMessage::new("user", "existing history")); + state.input_buffer = "/test".to_owned(); + state.cursor_position = state.input_buffer.len(); + let expected_history = state.history.snapshot(); + let app_state = Arc::new(Mutex::new(state)); + let mut demo_state = None; + + assert!(open_demo_if_requested(&app_state, &mut demo_state).await); + let live = app_state.lock().await; + assert_eq!(live.active_session_id, "live-session"); + assert_eq!(live.history.snapshot(), expected_history); + assert!(live.input_buffer.is_empty()); + let demo = demo_state.expect("demo view is separate from the live session"); + assert_eq!(demo.render_state().active_session_id, "static-visual-demo"); + assert_eq!(demo.render_state().history.len(), 4); +} + +#[tokio::test] +async fn demo_command_does_not_match_a_prompt_with_arguments() { + let mut state = AppState::new(); + state.input_buffer = "/test please".to_owned(); + let app_state = Arc::new(Mutex::new(state)); + let mut demo_state = None; + + assert!(!open_demo_if_requested(&app_state, &mut demo_state).await); + assert!(demo_state.is_none()); + assert_eq!(app_state.lock().await.input_buffer, "/test please"); +} + +#[test] +fn picker_navigation_stops_at_both_ends_and_reaches_long_list_tail() { + let last = 127; + let mut selected = 0; + assert_eq!( + picker_selection_for_key(selected, last + 1, KeyCode::Up), + Some(0) + ); + for _ in 0..last { + selected = picker_selection_for_key(selected, last + 1, KeyCode::Down).unwrap(); + } + assert_eq!(selected, last); + assert_eq!( + picker_selection_for_key(selected, last + 1, KeyCode::Down), + Some(last) + ); + assert_eq!( + picker_selection_for_key(selected, last + 1, KeyCode::Up), + Some(last - 1) + ); + assert_eq!(picker_selection_for_key(0, 0, KeyCode::Down), Some(0)); +} + +#[test] +fn subagent_picker_left_selects_and_right_returns() { + assert_eq!( + subagent_picker_action(KeyCode::Left), + Some(SubagentPickerAction::Select) + ); + assert_eq!( + subagent_picker_action(KeyCode::Right), + Some(SubagentPickerAction::Close) + ); + assert_eq!( + subagent_picker_action(KeyCode::Enter), + Some(SubagentPickerAction::Select) + ); +} + +#[test] +fn tasks_panel_owns_navigation_log_stop_and_close_keys() { + use rustcode::controller::TasksPanelInput; + for (key, expected) in [ + (KeyCode::Up, Some(TasksPanelInput::Up)), + (KeyCode::Down, Some(TasksPanelInput::Down)), + (KeyCode::Enter, Some(TasksPanelInput::Open)), + (KeyCode::Esc, Some(TasksPanelInput::Back)), + (KeyCode::Char('x'), Some(TasksPanelInput::Stop)), + (KeyCode::Char('q'), Some(TasksPanelInput::Close)), + (KeyCode::Char('a'), None), + (KeyCode::Backspace, None), + ] { + assert_eq!(super::tasks_panel_input_for_key(key), expected, "{key:?}"); + } +} + +#[test] +fn right_from_an_empty_child_composer_returns_to_its_parent() { + let mut state = AppState::new(); + let child = rustcode::app::SubagentController + .spawn( + &mut state, + "child", + None, + None, + false, + Vec::new(), + None, + None, + ) + .raw(); + state.selected_subagent_id = Some(child); + assert_eq!(agent_context_return_target(&state, KeyCode::Right), Some(0)); + + state.input_buffer = "draft".to_owned(); + assert_eq!(agent_context_return_target(&state, KeyCode::Right), None); +} + +#[test] +fn command_picker_filter_includes_visible_fuzzy_group_matches() { + let expected = crate::ui::PALETTE_ITEMS + .iter() + .find(|item| item.group == "System") + .expect("palette has a System group"); + assert!( + filtered_command_picker_items("system") + .iter() + .any(|item| item.name == expected.name) + ); +} + +#[test] +fn picker_search_supports_composer_cursor_editing_without_splitting_unicode() { + let mut state = AppState::new(); + state.command_picker_search = "café tools".to_owned(); + state.command_picker_search_cursor = state.command_picker_search.len(); + state.command_picker_index = 7; + let key = |code, modifiers| KeyEvent::new(code, modifiers); + + assert!(handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Left, KeyModifiers::NONE) + )); + assert_eq!( + state.command_picker_index, 7, + "cursor motion keeps selection" + ); + assert!(handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Left, KeyModifiers::ALT) + )); + assert_eq!( + &state.command_picker_search[..state.command_picker_search_cursor], + "café " + ); + assert!(handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Char('X'), KeyModifiers::NONE) + )); + assert_eq!(state.command_picker_search, "café Xtools"); + assert_eq!( + state.command_picker_index, 0, + "query changes reset selection" + ); + assert!(handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Left, KeyModifiers::NONE) + )); + assert!(handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Delete, KeyModifiers::ALT) + )); + assert_eq!(state.command_picker_search, "café "); + assert_eq!(state.command_picker_search_cursor, "café ".len()); + assert!(handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Home, KeyModifiers::NONE) + )); + assert!(handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Char('a'), KeyModifiers::CONTROL) + )); + assert_eq!(state.command_picker_search_cursor, 0); + assert!(!handle_picker_search_key( + &mut state, + PickerSearchTarget::Command, + key(KeyCode::Up, KeyModifiers::NONE) + )); +} + +#[test] +fn mcp_editor_paste_uses_active_utf8_cursor_for_key_and_bracketed_paste() { + use crate::ui::keymap::{KeyAction, KeyMap}; + + let keymap = KeyMap::from_environment(); + for modifiers in [ + KeyModifiers::CONTROL, + KeyModifiers::SUPER, + KeyModifiers::META, + ] { + assert_eq!( + keymap.resolve(KeyEvent::new(KeyCode::Char('v'), modifiers)), + KeyAction::Paste + ); + } + + let mut edit_state = rustcode::app::McpEditState { + is_add: true, + edit_index: None, + name_input: "café".to_owned(), + command_input: String::new(), + args_input: String::new(), + active_field: 0, + cursor_pos: "caf".len(), + }; + // A pasted line break becomes a space: the field holds one line. + edit_state.insert_str("X\r\nY"); + assert_eq!(edit_state.name_input, "cafX Yé"); + assert_eq!(edit_state.cursor_pos, "cafX Y".len()); +} + +#[tokio::test] +async fn selection_copy_feedback_reports_backend_result_without_chat_message() { + let state = Arc::new(Mutex::new(AppState::new())); + for (result, expected) in [ + ( + ClipboardCopyStatus::Confirmed, + "Copied selection to clipboard", + ), + ( + ClipboardCopyStatus::Requested, + "Copy sent to terminal; paste to verify", + ), + (ClipboardCopyStatus::Failed, "Copy failed; try again"), + ] { + report_selection_copy(&state, "selected text", |text| { + assert_eq!(text, "selected text"); + result + }) + .await; + let state = state.lock().await; + assert_eq!(state.active_transient_notice(), Some(expected)); + assert!(state.history.is_empty()); + } +} + +#[test] +fn shift_tab_is_normalized_from_supported_terminal_events() { + assert!(is_shift_tab(KeyEvent::new( + KeyCode::BackTab, + KeyModifiers::NONE + ))); + assert!(is_shift_tab(KeyEvent::new( + KeyCode::Tab, + KeyModifiers::SHIFT + ))); + assert!(!is_shift_tab(KeyEvent::new( + KeyCode::Tab, + KeyModifiers::NONE + ))); +} + +#[test] +fn keyboard_range_only_owns_unmodified_or_shifted_arrows() { + assert!(is_keyboard_range_key(KeyEvent::new( + KeyCode::Left, + KeyModifiers::NONE + ))); + assert!(is_keyboard_range_key(KeyEvent::new( + KeyCode::Down, + KeyModifiers::SHIFT + ))); + assert!(!is_keyboard_range_key(KeyEvent::new( + KeyCode::Left, + KeyModifiers::ALT + ))); + assert!(!is_keyboard_range_key(KeyEvent::new( + KeyCode::Char('x'), + KeyModifiers::NONE + ))); +} + +#[test] +fn ordinary_composer_key_exits_keyboard_range_mode() { + let mut transcript = TranscriptState::default(); + let area = Rect::new(0, 0, 8, 1); + transcript + .selection + .refresh(area, &Buffer::empty(area), &[false]); + transcript.selection.begin_keyboard_with_snapshot( + crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( + &AppState::new(), + )), + 0, + ); + assert!(transcript.selection.is_keyboard_mode()); + assert!(selection_owns_key( + &transcript, + KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE) + )); + assert!(!selection_owns_key( + &transcript, + KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL) + )); + // Ctrl+C stays out of the selection's hands so it can arm the exit; + // Cmd+C stays out too, but takes the copy-only path. + assert!(is_copy_or_exit_chord(KeyEvent::new( + KeyCode::Char('c'), + KeyModifiers::CONTROL + ))); + assert!(is_cmd_copy_chord(KeyEvent::new( + KeyCode::Char('C'), + KeyModifiers::SUPER + ))); + assert!(!selection_owns_key( + &transcript, + KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE) + )); + clear_selection_for_composer_key( + &mut transcript, + KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE), + ); + assert!(!transcript.selection.is_keyboard_mode()); + assert!(!transcript.selection.is_active()); +} + +/// The advertised copy binding reaches the selection handler for both +/// mouse and keyboard selections, and `ctrl+c` without a selection falls +/// through to interrupt/exit (#1566). +#[test] +fn ctrl_c_copies_every_selection_and_still_reaches_the_exit_arm() { + use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; + + // The hint and the handler share this definition: the footer promises + // exactly the chord the handler owns. + assert_eq!(rustcode::controller::copy_selection_binding(), "ctrl+c"); + let copy = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL); + assert!(is_copy_or_exit_chord(copy)); + // Cmd+C is handled as copy-only; Control takes precedence when both + // modifiers arrive in the same event. + let cmd_copy = KeyEvent::new(KeyCode::Char('c'), KeyModifiers::SUPER); + assert!(!is_copy_or_exit_chord(cmd_copy)); + assert!(is_cmd_copy_chord(cmd_copy)); + let mixed_copy = KeyEvent::new( + KeyCode::Char('c'), + KeyModifiers::SUPER | KeyModifiers::CONTROL, + ); + assert!(is_copy_or_exit_chord(mixed_copy)); + assert!(!is_cmd_copy_chord(mixed_copy)); + assert!(!is_copy_or_exit_chord(KeyEvent::new( + KeyCode::Char('c'), + KeyModifiers::NONE + ))); + + // A live selection does not take the chord away from the exit path, so + // copying and arming happen together. + let area = Rect::new(0, 0, 8, 1); + let mut buffer = Buffer::empty(area); + buffer.set_string(0, 0, "hello", ratatui::style::Style::default()); + + // Mouse selection. + let mut mouse = TranscriptState::default(); + mouse.selection.refresh(area, &buffer, &[false]); + let down = MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 0, + row: 0, + modifiers: KeyModifiers::NONE, + }; + mouse.selection.mouse(down); + mouse.selection.mouse(MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left), + column: 3, + row: 0, + modifiers: KeyModifiers::NONE, + }); + mouse.selection.mouse(MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + column: 3, + row: 0, + modifiers: KeyModifiers::NONE, + }); + assert!(mouse.selection.has_selection()); + assert!(!mouse.selection.is_keyboard_mode()); + assert_eq!(mouse.selection.selected_text().as_deref(), Some("hell")); + + // Keyboard selection offers the same copyable text. + let mut keyboard = TranscriptState::default(); + keyboard.selection.refresh(area, &buffer, &[false]); + keyboard.selection.begin_keyboard_with_snapshot( + crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( + &AppState::new(), + )), + 0, + ); + keyboard.selection.move_keyboard(KeyCode::Right); + assert!(keyboard.selection.has_selection()); + + // Esc is the only key the selection owns outright; the chord is handled + // before it so the double-press exit stays reachable. + assert!(!selection_owns_key(&mouse, copy)); + assert!(selection_owns_key( + &mouse, + KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE) + )); + + // No selection: the key is not owned, so the caller falls through to + // the existing interruption/exit behavior. + let idle = TranscriptState::default(); + assert!(!idle.selection.has_selection()); + assert!(!selection_owns_key( + &idle, + KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE) + )); +} + +/// Two presses of the chord must exit even while a selection is live. +/// +/// The selection handlers used to sit above the exit check and returned +/// early, so any selection made the double-press unreachable — and a +/// pinned selection survives a whole turn. +#[tokio::test] +async fn two_ctrl_c_presses_exit_while_a_selection_is_live() { + use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; + + let area = Rect::new(0, 0, 8, 1); + let mut buffer = Buffer::empty(area); + buffer.set_string(0, 0, "hello", ratatui::style::Style::default()); + + let mut transcript = TranscriptState::default(); + transcript.selection.refresh(area, &buffer, &[false]); + for event in [ + MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 0, + row: 0, + modifiers: KeyModifiers::NONE, + }, + MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left), + column: 3, + row: 0, + modifiers: KeyModifiers::NONE, + }, + MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + column: 3, + row: 0, + modifiers: KeyModifiers::NONE, + }, + ] { + transcript.selection.mouse(event); + } + assert!(transcript.selection.has_selection()); + + let app_state = Arc::new(Mutex::new(AppState::new())); + + // First press: copies and arms, without exiting. + assert!(matches!( + handle_copy_or_exit_chord(&app_state, &transcript).await, + InputFlow::ContinueIteration + )); + assert!(app_state.lock().await.ctrl_c_exit_armed()); + + // Second press inside the window exits. + assert!(matches!( + handle_copy_or_exit_chord(&app_state, &transcript).await, + InputFlow::Exit { update: false } + )); +} + +#[tokio::test] +async fn repeated_cmd_c_copies_selection_without_arming_exit() { + use crossterm::event::{MouseButton, MouseEvent, MouseEventKind}; + + let area = Rect::new(0, 0, 8, 1); + let mut buffer = Buffer::empty(area); + buffer.set_string(0, 0, "hello", ratatui::style::Style::default()); + let mut transcript = TranscriptState::default(); + // `/session` displays a fixed session panel whose selection is stored + // separately from the main transcript selection. + transcript.panel_selection_area = Some(area); + transcript.panel_selection_scrollable = false; + transcript.panel_selection.refresh(area, &buffer, &[false]); + for event in [ + MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 0, + row: 0, + modifiers: KeyModifiers::NONE, + }, + MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left), + column: 3, + row: 0, + modifiers: KeyModifiers::NONE, + }, + MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + column: 3, + row: 0, + modifiers: KeyModifiers::NONE, + }, + ] { + transcript.panel_selection.mouse(event); + } + assert_eq!( + transcript.panel_selection.selected_text().as_deref(), + Some("hell") + ); + + let app_state = Arc::new(Mutex::new(AppState::new())); + for _ in 0..2 { + let copied = std::sync::Arc::new(std::sync::Mutex::new(None)); + let copied_by_backend = copied.clone(); + assert!(matches!( + handle_cmd_copy_chord_with(&app_state, &transcript, move |text| { + *copied_by_backend.lock().unwrap() = Some(text.to_owned()); + rustcode::clipboard::ClipboardCopyStatus::Confirmed + }) + .await, + InputFlow::ContinueIteration + )); + assert_eq!(copied.lock().unwrap().as_deref(), Some("hell")); + assert!(!app_state.lock().await.ctrl_c_exit_armed()); + } +} + +#[tokio::test] +async fn cmd_c_copies_a_composer_selection_without_hanging() { + let app_state = Arc::new(Mutex::new(AppState::new())); + { + let mut state = app_state.lock().await; + state.input_buffer = "see ![image](file:///tmp/a.png) here".to_owned(); + state.composer_selection_anchor = Some(0); + state.cursor_position = 3; + } + let copied = std::sync::Arc::new(std::sync::Mutex::new(None)); + let copied_by_backend = copied.clone(); + let flow = tokio::time::timeout( + std::time::Duration::from_secs(2), + handle_cmd_copy_chord_with(&app_state, &TranscriptState::default(), move |text| { + *copied_by_backend.lock().unwrap() = Some(text.to_owned()); + rustcode::clipboard::ClipboardCopyStatus::Confirmed + }), + ) + .await + .expect("copying a composer selection must not deadlock on the state lock"); + assert!(matches!(flow, InputFlow::ContinueIteration)); + assert_eq!(copied.lock().unwrap().as_deref(), Some("see")); +} + +#[tokio::test] +async fn cmd_c_without_app_selection_never_arms_exit() { + let app_state = Arc::new(Mutex::new(AppState::new())); + let transcript = TranscriptState::default(); + // Cmd+C also breaks a pending Ctrl+C confirmation. A later Ctrl+C + // starts a fresh sequence instead of exiting unexpectedly. + assert!(!rustcode::app::handle_ctrl_c(&app_state).await); + assert!(app_state.lock().await.ctrl_c_exit_armed()); + for _ in 0..2 { + assert!(matches!( + handle_cmd_copy_chord(&app_state, &transcript).await, + InputFlow::ContinueIteration + )); + assert!(!app_state.lock().await.ctrl_c_exit_armed()); + } + assert!(!rustcode::app::handle_ctrl_c(&app_state).await); + assert!(app_state.lock().await.ctrl_c_exit_armed()); +} + +/// With no selection the chord is purely the exit affordance. +#[tokio::test] +async fn two_ctrl_c_presses_exit_with_no_selection() { + let transcript = TranscriptState::default(); + let app_state = Arc::new(Mutex::new(AppState::new())); + + assert!(matches!( + handle_copy_or_exit_chord(&app_state, &transcript).await, + InputFlow::ContinueIteration + )); + assert!(app_state.lock().await.ctrl_c_exit_armed()); + assert!(matches!( + handle_copy_or_exit_chord(&app_state, &transcript).await, + InputFlow::Exit { update: false } + )); +} + +/// Keyboard-select mode owns the chord with a collapsed caret: nothing to +/// copy, but it must still report progress and arm the exit. +#[tokio::test] +async fn collapsed_keyboard_selection_reports_instead_of_failing_silently() { + let mut transcript = TranscriptState::default(); + let area = Rect::new(0, 0, 8, 1); + transcript + .selection + .refresh(area, &Buffer::empty(area), &[false]); + transcript.selection.begin_keyboard_with_snapshot( + crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( + &AppState::new(), + )), + 0, + ); + assert!(transcript.selection.is_keyboard_mode()); + assert_eq!(transcript.selection.selected_text(), None); + + let app_state = Arc::new(Mutex::new(AppState::new())); + assert!(matches!( + handle_copy_or_exit_chord(&app_state, &transcript).await, + InputFlow::ContinueIteration + )); + assert!(app_state.lock().await.ctrl_c_exit_armed()); +} + +#[test] +fn command_panel_wheel_stops_at_bottom_and_reverses_immediately() { + let mut transcript = TranscriptState::default(); + transcript.panel_selection_area = Some(Rect::new(0, 0, 40, 10)); + transcript.panel_selection_scrollable = true; + transcript.panel_max_scroll_row = 7; + let mut row = 0; + scroll_panel_selection(&mut transcript, &mut row, 1); + assert_eq!(row, 1, "each wheel event moves one row"); + for _ in 0..100 { + scroll_panel_selection(&mut transcript, &mut row, 1); + } + assert_eq!(row, 7); + scroll_panel_selection(&mut transcript, &mut row, -1); + assert_eq!(row, 6, "no invisible scroll debt at the bottom"); + transcript.panel_max_scroll_row = 0; + scroll_panel_selection(&mut transcript, &mut row, 1); + assert_eq!(row, 0, "short or empty replacement content cannot scroll"); +} + +#[test] +fn command_panel_key_steps_clamp_before_and_after_movement() { + for step in [1, 10] { + let mut row = 0; + for _ in 0..100 { + scroll_command_panel(&mut row, 23, step); + } + assert_eq!(row, 23); + scroll_command_panel(&mut row, 23, -step); + assert_eq!(row, 23 - step as u16); + row = u16::MAX; + scroll_command_panel(&mut row, 15, -step); + assert_eq!(row, 15 - step as u16, "resize clamps before moving up"); + scroll_command_panel(&mut row, 0, step); + assert_eq!(row, 0); + } +} + +#[test] +fn informational_panel_selection_keeps_its_range_across_wheel_scroll() { + let area = Rect::new(0, 0, 12, 1); + let mut buffer = Buffer::empty(area); + buffer.set_string(0, 0, "panel text", ratatui::style::Style::default()); + + let mut transcript = TranscriptState::default(); + transcript.selection.refresh(area, &buffer, &[false]); + transcript.selection.mouse(MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 0, + row: 0, + modifiers: KeyModifiers::NONE, + }); + transcript.selection.mouse(MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left), + column: 2, + row: 0, + modifiers: KeyModifiers::NONE, + }); + transcript.selection.mouse(MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + column: 2, + row: 0, + modifiers: KeyModifiers::NONE, + }); + let transcript_text = transcript.selection.selected_text(); + + transcript.panel_selection_area = Some(area); + transcript.panel_selection.refresh(area, &buffer, &[false]); + transcript.panel_selection.mouse(MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 6, + row: 0, + modifiers: KeyModifiers::NONE, + }); + transcript.panel_selection.mouse(MouseEvent { + kind: MouseEventKind::Drag(MouseButton::Left), + column: 9, + row: 0, + modifiers: KeyModifiers::NONE, + }); + transcript.panel_selection.mouse(MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + column: 9, + row: 0, + modifiers: KeyModifiers::NONE, + }); + + assert_eq!( + transcript.panel_selection.selected_text().as_deref(), + Some("text") + ); + assert_eq!(transcript.selection.selected_text(), transcript_text); + let mut modal_scroll_row = 0; + assert!(scroll_panel_selection( + &mut transcript, + &mut modal_scroll_row, + 1, + )); + assert_eq!(modal_scroll_row, 0); + assert_eq!( + transcript.panel_selection.selected_text().as_deref(), + Some("text"), + "wheel input over a fixed info panel preserves the copyable range" + ); + clear_selection_for_composer_key( + &mut transcript, + KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE), + ); + assert!(!transcript.panel_selection.has_selection()); + assert_eq!(transcript.selection.selected_text(), transcript_text); +} + +#[test] +fn composer_keys_keep_reading_position_and_escape_returns_to_latest() { + let mut transcript = TranscriptState::default(); + transcript.scroll_up(3); + assert!(!return_to_latest_for_key( + &mut transcript, + KeyCode::Char('x') + )); + assert_eq!(transcript.scroll_rows(), 3); + + transcript.scroll_up(2); + assert!(return_to_latest_for_key(&mut transcript, KeyCode::Esc)); + assert_eq!(transcript.scroll_rows(), 0); +} + +#[test] +fn typing_and_submission_end_pinned_selection_while_transcript_navigation_keeps_it() { + let mut transcript = TranscriptState::default(); + let area = Rect::new(0, 0, 8, 2); + let buffer = Buffer::empty(area); + transcript.selection.refresh(area, &buffer, &[false, false]); + let down = MouseEvent { + kind: MouseEventKind::Down(MouseButton::Left), + column: 0, + row: 0, + modifiers: KeyModifiers::NONE, + }; + let begin = |transcript: &mut TranscriptState| { + transcript.selection.begin_with_snapshot( + down, + crate::ui::render_snapshot::render_snapshot(&rustcode::controller::render_state( + &AppState::new(), + )), + transcript.scroll_rows(), + ); + assert!(transcript.selection.is_active()); + }; + begin(&mut transcript); + assert!(is_transcript_navigation(KeyEvent::new( + KeyCode::PageUp, + KeyModifiers::NONE + ))); + clear_selection_for_composer_key( + &mut transcript, + KeyEvent::new(KeyCode::PageUp, KeyModifiers::NONE), + ); + assert!(transcript.selection.is_active()); + clear_selection_for_composer_key( + &mut transcript, + KeyEvent::new(KeyCode::Char('x'), KeyModifiers::NONE), + ); + assert!(!transcript.selection.is_active()); + begin(&mut transcript); + clear_selection_for_composer_key( + &mut transcript, + KeyEvent::new(KeyCode::Enter, KeyModifiers::NONE), + ); + assert!(!transcript.selection.is_active()); +} + +/// The Ctrl/Cmd+V fallback and the keymap paste share one insert helper, +/// so both land the same buffer for the same clipboard text at and just +/// below the large-paste threshold (#1527). +#[test] +fn clipboard_paste_paths_agree_on_threshold_and_newlines() { + let composer = Composer::default(); + for payload in [ + "y".repeat(299), + "z".repeat(300), + "one\r\ntwo\rthree".to_owned(), + ] { + let mut fallback = AppState::new(); + insert_clipboard_paste(&composer, &mut fallback, &payload); + + let mut keymap = AppState::new(); + composer.handle_paste(&mut keymap, &payload); + + assert_eq!( + fallback.input_buffer, keymap.input_buffer, + "fallback and keymap paste must insert the same buffer for {payload:?}" + ); + } +} + +#[test] +fn clipboard_paste_below_threshold_inserts_verbatim() { + let mut state = AppState::new(); + insert_clipboard_paste(&Composer::default(), &mut state, &"y".repeat(299)); + assert_eq!(state.input_buffer, "y".repeat(299)); + + let mut large = AppState::new(); + insert_clipboard_paste(&Composer::default(), &mut large, &"y".repeat(300)); + assert!(large.input_buffer.starts_with("")); +} diff --git a/scripts/comment-baseline.txt b/scripts/comment-baseline.txt index aca0bdc61..e64c13ae9 100644 --- a/scripts/comment-baseline.txt +++ b/scripts/comment-baseline.txt @@ -622,7 +622,9 @@ 12 harness/src/runtime/composer.rs 9 harness/src/runtime/detached.rs 2 harness/src/runtime/events.rs -136 harness/src/runtime/input.rs +60 harness/src/runtime/input.rs +50 harness/src/runtime/input/keyboard.rs +26 harness/src/runtime/input/tests.rs 6 harness/src/runtime/mod.rs 31 harness/src/runtime/orchestration.rs 83 harness/src/runtime/remote.rs diff --git a/scripts/rust-size-baseline.txt b/scripts/rust-size-baseline.txt index f39a06945..8247ca345 100644 --- a/scripts/rust-size-baseline.txt +++ b/scripts/rust-size-baseline.txt @@ -2,7 +2,6 @@ # Lower a cap when its file is split; never raise one. See scripts/check-rust-size.py. 3000 apps/desktop/src-tauri/src/machines.rs 2600 apps/desktop/src-tauri/src/updater.rs -3900 harness/src/runtime/input.rs 2500 harness/src/runtime/remote.rs 2400 harness/src/ui/history_cell.rs 3300 harness/src/ui/selection.rs