From 7a8a9456e9a17a63f3980e7b321de9dcbe1e823c Mon Sep 17 00:00:00 2001 From: Eric Traut Date: Sat, 10 Oct 2026 19:07:41 +0000 Subject: [PATCH] Reuse and prewarm the WSL clipboard text reader (#52967) ## Why WSL clipboard reads previously launched PowerShell for every paste. Process creation can hang under WSL and stall the shared clipboard worker. ## What changed - Reuse a persistent PowerShell reader on a dedicated thread, keeping clipboard requests bounded by their deadlines and restarting the reader after errors. - Prewarm the reader at startup when right-click paste is allowed on WSL, without accessing clipboard contents. - Use length-framed UTF-8 responses to preserve whitespace and distinguish consecutive pastes while enforcing message size limits. ## Testing Update the command-reader test to cover consecutive responses from one process, large clipboard text, UTF-8 and whitespace preservation, and read timeouts. GitOrigin-RevId: 36af338097d6b178ab4887faa5918240c47e1515 --- codex-rs/tui/src/app/right_click_paste.rs | 2 +- codex-rs/tui/src/app/startup.rs | 9 + codex-rs/tui/src/clipboard_copy/worker.rs | 27 ++- .../tui/src/clipboard_copy/worker_tests.rs | 24 ++- codex-rs/tui/src/clipboard_paste/text.rs | 190 +++++++++++++----- .../tui/src/clipboard_paste/text_tests.rs | 36 +++- 6 files changed, 210 insertions(+), 78 deletions(-) diff --git a/codex-rs/tui/src/app/right_click_paste.rs b/codex-rs/tui/src/app/right_click_paste.rs index 4b912ec841..68475c76be 100644 --- a/codex-rs/tui/src/app/right_click_paste.rs +++ b/codex-rs/tui/src/app/right_click_paste.rs @@ -36,7 +36,7 @@ impl PasteEnvironment { } } - fn allows(&self, mode: RightClickPaste) -> bool { + pub(super) fn allows(&self, mode: RightClickPaste) -> bool { if self.ssh || self.vscode == VscodeDetection::VsCode { return false; } diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 69a4ff5f3e..bfc9c7d210 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -980,6 +980,15 @@ See the Codex keymap documentation for supported actions and examples." #[cfg(test)] _test_codex_home: None, }; + if tui.is_owned_screen() + && app.right_click_paste_environment.wsl + && app + .right_click_paste_environment + .allows(app.local_settings.tui.right_click_paste) + { + // Prewarm WSL interop off the UI thread, without accessing clipboard contents. + let _ = tui.clipboard.warm_text_reader(tui.frame_requester()); + } app.remember_launch_permissions(); if !tui.is_terminal_focused() { app.recap.note_focus_lost(Instant::now()); diff --git a/codex-rs/tui/src/clipboard_copy/worker.rs b/codex-rs/tui/src/clipboard_copy/worker.rs index b86047441b..5cdeed4a20 100644 --- a/codex-rs/tui/src/clipboard_copy/worker.rs +++ b/codex-rs/tui/src/clipboard_copy/worker.rs @@ -11,6 +11,7 @@ use super::CopyFormat; use super::CopyStatus; use crate::tui::FrameRequester; use std::cell::Cell; +use std::cell::LazyCell; use std::sync::Arc; use std::sync::Mutex; use std::sync::Weak; @@ -96,6 +97,7 @@ pub(crate) enum PasteSource { } enum Request { + WarmTextReader, Copy { text: Arc, format: CopyFormat, @@ -221,6 +223,15 @@ impl ClipboardWorker { Ok(CopyStatus::Pending(id)) } + pub(crate) fn warm_text_reader(&mut self, frames: FrameRequester) -> Result<(), String> { + self.ensure_started(frames)?; + self.requests + .as_ref() + .ok_or("clipboard worker stopped")? + .send(Request::WarmTextReader) + .map_err(|_| "clipboard worker stopped".to_string()) + } + fn ensure_started(&mut self, frames: FrameRequester) -> Result<(), String> { if self.requests.is_none() { self.start( @@ -240,7 +251,7 @@ impl ClipboardWorker { ); (result, terminal_text.into_inner()) }, - crate::clipboard_paste::text::read, + crate::clipboard_paste::text::reader, )?; } Ok(()) @@ -340,7 +351,7 @@ impl ClipboardWorker { } } - fn start( + fn start( &mut self, frames: FrameRequester, mut copy: impl FnMut( @@ -350,19 +361,27 @@ impl ClipboardWorker { ) -> (Result, Option) + Send + 'static, - mut read: impl FnMut(Instant) -> Result + Send + 'static, - ) -> Result<(), String> { + make_reader: impl FnOnce() -> R + Send + 'static, + ) -> Result<(), String> + where + R: FnMut(Instant) -> Result, + { let (requests, incoming) = mpsc::channel::(); let (outgoing, responses) = mpsc::channel(); // Native calls can wait indefinitely; shutdown waits only for a bounded handoff. std::thread::Builder::new() .name("clipboard-copy".into()) .spawn(move || { + let mut read = LazyCell::new(make_reader); let mut lease: Option = None; // An ordinary copy must not relinquish PRIMARY, or vice versa. let mut primary_lease: Option = None; while let Ok(request) = incoming.recv() { let (outcome, terminal_text) = match request { + Request::WarmTextReader => { + LazyCell::force(&read); + continue; + } Request::Copy { text, format, diff --git a/codex-rs/tui/src/clipboard_copy/worker_tests.rs b/codex-rs/tui/src/clipboard_copy/worker_tests.rs index 1805813f53..be4f11b5bc 100644 --- a/codex-rs/tui/src/clipboard_copy/worker_tests.rs +++ b/codex-rs/tui/src/clipboard_copy/worker_tests.rs @@ -28,7 +28,7 @@ async fn blocked_copy_allows_overlay_exit_rejects_backlog_and_wakes_completion() released.recv().unwrap(); (Ok(CopyOutcome::Copied(Some(ClipboardLease::test()))), None) }, - |_| unreachable!("copy-only backend"), + || |_| unreachable!("copy-only backend"), ) .unwrap(); let mut app = Box::new(crate::app::test_support::make_test_app().await); @@ -137,7 +137,7 @@ fn dropping_worker_does_not_wait_for_blocked_backend() { finished.send(()).unwrap(); (Err("unavailable".into()), None) }, - |_| unreachable!("copy-only backend"), + || |_| unreachable!("copy-only backend"), ) .unwrap(); worker @@ -178,7 +178,7 @@ async fn expired_setup_discards_delivery_and_keeps_worker_busy_until_it_returns( }); (outcome, None) }, - |_| unreachable!("copy-only backend"), + || |_| unreachable!("copy-only backend"), ) .unwrap(); worker @@ -293,10 +293,12 @@ async fn right_click_paste_uses_normal_input_and_discards_stale_reads() { .start( tui.frame_requester(), |_, _, _| unreachable!("no selection"), - move |_| { - started.send(()).unwrap(); - released.recv().unwrap(); - Ok("café\r\nsecond line\n".into()) + move || { + move |_| { + started.send(()).unwrap(); + released.recv().unwrap(); + Ok("café\r\nsecond line\n".into()) + } }, ) .unwrap(); @@ -380,9 +382,11 @@ fn expired_text_read_rejects_backlog_and_discards_late_completion() { .start( FrameRequester::test_dummy(), |_, _, _| unreachable!(), - move |_| { - released.recv().unwrap(); - Ok("late".into()) + move || { + move |_| { + released.recv().unwrap(); + Ok("late".into()) + } }, ) .unwrap(); diff --git a/codex-rs/tui/src/clipboard_paste/text.rs b/codex-rs/tui/src/clipboard_paste/text.rs index 32fcb1b855..17eee61566 100644 --- a/codex-rs/tui/src/clipboard_paste/text.rs +++ b/codex-rs/tui/src/clipboard_paste/text.rs @@ -4,33 +4,82 @@ use codex_protocol::user_input::MAX_USER_INPUT_TEXT_CHARS; use std::time::Instant; -pub(crate) fn read(deadline: Instant) -> Result { - if crate::clipboard_copy::is_ssh_session() { - return Err("clipboard text is unavailable over SSH".into()); - } +/// Constructed on the clipboard worker, never on the UI thread. +pub(crate) fn reader() -> impl FnMut(Instant) -> Result { #[cfg(target_os = "linux")] - if super::is_probably_wsl() { - let executable = codex_utils_path::system_executable("powershell.exe") - .ok_or("Windows clipboard reader is unavailable")?; - let mut command = tokio::process::Command::new(executable); - command.args(["-NoProfile", "-NonInteractive", "-Command", - "$ErrorActionPreference = 'Stop'; [Console]::OutputEncoding = [System.Text.UTF8Encoding]::new($false); [Console]::Out.Write((Get-Clipboard -Raw))"]); - return tokio::runtime::Builder::new_current_thread() - .enable_all() - .build() - .map_err(|_| "could not start clipboard reader")? - .block_on(read_command(command, deadline)); - } - #[cfg(not(target_os = "android"))] - { - native_result( - arboard::Clipboard::new().and_then(|mut clipboard| clipboard.get_text()), - deadline, - ) - } - #[cfg(target_os = "android")] - { - validate(String::new(), deadline) + let windows = + (super::is_probably_wsl() && !crate::clipboard_copy::is_ssh_session()).then(|| { + use std::sync::mpsc; + + let (requests, reads) = mpsc::sync_channel::<( + Instant, + mpsc::Sender>, + )>(/*bound*/ 1); + // WSL process creation itself can hang. Never do it on the shared copy worker, + // including on retries; at most one Windows reader can be starting or running. + std::thread::Builder::new() + .name("wsl-clipboard-reader".into()) + .spawn(move || { + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build(); + let mut child = runtime + .as_ref() + .ok() + .and_then(|runtime| start_windows_reader(runtime).ok()); + while let Ok((deadline, response)) = reads.recv() { + if Instant::now() >= deadline { + continue; + } + let result = match &runtime { + Ok(runtime) => { + if child.is_none() { + child = start_windows_reader(runtime).ok(); + } + match child.as_mut() { + Some(child) => runtime.block_on(read_command(child, deadline)), + None => Err("Windows clipboard reader is unavailable".into()), + } + } + Err(_) => Err("could not start clipboard reader".into()), + }; + // Never mistake a partial response for the next paste. + if result.is_err() { + child.take(); + } + let _ = response.send(result); + } + }) + .map(|_| requests) + .map_err(|_| "could not start clipboard reader".to_string()) + }); + move |deadline| { + if crate::clipboard_copy::is_ssh_session() { + return Err("clipboard text is unavailable over SSH".into()); + } + #[cfg(target_os = "linux")] + if let Some(windows) = &windows { + let (response, result) = std::sync::mpsc::channel(); + windows + .as_ref() + .map_err(Clone::clone)? + .try_send((deadline, response)) + .map_err(|_| "Windows clipboard reader is busy or unavailable")?; + return result + .recv_timeout(deadline.saturating_duration_since(Instant::now())) + .map_err(|_| "clipboard read timed out")?; + } + #[cfg(not(target_os = "android"))] + { + native_result( + arboard::Clipboard::new().and_then(|mut clipboard| clipboard.get_text()), + deadline, + ) + } + #[cfg(target_os = "android")] + { + validate(String::new(), deadline) + } } } @@ -57,52 +106,85 @@ fn validate(text: String, deadline: Instant) -> Result { } } -#[cfg(any(target_os = "linux", all(test, unix)))] -async fn read_command( - mut command: tokio::process::Command, - deadline: Instant, -) -> Result { +#[cfg(target_os = "linux")] +fn start_windows_reader( + runtime: &tokio::runtime::Runtime, +) -> Result { use std::process::Stdio; - use tokio::io::AsyncReadExt; - let mut child = command - .stdin(Stdio::null()) + let _guard = runtime.enter(); + let executable = codex_utils_path::system_executable("powershell.exe") + .ok_or("Windows clipboard reader is unavailable")?; + let mut command = tokio::process::Command::new(executable); + // Length-framed UTF-8 preserves every newline and whitespace, including empty text. + // Neither the prompt nor clipboard contents are ever evaluated as PowerShell. + command.args([ + "-NoProfile", + "-NonInteractive", + "-Command", + r#" +$ErrorActionPreference = 'Stop' +$out = [Console]::OpenStandardOutput() +$utf8 = [System.Text.UTF8Encoding]::new($false) +while ($null -ne [Console]::ReadLine()) { + $bytes = $utf8.GetBytes([string](Get-Clipboard -Raw)) + $header = [BitConverter]::GetBytes([uint32]$bytes.Length) + $out.Write($header, 0, $header.Length) + $out.Write($bytes, 0, $bytes.Length) + $out.Flush() +} +"#, + ]); + command + .stdin(Stdio::piped()) .stdout(Stdio::piped()) .stderr(Stdio::null()) .kill_on_drop(/*kill_on_drop*/ true) .spawn() - .map_err(|_| "could not start Windows clipboard reader")?; - // Spawn can itself stall under WSL. Both the UI and this read retain the original deadline. + .map_err(|_| "could not start Windows clipboard reader".into()) +} + +#[cfg(any(target_os = "linux", all(test, unix)))] +async fn read_command( + child: &mut tokio::process::Child, + deadline: Instant, +) -> Result { + use tokio::io::AsyncReadExt; + use tokio::io::AsyncWriteExt; + let result = tokio::time::timeout_at(deadline.into(), async { + let stdin = child + .stdin + .as_mut() + .ok_or("clipboard reader has no input")?; + stdin + .write_all(b"\n") + .await + .map_err(|_| "could not start clipboard read")?; + stdin + .flush() + .await + .map_err(|_| "could not start clipboard read")?; let stdout = child .stdout - .take() + .as_mut() .ok_or("clipboard reader has no output")?; - let limit = MAX_USER_INPUT_TEXT_CHARS * 4; - let mut bytes = Vec::new(); - stdout - .take((limit + 1) as u64) - .read_to_end(&mut bytes) + let size = stdout + .read_u32_le() .await - .map_err(|_| "could not read clipboard text")?; - if bytes.len() > limit { + .map_err(|_| "could not read clipboard text")? as usize; + if size > MAX_USER_INPUT_TEXT_CHARS * 4 { return Err("clipboard text exceeds the message size limit"); } - if !child - .wait() + let mut bytes = vec![0; size]; + stdout + .read_exact(&mut bytes) .await - .map_err(|_| "clipboard reader failed")? - .success() - { - return Err("clipboard text is unavailable"); - } + .map_err(|_| "could not read clipboard text")?; String::from_utf8(bytes).map_err(|_| "clipboard text is not UTF-8") }) .await .unwrap_or(Err("clipboard read timed out")); - if result.is_err() { - let _ = child.kill().await; - } validate(result.map_err(str::to_owned)?, deadline) } diff --git a/codex-rs/tui/src/clipboard_paste/text_tests.rs b/codex-rs/tui/src/clipboard_paste/text_tests.rs index 387cc39472..23006894d0 100644 --- a/codex-rs/tui/src/clipboard_paste/text_tests.rs +++ b/codex-rs/tui/src/clipboard_paste/text_tests.rs @@ -16,20 +16,38 @@ fn text_preserves_whitespace_and_rejects_late_or_oversized_reads() { #[cfg(unix)] #[tokio::test] async fn command_drains_large_output_and_bounds_waiting() { - let mut command = tokio::process::Command::new("sh"); - command.args([ - "-c", - "head -c 131072 /dev/zero | tr '\\000' x; printf '\\n'", - ]); + use std::process::Stdio; + + let mut child = tokio::process::Command::new("sh") + .args([ + "-c", + // Two distinct framed clipboard results, only in response to separate requests. + r#"read -r request; printf '\001\000\002\000'; head -c 131072 /dev/zero | tr '\000' x; printf '\n'; read -r request; printf '\010\000\000\000 café\r\n'"#, + ]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .kill_on_drop(/*kill_on_drop*/ true) + .spawn() + .unwrap(); + let deadline = Instant::now() + Duration::from_secs(/*secs*/ 5); assert_eq!( - read_command(command, Instant::now() + Duration::from_secs(/*secs*/ 5)).await, + read_command(&mut child, deadline).await, Ok(format!("{}\n", "x".repeat(/*n*/ 131072))) ); - let mut command = tokio::process::Command::new("sh"); - command.args(["-c", "exec sleep 10"]); + assert_eq!( + read_command(&mut child, deadline).await, + Ok(" café\r\n".into()) + ); + let mut child = tokio::process::Command::new("sh") + .args(["-c", "exec sleep 10"]) + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .kill_on_drop(/*kill_on_drop*/ true) + .spawn() + .unwrap(); assert_eq!( read_command( - command, + &mut child, Instant::now() + Duration::from_millis(/*millis*/ 20) ) .await,