mirror of
https://github.com/openai/codex.git
synced 2026-11-24 23:20:47 +00:00
Prefer terminal clipboard writes in VS Code dev containers (#63740)
## Why A native clipboard write inside a dev container can succeed on the container's desktop while leaving the host clipboard unchanged. ## What changed Detect VS Code dev containers with `REMOTE_CONTAINERS=true` and route clipboard copies through tmux or OSC 52. On Linux with a nonempty `WAYLAND_DISPLAY`, use the native clipboard for copies over the 100,000-byte terminal limit and retain clipboard ownership. Host delivery remains unconfirmed on both paths. The copy status asks users to try pasting and points them to `/export` if the text is missing. Keep that status out of exported transcripts. ## Testing Add coverage for dev container detection, terminal send success and failure, and clipboard ownership at the terminal size limit and one byte over it. GitOrigin-RevId: 057f7956fce8a16c8a3022b697e443b524740376
This commit is contained in:
@@ -214,6 +214,15 @@ impl TerminalInfo {
|
||||
pub fn is_zellij(&self) -> bool {
|
||||
matches!(self.multiplexer, Some(Multiplexer::Zellij { .. }))
|
||||
}
|
||||
|
||||
/// Whether this terminal is VS Code running in a dev container.
|
||||
pub fn is_vscode_dev_container(&self) -> bool {
|
||||
self.is_vscode_dev_container_in(&ProcessEnvironment)
|
||||
}
|
||||
|
||||
fn is_vscode_dev_container_in(&self, env: &dyn Environment) -> bool {
|
||||
self.name == TerminalName::VsCode && env.var("REMOTE_CONTAINERS").as_deref() == Some("true")
|
||||
}
|
||||
}
|
||||
|
||||
static TERMINAL_INFO: OnceLock<TerminalInfo> = OnceLock::new();
|
||||
|
||||
@@ -42,6 +42,24 @@ fn terminal_info(
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dev_container_requires_vscode_and_an_enabled_container_marker() {
|
||||
for (program, marker, expected) in [
|
||||
("vscode", Some("true"), true),
|
||||
("VSCode", Some("true"), true),
|
||||
("vscode", None, false),
|
||||
("vscode", Some("false"), false),
|
||||
("kitty", Some("true"), false),
|
||||
] {
|
||||
let mut env = FakeEnvironment::new().with_var("TERM_PROGRAM", program);
|
||||
if let Some(marker) = marker {
|
||||
env = env.with_var("REMOTE_CONTAINERS", marker);
|
||||
}
|
||||
let terminal = detect_terminal_info_from_env(&env);
|
||||
assert_eq!(terminal.is_vscode_dev_container_in(&env), expected);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn detects_term_program() {
|
||||
let env = FakeEnvironment::new()
|
||||
|
||||
@@ -257,12 +257,13 @@ fn render_markdown_transcript(cells: &[Arc<dyn HistoryCell>]) -> Result<String,
|
||||
[
|
||||
"• Saved conversation to ",
|
||||
"• Copied conversation to clipboard",
|
||||
"• Copy unconfirmed; /export saves chat",
|
||||
"■ Export failed: ",
|
||||
"■ Copy failed: ",
|
||||
]
|
||||
.iter()
|
||||
.any(|prefix| text.starts_with(prefix))
|
||||
|| text.strip_prefix("• ")
|
||||
== Some(crate::clipboard_copy::UNCONFIRMED_COPY_MESSAGE)
|
||||
})
|
||||
{
|
||||
continue;
|
||||
|
||||
@@ -50,7 +50,7 @@ fn markdown_transcript_preserves_messages_and_formats_activity() {
|
||||
"■ Export failed: missing parent".into(),
|
||||
])),
|
||||
Arc::new(PlainHistoryCell::new(vec![
|
||||
"• Copy unconfirmed; /export saves chat".into(),
|
||||
"• Try pasting. If the text isn’t there, use /export to save the chat.".into(),
|
||||
])),
|
||||
user("", vec!["image.png".into()]),
|
||||
user("[Image #1] describe this", vec!["image.png".into()]),
|
||||
|
||||
+1
-1
@@ -5,4 +5,4 @@ expression: "render_bottom_popup(&chat, 80)"
|
||||
› Ask Codex to do anything
|
||||
|
||||
GPT-5.6-Sol default · /tmp/project
|
||||
Copy unconfirmed; /export saves chat
|
||||
Try pasting. If the text isn’t there, use /export to save the chat.
|
||||
|
||||
+1
-1
@@ -3,4 +3,4 @@ source: tui/src/chatwidget/tests/slash_commands.rs
|
||||
assertion_line: 2404
|
||||
expression: rendered
|
||||
---
|
||||
• Copy unconfirmed; /export saves chat
|
||||
• Try pasting. If the text isn’t there, use /export to save the chat.
|
||||
|
||||
@@ -5,9 +5,9 @@
|
||||
//! 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, Rex, and SSH, use OSC 52 only if native copying fails.
|
||||
//! VS Code dev containers prefer the terminal. Oversized copies can use a shared
|
||||
//! Wayland clipboard, but host delivery remains unconfirmed. Other sessions also copy natively
|
||||
//! because terminal writes have no delivery acknowledgement.
|
||||
//!
|
||||
//! On Linux, X11 and some Wayland compositors require the process that wrote the
|
||||
//! clipboard to keep its handle open. `ClipboardLease` wraps the `arboard::Clipboard`
|
||||
@@ -37,6 +37,9 @@ use tmux::copy as tmux_clipboard_copy;
|
||||
/// Maximum raw bytes sent through tmux or directly encoded into OSC 52.
|
||||
/// Large payloads are rejected before encoding to avoid overwhelming the terminal.
|
||||
const OSC52_MAX_RAW_BYTES: usize = 100_000;
|
||||
pub(crate) const UNCONFIRMED_COPY_MESSAGE: &str =
|
||||
"Try pasting. If the text isn’t there, use /export to save the chat.";
|
||||
|
||||
/// Whether copied text should also have a rendered HTML representation and its source.
|
||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
||||
pub(crate) enum CopyFormat {
|
||||
@@ -46,24 +49,23 @@ pub(crate) enum CopyFormat {
|
||||
MarkdownSelection(Arc<str>),
|
||||
}
|
||||
|
||||
/// A native clipboard write or an unacknowledged request to the user's terminal.
|
||||
/// Host delivery status and any native clipboard ownership to retain.
|
||||
pub(crate) enum CopyOutcome {
|
||||
Copied(Option<ClipboardLease>),
|
||||
Requested,
|
||||
Unconfirmed(Option<ClipboardLease>),
|
||||
}
|
||||
|
||||
impl CopyOutcome {
|
||||
/// Replace native ownership only when a backend supplies a new lease.
|
||||
pub(crate) fn store(self, lease: &mut Option<ClipboardLease>) -> CopyStatus {
|
||||
match self {
|
||||
Self::Copied(next_lease) => {
|
||||
if let Some(next_lease) = next_lease {
|
||||
*lease = Some(next_lease);
|
||||
}
|
||||
CopyStatus::Confirmed
|
||||
}
|
||||
Self::Requested => CopyStatus::Unconfirmed,
|
||||
let (status, next_lease) = match self {
|
||||
Self::Copied(next) => (CopyStatus::Confirmed, next),
|
||||
Self::Unconfirmed(next) => (CopyStatus::Unconfirmed, next),
|
||||
};
|
||||
if let Some(next) = next_lease {
|
||||
*lease = Some(next);
|
||||
}
|
||||
status
|
||||
}
|
||||
}
|
||||
|
||||
@@ -80,7 +82,7 @@ impl CopyStatus {
|
||||
pub(crate) fn message(self, label: &str) -> String {
|
||||
match self {
|
||||
Self::Confirmed => format!("Copied {label} to clipboard"),
|
||||
Self::Unconfirmed => "Copy unconfirmed; /export saves chat".to_string(),
|
||||
Self::Unconfirmed => UNCONFIRMED_COPY_MESSAGE.to_string(),
|
||||
Self::Pending(_) => format!("Copying {label}…"),
|
||||
Self::Busy => "Copy already in progress".to_string(),
|
||||
}
|
||||
@@ -89,13 +91,11 @@ impl CopyStatus {
|
||||
|
||||
/// Copy text to the system clipboard.
|
||||
///
|
||||
/// Try native copying, then independently attempt terminal forwarding in tmux,
|
||||
/// Outside VS Code dev containers, try native copying, then independently forward in tmux,
|
||||
/// 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.
|
||||
/// A terminal-only send returns `Requested`. Store the outcome to retain any
|
||||
/// existing native lease unless the backend supplies a replacement.
|
||||
/// Store the outcome to retain native ownership even when host delivery is unconfirmed.
|
||||
///
|
||||
/// OSC 52 is supported by kitty, WezTerm, iTerm2, Ghostty, and others.
|
||||
fn copy_to_clipboard(
|
||||
@@ -114,7 +114,8 @@ fn copy_to_clipboard(
|
||||
#[cfg(not(target_os = "android"))]
|
||||
let native_copy = {
|
||||
// Bound WSL native setup: even initialization can block forever.
|
||||
let clipboard = (!environment.wsl_session).then(arboard::Clipboard::new);
|
||||
let clipboard = (environment.uses_native(text) && !environment.wsl_session)
|
||||
.then(arboard::Clipboard::new);
|
||||
move |text: &str, html: Option<&str>| {
|
||||
let clipboard = match clipboard {
|
||||
Some(clipboard) => clipboard.map_err(|e| format!("clipboard unavailable: {e}"))?,
|
||||
@@ -179,6 +180,20 @@ struct CopyEnvironment {
|
||||
wsl_session: bool,
|
||||
}
|
||||
|
||||
impl CopyEnvironment {
|
||||
fn uses_native(self, text: &str) -> bool {
|
||||
match self.terminal_copy {
|
||||
ClipboardCopyMode::PreferTerminal {
|
||||
native_for_large_copies,
|
||||
..
|
||||
} => native_for_large_copies && text.len() > OSC52_MAX_RAW_BYTES,
|
||||
ClipboardCopyMode::FallbackOsc52
|
||||
| ClipboardCopyMode::Osc52
|
||||
| ClipboardCopyMode::Tmux => true,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn copy_to_clipboard_with(
|
||||
text: &str,
|
||||
format: CopyFormat,
|
||||
@@ -193,7 +208,10 @@ fn copy_to_clipboard_with(
|
||||
}
|
||||
|
||||
let terminal_copy = || {
|
||||
if environment.terminal_copy == ClipboardCopyMode::Tmux {
|
||||
if matches!(
|
||||
environment.terminal_copy,
|
||||
ClipboardCopyMode::Tmux | ClipboardCopyMode::PreferTerminal { tmux: true, .. }
|
||||
) {
|
||||
let raw_bytes = text.len();
|
||||
let result = if raw_bytes > OSC52_MAX_RAW_BYTES {
|
||||
Err(format!(
|
||||
@@ -221,6 +239,17 @@ fn copy_to_clipboard_with(
|
||||
};
|
||||
arboard_copy_fn(text, html.as_deref()).map_err(|error| format!("native clipboard: {error}"))
|
||||
};
|
||||
if matches!(
|
||||
environment.terminal_copy,
|
||||
ClipboardCopyMode::PreferTerminal { .. }
|
||||
) {
|
||||
// Wayland may be shared with the host, but arboard can fall back to private X11.
|
||||
return if environment.uses_native(text) {
|
||||
native_copy().map(CopyOutcome::Unconfirmed)
|
||||
} else {
|
||||
terminal_copy().map(|()| CopyOutcome::Unconfirmed(None))
|
||||
};
|
||||
}
|
||||
let native_result = if environment.wsl_session && !environment.forwarded_x11 {
|
||||
wsl_copy_fn(text).map(|()| None).or_else(|windows_error| {
|
||||
native_copy().map_err(|native_error| {
|
||||
@@ -240,7 +269,7 @@ fn copy_to_clipboard_with(
|
||||
Ok(lease) => Ok(CopyOutcome::Copied(lease)),
|
||||
Err(native_error) => terminal_result
|
||||
.unwrap_or_else(terminal_copy)
|
||||
.map(|()| CopyOutcome::Requested)
|
||||
.map(|()| CopyOutcome::Unconfirmed(None))
|
||||
.map_err(|terminal_error| {
|
||||
format!("{native_error}; terminal clipboard: {terminal_error}")
|
||||
}),
|
||||
@@ -705,7 +734,7 @@ mod tests {
|
||||
},
|
||||
);
|
||||
|
||||
assert!(matches!(result, Ok(CopyOutcome::Requested)));
|
||||
assert!(matches!(result, Ok(CopyOutcome::Unconfirmed(None))));
|
||||
assert_eq!(osc_calls.get(), 1);
|
||||
assert_eq!(native_calls.get(), 1);
|
||||
assert_eq!(wsl_calls.get(), 0);
|
||||
@@ -742,7 +771,7 @@ mod tests {
|
||||
},
|
||||
);
|
||||
|
||||
assert!(matches!(result, Ok(CopyOutcome::Requested)));
|
||||
assert!(matches!(result, Ok(CopyOutcome::Unconfirmed(None))));
|
||||
assert_eq!(tmux_calls.get(), 1);
|
||||
assert_eq!(osc_calls.get(), 0);
|
||||
assert_eq!(native_calls.get(), 1);
|
||||
@@ -803,7 +832,7 @@ mod tests {
|
||||
},
|
||||
);
|
||||
|
||||
assert!(matches!(result, Ok(CopyOutcome::Requested)));
|
||||
assert!(matches!(result, Ok(CopyOutcome::Unconfirmed(None))));
|
||||
assert_eq!(osc_calls.get(), 1);
|
||||
assert_eq!(native_calls.get(), 1);
|
||||
assert_eq!(wsl_calls.get(), 1);
|
||||
|
||||
@@ -81,6 +81,65 @@ fn local_tmux_environment() -> CopyEnvironment {
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn terminal_only_copy_reports_the_send_result() {
|
||||
let environment = CopyEnvironment {
|
||||
terminal_copy: ClipboardCopyMode::PreferTerminal {
|
||||
tmux: false,
|
||||
native_for_large_copies: false,
|
||||
},
|
||||
forwarded_x11: false,
|
||||
wsl_session: false,
|
||||
};
|
||||
for send in [Ok(()), Err("write failed".to_string())] {
|
||||
let result = copy_to_clipboard_with(
|
||||
"hello",
|
||||
CopyFormat::Markdown,
|
||||
environment,
|
||||
|_| panic!("not in tmux"),
|
||||
|text| {
|
||||
assert_eq!(text, "hello");
|
||||
send.clone()
|
||||
},
|
||||
|_, _| panic!("must not write to the container clipboard"),
|
||||
|_| panic!("must not write to the WSL clipboard"),
|
||||
);
|
||||
assert_eq!(
|
||||
result.map(|outcome| outcome.store(&mut None)),
|
||||
send.map(|()| CopyStatus::Unconfirmed)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn oversized_dev_container_copy_can_keep_native_ownership_without_confirming_delivery() {
|
||||
let environment = CopyEnvironment {
|
||||
terminal_copy: ClipboardCopyMode::PreferTerminal {
|
||||
tmux: true,
|
||||
native_for_large_copies: true,
|
||||
},
|
||||
..local_tmux_environment()
|
||||
};
|
||||
for size in [OSC52_MAX_RAW_BYTES, OSC52_MAX_RAW_BYTES + 1] {
|
||||
let text = "x".repeat(size);
|
||||
let result = copy_to_clipboard_with(
|
||||
&text,
|
||||
CopyFormat::PlainText,
|
||||
environment,
|
||||
|_| Ok(()),
|
||||
|_| panic!("no OSC 52 fallback expected"),
|
||||
|actual, _| {
|
||||
assert_eq!(actual, text);
|
||||
Ok(Some(ClipboardLease::test()))
|
||||
},
|
||||
|_| panic!("must not target the WSL clipboard"),
|
||||
);
|
||||
let mut lease = None;
|
||||
assert_eq!(result.unwrap().store(&mut lease), CopyStatus::Unconfirmed);
|
||||
assert_eq!(lease.is_some(), size > OSC52_MAX_RAW_BYTES);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rex_selects_osc52_without_ssh_or_tmux() {
|
||||
assert_eq!(
|
||||
|
||||
@@ -421,7 +421,7 @@ impl ClipboardWorker {
|
||||
});
|
||||
match primary {
|
||||
Some(result) if destination == CopyDestination::Primary => {
|
||||
(result.map(|_| super::CopyOutcome::Requested), None)
|
||||
(result.map(|_| super::CopyOutcome::Unconfirmed(None)), None)
|
||||
}
|
||||
// Unavailable PRIMARY must not break configured CLIPBOARD copy.
|
||||
_ => copy(&text, format, &setup),
|
||||
|
||||
@@ -9,6 +9,11 @@ pub(crate) enum ClipboardCopyMode {
|
||||
FallbackOsc52,
|
||||
Osc52,
|
||||
Tmux,
|
||||
/// The native clipboard may belong to a private desktop.
|
||||
PreferTerminal {
|
||||
native_for_large_copies: bool,
|
||||
tmux: bool,
|
||||
},
|
||||
}
|
||||
|
||||
impl ClipboardCopyMode {
|
||||
@@ -28,14 +33,23 @@ pub(crate) struct ClipboardCapabilities {
|
||||
|
||||
impl ClipboardCapabilities {
|
||||
pub(crate) fn detect() -> Self {
|
||||
let terminal = codex_terminal_detection::terminal_info();
|
||||
let ssh = is_ssh_session();
|
||||
let tmux = is_tmux_session();
|
||||
Self {
|
||||
copy_mode: if is_tmux_session() {
|
||||
copy_mode: if terminal.is_vscode_dev_container() {
|
||||
ClipboardCopyMode::PreferTerminal {
|
||||
native_for_large_copies: cfg!(target_os = "linux")
|
||||
&& std::env::var_os("WAYLAND_DISPLAY")
|
||||
.is_some_and(|display| !display.is_empty()),
|
||||
tmux,
|
||||
}
|
||||
} else if tmux {
|
||||
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)
|
||||
ClipboardCopyMode::for_terminal(terminal.name)
|
||||
},
|
||||
forwarded_x11: ssh && std::env::var("DISPLAY").is_ok_and(|display| !display.is_empty()),
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user