Forward TUI clipboard copies to Rex clients (#62931)

## Why

A client can attach to a Rex session after Codex starts. A successful
native clipboard write can update the host clipboard without reaching
the attached client.

## What changed

Use shared terminal detection to select OSC 52 forwarding in Rex, even
when native copying succeeds. Keep environment-based routing for tmux,
Herdr, and SSH. Use the same terminal detector to recognize VS Code for
keyboard handling, with the existing Windows probe as a fallback.

## Testing

Cover OSC 52 selection for Rex without SSH or tmux and verify that
forwarding runs after a successful native copy.

GitOrigin-RevId: 47db5868d87aaf2aeee9cdd59307aa1be532c11e
This commit is contained in:
Eric Traut
2026-11-21 08:37:40 +00:00
committed by copyberry
parent ddfaef91b2
commit 556901ba72
5 changed files with 90 additions and 88 deletions
+19 -35
View File
@@ -2,12 +2,12 @@
//!
//! Local copying uses the native clipboard, or the Windows clipboard directly on WSL.
//! WSL sessions over SSH with a forwarded X11 display use the native clipboard instead.
//! In tmux and Herdr, also forward to the attached terminal so clients attached after Codex
//! In tmux, Herdr, and Rex, also forward to the attached terminal so clients attached after Codex
//! started receive the copy. Over SSH, wrap OSC 52 for GNU screen when detected.
//!
//! Terminal writes have no delivery acknowledgement: a successful send must not
//! suppress native copying. Both the host and attached client's clipboards may
//! change. Outside tmux, Herdr, and SSH, use OSC 52 only if native copying fails.
//! change. Outside tmux, Herdr, Rex, and SSH, use OSC 52 only if native copying fails.
//!
//! On Linux, X11 and some Wayland compositors require the process that wrote the
//! clipboard to keep its handle open. `ClipboardLease` wraps the `arboard::Clipboard`
@@ -25,6 +25,10 @@ mod tmux;
pub(crate) mod worker;
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 base64::Engine;
use std::io::Write;
use std::sync::Arc;
@@ -86,7 +90,7 @@ impl CopyStatus {
/// Copy text to the system clipboard.
///
/// Try native copying, then independently attempt terminal forwarding in tmux,
/// Herdr, or SSH. A terminal send is best effort and does not confirm clipboard delivery.
/// Herdr, Rex, or SSH. A terminal send is best effort and does not confirm clipboard delivery.
/// Terminal forwarding may replace native HTML with plain text.
///
/// Native or WSL success returns `Copied`, even if terminal forwarding fails.
@@ -101,14 +105,11 @@ fn copy_to_clipboard(
osc52: impl Fn(&str) -> Result<(), String>,
) -> Result<CopyOutcome, String> {
let wsl_deadline = std::time::Instant::now() + std::time::Duration::from_secs(/*secs*/ 5);
let ssh_session = is_ssh_session();
let capabilities = ClipboardCapabilities::detect();
let environment = CopyEnvironment {
herdr_session: std::env::var("HERDR_ENV").is_ok_and(|value| value == "1"),
ssh_session,
forwarded_x11: ssh_session
&& std::env::var("DISPLAY").is_ok_and(|display| !display.is_empty()),
terminal_copy: capabilities.copy_mode,
forwarded_x11: capabilities.forwarded_x11,
wsl_session: is_wsl_session(),
tmux_session: is_tmux_session(),
};
#[cfg(not(target_os = "android"))]
let native_copy = {
@@ -170,15 +171,12 @@ impl ClipboardLease {
}
}
/// Core copy logic with injected backends, enabling deterministic unit tests
/// without touching real clipboards or terminal I/O.
/// Inputs to clipboard routing, independent of terminal identity.
#[derive(Clone, Copy)]
struct CopyEnvironment {
herdr_session: bool,
ssh_session: bool,
terminal_copy: ClipboardCopyMode,
forwarded_x11: bool,
wsl_session: bool,
tmux_session: bool,
}
fn copy_to_clipboard_with(
@@ -195,7 +193,7 @@ fn copy_to_clipboard_with(
}
let terminal_copy = || {
if environment.tmux_session {
if environment.terminal_copy == ClipboardCopyMode::Tmux {
let raw_bytes = text.len();
let result = if raw_bytes > OSC52_MAX_RAW_BYTES {
Err(format!(
@@ -237,8 +235,7 @@ fn copy_to_clipboard_with(
// Persistent multiplexer sessions may gain remote clients after Codex starts, so still
// forward even when no SSH variables were inherited or native copying succeeded.
let terminal_result =
(environment.tmux_session || environment.herdr_session || environment.ssh_session)
.then(terminal_copy);
(environment.terminal_copy != ClipboardCopyMode::FallbackOsc52).then(terminal_copy);
match native_result {
Ok(lease) => Ok(CopyOutcome::Copied(lease)),
Err(native_error) => terminal_result
@@ -250,16 +247,6 @@ fn copy_to_clipboard_with(
}
}
/// Detect whether the current process is running inside an SSH session.
pub(crate) fn is_ssh_session() -> bool {
std::env::var_os("SSH_TTY").is_some() || std::env::var_os("SSH_CONNECTION").is_some()
}
/// Detect whether the current process is running inside tmux.
fn is_tmux_session() -> bool {
std::env::var_os("TMUX").is_some() || std::env::var_os("TMUX_PANE").is_some()
}
#[cfg(target_os = "linux")]
pub(crate) fn is_wsl_session() -> bool {
crate::clipboard_paste::is_probably_wsl()
@@ -365,6 +352,7 @@ mod tests {
use pretty_assertions::assert_eq;
use std::cell::Cell;
use super::ClipboardCopyMode;
use super::CopyEnvironment;
use super::CopyFormat;
use super::CopyOutcome;
@@ -376,28 +364,24 @@ mod tests {
fn remote_environment() -> CopyEnvironment {
CopyEnvironment {
herdr_session: false,
ssh_session: true,
terminal_copy: ClipboardCopyMode::Osc52,
forwarded_x11: false,
wsl_session: true,
tmux_session: false,
}
}
fn remote_tmux_environment() -> CopyEnvironment {
CopyEnvironment {
tmux_session: true,
terminal_copy: ClipboardCopyMode::Tmux,
..remote_environment()
}
}
fn local_environment() -> CopyEnvironment {
CopyEnvironment {
herdr_session: false,
ssh_session: false,
terminal_copy: ClipboardCopyMode::FallbackOsc52,
forwarded_x11: false,
wsl_session: false,
tmux_session: false,
}
}
@@ -737,7 +721,7 @@ mod tests {
"hello",
CopyFormat::PlainText,
CopyEnvironment {
tmux_session: true,
terminal_copy: ClipboardCopyMode::Tmux,
..local_environment()
},
|_| {
@@ -1,5 +1,6 @@
//! Clipboard routing, native ownership, and payload-boundary regressions.
use super::ClipboardCopyMode;
use super::ClipboardLease;
use super::CopyEnvironment;
use super::CopyFormat;
@@ -7,6 +8,7 @@ use super::CopyOutcome;
use super::CopyStatus;
use super::OSC52_MAX_RAW_BYTES;
use super::copy_to_clipboard_with;
use codex_terminal_detection::TerminalName;
use pretty_assertions::assert_eq;
use std::cell::RefCell;
@@ -17,10 +19,8 @@ fn local_tmux_preserves_native_html_when_terminal_silently_rejects_copy() {
"**hello**",
CopyFormat::Markdown,
CopyEnvironment {
herdr_session: false,
ssh_session: false,
terminal_copy: ClipboardCopyMode::Tmux,
forwarded_x11: false,
tmux_session: true,
wsl_session: false,
},
|_| {
@@ -50,10 +50,8 @@ fn copy_uses_osc52_when_tmux_fails_even_if_native_copy_succeeds() {
"hello",
CopyFormat::PlainText,
CopyEnvironment {
herdr_session: false,
ssh_session: false,
terminal_copy: ClipboardCopyMode::Tmux,
forwarded_x11: false,
tmux_session: true,
wsl_session: false,
},
|_| {
@@ -77,28 +75,32 @@ fn copy_uses_osc52_when_tmux_fails_even_if_native_copy_succeeds() {
fn local_tmux_environment() -> CopyEnvironment {
CopyEnvironment {
herdr_session: false,
tmux_session: true,
ssh_session: false,
terminal_copy: ClipboardCopyMode::Tmux,
forwarded_x11: false,
wsl_session: false,
}
}
#[test]
fn herdr_forwards_to_osc52_even_when_native_copy_succeeds() {
fn rex_selects_osc52_without_ssh_or_tmux() {
assert_eq!(
ClipboardCopyMode::for_terminal(TerminalName::Rex),
ClipboardCopyMode::Osc52,
);
}
#[test]
fn osc52_forwarding_runs_even_when_native_copy_succeeds() {
let calls = RefCell::new(Vec::new());
let result = copy_to_clipboard_with(
"hello",
CopyFormat::PlainText,
CopyEnvironment {
herdr_session: true,
ssh_session: false,
terminal_copy: ClipboardCopyMode::Osc52,
forwarded_x11: false,
tmux_session: false,
wsl_session: false,
},
|_| panic!("Herdr should use OSC 52 directly"),
|_| panic!("forwarding should use OSC 52 directly"),
|_| {
calls.borrow_mut().push("osc52");
Ok(())
+1
View File
@@ -240,6 +240,7 @@ mod subscription;
mod system_motion;
mod task_mentions;
mod temporary_structured_request;
mod terminal_capabilities;
mod terminal_hyperlinks;
mod terminal_palette;
mod terminal_probe;
+51
View File
@@ -0,0 +1,51 @@
//! Derives TUI capabilities from terminal identity and session environment.
//! Keep environment-specific clipboard decisions here so delivery code only sees a strategy.
use codex_terminal_detection::TerminalName;
/// How clipboard writes should reach the attached terminal.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum ClipboardCopyMode {
FallbackOsc52,
Osc52,
Tmux,
}
impl ClipboardCopyMode {
pub(crate) fn for_terminal(terminal: TerminalName) -> Self {
if terminal == TerminalName::Rex {
Self::Osc52
} else {
Self::FallbackOsc52
}
}
}
pub(crate) struct ClipboardCapabilities {
pub(crate) copy_mode: ClipboardCopyMode,
pub(crate) forwarded_x11: bool,
}
impl ClipboardCapabilities {
pub(crate) fn detect() -> Self {
let ssh = is_ssh_session();
Self {
copy_mode: if is_tmux_session() {
ClipboardCopyMode::Tmux
} else if ssh || std::env::var("HERDR_ENV").is_ok_and(|value| value == "1") {
ClipboardCopyMode::Osc52
} else {
ClipboardCopyMode::for_terminal(codex_terminal_detection::terminal_info().name)
},
forwarded_x11: ssh && std::env::var("DISPLAY").is_ok_and(|display| !display.is_empty()),
}
}
}
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 {
std::env::var_os("TMUX").is_some() || std::env::var_os("TMUX_PANE").is_some()
}
+3 -39
View File
@@ -88,30 +88,13 @@ pub(super) fn running_in_vscode_terminal() -> bool {
}
pub(crate) fn detect_vscode_terminal() -> VscodeDetection {
if term_program_is_vscode(std::env::var("TERM_PROGRAM").ok().as_deref()) {
return VscodeDetection::VsCode;
}
vscode_terminal_detected(
std::env::var("TERM_PROGRAM").ok().as_deref(),
windows_vscode_detection(),
)
}
fn vscode_terminal_detected(
linux_term_program: Option<&str>,
windows_detection: VscodeDetection,
) -> VscodeDetection {
if term_program_is_vscode(linux_term_program) {
if terminal_info().name == TerminalName::VsCode {
VscodeDetection::VsCode
} else {
windows_detection
windows_vscode_detection()
}
}
fn term_program_is_vscode(value: Option<&str>) -> bool {
value.is_some_and(|value| value.eq_ignore_ascii_case("vscode"))
}
fn windows_vscode_detection() -> VscodeDetection {
#[cfg(target_os = "linux")]
{
@@ -198,7 +181,7 @@ fn read_windows_vscode_detection_with_timeout(
.lines()
.find_map(|line| line.trim_end_matches('\r').strip_prefix("TERM_PROGRAM="))
.filter(|value| !value.trim().is_empty());
if term_program_is_vscode(term_program) {
if term_program.is_some_and(|value| value.eq_ignore_ascii_case("vscode")) {
VscodeDetection::VsCode
} else {
VscodeDetection::Other
@@ -391,7 +374,6 @@ mod tests {
use super::parse_bool_env;
use super::tmux_session_detected;
use super::tmux_should_enable_modify_other_keys_for;
use super::vscode_terminal_detected;
use codex_terminal_detection::TerminalName;
use crossterm::Command;
use crossterm::event::PushKeyboardEnhancementFlags;
@@ -538,24 +520,6 @@ mod tests {
}
}
#[test]
fn vscode_terminal_detection_uses_linux_and_windows_term_program() {
for detection in [
VscodeDetection::VsCode,
VscodeDetection::Other,
VscodeDetection::Unknown,
] {
assert_eq!(
vscode_terminal_detected(Some("vscode"), detection),
VscodeDetection::VsCode,
);
assert_eq!(
vscode_terminal_detected(/*linux_term_program*/ None, detection),
detection,
);
}
}
#[test]
fn tmux_session_detection_accepts_tmux_or_tmux_pane() {
assert!(tmux_session_detected(