diff --git a/codex-rs/config/src/types.rs b/codex-rs/config/src/types.rs index b2cad6b4cd..a59f1252c3 100644 --- a/codex-rs/config/src/types.rs +++ b/codex-rs/config/src/types.rs @@ -710,6 +710,19 @@ pub enum TuiPetAnchor { ScreenBottom, } +/// When transcript mouse selections are copied on release. +#[derive(Serialize, Deserialize, Debug, Clone, Copy, PartialEq, Eq, JsonSchema, Default)] +#[serde(rename_all = "lowercase")] +pub enum CopyOnSelect { + /// Use the terminal-specific default. + #[default] + Auto, + /// Copy every nonempty transcript mouse selection on release. + Always, + /// Require an explicit copy action. + Never, +} + #[derive(Serialize, Deserialize, Debug, Clone, PartialEq, Eq, Default, JsonSchema)] #[schemars(deny_unknown_fields)] pub struct TuiNotificationSettings { @@ -803,6 +816,12 @@ pub struct Tui { #[serde(default = "default_true")] pub fullscreen_transcript: bool, + /// Copy selected transcript text when the mouse button is released. + /// Defaults to `auto`: enabled in tmux/Zellij and in direct macOS terminals except Ghostty/Kitty. + /// On other platforms, direct terminals default off except iTerm2/Terminal.app. + #[serde(default)] + pub copy_on_select: CopyOnSelect, + /// Controls whether the TUI uses the terminal's alternate screen buffer. /// /// - `auto` (default): Use alternate screen. diff --git a/codex-rs/core/config.schema.json b/codex-rs/core/config.schema.json index 4fee3989b2..68b12c3bd2 100644 --- a/codex-rs/core/config.schema.json +++ b/codex-rs/core/config.schema.json @@ -1262,6 +1262,32 @@ }, "type": "object" }, + "CopyOnSelect": { + "description": "When transcript mouse selections are copied on release.", + "oneOf": [ + { + "description": "Use the terminal-specific default.", + "enum": [ + "auto" + ], + "type": "string" + }, + { + "description": "Copy every nonempty transcript mouse selection on release.", + "enum": [ + "always" + ], + "type": "string" + }, + { + "description": "Require an explicit copy action.", + "enum": [ + "never" + ], + "type": "string" + } + ] + }, "CredentialAuthMethod": { "description": "Authentication formats supported by declarative credential providers.", "enum": [ @@ -4240,6 +4266,15 @@ "description": "Generate automatic conversation recaps when the terminal is unfocused. Defaults to `true`. Disabling this leaves `/recap` available on demand.", "type": "boolean" }, + "copy_on_select": { + "allOf": [ + { + "$ref": "#/definitions/CopyOnSelect" + } + ], + "default": "auto", + "description": "Copy selected transcript text when the mouse button is released. Defaults to `auto`: enabled in tmux/Zellij and in direct macOS terminals except Ghostty/Kitty. On other platforms, direct terminals default off except iTerm2/Terminal.app." + }, "disable_paste_burst": { "description": "When true, disables burst-paste detection for typed input entirely. All characters are inserted as they are received, and no buffering or placeholder replacement will occur for fast keypress bursts. Overrides the legacy top-level `disable_paste_burst` setting. Defaults to `false`.", "type": "boolean" diff --git a/codex-rs/core/src/config/config_tests.rs b/codex-rs/core/src/config/config_tests.rs index 431ff717d7..08d2d80d6c 100644 --- a/codex-rs/core/src/config/config_tests.rs +++ b/codex-rs/core/src/config/config_tests.rs @@ -1263,6 +1263,7 @@ fn config_toml_deserializes_model_availability_nux() { question_esc_back: true, raw_output_mode: false, fullscreen_transcript: true, + copy_on_select: Default::default(), alternate_screen: AltScreenMode::default(), status_line: None, status_line_use_colors: true, @@ -4402,6 +4403,7 @@ fn tui_config_missing_notifications_field_defaults_to_enabled() { question_esc_back: true, raw_output_mode: false, fullscreen_transcript: true, + copy_on_select: Default::default(), alternate_screen: AltScreenMode::Auto, status_line: None, status_line_use_colors: true, diff --git a/codex-rs/core/src/config/mod.rs b/codex-rs/core/src/config/mod.rs index 73ec14ef53..a4126bb5c5 100644 --- a/codex-rs/core/src/config/mod.rs +++ b/codex-rs/core/src/config/mod.rs @@ -786,6 +786,9 @@ pub struct Config { /// Own the fullscreen transcript when the alternate screen is enabled. pub tui_fullscreen_transcript: bool, + /// Override the terminal-specific default for copying transcript mouse selections. + pub tui_copy_on_select: codex_config::types::CopyOnSelect, + /// Start the TUI in the specified collaboration mode (plan/default). /// Controls whether the TUI uses the terminal's alternate screen buffer. @@ -4475,6 +4478,11 @@ impl Config { .tui .as_ref() .is_none_or(|tui| tui.fullscreen_transcript), + tui_copy_on_select: cfg + .tui + .as_ref() + .map(|tui| tui.copy_on_select) + .unwrap_or_default(), tui_alternate_screen: cfg .tui .as_ref() diff --git a/codex-rs/thread-manager-sample/src/main.rs b/codex-rs/thread-manager-sample/src/main.rs index 308ce8b2e5..3b0fa8d8de 100644 --- a/codex-rs/thread-manager-sample/src/main.rs +++ b/codex-rs/thread-manager-sample/src/main.rs @@ -237,6 +237,7 @@ fn new_config(model: Option, arg0_paths: Arg0DispatchPaths) -> anyhow::R tui_auto_recap: true, model_availability_nux: ModelAvailabilityNuxConfig::default(), tui_fullscreen_transcript: false, + tui_copy_on_select: Default::default(), tui_alternate_screen: AltScreenMode::Auto, tui_status_line: None, tui_status_line_use_colors: true, diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index 18ba695600..650c6ccc12 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -41,6 +41,9 @@ impl App { let chat_widget = &self.chat_widget; let transcript_width = chat_widget.history_wrap_width(width); let view = &mut self.transcript_view; + view.copy_on_select = self + .local_settings + .copy_on_select(&codex_terminal_detection::terminal_info()); view.set_keymap_bindings(&self.keymap); view.set_presentation(view.is_detailed(), chat_widget.history_render_mode()); let active_key = chat_widget.active_cell_transcript_key(); @@ -452,14 +455,21 @@ impl App { return self.handle_owned_backtrack_event(tui, event); }; let resume_following = matches!(action, ViewAction::CopyAndFollow(_)); + let copy_on_select = matches!(action, ViewAction::CopyOnSelect(_)); match action { ViewAction::Changed => {} - ViewAction::Copy(text) | ViewAction::CopyAndFollow(text) => { - let result = self.transcript_view.copy_selected_text_with( - &self.transcript_cells, - &text, - |text| tui.copy_transcript_selection(text), - ); + ViewAction::Copy(text) + | ViewAction::CopyOnSelect(text) + | ViewAction::CopyAndFollow(text) => { + let result = if copy_on_select { + tui.copy_transcript_selection(&text) + } else { + self.transcript_view.copy_selected_text_with( + &self.transcript_cells, + &text, + |text| tui.copy_transcript_selection(text), + ) + }; self.transcript_view .show_copy_feedback(&result, text.chars().count()); if resume_following diff --git a/codex-rs/tui/src/app/owned_transcript_tests.rs b/codex-rs/tui/src/app/owned_transcript_tests.rs index c06fef4b58..6d05952861 100644 --- a/codex-rs/tui/src/app/owned_transcript_tests.rs +++ b/codex-rs/tui/src/app/owned_transcript_tests.rs @@ -11,6 +11,7 @@ use crate::session_state::ThreadSessionState; use crate::test_support::test_path_buf; use codex_app_server_protocol::AskForApproval; use codex_config::types::ApprovalsReviewer; +use codex_config::types::CopyOnSelect; use codex_protocol::models::PermissionProfile; use crossterm::event::MouseButton::Left; use crossterm::event::MouseButton::Right; @@ -1349,6 +1350,7 @@ fn row_containing(tui: &tui::Tui, text: &str) -> u16 { #[tokio::test] async fn fullscreen_composer_mouse_copy_and_input_ownership() -> Result<()> { let mut app = crate::app::test_support::make_test_app().await; + app.local_settings.tui.copy_on_select = CopyOnSelect::Never; let mut server = Box::pin(crate::start_embedded_app_server_for_picker(&app.config)).await?; let mut tui = crate::tui::test_support::make_test_tui()?; tui.set_owned_screen(/*owned*/ true)?; @@ -1381,10 +1383,21 @@ async fn fullscreen_composer_mouse_copy_and_input_ownership() -> Result<()> { } let copy_events = [ TuiEvent::Key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::SUPER)), + TuiEvent::Key(KeyEvent::new(KeyCode::Char('c'), KeyModifiers::CONTROL)), mouse(Down(Right), x + 2, y), ]; let mut selection_frames = Vec::new(); - for event in ©_events { + for (index, event) in copy_events.iter().enumerate() { + // Each confirmed copy clears the selection, so select again for the next gesture. + if index > 0 { + for event in [ + mouse(Down(Left), x, y), + mouse(Drag(Left), x + 5, y), + mouse(Up(Left), x + 5, y), + ] { + assert!(app.handle_owned_transcript_event(&mut tui, &mut server, &event)?); + } + } for result in [ Err("clipboard unavailable".to_string()), Ok(crate::clipboard_copy::CopyStatus::Unconfirmed), @@ -1411,8 +1424,7 @@ async fn fullscreen_composer_mouse_copy_and_input_ownership() -> Result<()> { } }) .collect::(); - let cleared = matches!(event, TuiEvent::Mouse(_)) - && result == Ok(crate::clipboard_copy::CopyStatus::Confirmed); + let cleared = result == Ok(crate::clipboard_copy::CopyStatus::Confirmed); assert_eq!( ( app.chat_widget.capture_thread_input_state(), @@ -1429,10 +1441,10 @@ async fn fullscreen_composer_mouse_copy_and_input_ownership() -> Result<()> { }, ) ); - let gesture = if matches!(event, TuiEvent::Mouse(_)) { - "right-click" - } else { - "keyboard" + let gesture = match event { + TuiEvent::Mouse(_) => "right-click", + TuiEvent::Key(key) if key.modifiers == KeyModifiers::SUPER => "cmd-c", + _ => "ctrl-c", }; selection_frames.push(format!( "{gesture} {result:?}\n{rendered_draft}\n{selection}" diff --git a/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__tests__fullscreen_composer_right_click_copy.snap b/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__tests__fullscreen_composer_right_click_copy.snap index 114eff9b5b..ebc424a3b0 100644 --- a/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__tests__fullscreen_composer_right_click_copy.snap +++ b/codex-rs/tui/src/app/snapshots/codex_tui__app__owned_transcript__tests__fullscreen_composer_right_click_copy.snap @@ -1,20 +1,31 @@ --- source: tui/src/app/owned_transcript_tests.rs -assertion_line: 1245 expression: "format!(\"{}\\n\\n{}\", selection_frames.join(\"\\n\\n\"),\nnormalize_snapshot_paths(buffer_text(crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal))))" --- -keyboard Err("clipboard unavailable") +cmd-c Err("clipboard unavailable") hello world ^^^^^······ -keyboard Ok(Unconfirmed) +cmd-c Ok(Unconfirmed) hello world ^^^^^······ -keyboard Ok(Confirmed) +cmd-c Ok(Confirmed) +hello world +··········· + +ctrl-c Err("clipboard unavailable") hello world ^^^^^······ +ctrl-c Ok(Unconfirmed) +hello world +^^^^^······ + +ctrl-c Ok(Confirmed) +hello world +··········· + right-click Err("clipboard unavailable") hello world ^^^^^······ diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 4e17f2df3a..bdfc3aa23e 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -9583,6 +9583,7 @@ async fn clear_only_ui_reset_preserves_chat_session_state() { app.overlay = Some(Overlay::new_transcript( app.transcript_cells.clone(), crate::keymap::RuntimeKeymap::defaults().pager, + /*copy_on_select*/ false, )); app.deferred_history_lines = vec![Line::from("stale buffered line").into()]; app.has_emitted_history_lines = true; diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index 1cdadf53b2..4e63f0caef 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -169,6 +169,8 @@ impl App { self.overlay = Some(Overlay::new_transcript( self.transcript_cells.clone(), self.keymap.pager.clone(), + self.local_settings + .copy_on_select(&codex_terminal_detection::terminal_info()), )); if self.scrollback_has_older_history && let Some(Overlay::Transcript(overlay)) = self.overlay.as_mut() diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 158c39f1c7..3f2e483f71 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -245,7 +245,8 @@ //! The burst detector can also be disabled (`disable_paste_burst`), which bypasses the state //! machine and treats the key stream as normal typing. When toggling from enabled → disabled, the //! composer flushes/clears any in-flight burst state so it cannot leak into subsequent input. -//! Mouse edits flush pending typing; selection and copy behavior lives in [`mouse`]. +//! Mouse edits flush pending typing; selection and copy behavior lives in [`mouse`]. Confirmed +//! copies clear the selection while preserving the draft and cursor. //! //! For the detailed burst state machine, see `codex-rs/tui/src/bottom_pane/paste_burst.rs`. //! diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/mouse.rs b/codex-rs/tui/src/bottom_pane/chat_composer/mouse.rs index b99763c90a..5f4ca77893 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/mouse.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/mouse.rs @@ -1,7 +1,7 @@ //! Mouse gestures flush pending typing before layout and hit testing. Left dragging selects //! editable text using the textarea's last rendered viewport and hides completion suggestions. //! Double/triple clicks select words/logical lines using the transcript's shared gesture rules. -//! Copy preserves the draft; confirmed right-click copies clear selection, keyboard copies retain it. +//! Copy preserves the draft and cursor; confirmed copies clear selection for every gesture. use super::*; use crate::clipboard_copy::CopyStatus; @@ -36,7 +36,7 @@ impl ChatComposer { let text = &self.draft.textarea.text()[range]; let char_count = text.chars().count(); let result = copy(text); - if matches!(event, TuiEvent::Mouse(_)) && result == Ok(CopyStatus::Confirmed) { + if result == Ok(CopyStatus::Confirmed) { self.draft.textarea.set_cursor(self.draft.textarea.cursor()); } Some((char_count, result)) diff --git a/codex-rs/tui/src/local_settings.rs b/codex-rs/tui/src/local_settings.rs index aab16143cc..6a3c00fee5 100644 --- a/codex-rs/tui/src/local_settings.rs +++ b/codex-rs/tui/src/local_settings.rs @@ -10,9 +10,13 @@ use crate::legacy_core::config::Config; use crate::legacy_core::config::TerminalResizeReflowConfig; use crate::legacy_core::config::TerminalResizeReflowMaxRows; use crate::transcript_mode::TranscriptMode; +use codex_config::types::CopyOnSelect; use codex_config::types::History; use codex_config::types::Notice; use codex_config::types::Tui; +use codex_terminal_detection::Multiplexer; +use codex_terminal_detection::TerminalInfo; +use codex_terminal_detection::TerminalName; use codex_utils_absolute_path::AbsolutePathBuf; #[derive(Clone, Debug, PartialEq)] @@ -72,6 +76,7 @@ impl LocalSettings { question_esc_back: config.tui_question_esc_back, raw_output_mode: config.tui_raw_output_mode, fullscreen_transcript: config.tui_fullscreen_transcript, + copy_on_select: config.tui_copy_on_select, alternate_screen: config.tui_alternate_screen, status_line: config.tui_status_line.clone(), status_line_use_colors: config.tui_status_line_use_colors, @@ -122,6 +127,25 @@ impl LocalSettings { settings } + /// Prefer explicit overrides; tmux/Zellij always default to copying on release. + /// Direct macOS terminals default on except Ghostty/Kitty, which forward Cmd-C. + pub(crate) fn copy_on_select(&self, terminal: &TerminalInfo) -> bool { + match self.tui.copy_on_select { + CopyOnSelect::Always => true, + CopyOnSelect::Never => false, + CopyOnSelect::Auto => match terminal.multiplexer { + Some(Multiplexer::Tmux { .. } | Multiplexer::Zellij { .. }) => true, + None if cfg!(target_os = "macos") => { + !matches!(terminal.name, TerminalName::Ghostty | TerminalName::Kitty) + } + None => matches!( + terminal.name, + TerminalName::Iterm2 | TerminalName::AppleTerminal + ), + }, + } + } + pub(crate) fn terminal_resize_reflow(&self) -> TerminalResizeReflowConfig { TerminalResizeReflowConfig { max_rows: match self.tui.terminal_resize_reflow_max_rows { diff --git a/codex-rs/tui/src/local_settings_tests.rs b/codex-rs/tui/src/local_settings_tests.rs index 99a67e46cd..7422aa7ea4 100644 --- a/codex-rs/tui/src/local_settings_tests.rs +++ b/codex-rs/tui/src/local_settings_tests.rs @@ -3,6 +3,7 @@ use crate::legacy_core::config::ConfigBuilder; use crate::legacy_core::config::edit::ConfigEditsBuilder; use codex_config::LoaderOverrides; use codex_config::types::SessionPickerViewMode; +use codex_terminal_detection::Multiplexer; use pretty_assertions::assert_eq; #[tokio::test] @@ -17,6 +18,7 @@ async fn launch_screen_mode_survives_configuration_reload() -> anyhow::Result<() .build() .await?; config.tui_fullscreen_transcript = true; + config.tui_copy_on_select = CopyOnSelect::Always; config.tui_alternate_screen = AltScreenMode::Auto; for (alternate_screen, owned, expected_mode, expected_alt) in [ @@ -35,6 +37,7 @@ async fn launch_screen_mode_survives_configuration_reload() -> anyhow::Result<() let mut reloaded_config = config.clone(); reloaded_config.tui_fullscreen_transcript = false; + reloaded_config.tui_copy_on_select = CopyOnSelect::Never; reloaded_config.tui_alternate_screen = AltScreenMode::Never; reloaded_config.tui_theme = Some("nord".into()); let mut expected = LocalSettings::from(&reloaded_config); @@ -99,6 +102,7 @@ show_tooltips = false show_server_version_notice = false auto_recap = false fullscreen_transcript = true +copy_on_select = "never" vim_mode_default = true terminal_resize_reflow_max_rows = 0 session_picker_view = "comfortable" @@ -153,6 +157,7 @@ fast_default_opt_out = true expected.show_server_version_notice = false; expected.auto_recap = false; expected.fullscreen_transcript = true; + expected.copy_on_select = CopyOnSelect::Never; expected.vim_mode_default = true; expected.terminal_resize_reflow_max_rows = Some(0); expected.session_picker_view = Some(SessionPickerViewMode::Comfortable); @@ -182,6 +187,83 @@ fast_default_opt_out = true Ok(()) } +#[tokio::test] +async fn copy_on_select_respects_terminal_defaults_and_config_overrides() -> anyhow::Result<()> { + for (configured, launch_override, expected) in [ + (None, None, CopyOnSelect::Auto), + (Some("auto"), None, CopyOnSelect::Auto), + (Some("always"), None, CopyOnSelect::Always), + (Some("never"), None, CopyOnSelect::Never), + (Some("never"), Some("always"), CopyOnSelect::Always), + (Some("always"), Some("never"), CopyOnSelect::Never), + (Some("always"), Some("auto"), CopyOnSelect::Auto), + (Some("never"), Some("auto"), CopyOnSelect::Auto), + ] { + let home = tempfile::tempdir()?; + let config_path = home.path().join("config.toml"); + let config_text = configured + .map(|mode| format!("[tui]\ncopy_on_select = \"{mode}\"\n")) + .unwrap_or_default(); + std::fs::write(&config_path, &config_text)?; + let config = ConfigBuilder::default() + .codex_home(home.path().to_path_buf()) + .strict_config(true) + .loader_overrides(LoaderOverrides { + ignore_project_config: true, + ..LoaderOverrides::without_managed_config_for_tests() + }) + .cli_overrides( + launch_override + .map(|mode| ("tui.copy_on_select".into(), mode.into())) + .into_iter() + .collect(), + ) + .build() + .await?; + let local = LocalSettings::from(&config); + assert_eq!( + (config.tui_copy_on_select, local.tui.copy_on_select), + (expected, expected), + ); + for (name, multiplexer, default_enabled) in [ + (TerminalName::Iterm2, None, true), + (TerminalName::AppleTerminal, None, true), + (TerminalName::Ghostty, None, false), + (TerminalName::Kitty, None, false), + (TerminalName::Unknown, None, cfg!(target_os = "macos")), + ( + TerminalName::Ghostty, + Some(Multiplexer::Tmux { version: None }), + true, + ), + ( + TerminalName::Kitty, + Some(Multiplexer::Zellij { version: None }), + true, + ), + ] { + let terminal = TerminalInfo { + name, + multiplexer, + term_program: None, + version: None, + term: None, + }; + assert_eq!( + local.copy_on_select(&terminal), + match expected { + CopyOnSelect::Auto => default_enabled, + CopyOnSelect::Always => true, + CopyOnSelect::Never => false, + }, + "terminal={terminal:?}, override={expected:?}", + ); + } + assert_eq!(std::fs::read_to_string(config_path)?, config_text); + } + Ok(()) +} + #[tokio::test] async fn local_writes_preserve_selected_user_file_and_home_destinations() -> anyhow::Result<()> { let home = tempfile::tempdir()?; diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 9bfc6aa2ac..370ee16e82 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -48,8 +48,14 @@ pub(crate) enum Overlay { } impl Overlay { - pub(crate) fn new_transcript(cells: Vec>, keymap: PagerKeymap) -> Self { - Self::Transcript(TranscriptOverlay::new(cells, keymap)) + pub(crate) fn new_transcript( + cells: Vec>, + keymap: PagerKeymap, + copy_on_select: bool, + ) -> Self { + let mut overlay = TranscriptOverlay::new(cells, keymap); + overlay.view.copy_on_select = copy_on_select; + Self::Transcript(overlay) } pub(crate) fn new_static_with_lines( diff --git a/codex-rs/tui/src/pager_overlay/transcript.rs b/codex-rs/tui/src/pager_overlay/transcript.rs index af5f6aa9d5..8160732866 100644 --- a/codex-rs/tui/src/pager_overlay/transcript.rs +++ b/codex-rs/tui/src/pager_overlay/transcript.rs @@ -426,14 +426,20 @@ impl TranscriptOverlay { fn apply_action(&mut self, tui: &mut tui::Tui, action: ViewAction) { self.notice = None; let resume_following = matches!(action, ViewAction::CopyAndFollow(_)); + let copy_on_select = matches!(action, ViewAction::CopyOnSelect(_)); match action { ViewAction::Changed => {} - ViewAction::Copy(text) | ViewAction::CopyAndFollow(text) => { - let result = self - .view - .copy_selected_text_with(&self.cells, &text, |text| { - tui.copy_transcript_selection(text) - }); + ViewAction::Copy(text) + | ViewAction::CopyOnSelect(text) + | ViewAction::CopyAndFollow(text) => { + let result = if copy_on_select { + tui.copy_transcript_selection(&text) + } else { + self.view + .copy_selected_text_with(&self.cells, &text, |text| { + tui.copy_transcript_selection(text) + }) + }; if resume_following && matches!(result, Ok(crate::clipboard_copy::CopyStatus::Confirmed)) { diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 5a976e468d..2f90753872 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -335,6 +335,7 @@ struct SessionPickerViewPersistence { struct SessionPickerRunOptions { use_theme_colors: bool, + copy_on_select: bool, show_all: bool, filter_cwd: Option, local_filter_cwd: Option, @@ -445,6 +446,7 @@ async fn run_resume_picker_with_launch_context( let runtime_keymap = picker_runtime_keymap(local_settings)?; let options = SessionPickerRunOptions { use_theme_colors: local_settings.tui.status_line_use_colors, + copy_on_select: local_settings.copy_on_select(&codex_terminal_detection::terminal_info()), show_all, filter_cwd: cwd_filter, local_filter_cwd, @@ -504,6 +506,7 @@ pub async fn run_fork_picker_with_app_server( let runtime_keymap = picker_runtime_keymap(local_settings)?; let options = SessionPickerRunOptions { use_theme_colors: local_settings.tui.status_line_use_colors, + copy_on_select: local_settings.copy_on_select(&codex_terminal_detection::terminal_info()), show_all, filter_cwd: cwd_filter, local_filter_cwd, @@ -558,6 +561,7 @@ async fn run_session_picker_with_loader( ); state.local_filter_cwd = options.local_filter_cwd; state.use_theme_colors = options.use_theme_colors; + state.copy_on_select = options.copy_on_select; state.worktrees_enabled = options.worktrees_enabled; state.density = options.initial_density; state.view_persistence = options.view_persistence; @@ -827,6 +831,7 @@ impl Drop for AltScreenGuard<'_> { struct PickerState { clock_format: ClockFormat, use_theme_colors: bool, + copy_on_select: bool, // Resolve local filesystem membership once per cwd for each page-loading cycle. local_cwd_matches: HashMap, requester: FrameRequester, @@ -1027,6 +1032,7 @@ impl PickerState { Self { clock_format: ClockFormat::system(), use_theme_colors: true, + copy_on_select: false, requester, relative_time_reference: None, pagination: PaginationState::new(), @@ -1128,7 +1134,11 @@ impl PickerState { else { return; }; - let mut overlay = Overlay::new_transcript(cells.clone(), self.keymap.pager.clone()); + let mut overlay = Overlay::new_transcript( + cells.clone(), + self.keymap.pager.clone(), + self.copy_on_select, + ); if let Overlay::Transcript(view) = &mut overlay { view.set_keymap_bindings(&self.keymap); } diff --git a/codex-rs/tui/src/transcript_view.rs b/codex-rs/tui/src/transcript_view.rs index d7c03bb2d7..16ea34bb88 100644 --- a/codex-rs/tui/src/transcript_view.rs +++ b/codex-rs/tui/src/transcript_view.rs @@ -84,6 +84,7 @@ struct VisibleRow { /// Shared scrolling and interaction state for compact and detailed transcript presentations. pub(crate) struct TranscriptView { + pub(crate) copy_on_select: bool, position: Position, follow_control: follow_control::FollowControl, copy_feedback: Option, @@ -114,6 +115,7 @@ pub(crate) struct TranscriptView { impl Default for TranscriptView { fn default() -> Self { Self { + copy_on_select: false, position: Position::Latest, follow_control: follow_control::FollowControl::default(), copy_feedback: None, @@ -589,3 +591,7 @@ impl TranscriptView { #[cfg(test)] #[path = "transcript_view_tests.rs"] mod tests; + +#[cfg(test)] +#[path = "transcript_view/copy_on_select_tests.rs"] +mod copy_on_select_tests; diff --git a/codex-rs/tui/src/transcript_view/copy_on_select_tests.rs b/codex-rs/tui/src/transcript_view/copy_on_select_tests.rs new file mode 100644 index 0000000000..f3df68a0f0 --- /dev/null +++ b/codex-rs/tui/src/transcript_view/copy_on_select_tests.rs @@ -0,0 +1,156 @@ +//! Automatic copies retain completed mouse selections. + +use super::*; +use crate::history_cell::AgentMarkdownCell; +use crate::transcript_view::tests::cell; +use crate::transcript_view::tests::render; +use crate::transcript_view::tests::text; +use crossterm::event::KeyModifiers; +use crossterm::event::MouseButton; +use crossterm::event::MouseEvent; +use crossterm::event::MouseEventKind; +use pretty_assertions::assert_eq; +use std::time::Instant; + +fn mouse(kind: MouseEventKind, column: u16) -> MouseEvent { + MouseEvent { + kind, + column, + row: 0, + modifiers: KeyModifiers::NONE, + } +} + +#[test] +fn copy_on_select_waits_for_release_and_retains_selection() { + let cells = vec![cell("selected text")]; + for enabled in [false, true] { + let mut view = TranscriptView { + copy_on_select: enabled, + ..Default::default() + }; + render(&mut view, &cells, /*width*/ 20, /*height*/ 1); + for event in [ + mouse(MouseEventKind::Down(MouseButton::Left), /*column*/ 0), + mouse(MouseEventKind::Drag(MouseButton::Left), /*column*/ 5), + ] { + assert!(matches!( + view.handle_mouse(event, &cells), + Some(ViewAction::Changed) + )); + } + let release = mouse(MouseEventKind::Up(MouseButton::Left), /*column*/ 8); + let copied = match view.handle_mouse(release, &cells) { + Some(ViewAction::CopyOnSelect(text)) => Some(text), + Some(ViewAction::Changed) => None, + _ => panic!("release must finish the selection"), + }; + assert_eq!(copied.as_deref(), enabled.then_some("selected")); + assert_eq!(view.selected_text(&cells).as_deref(), Some("selected")); + assert!(view.handle_mouse(release, &cells).is_none()); + assert!(!view.tick_selection(&cells)); + if copied.is_some() { + let buffer = render(&mut view, &cells, /*width*/ 20, /*height*/ 1); + let highlight = (0..20) + .map(|column| { + if buffer[(column, 0)] + .modifier + .contains(ratatui::style::Modifier::REVERSED) + { + '^' + } else { + '·' + } + }) + .collect::(); + insta::assert_snapshot!( + format!("{}\n{highlight}", text(&buffer)), + @" + selected text + ^^^^^^^^············ + " + ); + } + } +} + +#[test] +fn copy_on_select_copies_word_and_line_on_release_without_dragging() { + let cells = vec![cell("alpha beta gamma")]; + let mut view = TranscriptView { + copy_on_select: true, + ..Default::default() + }; + render(&mut view, &cells, /*width*/ 24, /*height*/ 1); + let down = mouse(MouseEventKind::Down(MouseButton::Left), /*column*/ 7); + let up = MouseEvent { + kind: MouseEventKind::Up(MouseButton::Left), + ..down + }; + for expected in [None, Some("beta"), Some("alpha beta gamma")] { + if let Some((at, ..)) = &mut view.last_click { + *at = Instant::now(); + } + assert!(matches!( + view.handle_mouse(down, &cells), + Some(ViewAction::Changed) + )); + let copied = match view.handle_mouse(up, &cells) { + Some(ViewAction::CopyOnSelect(text)) => Some(text), + Some(ViewAction::Changed) => None, + _ => panic!("release must finish the repeated click"), + }; + assert_eq!( + (copied.as_deref(), view.selected_text(&cells).as_deref()), + (expected, expected) + ); + assert!(view.handle_mouse(up, &cells).is_none()); + } +} + +#[test] +fn copy_on_select_preserves_link_activation_and_ignores_empty_drags() { + let cells: Vec> = vec![Arc::new(AgentMarkdownCell::new( + "[example.com](https://example.com/docs)".into(), + std::path::Path::new("/"), + ))]; + for (drag, release) in [(None, 2), (Some(5), 5), (Some(5), 2)] { + let mut view = TranscriptView { + copy_on_select: true, + ..Default::default() + }; + render(&mut view, &cells, /*width*/ 30, /*height*/ 1); + let down = mouse(MouseEventKind::Down(MouseButton::Left), /*column*/ 2); + assert!(matches!( + view.handle_mouse(down, &cells), + Some(ViewAction::Changed) + )); + if let Some(column) = drag { + assert!(matches!( + view.handle_mouse( + mouse(MouseEventKind::Drag(MouseButton::Left), column), + &cells + ), + Some(ViewAction::Changed) + )); + } + let action = view.handle_mouse( + mouse(MouseEventKind::Up(MouseButton::Left), release), + &cells, + ); + match (drag, release, action) { + (None, _, Some(ViewAction::OpenLink(url))) => { + assert_eq!(url, "https://example.com/docs"); + assert_eq!(view.selected_text(&cells), None); + } + (Some(_), 5, Some(ViewAction::CopyOnSelect(copied))) => { + assert_eq!(copied, "exa"); + assert_eq!(view.selected_text(&cells).as_deref(), Some("exa")); + } + (Some(_), 2, Some(ViewAction::Changed)) => { + assert_eq!(view.selected_text(&cells), None); + } + _ => panic!("only a nonempty link drag should copy"), + } + } +} diff --git a/codex-rs/tui/src/transcript_view/input.rs b/codex-rs/tui/src/transcript_view/input.rs index a116a2f9c3..f92a319bb7 100644 --- a/codex-rs/tui/src/transcript_view/input.rs +++ b/codex-rs/tui/src/transcript_view/input.rs @@ -1,6 +1,8 @@ //! Transcript gestures leave ordinary typing and composer editing with the existing input path. //! Stationary link clicks open on release; dragging or scrolling keeps the gesture in selection. //! Shift-click extends the existing selection from its original text unit. +//! Optional automatic copying happens only when a nonempty mouse selection is released. +//! Automatic copies retain the selection; explicit copies clear it after confirmed delivery. use crate::key_hint::KeyBindingListExt; use crossterm::event::KeyCode; @@ -17,6 +19,7 @@ use super::*; pub(crate) enum ViewAction { Changed, Copy(String), + CopyOnSelect(String), CopyAndFollow(String), OpenLink(String), } @@ -258,12 +261,18 @@ impl TranscriptView { self.extend_selection(event.column, event.row); } self.end_drag(); - if self.selected_text(cells).is_none() { + let selected = self.selected_text(cells); + if selected.is_none() { self.end_selection(cells); } if let Some(link) = link { return Some(ViewAction::OpenLink(link)); } + if self.copy_on_select + && let Some(text) = selected.filter(|text| !text.is_empty()) + { + return Some(ViewAction::CopyOnSelect(text)); + } } _ => return None, } diff --git a/codex-rs/tui/src/tui/selection_clipboard_tests.rs b/codex-rs/tui/src/tui/selection_clipboard_tests.rs index fc8af07e7c..0a28ea6eb8 100644 --- a/codex-rs/tui/src/tui/selection_clipboard_tests.rs +++ b/codex-rs/tui/src/tui/selection_clipboard_tests.rs @@ -20,6 +20,7 @@ async fn selection_clipboard_survives_overlay_close_and_later_terminal_requests( let mut overlay = Overlay::new_transcript( vec![Arc::new(PlainHistoryCell::new(vec!["selected".into()]))], RuntimeKeymap::defaults().pager, + /*copy_on_select*/ false, ); assert_eq!( tui.copy_transcript_selection_with("selected", |text| {