From bede3b5df8dfcdfa4ff74c8d762f1fb72ccaff9e Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Wed, 25 Nov 2026 00:13:01 +0000 Subject: [PATCH] Centralize TUI clipboard decisions in terminal capabilities (#63797) ## Why Terminal checks for clipboard behavior are spread across the clipboard worker, local settings, and right-click paste handling. ## What changed Use `terminal_capabilities` to determine whether the terminal forwards copy shortcuts or handles paste itself, whether X11 primary selection is available, and how to send OSC 52 through tmux or GNU Screen. Have TUI callers use the same SSH and WSL session checks. Keep the automatic copy-on-select decision in settings and base it on whether the terminal forwards the copy shortcut. Route tmux clipboard copies through the client buffer with OSC 52 as a fallback. GitOrigin-RevId: 623599783b70d66a06c52458fc82305a422cf507 --- codex-rs/tui/src/app/footer_selection.rs | 4 +- codex-rs/tui/src/app/history_ui.rs | 2 +- codex-rs/tui/src/app/history_ui_tests.rs | 2 +- codex-rs/tui/src/app/owned_transcript.rs | 7 +- codex-rs/tui/src/app/right_click_paste.rs | 16 +-- .../tui/src/app/right_click_paste_tests.rs | 22 ++-- codex-rs/tui/src/app/test_support.rs | 2 +- codex-rs/tui/src/app/tests.rs | 4 +- codex-rs/tui/src/app_backtrack.rs | 3 +- codex-rs/tui/src/chatwidget/clipboard.rs | 4 +- codex-rs/tui/src/chatwidget/config_panel.rs | 4 +- .../src/chatwidget/tests/slash_commands.rs | 4 +- codex-rs/tui/src/clipboard_copy.rs | 50 +++----- codex-rs/tui/src/clipboard_copy/primary.rs | 10 +- .../tui/src/clipboard_copy/routing_tests.rs | 12 +- codex-rs/tui/src/clipboard_copy/worker.rs | 8 +- codex-rs/tui/src/clipboard_paste/text.rs | 6 +- codex-rs/tui/src/device_login.rs | 2 +- codex-rs/tui/src/local_settings.rs | 49 ++------ codex-rs/tui/src/local_settings_tests.rs | 6 +- codex-rs/tui/src/resume_picker.rs | 4 +- codex-rs/tui/src/session_lock/linux.rs | 3 +- codex-rs/tui/src/terminal_capabilities.rs | 118 ++++++++++++++++-- .../terminal_capabilities/keyboard_modes.rs | 8 +- codex-rs/tui/src/tui.rs | 3 - 25 files changed, 194 insertions(+), 159 deletions(-) diff --git a/codex-rs/tui/src/app/footer_selection.rs b/codex-rs/tui/src/app/footer_selection.rs index 411a476707..82a13f757e 100644 --- a/codex-rs/tui/src/app/footer_selection.rs +++ b/codex-rs/tui/src/app/footer_selection.rs @@ -41,9 +41,7 @@ impl App { selection.clear(); return Ok(false); } - selection.view.copy_on_select = self - .local_settings - .copy_on_select(&codex_terminal_detection::terminal_info()); + selection.view.copy_on_select = self.local_settings.copy_on_select(); selection.view.copy_on_select_clear_selection = self.local_settings.tui.copy_on_select_clear_selection; selection.view.primary_selection = self.right_click_paste_environment.primary; diff --git a/codex-rs/tui/src/app/history_ui.rs b/codex-rs/tui/src/app/history_ui.rs index 8228d9b8b7..def6eee7d5 100644 --- a/codex-rs/tui/src/app/history_ui.rs +++ b/codex-rs/tui/src/app/history_ui.rs @@ -28,7 +28,7 @@ impl App { .downcast_mut::() && !self.app_server_target.uses_remote_workspace() && crate::projectless::has_only_local_environments(&self.environment_manager) - && !crate::clipboard_copy::is_ssh_session() + && !crate::terminal_capabilities::is_ssh_session() { image.link_local_image(); } diff --git a/codex-rs/tui/src/app/history_ui_tests.rs b/codex-rs/tui/src/app/history_ui_tests.rs index 46bbd9eb47..195652ff4f 100644 --- a/codex-rs/tui/src/app/history_ui_tests.rs +++ b/codex-rs/tui/src/app/history_ui_tests.rs @@ -41,7 +41,7 @@ async fn viewed_image_links_follow_workspace_locality() -> Result<()> { let endpoint = crate::resolve_remote_addr("ws://127.0.0.1:4500")?; let (mut app, _, _) = make_test_app_with_channels().await; let mut tui = crate::tui::test_support::make_test_tui()?; - let local_links = !crate::clipboard_copy::is_ssh_session(); + let local_links = !crate::terminal_capabilities::is_ssh_session(); for (target, linked) in [ (AppServerTarget::Embedded, local_links), ( diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index 0a0cb29c9c..b593110d70 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -178,8 +178,7 @@ impl App { event: crossterm::event::MouseEvent, ) -> bool { let selection_copy = crate::tui::SelectionCopy::on_select( - self.local_settings - .copy_on_select(&codex_terminal_detection::terminal_info()), + self.local_settings.copy_on_select(), self.right_click_paste_environment.primary, // Editable selections remain visible so the next input can replace them. /*clear_selection*/ @@ -214,9 +213,7 @@ impl App { let view = &mut self.transcript_view; view.mouse_scroll_speed = self.local_settings.tui.mouse_scroll_speed.unwrap_or(1.0); view.primary_selection = self.right_click_paste_environment.primary; - view.copy_on_select = self - .local_settings - .copy_on_select(&codex_terminal_detection::terminal_info()); + view.copy_on_select = self.local_settings.copy_on_select(); view.copy_on_select_clear_selection = self.local_settings.tui.copy_on_select_clear_selection; view.set_keymap_bindings(&self.keymap); diff --git a/codex-rs/tui/src/app/right_click_paste.rs b/codex-rs/tui/src/app/right_click_paste.rs index 529a957ab9..8aa2414139 100644 --- a/codex-rs/tui/src/app/right_click_paste.rs +++ b/codex-rs/tui/src/app/right_click_paste.rs @@ -7,8 +7,8 @@ use super::*; use crate::bottom_pane::ClipboardPasteTarget; use crate::clipboard_copy::worker::PasteSource; +use crate::terminal_capabilities::PasteOwner; use crate::transcript_mode::TranscriptMode; -use crate::tui::VscodeDetection; use codex_config::types::RightClickPaste; use crossterm::event::MouseButton; use crossterm::event::MouseEvent; @@ -27,7 +27,7 @@ pub(crate) struct PasteEnvironment { pub(super) platform_default: bool, pub(super) ssh: bool, pub(super) wsl: bool, - pub(super) vscode: VscodeDetection, + pub(super) owner: PasteOwner, } impl PasteEnvironment { @@ -35,9 +35,9 @@ impl PasteEnvironment { Self { primary: crate::clipboard_copy::primary::available(), platform_default: cfg!(any(target_os = "windows", target_os = "linux")), - ssh: crate::clipboard_copy::is_ssh_session(), - wsl: crate::clipboard_copy::is_wsl_session(), - vscode: tui::detect_vscode_terminal(), + ssh: crate::terminal_capabilities::is_ssh_session(), + wsl: crate::terminal_capabilities::is_wsl_session(), + owner: crate::terminal_capabilities::paste_owner(), } } @@ -61,10 +61,10 @@ impl PasteEnvironment { if self.ssh { return Err("Unavailable over SSH; use your terminal's paste command"); } - if self.vscode == VscodeDetection::VsCode { - return Err("VS Code handles pasting; use its terminal paste command"); + if let PasteOwner::Terminal(reason) = self.owner { + return Err(reason); } - if mode == RightClickPaste::Auto && self.wsl && self.vscode == VscodeDetection::Unknown { + if mode == RightClickPaste::Auto && self.wsl && self.owner == PasteOwner::Unknown { return Err( "Auto cannot identify this WSL terminal; use On or your terminal's paste command", ); diff --git a/codex-rs/tui/src/app/right_click_paste_tests.rs b/codex-rs/tui/src/app/right_click_paste_tests.rs index a88ecbd33c..6bbf94beea 100644 --- a/codex-rs/tui/src/app/right_click_paste_tests.rs +++ b/codex-rs/tui/src/app/right_click_paste_tests.rs @@ -4,9 +4,9 @@ use pretty_assertions::assert_eq; #[test] fn policy_preserves_explicit_modes_and_terminal_ownership() { - use VscodeDetection::Other; - use VscodeDetection::Unknown; - use VscodeDetection::VsCode; + use PasteOwner::Application; + use PasteOwner::Unknown; + const SSH_UNAVAILABLE: &str = "Unavailable over SSH; use your terminal's paste command"; const VSCODE_UNAVAILABLE: &str = "VS Code handles pasting; use its terminal paste command"; const WSL_AUTO_UNAVAILABLE: &str = @@ -18,14 +18,14 @@ fn policy_preserves_explicit_modes_and_terminal_ownership() { } else { Ok(true) }; - for (platform_default, ssh, wsl, vscode, on_status, auto_status) in [ - (true, false, false, Other, on, Ok(true)), - (false, false, false, Other, on, Ok(false)), + for (platform_default, ssh, wsl, owner, on_status, auto_status) in [ + (true, false, false, Application, on, Ok(true)), + (false, false, false, Application, on, Ok(false)), ( true, true, false, - Other, + Application, Err(SSH_UNAVAILABLE), Err(SSH_UNAVAILABLE), ), @@ -33,19 +33,19 @@ fn policy_preserves_explicit_modes_and_terminal_ownership() { true, false, false, - VsCode, + PasteOwner::Terminal(VSCODE_UNAVAILABLE), Err(VSCODE_UNAVAILABLE), Err(VSCODE_UNAVAILABLE), ), (true, false, true, Unknown, on, Err(WSL_AUTO_UNAVAILABLE)), - (true, false, true, Other, on, Ok(true)), + (true, false, true, Application, on, Ok(true)), ] { let env = PasteEnvironment { primary: false, platform_default, ssh, wsl, - vscode, + owner, }; assert_eq!( [ @@ -63,7 +63,7 @@ fn policy_preserves_explicit_modes_and_terminal_ownership() { platform_default: true, ssh: false, wsl: false, - vscode: Other, + owner: Application, }; assert_eq!( [RightClickPaste::Off, RightClickPaste::On] diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index dacaa7f522..61eae7b829 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -123,7 +123,7 @@ pub(crate) async fn make_test_app() -> Box { platform_default: true, ssh: false, wsl: false, - vscode: crate::tui::VscodeDetection::Other, + owner: crate::terminal_capabilities::PasteOwner::Application, }, reconnect: Default::default(), daemon_cli_executable: None, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index b8480221c9..15e851c078 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -9202,7 +9202,7 @@ async fn make_test_app() -> Box { platform_default: true, ssh: false, wsl: false, - vscode: crate::tui::VscodeDetection::Other, + owner: crate::terminal_capabilities::PasteOwner::Application, }, daemon_cli_executable: None, pending_update_action: None, @@ -9351,7 +9351,7 @@ pub(super) async fn make_test_app_with_channels() -> ( platform_default: true, ssh: false, wsl: false, - vscode: crate::tui::VscodeDetection::Other, + owner: crate::terminal_capabilities::PasteOwner::Application, }, daemon_cli_executable: None, pending_update_action: None, diff --git a/codex-rs/tui/src/app_backtrack.rs b/codex-rs/tui/src/app_backtrack.rs index a42e2d25b0..b982404997 100644 --- a/codex-rs/tui/src/app_backtrack.rs +++ b/codex-rs/tui/src/app_backtrack.rs @@ -210,8 +210,7 @@ impl App { Overlay::new_transcript( self.transcript_cells.clone(), self.keymap.pager.clone(), - self.local_settings - .copy_on_select(&codex_terminal_detection::terminal_info()), + self.local_settings.copy_on_select(), self.local_settings .tui .mouse_scroll_speed diff --git a/codex-rs/tui/src/chatwidget/clipboard.rs b/codex-rs/tui/src/chatwidget/clipboard.rs index 119eceaeb8..41062bc43d 100644 --- a/codex-rs/tui/src/chatwidget/clipboard.rs +++ b/codex-rs/tui/src/chatwidget/clipboard.rs @@ -45,8 +45,8 @@ impl ChatWidget { return Some(KeyEventAction::None); } let local_linux = cfg!(target_os = "linux") - && !crate::clipboard_copy::is_ssh_session() - && !crate::clipboard_copy::is_wsl_session(); + && !crate::terminal_capabilities::is_ssh_session() + && !crate::terminal_capabilities::is_wsl_session(); let text_fallback = (shift_insert || (key.modifiers == KeyModifiers::CONTROL && (cfg!(windows) || local_linux))) .then_some(key.code); diff --git a/codex-rs/tui/src/chatwidget/config_panel.rs b/codex-rs/tui/src/chatwidget/config_panel.rs index 3fed0edb4a..732f33547e 100644 --- a/codex-rs/tui/src/chatwidget/config_panel.rs +++ b/codex-rs/tui/src/chatwidget/config_panel.rs @@ -223,9 +223,7 @@ impl ChatWidget { fn config_panel_status(&self) -> ConfigPanelStatus { ConfigPanelStatus { transcript_mode: self.local_settings.transcript_mode, - copy_on_select: self - .local_settings - .copy_on_select(&codex_terminal_detection::terminal_info()), + copy_on_select: self.local_settings.copy_on_select(), right_click_paste: crate::app::PasteEnvironment::detect().status( self.local_settings.tui.right_click_paste, self.local_settings.transcript_mode, diff --git a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs index 673d292bfd..4211c44d20 100644 --- a/codex-rs/tui/src/chatwidget/tests/slash_commands.rs +++ b/codex-rs/tui/src/chatwidget/tests/slash_commands.rs @@ -2594,8 +2594,8 @@ async fn copy_shortcut_can_be_remapped() { let (mut chat, mut rx, _op_rx) = make_chatwidget_manual(/*model_override*/ None).await; let ctrl_v_pastes_text = cfg!(windows) || (cfg!(target_os = "linux") - && !crate::clipboard_copy::is_ssh_session() - && !crate::clipboard_copy::is_wsl_session()); + && !crate::terminal_capabilities::is_ssh_session() + && !crate::terminal_capabilities::is_wsl_session()); for (code, modifiers) in [ (KeyCode::Char('v'), KeyModifiers::CONTROL), (KeyCode::Char('V'), KeyModifiers::CONTROL), diff --git a/codex-rs/tui/src/clipboard_copy.rs b/codex-rs/tui/src/clipboard_copy.rs index 5374aa170f..7ec4c353a6 100644 --- a/codex-rs/tui/src/clipboard_copy.rs +++ b/codex-rs/tui/src/clipboard_copy.rs @@ -26,9 +26,9 @@ mod wsl; use crate::terminal_capabilities::ClipboardCapabilities; use crate::terminal_capabilities::ClipboardCopyMode; -pub(crate) use crate::terminal_capabilities::is_ssh_session; -use crate::terminal_capabilities::is_tmux_session; -use crate::terminal_capabilities::tmux_clipboard::copy as tmux_clipboard_copy; +use crate::terminal_capabilities::Osc52Target; +use crate::terminal_capabilities::copy_to_client_buffer; +use crate::terminal_capabilities::is_wsl_session; use base64::Engine; use std::io::Write; use std::sync::Arc; @@ -134,7 +134,7 @@ fn copy_to_clipboard( text, format, environment, - tmux_clipboard_copy, + copy_to_client_buffer, osc52, native_copy, |text| wsl::copy(text, wsl_deadline), @@ -188,7 +188,7 @@ impl CopyEnvironment { } => native_for_large_copies && text.len() > OSC52_MAX_RAW_BYTES, ClipboardCopyMode::FallbackOsc52 | ClipboardCopyMode::Osc52 - | ClipboardCopyMode::Tmux => true, + | ClipboardCopyMode::ClientBuffer => true, } } } @@ -197,7 +197,7 @@ fn copy_to_clipboard_with( text: &str, format: CopyFormat, environment: CopyEnvironment, - tmux_copy_fn: impl Fn(&str) -> Result<(), String>, + client_buffer_copy_fn: impl Fn(&str) -> Result<(), String>, osc52_copy_fn: impl Fn(&str) -> Result<(), String>, arboard_copy_fn: impl FnOnce(&str, Option<&str>) -> Result, String>, wsl_copy_fn: impl Fn(&str) -> Result<(), String>, @@ -209,7 +209,11 @@ fn copy_to_clipboard_with( let terminal_copy = || { if matches!( environment.terminal_copy, - ClipboardCopyMode::Tmux | ClipboardCopyMode::PreferTerminal { tmux: true, .. } + ClipboardCopyMode::ClientBuffer + | ClipboardCopyMode::PreferTerminal { + client_buffer: true, + .. + } ) { let raw_bytes = text.len(); let result = if raw_bytes > OSC52_MAX_RAW_BYTES { @@ -217,11 +221,11 @@ fn copy_to_clipboard_with( "tmux clipboard payload too large ({raw_bytes} bytes; max {OSC52_MAX_RAW_BYTES})" )) } else { - tmux_copy_fn(text) + client_buffer_copy_fn(text) }; - result.or_else(|tmux_error| { + result.or_else(|client_error| { osc52_copy_fn(text).map_err(|osc_error| { - format!("tmux clipboard: {tmux_error}; OSC 52 fallback: {osc_error}") + format!("tmux clipboard: {client_error}; OSC 52 fallback: {osc_error}") }) }) } else { @@ -275,16 +279,6 @@ fn copy_to_clipboard_with( } } -#[cfg(target_os = "linux")] -pub(crate) fn is_wsl_session() -> bool { - crate::clipboard_paste::is_probably_wsl() -} - -#[cfg(not(target_os = "linux"))] -pub(crate) fn is_wsl_session() -> bool { - false -} - /// Write to the native clipboard. The TUI owns any process-wide stderr redirection. #[cfg(not(target_os = "android"))] fn arboard_copy( @@ -339,12 +333,6 @@ fn write_osc52_to_writer(mut writer: impl Write, sequence: &str) -> Result<(), S .map_err(|e| format!("failed to flush OSC 52: {e}")) } -enum Osc52Target { - Direct, - Tmux, - Screen, -} - fn osc52_sequence(text: &str, target: Osc52Target) -> Result { let raw_bytes = text.len(); if raw_bytes > OSC52_MAX_RAW_BYTES { @@ -357,8 +345,8 @@ fn osc52_sequence(text: &str, target: Osc52Target) -> Result { let osc = format!("\x1b]52;c;{encoded}\x07"); Ok(match target { Osc52Target::Direct => osc, - Osc52Target::Tmux => format!("\x1bPtmux;\x1b{osc}\x1b\\"), - Osc52Target::Screen => { + Osc52Target::EscapedDcs => crate::terminal_capabilities::escaped_dcs(&osc), + Osc52Target::ChunkedDcs => { // Screen buffers each DCS separately. Stay below even its older 256-byte // string limit while forwarding one continuous OSC 52 to the outer terminal. const CHUNK_SIZE: usize = 252; @@ -400,7 +388,7 @@ mod tests { fn remote_tmux_environment() -> CopyEnvironment { CopyEnvironment { - terminal_copy: ClipboardCopyMode::Tmux, + terminal_copy: ClipboardCopyMode::ClientBuffer, ..remote_environment() } } @@ -449,7 +437,7 @@ mod tests { #[test] fn osc52_wraps_tmux_passthrough() { assert_eq!( - osc52_sequence("hello", Osc52Target::Tmux), + osc52_sequence("hello", Osc52Target::EscapedDcs), Ok("\u{1b}Ptmux;\u{1b}\u{1b}]52;c;aGVsbG8=\u{7}\u{1b}\\".to_string()) ); } @@ -749,7 +737,7 @@ mod tests { "hello", CopyFormat::PlainText, CopyEnvironment { - terminal_copy: ClipboardCopyMode::Tmux, + terminal_copy: ClipboardCopyMode::ClientBuffer, ..local_environment() }, |_| { diff --git a/codex-rs/tui/src/clipboard_copy/primary.rs b/codex-rs/tui/src/clipboard_copy/primary.rs index d24e31e43d..ebca200551 100644 --- a/codex-rs/tui/src/clipboard_copy/primary.rs +++ b/codex-rs/tui/src/clipboard_copy/primary.rs @@ -6,15 +6,7 @@ use super::ClipboardLease; use super::CopyOutcome; use std::time::Instant; -pub(crate) fn available() -> bool { - cfg!(target_os = "linux") - && std::env::var_os("DISPLAY").is_some() - && std::env::var_os("WAYLAND_DISPLAY").is_none() - && !super::is_ssh_session() - && !super::is_tmux_session() - && !super::is_wsl_session() - && crate::tui::detect_vscode_terminal() != crate::tui::VscodeDetection::VsCode -} +pub(crate) use crate::terminal_capabilities::primary_selection_available as available; #[cfg(target_os = "linux")] pub(super) fn copy( diff --git a/codex-rs/tui/src/clipboard_copy/routing_tests.rs b/codex-rs/tui/src/clipboard_copy/routing_tests.rs index 3fdc69d561..5e2227a5cb 100644 --- a/codex-rs/tui/src/clipboard_copy/routing_tests.rs +++ b/codex-rs/tui/src/clipboard_copy/routing_tests.rs @@ -19,7 +19,7 @@ fn local_tmux_preserves_native_html_when_terminal_silently_rejects_copy() { "**hello**", CopyFormat::Markdown, CopyEnvironment { - terminal_copy: ClipboardCopyMode::Tmux, + terminal_copy: ClipboardCopyMode::ClientBuffer, forwarded_x11: false, wsl_session: false, }, @@ -50,7 +50,7 @@ fn copy_uses_osc52_when_tmux_fails_even_if_native_copy_succeeds() { "hello", CopyFormat::PlainText, CopyEnvironment { - terminal_copy: ClipboardCopyMode::Tmux, + terminal_copy: ClipboardCopyMode::ClientBuffer, forwarded_x11: false, wsl_session: false, }, @@ -75,7 +75,7 @@ fn copy_uses_osc52_when_tmux_fails_even_if_native_copy_succeeds() { fn local_tmux_environment() -> CopyEnvironment { CopyEnvironment { - terminal_copy: ClipboardCopyMode::Tmux, + terminal_copy: ClipboardCopyMode::ClientBuffer, forwarded_x11: false, wsl_session: false, } @@ -85,7 +85,7 @@ fn local_tmux_environment() -> CopyEnvironment { fn terminal_only_copy_reports_the_send_result() { let environment = CopyEnvironment { terminal_copy: ClipboardCopyMode::PreferTerminal { - tmux: false, + client_buffer: false, native_for_large_copies: false, }, forwarded_x11: false, @@ -115,7 +115,7 @@ fn terminal_only_copy_reports_the_send_result() { fn oversized_dev_container_copy_can_keep_native_ownership_without_confirming_delivery() { let environment = CopyEnvironment { terminal_copy: ClipboardCopyMode::PreferTerminal { - tmux: true, + client_buffer: true, native_for_large_copies: true, }, ..local_tmux_environment() @@ -237,7 +237,7 @@ fn confirmed_copy_without_new_lease_preserves_native_ownership() { #[test] fn screen_forwards_one_complete_osc52_across_bounded_passthrough_strings() { for text in ["hello", &"世界".repeat(500)] { - let sequence = super::osc52_sequence(text, super::Osc52Target::Screen).unwrap(); + let sequence = super::osc52_sequence(text, super::Osc52Target::ChunkedDcs).unwrap(); let chunks = sequence .strip_prefix("\x1bP") .unwrap() diff --git a/codex-rs/tui/src/clipboard_copy/worker.rs b/codex-rs/tui/src/clipboard_copy/worker.rs index fba8915ac4..eca8da3ac0 100644 --- a/codex-rs/tui/src/clipboard_copy/worker.rs +++ b/codex-rs/tui/src/clipboard_copy/worker.rs @@ -243,13 +243,7 @@ impl ClipboardWorker { format, || setup.begin_delivery(), |text| { - let target = if std::env::var_os("TMUX").is_some() { - super::Osc52Target::Tmux - } else if std::env::var_os("STY").is_some() { - super::Osc52Target::Screen - } else { - super::Osc52Target::Direct - }; + let target = super::Osc52Target::detect(); terminal_sequence.set(Some(super::osc52_sequence(text, target)?)); Ok(()) }, diff --git a/codex-rs/tui/src/clipboard_paste/text.rs b/codex-rs/tui/src/clipboard_paste/text.rs index 17eee61566..be02ee90bb 100644 --- a/codex-rs/tui/src/clipboard_paste/text.rs +++ b/codex-rs/tui/src/clipboard_paste/text.rs @@ -7,8 +7,8 @@ use std::time::Instant; /// Constructed on the clipboard worker, never on the UI thread. pub(crate) fn reader() -> impl FnMut(Instant) -> Result { #[cfg(target_os = "linux")] - let windows = - (super::is_probably_wsl() && !crate::clipboard_copy::is_ssh_session()).then(|| { + let windows = (super::is_probably_wsl() && !crate::terminal_capabilities::is_ssh_session()) + .then(|| { use std::sync::mpsc; let (requests, reads) = mpsc::sync_channel::<( @@ -54,7 +54,7 @@ pub(crate) fn reader() -> impl FnMut(Instant) -> Result { .map_err(|_| "could not start clipboard reader".to_string()) }); move |deadline| { - if crate::clipboard_copy::is_ssh_session() { + if crate::terminal_capabilities::is_ssh_session() { return Err("clipboard text is unavailable over SSH".into()); } #[cfg(target_os = "linux")] diff --git a/codex-rs/tui/src/device_login.rs b/codex-rs/tui/src/device_login.rs index d0adcfbde0..a0e6a5f9a7 100644 --- a/codex-rs/tui/src/device_login.rs +++ b/codex-rs/tui/src/device_login.rs @@ -18,7 +18,7 @@ use codex_app_server_protocol::ThreadStatus; use std::io; pub(crate) async fn prefer_device_login() -> bool { - if crate::clipboard_copy::is_ssh_session() + if crate::terminal_capabilities::is_ssh_session() || cfg!(target_os = "linux") && !["DISPLAY", "WAYLAND_DISPLAY"] .iter() diff --git a/codex-rs/tui/src/local_settings.rs b/codex-rs/tui/src/local_settings.rs index 1df22eed1d..8c0def4b50 100644 --- a/codex-rs/tui/src/local_settings.rs +++ b/codex-rs/tui/src/local_settings.rs @@ -17,8 +17,6 @@ use codex_config::types::CopyOnSelect; use codex_config::types::History; use codex_config::types::Notice; use codex_config::types::Tui; -use codex_terminal_detection::TerminalInfo; -use codex_terminal_detection::TerminalName; use codex_utils_absolute_path::AbsolutePathBuf; #[derive(Clone, Debug, PartialEq)] @@ -238,49 +236,16 @@ impl LocalSettings { settings } - /// Copy on release unless a direct terminal is known to forward its default copy shortcut. - /// Multiplexers, unknown terminals and Ghostty without a recognized version default to copying. - pub(crate) fn copy_on_select(&self, terminal: &TerminalInfo) -> bool { + /// Copy on release unless the default copy shortcut reaches the application. + pub(crate) fn copy_on_select(&self) -> bool { + self.copy_on_select_with(crate::terminal_capabilities::forwards_copy_shortcut()) + } + + fn copy_on_select_with(&self, forwards_copy_shortcut: bool) -> bool { match self.tui.copy_on_select { CopyOnSelect::Always => true, CopyOnSelect::Never => false, - CopyOnSelect::Auto => { - terminal.multiplexer.is_some() - || match terminal.name { - // Since 1.2, both Ghostty's Cmd-C and Ctrl-Shift-C bindings are - // "performable": they forward the key if Ghostty has no selection. - TerminalName::Ghostty => !terminal - .version - .as_deref() - .and_then(|version| semver::Version::parse(version).ok()) - .is_some_and(|version| { - version - >= semver::Version::new( - /*major*/ 1, /*minor*/ 2, /*patch*/ 0, - ) - }), - // Kitty's Cmd-C uses copy_or_noop. Its Ctrl-Shift-C consumes the key. - TerminalName::Kitty => !cfg!(target_os = "macos"), - // Windows Terminal's Copy action forwards its key when unselected, - // including when the CLI runs in WSL. - TerminalName::WindowsTerminal => false, - // VS Code gates Copy on native selection. Only Windows' default - // (plain Ctrl-C) is also forwarded by the legacy xterm.js encoder. - TerminalName::VsCode => !cfg!(target_os = "windows"), - TerminalName::AppleTerminal - | TerminalName::Iterm2 - | TerminalName::WarpTerminal - | TerminalName::WezTerm - | TerminalName::Rex - | TerminalName::Orca - | TerminalName::Alacritty - | TerminalName::Konsole - | TerminalName::GnomeTerminal - | TerminalName::Vte - | TerminalName::Dumb - | TerminalName::Unknown => true, - } - } + CopyOnSelect::Auto => !forwards_copy_shortcut, } } diff --git a/codex-rs/tui/src/local_settings_tests.rs b/codex-rs/tui/src/local_settings_tests.rs index 003a2260d0..8661e569bd 100644 --- a/codex-rs/tui/src/local_settings_tests.rs +++ b/codex-rs/tui/src/local_settings_tests.rs @@ -7,6 +7,8 @@ use codex_config::types::RightClickPaste; use codex_config::types::SessionPickerViewMode; use codex_config::types::StatusLineSelection; use codex_terminal_detection::Multiplexer; +use codex_terminal_detection::TerminalInfo; +use codex_terminal_detection::TerminalName; use pretty_assertions::assert_eq; #[tokio::test] @@ -477,7 +479,9 @@ async fn copy_on_select_respects_terminal_defaults_and_config_overrides() -> any term: None, }; assert_eq!( - local.copy_on_select(&terminal), + local.copy_on_select_with( + crate::terminal_capabilities::forwards_copy_shortcut_for(&terminal) + ), match expected { CopyOnSelect::Auto => default_enabled, CopyOnSelect::Always => true, diff --git a/codex-rs/tui/src/resume_picker.rs b/codex-rs/tui/src/resume_picker.rs index 337e6ab238..0c806a0142 100644 --- a/codex-rs/tui/src/resume_picker.rs +++ b/codex-rs/tui/src/resume_picker.rs @@ -640,7 +640,7 @@ async fn run_resume_picker_with_launch_context( .map(AppServerSession::backend_id) .collect(), use_theme_colors: local_settings.tui.status_line_use_colors, - copy_on_select: local_settings.copy_on_select(&codex_terminal_detection::terminal_info()), + copy_on_select: local_settings.copy_on_select(), copy_on_select_clear_selection: local_settings.tui.copy_on_select_clear_selection, mouse_scroll_speed: local_settings.tui.mouse_scroll_speed.unwrap_or(1.0), show_all, @@ -698,7 +698,7 @@ pub async fn run_fork_picker_with_app_server( .into_iter() .collect(), use_theme_colors: local_settings.tui.status_line_use_colors, - copy_on_select: local_settings.copy_on_select(&codex_terminal_detection::terminal_info()), + copy_on_select: local_settings.copy_on_select(), copy_on_select_clear_selection: local_settings.tui.copy_on_select_clear_selection, mouse_scroll_speed: local_settings.tui.mouse_scroll_speed.unwrap_or(1.0), show_all, diff --git a/codex-rs/tui/src/session_lock/linux.rs b/codex-rs/tui/src/session_lock/linux.rs index 79bdeed875..7bb552287b 100644 --- a/codex-rs/tui/src/session_lock/linux.rs +++ b/codex-rs/tui/src/session_lock/linux.rs @@ -52,8 +52,7 @@ pub(super) async fn observe() -> anyhow::Result { } else { // Graphical terminals may be launched by the per-user service manager, outside // the login scope. Prefer the client environment's explicit session association. - if std::env::var_os("SSH_CONNECTION").is_some() || std::env::var_os("SSH_TTY").is_some() - { + if crate::terminal_capabilities::is_ssh_session() { anyhow::bail!("remote terminal has no graphical session"); } match std::env::var("XDG_SESSION_ID") { diff --git a/codex-rs/tui/src/terminal_capabilities.rs b/codex-rs/tui/src/terminal_capabilities.rs index 44b4d66206..00d353ac6a 100644 --- a/codex-rs/tui/src/terminal_capabilities.rs +++ b/codex-rs/tui/src/terminal_capabilities.rs @@ -9,7 +9,7 @@ mod resize_reflow_cap; mod terminal_identity; pub(crate) mod terminal_probe; mod tmux; -pub(crate) mod tmux_clipboard; +mod tmux_clipboard; use codex_terminal_detection::Multiplexer; use codex_terminal_detection::TerminalInfo; @@ -25,12 +25,23 @@ pub(crate) use resize_reflow_cap::resize_reflow_max_rows; pub(crate) use terminal_identity::requires_inline_screen; pub(crate) use tmux::MouseCapture; pub(crate) use tmux::sample_mouse; +pub(crate) use tmux_clipboard::copy as copy_to_client_buffer; + +#[cfg(target_os = "linux")] +pub(crate) fn is_wsl_session() -> bool { + crate::clipboard_paste::is_probably_wsl() +} + +#[cfg(not(target_os = "linux"))] +pub(crate) fn is_wsl_session() -> bool { + false +} pub(crate) fn is_ssh_session() -> bool { std::env::var_os("SSH_TTY").is_some() || std::env::var_os("SSH_CONNECTION").is_some() } -pub(crate) fn is_tmux_session() -> bool { +fn is_tmux_session() -> bool { tmux_transport() || std::env::var_os("TMUX_PANE").is_some() } @@ -42,6 +53,12 @@ fn screen_active() -> bool { std::env::var_os("STY").is_some() } +/// Escape embedded commands for a DCS passthrough transport. +pub(crate) fn escaped_dcs(command: &str) -> String { + let escaped = command.replace('\x1b', "\x1b\x1b"); + format!("\x1bPtmux;{escaped}\x1b\\") +} + pub(crate) struct SessionCapabilities { pub(crate) mouse_capture: MouseCapture, virtual_image_base: Option, @@ -110,11 +127,11 @@ pub(crate) fn scrollback_strategy(terminal: &TerminalInfo) -> ScrollbackStrategy pub(crate) enum ClipboardCopyMode { FallbackOsc52, Osc52, - Tmux, + ClientBuffer, /// The native clipboard may belong to a private desktop. PreferTerminal { native_for_large_copies: bool, - tmux: bool, + client_buffer: bool, }, } @@ -135,7 +152,7 @@ pub(crate) struct ClipboardCapabilities { impl ClipboardCapabilities { pub(crate) fn detect() -> Self { - let terminal = codex_terminal_detection::terminal_info(); + let terminal = terminal_info(); let ssh = is_ssh_session(); let tmux = is_tmux_session(); Self { @@ -144,10 +161,10 @@ impl ClipboardCapabilities { native_for_large_copies: cfg!(target_os = "linux") && std::env::var_os("WAYLAND_DISPLAY") .is_some_and(|display| !display.is_empty()), - tmux, + client_buffer: tmux, } } else if tmux { - ClipboardCopyMode::Tmux + ClipboardCopyMode::ClientBuffer } else if ssh || std::env::var("HERDR_ENV").is_ok_and(|value| value == "1") { ClipboardCopyMode::Osc52 } else { @@ -158,6 +175,93 @@ impl ClipboardCapabilities { } } +pub(crate) fn forwards_copy_shortcut() -> bool { + forwards_copy_shortcut_for(&terminal_info()) +} + +pub(crate) fn forwards_copy_shortcut_for(terminal: &TerminalInfo) -> bool { + terminal.multiplexer.is_none() + && match terminal.name { + // Since 1.2, both Ghostty's Cmd-C and Ctrl-Shift-C bindings are + // "performable": they forward the key if Ghostty has no selection. + TerminalName::Ghostty => terminal + .version + .as_deref() + .and_then(|version| semver::Version::parse(version).ok()) + .is_some_and(|version| { + version + >= semver::Version::new( + /*major*/ 1, /*minor*/ 2, /*patch*/ 0, + ) + }), + // Kitty's Cmd-C uses copy_or_noop. Its Ctrl-Shift-C consumes the key. + TerminalName::Kitty => cfg!(target_os = "macos"), + // Windows Terminal's Copy action forwards its key when unselected, + // including when the CLI runs in WSL. + TerminalName::WindowsTerminal => true, + // VS Code gates Copy on native selection. Only Windows' default + // (plain Ctrl-C) is also forwarded by the legacy xterm.js encoder. + TerminalName::VsCode => cfg!(target_os = "windows"), + TerminalName::AppleTerminal + | TerminalName::Iterm2 + | TerminalName::WarpTerminal + | TerminalName::WezTerm + | TerminalName::Rex + | TerminalName::Orca + | TerminalName::Alacritty + | TerminalName::Konsole + | TerminalName::GnomeTerminal + | TerminalName::Vte + | TerminalName::Dumb + | TerminalName::Unknown => false, + } +} + +pub(crate) enum Osc52Target { + Direct, + EscapedDcs, + ChunkedDcs, +} + +impl Osc52Target { + pub(crate) fn detect() -> Self { + if tmux_transport() { + Self::EscapedDcs + } else if screen_active() { + Self::ChunkedDcs + } else { + Self::Direct + } + } +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum PasteOwner { + Terminal(&'static str), + Application, + Unknown, +} + +pub(crate) fn paste_owner() -> PasteOwner { + match keyboard_modes::detect_vscode_terminal() { + keyboard_modes::VscodeDetection::VsCode => { + PasteOwner::Terminal("VS Code handles pasting; use its terminal paste command") + } + keyboard_modes::VscodeDetection::Other => PasteOwner::Application, + keyboard_modes::VscodeDetection::Unknown => PasteOwner::Unknown, + } +} + +pub(crate) fn primary_selection_available() -> bool { + cfg!(target_os = "linux") + && std::env::var_os("DISPLAY").is_some() + && std::env::var_os("WAYLAND_DISPLAY").is_none() + && !is_ssh_session() + && !is_tmux_session() + && !is_wsl_session() + && !matches!(paste_owner(), PasteOwner::Terminal(_)) +} + pub(crate) fn title_encoding() -> crate::terminal_title::TitleEncoding { use crate::terminal_title::TitleEncoding; // Screen remains an output hop when another multiplexer runs inside it. diff --git a/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs b/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs index 63bdf94475..7baf7c8db2 100644 --- a/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs +++ b/codex-rs/tui/src/terminal_capabilities/keyboard_modes.rs @@ -23,7 +23,7 @@ const DISABLE_KEYBOARD_ENHANCEMENT_ENV_VAR: &str = "CODEX_TUI_DISABLE_KEYBOARD_E static REPORTS_KEY_RELEASES: AtomicBool = AtomicBool::new(/*v*/ false); #[derive(Clone, Copy, Debug, PartialEq, Eq)] -pub(crate) enum VscodeDetection { +pub(super) enum VscodeDetection { VsCode, Other, Unknown, @@ -31,7 +31,7 @@ pub(crate) enum VscodeDetection { pub(crate) fn keyboard_enhancement_disabled() -> bool { let disable_env = std::env::var(DISABLE_KEYBOARD_ENHANCEMENT_ENV_VAR).ok(); - let is_wsl = crate::clipboard_copy::is_wsl_session(); + let is_wsl = super::is_wsl_session(); let vscode_detection = if is_wsl { detect_vscode_terminal() } else { @@ -83,7 +83,7 @@ pub(super) fn running_in_vscode_terminal() -> bool { detect_vscode_terminal() == VscodeDetection::VsCode } -pub(crate) fn detect_vscode_terminal() -> VscodeDetection { +pub(super) fn detect_vscode_terminal() -> VscodeDetection { if terminal_info().name == TerminalName::VsCode { VscodeDetection::VsCode } else { @@ -107,7 +107,7 @@ fn windows_vscode_detection() -> VscodeDetection { #[cfg(target_os = "linux")] fn read_windows_vscode_detection() -> VscodeDetection { - if !crate::clipboard_copy::is_wsl_session() { + if !super::is_wsl_session() { return VscodeDetection::Other; } read_windows_vscode_detection_with_timeout( diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index 2d060464c7..04489001a4 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -114,9 +114,6 @@ pub(crate) struct InitializedTerminal { pub(crate) stderr_guard: terminal_stderr::TerminalStderrGuard, } -pub(crate) use keyboard_modes::VscodeDetection; -pub(crate) use keyboard_modes::detect_vscode_terminal; - pub(crate) fn reports_key_releases() -> bool { keyboard_modes::reports_key_releases() }