From 1f9549e265e3ed7604710aae4d12eb82557a7a0c Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Thu, 26 Nov 2026 17:42:36 +0000 Subject: [PATCH] Support PRIMARY selection in Wayland sessions (#64192) ## Why The TUI disabled PRIMARY whenever `WAYLAND_DISPLAY` was set, so it couldn't publish selected text to PRIMARY or paste from it with a middle click in Wayland sessions. ## What changed Probe Wayland PRIMARY support in the background and use the result for selection copying and middle-click paste. If the compositor lacks the Wayland data-control protocol, allow XWayland fallback only when the Wayland and X11 sockets have matching listener credentials. ## Testing Add a unit test covering native Wayland support, the same-session XWayland fallback, remote X11 displays, and unsuccessful probes. GitOrigin-RevId: 9b5c1536762383c0fe770dd86d58a49a1f3633a8 --- codex-rs/Cargo.lock | 2 + codex-rs/Cargo.toml | 1 + codex-rs/tui/Cargo.toml | 2 + codex-rs/tui/src/app.rs | 1 + codex-rs/tui/src/app/footer_selection.rs | 2 +- codex-rs/tui/src/app/owned_transcript.rs | 3 +- codex-rs/tui/src/app/right_click_paste.rs | 6 +- .../tui/src/app/right_click_paste_tests.rs | 2 - codex-rs/tui/src/app/test_support.rs | 1 - codex-rs/tui/src/app/tests.rs | 2 - codex-rs/tui/src/clipboard_copy/primary.rs | 7 +- codex-rs/tui/src/pager_overlay.rs | 1 - codex-rs/tui/src/pager_overlay/transcript.rs | 1 + codex-rs/tui/src/terminal_capabilities.rs | 16 ++-- .../tui/src/terminal_capabilities/primary.rs | 83 +++++++++++++++++++ .../terminal_capabilities/primary_tests.rs | 21 +++++ codex-rs/tui/src/tui.rs | 6 ++ codex-rs/tui/src/tui/selection_clipboard.rs | 2 +- 18 files changed, 132 insertions(+), 27 deletions(-) create mode 100644 codex-rs/tui/src/terminal_capabilities/primary.rs create mode 100644 codex-rs/tui/src/terminal_capabilities/primary_tests.rs diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index a56862e7ad..cc2984279d 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5465,6 +5465,7 @@ dependencies = [ "itertools 0.14.0", "lazy_static", "libc", + "nix 0.31.3", "objc2", "objc2-app-kit", "objc2-foundation", @@ -5514,6 +5515,7 @@ dependencies = [ "windows-sys 0.61.2", "winsplit", "wiremock", + "wl-clipboard-rs", "zbus", ] diff --git a/codex-rs/Cargo.toml b/codex-rs/Cargo.toml index 0ad5a4e463..7820314824 100644 --- a/codex-rs/Cargo.toml +++ b/codex-rs/Cargo.toml @@ -599,6 +599,7 @@ wildmatch = "2.6.1" winapi-util = "0.1.11" windows-sys = "0.61.2" winreg = "0.55.0" +wl-clipboard-rs = "0.9.3" # Keep the zip 2.x feature set. In zip 9, `bzip2-rs` selects the bzip2-sys # backend we already build; the default selects libbz2-rs-sys instead. zip = { version = "9.0.0", default-features = false, features = [ diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index 6e8f7f3bca..74808567bc 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -155,6 +155,8 @@ objc2-app-kit = { version = "0.3.2", default-features = false, features = ["std" objc2-foundation = { version = "0.3.2", default-features = false, features = ["std", "NSArray", "NSData", "NSDateFormatter", "NSEnumerator", "NSFormatter", "NSLocale", "NSString"] } [target.'cfg(target_os = "linux")'.dependencies] +nix = { version = "0.31.3", features = ["socket"] } +wl-clipboard-rs = { workspace = true } # Keep the same executor features as the credential store, which also uses zbus. zbus = "4.4.0" diff --git a/codex-rs/tui/src/app.rs b/codex-rs/tui/src/app.rs index 4a1ade7037..bd10da1dcc 100644 --- a/codex-rs/tui/src/app.rs +++ b/codex-rs/tui/src/app.rs @@ -922,6 +922,7 @@ impl App { } _ => self.sidebar_press = None, } + self.transcript_view.primary_selection = tui.primary_selection_available(); self.transcript_view.bidi_layout = tui.terminal.bidi_layout; self.transcript_view.agent_links = self .side_retention_enabled(tui) diff --git a/codex-rs/tui/src/app/footer_selection.rs b/codex-rs/tui/src/app/footer_selection.rs index 82a13f757e..2521620779 100644 --- a/codex-rs/tui/src/app/footer_selection.rs +++ b/codex-rs/tui/src/app/footer_selection.rs @@ -44,7 +44,7 @@ impl App { 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; + selection.view.primary_selection = tui.primary_selection_available(); selection.handle_event(event, tui.terminal.previous_buffer()) }; let Some(action) = action else { diff --git a/codex-rs/tui/src/app/owned_transcript.rs b/codex-rs/tui/src/app/owned_transcript.rs index dd76d55da0..50a3d7f782 100644 --- a/codex-rs/tui/src/app/owned_transcript.rs +++ b/codex-rs/tui/src/app/owned_transcript.rs @@ -184,7 +184,7 @@ impl App { ) -> bool { let selection_copy = crate::tui::SelectionCopy::on_select( self.local_settings.copy_on_select(), - self.right_click_paste_environment.primary, + tui.primary_selection_available(), // Editable selections remain visible so the next input can replace them. /*clear_selection*/ false, @@ -217,7 +217,6 @@ impl App { let transcript_width = chat_widget.history_wrap_width(width); 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(); view.copy_on_select_clear_selection = self.local_settings.tui.copy_on_select_clear_selection; diff --git a/codex-rs/tui/src/app/right_click_paste.rs b/codex-rs/tui/src/app/right_click_paste.rs index 8aa2414139..237324a21c 100644 --- a/codex-rs/tui/src/app/right_click_paste.rs +++ b/codex-rs/tui/src/app/right_click_paste.rs @@ -1,4 +1,4 @@ -//! Clipboard text paste from keyboard shortcuts, right-click, or X11 middle-click PRIMARY. +//! Clipboard text paste from keyboard shortcuts, right-click, or middle-click PRIMARY. //! The policy also reports why a configured mode is unavailable in this terminal. //! Existing selection handlers run first. Only a draw may deliver a read, so real input //! invalidates pending paste before completion and is never replaced by clipboard text. @@ -23,7 +23,6 @@ pub(super) struct PendingPaste { } pub(crate) struct PasteEnvironment { - pub(super) primary: bool, pub(super) platform_default: bool, pub(super) ssh: bool, pub(super) wsl: bool, @@ -33,7 +32,6 @@ pub(crate) struct PasteEnvironment { impl PasteEnvironment { pub(crate) fn detect() -> Self { Self { - primary: crate::clipboard_copy::primary::available(), platform_default: cfg!(any(target_os = "windows", target_os = "linux")), ssh: crate::terminal_capabilities::is_ssh_session(), wsl: crate::terminal_capabilities::is_wsl_session(), @@ -100,7 +98,7 @@ impl App { self.local_settings.transcript_mode, ) } - PasteSource::Primary => self.right_click_paste_environment.primary, + PasteSource::Primary => tui.primary_selection_available(), }; if (shortcut.is_none() && !tui.is_owned_screen()) || self.overlay.is_some() 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 6bbf94beea..adc696cad5 100644 --- a/codex-rs/tui/src/app/right_click_paste_tests.rs +++ b/codex-rs/tui/src/app/right_click_paste_tests.rs @@ -41,7 +41,6 @@ fn policy_preserves_explicit_modes_and_terminal_ownership() { (true, false, true, Application, on, Ok(true)), ] { let env = PasteEnvironment { - primary: false, platform_default, ssh, wsl, @@ -59,7 +58,6 @@ fn policy_preserves_explicit_modes_and_terminal_ownership() { } let env = PasteEnvironment { - primary: false, platform_default: true, ssh: false, wsl: false, diff --git a/codex-rs/tui/src/app/test_support.rs b/codex-rs/tui/src/app/test_support.rs index 36280c3333..f491f46c41 100644 --- a/codex-rs/tui/src/app/test_support.rs +++ b/codex-rs/tui/src/app/test_support.rs @@ -120,7 +120,6 @@ pub(crate) async fn make_test_app() -> Box { app_server_backend_id: None, pending_right_click_paste: None, right_click_paste_environment: super::right_click_paste::PasteEnvironment { - primary: false, platform_default: true, ssh: false, wsl: false, diff --git a/codex-rs/tui/src/app/tests.rs b/codex-rs/tui/src/app/tests.rs index 999a5196d5..b8aeba7d40 100644 --- a/codex-rs/tui/src/app/tests.rs +++ b/codex-rs/tui/src/app/tests.rs @@ -9157,7 +9157,6 @@ async fn make_test_app() -> Box { reconnect: Default::default(), pending_right_click_paste: None, right_click_paste_environment: super::right_click_paste::PasteEnvironment { - primary: false, platform_default: true, ssh: false, wsl: false, @@ -9307,7 +9306,6 @@ pub(super) async fn make_test_app_with_channels() -> ( reconnect: Default::default(), pending_right_click_paste: None, right_click_paste_environment: super::right_click_paste::PasteEnvironment { - primary: false, platform_default: true, ssh: false, wsl: false, diff --git a/codex-rs/tui/src/clipboard_copy/primary.rs b/codex-rs/tui/src/clipboard_copy/primary.rs index ebca200551..b75ddc11e3 100644 --- a/codex-rs/tui/src/clipboard_copy/primary.rs +++ b/codex-rs/tui/src/clipboard_copy/primary.rs @@ -1,13 +1,10 @@ -//! Local X11 PRIMARY selection. Never forward PRIMARY over SSH or tmux, or -//! accidentally target a Wayland compositor or WSL host clipboard. +//! Local Linux PRIMARY selection. Never forward PRIMARY over SSH, tmux, or WSL. #[cfg(target_os = "linux")] use super::ClipboardLease; use super::CopyOutcome; use std::time::Instant; -pub(crate) use crate::terminal_capabilities::primary_selection_available as available; - #[cfg(target_os = "linux")] pub(super) fn copy( text: &str, @@ -20,7 +17,7 @@ pub(super) fn copy( .set() .clipboard(arboard::LinuxClipboardKind::Primary) .text(text) - .map_err(|err| format!("X11 primary selection: {err}"))?; + .map_err(|err| format!("primary selection: {err}"))?; Ok(CopyOutcome::Copied(Some(ClipboardLease::native_linux( clipboard, )))) diff --git a/codex-rs/tui/src/pager_overlay.rs b/codex-rs/tui/src/pager_overlay.rs index 9f40e05f9f..8585497877 100644 --- a/codex-rs/tui/src/pager_overlay.rs +++ b/codex-rs/tui/src/pager_overlay.rs @@ -67,7 +67,6 @@ impl Overlay { overlay.view.bidi_layout = bidi_layout; overlay.view.copy_on_select = copy_on_select; overlay.view.mouse_scroll_speed = mouse_scroll_speed; - overlay.view.primary_selection = crate::clipboard_copy::primary::available(); Self::Transcript(overlay) } diff --git a/codex-rs/tui/src/pager_overlay/transcript.rs b/codex-rs/tui/src/pager_overlay/transcript.rs index cbf61a4735..50d68dcfb3 100644 --- a/codex-rs/tui/src/pager_overlay/transcript.rs +++ b/codex-rs/tui/src/pager_overlay/transcript.rs @@ -225,6 +225,7 @@ impl TranscriptOverlay { mouse.column = self.content_area.x; mouse.row = self.content_area.bottom().saturating_sub(1); } + self.view.primary_selection = tui.primary_selection_available(); self.view.handle_mouse(mouse, &self.cells) } TuiEvent::Paste(text) => { diff --git a/codex-rs/tui/src/terminal_capabilities.rs b/codex-rs/tui/src/terminal_capabilities.rs index ab1215caea..21e1ad3b68 100644 --- a/codex-rs/tui/src/terminal_capabilities.rs +++ b/codex-rs/tui/src/terminal_capabilities.rs @@ -286,14 +286,14 @@ pub(crate) fn paste_owner() -> PasteOwner { } } -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(_)) +#[cfg(target_os = "linux")] +mod primary; +#[cfg(target_os = "linux")] +pub(crate) use primary::detect_primary_selection; + +#[cfg(not(target_os = "linux"))] +pub(crate) fn detect_primary_selection() -> std::sync::Arc { + Default::default() } pub(crate) fn title_encoding() -> crate::terminal_title::TitleEncoding { diff --git a/codex-rs/tui/src/terminal_capabilities/primary.rs b/codex-rs/tui/src/terminal_capabilities/primary.rs new file mode 100644 index 0000000000..622efe2b0f --- /dev/null +++ b/codex-rs/tui/src/terminal_capabilities/primary.rs @@ -0,0 +1,83 @@ +//! Detect local Linux PRIMARY without blocking input or consuming an inherited Wayland socket. + +use super::PasteOwner; +use nix::sys::socket::getsockopt; +use nix::sys::socket::sockopt::PeerCredentials; +use std::os::linux::net::SocketAddrExt; +use std::os::unix::net::SocketAddr; +use std::os::unix::net::UnixStream; +use std::path::PathBuf; +use std::sync::Arc; +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering; +use wl_clipboard_rs::utils::PrimarySelectionCheckError; +use wl_clipboard_rs::utils::is_primary_selection_supported; + +pub(crate) fn detect_primary_selection() -> Arc { + if super::is_ssh_session() + || super::is_tmux_session() + || super::is_wsl_session() + || matches!(super::paste_owner(), PasteOwner::Terminal(_)) + || std::env::var_os("WAYLAND_SOCKET").is_some() + { + return Default::default(); + } + let display = std::env::var_os("DISPLAY"); + let Some(wayland) = std::env::var_os("WAYLAND_DISPLAY") else { + return Arc::new(AtomicBool::new(display.is_some())); + }; + + let available = Arc::new(AtomicBool::new(false)); + let result = Arc::clone(&available); + let _ = std::thread::Builder::new().spawn(move || { + let supported = wayland_primary_available( + is_primary_selection_supported(), + display.as_deref(), + |number| same_listener(PathBuf::from(wayland), number).unwrap_or(false), + ); + result.store(supported, Ordering::Relaxed); + }); + available +} + +fn wayland_primary_available( + probe: Result, + display: Option<&std::ffi::OsStr>, + same_session: impl FnOnce(u16) -> bool, +) -> bool { + // Arboard may retry X11 on a later connection failure. Reject remote addresses. + let number = display.and_then(|display| { + let (host, suffix) = display.to_str()?.rsplit_once(':')?; + if !matches!(host, "" | "unix/") { + return None; + } + suffix.split('.').next()?.parse().ok() + }); + match probe { + Ok(supported) => supported && (display.is_none() || number.is_some()), + Err(PrimarySelectionCheckError::MissingProtocol) => number.is_some_and(same_session), + Err(_) => false, + } +} + +// Mutter opens both listeners and passes the X11 sockets to XWayland. Linux +// reports the listener's credentials even after the file descriptor is passed. +fn same_listener(mut wayland: PathBuf, number: u16) -> Option { + if !wayland.is_absolute() { + wayland = PathBuf::from(std::env::var_os("XDG_RUNTIME_DIR")?).join(wayland); + } + let compositor = UnixStream::connect(wayland).ok()?; + let path = format!("/tmp/.X11-unix/X{number}"); + // Match x11rb's preference for the abstract socket over the filesystem socket. + let address = SocketAddr::from_abstract_name(path.as_bytes()).ok()?; + let x11 = UnixStream::connect_addr(&address) + .or_else(|_| UnixStream::connect(path)) + .ok()?; + let owner = getsockopt(&compositor, PeerCredentials).ok()?; + // A peer outside our PID namespace can have an invisible (zero) PID. + Some(owner.pid() > 0 && owner == getsockopt(&x11, PeerCredentials).ok()?) +} + +#[cfg(test)] +#[path = "primary_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/terminal_capabilities/primary_tests.rs b/codex-rs/tui/src/terminal_capabilities/primary_tests.rs new file mode 100644 index 0000000000..21f3c9f6d5 --- /dev/null +++ b/codex-rs/tui/src/terminal_capabilities/primary_tests.rs @@ -0,0 +1,21 @@ +#![cfg(test)] + +use super::wayland_primary_available; +use std::ffi::OsStr; +use wl_clipboard_rs::utils::PrimarySelectionCheckError::MissingProtocol; +use wl_clipboard_rs::utils::PrimarySelectionCheckError::NoSeats; + +#[test] +fn missing_data_control_requires_the_compositors_own_x11_listener() { + let available = |probe, display: Option<&str>| { + wayland_primary_available(probe, display.map(OsStr::new), |number| number == 0) + }; + assert!(available(Ok(true), None)); + assert!(available(Err(MissingProtocol), Some(":0.0"))); + assert!(!available(Err(MissingProtocol), Some(":99"))); + assert!(!available(Err(MissingProtocol), None)); + assert!(!available(Err(MissingProtocol), Some("localhost:0"))); + assert!(!available(Ok(true), Some("localhost:0"))); + assert!(!available(Ok(false), Some(":0"))); + assert!(!available(Err(NoSeats), Some(":0"))); +} diff --git a/codex-rs/tui/src/tui.rs b/codex-rs/tui/src/tui.rs index a7b526e6bd..ab0d1a1d52 100644 --- a/codex-rs/tui/src/tui.rs +++ b/codex-rs/tui/src/tui.rs @@ -754,6 +754,7 @@ pub struct Tui { owned_screen: bool, pub(crate) mouse_capture: MouseCapture, // Copies and native ownership survive closing an overlay or startup picker. + primary_selection: Arc, pub(crate) clipboard: crate::clipboard_copy::worker::ClipboardWorker, // Keeps unmanaged process stderr writes out of the inline viewport. _stderr_guard: terminal_stderr::TerminalStderrGuard, @@ -830,6 +831,7 @@ impl Tui { alt_screen_enabled: true, owned_screen: false, mouse_capture: MouseCapture::Inherit, + primary_selection: terminal_capabilities::detect_primary_selection(), clipboard: Default::default(), _stderr_guard: stderr_guard, } @@ -905,6 +907,10 @@ impl Tui { crate::transcript_mode::TranscriptMode::resolve(self.owned_screen, self.alt_screen_enabled) } + pub(crate) fn primary_selection_available(&self) -> bool { + self.primary_selection.load(Ordering::Relaxed) + } + /// Retain the mouse capture policy across temporary editor, suspend and panic handoffs. /// Actual terminal capture is tracked by AlternateScreen so partial writes remain cleanable. pub(crate) fn set_mouse_capture(&mut self, mouse_capture: MouseCapture) -> Result<()> { diff --git a/codex-rs/tui/src/tui/selection_clipboard.rs b/codex-rs/tui/src/tui/selection_clipboard.rs index 09ec4917b0..073db20580 100644 --- a/codex-rs/tui/src/tui/selection_clipboard.rs +++ b/codex-rs/tui/src/tui/selection_clipboard.rs @@ -44,7 +44,7 @@ impl SelectionCopy { } impl Tui { - /// Copy to CLIPBOARD and/or publish X11 PRIMARY under one selection policy. + /// Copy to CLIPBOARD and/or publish PRIMARY under one selection policy. pub(crate) fn copy_selection( &mut self, text: &str,