mirror of
https://github.com/openai/codex.git
synced 2026-12-02 00:31:03 +00:00
Use an in-memory clipboard in TUI tests (#64797)
## Why TUI copy tests can verify the text sent to the clipboard and `PRIMARY` without depending on the host clipboard or waiting for a background worker. ## What changed Give each test TUI its own in-memory clipboard and `PRIMARY` selection. Handle requests inline and expose completions through the normal worker polling path. ## Testing Assert copied text in transcript, sidebar preview, and turn tip tests. Verify that a second TUI's copy leaves the first TUI's Markdown clipboard text and plain-text `PRIMARY` selection available for paste. GitOrigin-RevId: 159845b17f0dac26b4b12c3851c101afe8d21d2d
This commit is contained in:
@@ -6,6 +6,7 @@ use crate::app::tests::make_test_app_with_channels;
|
||||
use crate::app_command::AppCommand as Op;
|
||||
use crate::chatwidget::tests::helpers::normalize_snapshot_paths;
|
||||
use crate::chatwidget::tests::helpers::render_bottom_popup;
|
||||
use crate::clipboard_copy::worker::PasteSource;
|
||||
use crate::history_cell::HistoryRenderMode;
|
||||
use crate::history_cell::PlainHistoryCell;
|
||||
use codex_app_server_protocol::ItemCompletedNotification;
|
||||
@@ -473,7 +474,7 @@ async fn plan_menu_allows_transcript_selection_and_copy_but_respects_popup_bound
|
||||
TuiEvent::Key(KeyEvent::new(KeyCode::Insert, KeyModifiers::CONTROL)),
|
||||
)
|
||||
.await?;
|
||||
assert!(tui.clipboard.is_busy());
|
||||
assert_eq!(tui.clipboard.copied_text(PasteSource::Clipboard), selected);
|
||||
assert!(app.chat_widget.has_active_modal());
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
let buffer = crate::custom_terminal::test_support::last_rendered_buffer(&tui.terminal);
|
||||
|
||||
@@ -6,6 +6,7 @@ use crate::app::owned_transcript::tests::attach_thread;
|
||||
use crate::app::test_support::enable_side_retention;
|
||||
use crate::app::test_support::side_frame;
|
||||
use crate::app::tests::make_test_app_with_channels;
|
||||
use crate::clipboard_copy::worker::PasteSource;
|
||||
use crate::history_cell::AgentMarkdownCell;
|
||||
use crate::keymap::KeymapContext;
|
||||
use codex_config::types::KeybindingSpec;
|
||||
@@ -322,7 +323,6 @@ async fn document_preview_scenario() -> Result<()> {
|
||||
Box::pin(app.handle_tui_event(&mut tui, &mut server, TuiEvent::Key(copy))).await?,
|
||||
AppRunControl::Continue
|
||||
));
|
||||
assert!(tui.clipboard.is_busy());
|
||||
let pane = app.sidebar_mut();
|
||||
let document = match pane.visible_content().unwrap() {
|
||||
sidebar::SidebarContent::Document(id) => id,
|
||||
@@ -339,16 +339,7 @@ async fn document_preview_scenario() -> Result<()> {
|
||||
sidebar::SidebarContent::Document(document),
|
||||
sidebar::PaneFocus::Main,
|
||||
);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
loop {
|
||||
if tui.clipboard.poll().is_some() {
|
||||
break;
|
||||
}
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("active copy completes");
|
||||
tui.clipboard.poll();
|
||||
tui.clipboard.advance(tui.frame_requester());
|
||||
assert!(tui.clipboard.is_busy(), "visible preview publishes PRIMARY");
|
||||
let pane = app.sidebar_mut();
|
||||
@@ -363,18 +354,12 @@ async fn document_preview_scenario() -> Result<()> {
|
||||
sidebar::SidebarContent::Chooser,
|
||||
sidebar::PaneFocus::Sidebar,
|
||||
);
|
||||
tokio::time::timeout(std::time::Duration::from_secs(5), async {
|
||||
while tui.clipboard.is_busy() {
|
||||
tui.clipboard.poll();
|
||||
tokio::task::yield_now().await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.expect("PRIMARY publication completes");
|
||||
tui.clipboard.poll();
|
||||
tui.clipboard.advance(tui.frame_requester());
|
||||
assert!(
|
||||
!tui.clipboard.is_busy(),
|
||||
"hidden preview must not publish PRIMARY"
|
||||
assert_eq!(tui.clipboard.copied_text(PasteSource::Clipboard), "Mi");
|
||||
assert_eq!(
|
||||
tui.clipboard.copied_text(PasteSource::Primary),
|
||||
"visible preview"
|
||||
);
|
||||
app.sidebar_mut().show(
|
||||
sidebar::SidebarContent::Document(document),
|
||||
|
||||
@@ -139,6 +139,7 @@ use crate::app_event::HistoryBatchEntryResponse;
|
||||
use crate::app_server_session::user_message_submission::ActiveTurnSteerRace;
|
||||
use crate::app_server_session::user_message_submission::active_turn_not_steerable_turn_error;
|
||||
use crate::app_server_session::user_message_submission::active_turn_steer_race;
|
||||
use crate::clipboard_copy::worker::PasteSource;
|
||||
use crate::test_support::boxed_future;
|
||||
use codex_app_server_protocol::ThreadItem;
|
||||
|
||||
@@ -5276,7 +5277,7 @@ async fn handle_start_side_seeds_navigation_before_thread_started() -> Result<()
|
||||
}
|
||||
assert!(parent.view.has_selection_range());
|
||||
keys!(KeyEvent::new(KeyCode::Insert, KeyModifiers::CONTROL));
|
||||
assert!(tui.clipboard.is_busy());
|
||||
assert_eq!(tui.clipboard.copied_text(PasteSource::Clipboard), "Co");
|
||||
assert_eq!(app.current_displayed_thread_id(), Some(side_thread_id));
|
||||
|
||||
// Open a sibling from the chooser, then revisit each retained conversation.
|
||||
|
||||
@@ -4,6 +4,7 @@ use super::*;
|
||||
use crate::app::owned_transcript::tests::attach_thread;
|
||||
use crate::app::owned_transcript::tests::buffer_text;
|
||||
use crate::app::owned_transcript::tests::user_cell;
|
||||
use crate::clipboard_copy::worker::PasteSource;
|
||||
use codex_config::types::CopyOnSelect;
|
||||
use crossterm::event::MouseButton::Left;
|
||||
use crossterm::event::MouseEvent;
|
||||
@@ -314,6 +315,7 @@ async fn turn_tip_placements_and_completion_barrier() -> Result<()> {
|
||||
)?);
|
||||
app.render_owned_transcript(&mut tui, size)?;
|
||||
}
|
||||
assert_eq!(tui.clipboard.copied_text(PasteSource::Clipboard), "/help");
|
||||
let mut selection = app.chat_widget.rendered_selection.borrow_mut();
|
||||
let crate::rendered_selection::RenderedSelection { view, cells, .. } =
|
||||
&mut *selection;
|
||||
@@ -529,6 +531,7 @@ async fn working_tip_stays_put_through_mouse_selection() -> Result<()> {
|
||||
let crate::rendered_selection::RenderedSelection { view, cells, .. } = &mut *selection;
|
||||
assert_eq!(view.selected_text(cells), Some("/help".into()));
|
||||
}
|
||||
assert_eq!(tui.clipboard.copied_text(PasteSource::Clipboard), "/help");
|
||||
insta::assert_snapshot!(
|
||||
"working_tip_selected",
|
||||
crate::chatwidget::tests::helpers::normalize_working_snapshot(buffer_text(
|
||||
|
||||
@@ -90,6 +90,16 @@ pub(crate) enum CopyDestination {
|
||||
ClipboardAndPrimary(Arc<str>),
|
||||
}
|
||||
|
||||
impl CopyDestination {
|
||||
fn primary_text<'a>(&'a self, text: &'a Arc<str>) -> Option<&'a Arc<str>> {
|
||||
match self {
|
||||
Self::Clipboard => None,
|
||||
Self::Primary => Some(text),
|
||||
Self::ClipboardAndPrimary(plain_text) => Some(plain_text),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, PartialEq, Eq)]
|
||||
pub(crate) enum PasteSource {
|
||||
Clipboard,
|
||||
@@ -125,9 +135,34 @@ struct Response {
|
||||
terminal_sequence: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
enum Backend {
|
||||
#[default]
|
||||
NotStarted,
|
||||
Thread(mpsc::Sender<Request>),
|
||||
#[cfg(test)]
|
||||
InMemory(test_support::MemoryClipboard),
|
||||
}
|
||||
|
||||
impl Backend {
|
||||
fn send(&mut self, request: Request) -> Result<(), String> {
|
||||
match self {
|
||||
Self::NotStarted => Err("clipboard worker stopped".into()),
|
||||
Self::Thread(requests) => requests
|
||||
.send(request)
|
||||
.map_err(|_| "clipboard worker stopped".to_string()),
|
||||
#[cfg(test)]
|
||||
Self::InMemory(clipboard) => {
|
||||
clipboard.handle(request);
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
pub(crate) struct ClipboardWorker {
|
||||
requests: Option<mpsc::Sender<Request>>,
|
||||
backend: Backend,
|
||||
responses: Option<mpsc::Receiver<Response>>,
|
||||
pending: Option<(u64, Arc<CopySetup>)>,
|
||||
next_id: u64,
|
||||
@@ -170,11 +205,7 @@ impl ClipboardWorker {
|
||||
frames: FrameRequester,
|
||||
) -> (CopyResult, Arc<()>) {
|
||||
let owner = Arc::new(());
|
||||
let primary = match &destination {
|
||||
CopyDestination::Clipboard => None,
|
||||
CopyDestination::Primary => Some(Arc::clone(&text)),
|
||||
CopyDestination::ClipboardAndPrimary(plain_text) => Some(Arc::clone(plain_text)),
|
||||
};
|
||||
let primary = destination.primary_text(&text).cloned();
|
||||
self.primary = None;
|
||||
let scope = primary.as_ref().map(|_| Arc::downgrade(&owner));
|
||||
let result = self.copy_to(text, format, destination, frames, scope);
|
||||
@@ -206,16 +237,12 @@ impl ClipboardWorker {
|
||||
frames: frames.clone(),
|
||||
owner,
|
||||
});
|
||||
self.requests
|
||||
.as_ref()
|
||||
.ok_or("clipboard worker stopped")?
|
||||
.send(Request::Copy {
|
||||
text,
|
||||
format,
|
||||
destination,
|
||||
setup: Arc::clone(&setup),
|
||||
})
|
||||
.map_err(|_| "clipboard worker stopped".to_string())?;
|
||||
self.backend.send(Request::Copy {
|
||||
text,
|
||||
format,
|
||||
destination,
|
||||
setup: Arc::clone(&setup),
|
||||
})?;
|
||||
self.pending = Some((id, setup));
|
||||
// Retain the last completion while a newer request runs so a temporarily hidden
|
||||
// view can still finish its feedback. Consumers already match request IDs.
|
||||
@@ -225,15 +252,16 @@ impl ClipboardWorker {
|
||||
|
||||
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())
|
||||
self.backend.send(Request::WarmTextReader)
|
||||
}
|
||||
|
||||
fn ensure_started(&mut self, frames: FrameRequester) -> Result<(), String> {
|
||||
if self.requests.is_none() {
|
||||
#[cfg(test)]
|
||||
if let Backend::InMemory(clipboard) = &mut self.backend {
|
||||
clipboard.frames = frames;
|
||||
return Ok(());
|
||||
}
|
||||
if matches!(self.backend, Backend::NotStarted) {
|
||||
self.start(
|
||||
frames,
|
||||
|text, format, setup| {
|
||||
@@ -292,15 +320,11 @@ impl ClipboardWorker {
|
||||
.as_mut()
|
||||
.ok_or("no clipboard read pending")?;
|
||||
let (response, receiver) = mpsc::channel();
|
||||
self.requests
|
||||
.as_ref()
|
||||
.ok_or("clipboard worker stopped")?
|
||||
.send(Request::Read {
|
||||
source: read.source,
|
||||
deadline: read.deadline,
|
||||
response,
|
||||
})
|
||||
.map_err(|_| "clipboard worker stopped".to_string())?;
|
||||
self.backend.send(Request::Read {
|
||||
source: read.source,
|
||||
deadline: read.deadline,
|
||||
response,
|
||||
})?;
|
||||
read.response = Some(receiver);
|
||||
Ok(())
|
||||
}
|
||||
@@ -402,14 +426,7 @@ impl ClipboardWorker {
|
||||
destination,
|
||||
setup,
|
||||
} => {
|
||||
let plain_text = match &destination {
|
||||
CopyDestination::Clipboard => None,
|
||||
CopyDestination::Primary => Some(&text),
|
||||
CopyDestination::ClipboardAndPrimary(plain_text) => {
|
||||
Some(plain_text)
|
||||
}
|
||||
};
|
||||
let primary = plain_text.map(|text| {
|
||||
let primary = destination.primary_text(&text).map(|text| {
|
||||
super::primary::copy(text, || setup.begin_delivery())
|
||||
.map(|outcome| outcome.store(&mut primary_lease))
|
||||
});
|
||||
@@ -453,7 +470,7 @@ impl ClipboardWorker {
|
||||
drop(outgoing);
|
||||
})
|
||||
.map_err(|error| format!("could not start clipboard worker: {error}"))?;
|
||||
self.requests = Some(requests);
|
||||
self.backend = Backend::Thread(requests);
|
||||
self.responses = Some(responses);
|
||||
Ok(())
|
||||
}
|
||||
@@ -539,7 +556,7 @@ impl ClipboardWorker {
|
||||
|
||||
impl Drop for ClipboardWorker {
|
||||
fn drop(&mut self) {
|
||||
self.requests.take();
|
||||
self.backend = Backend::NotStarted;
|
||||
// A confirmed Linux copy needs time to hand ownership to the clipboard manager.
|
||||
// Keep this bounded: even dropping a native clipboard can stall on an X11 server.
|
||||
if let Some(responses) = &self.responses {
|
||||
@@ -554,6 +571,10 @@ impl Drop for ClipboardWorker {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "worker_test_support.rs"]
|
||||
mod test_support;
|
||||
|
||||
#[cfg(test)]
|
||||
#[path = "worker_tests.rs"]
|
||||
mod tests;
|
||||
|
||||
@@ -0,0 +1,85 @@
|
||||
//! Per-TUI clipboard storage. Requests take effect inline, while the UI still
|
||||
//! observes their completion through the worker's normal polling path.
|
||||
|
||||
use super::Backend;
|
||||
use super::ClipboardWorker;
|
||||
use super::CopyDestination;
|
||||
use super::CopyStatus;
|
||||
use super::FrameRequester;
|
||||
use super::PasteSource;
|
||||
use super::Request;
|
||||
use super::Response;
|
||||
use std::sync::Arc;
|
||||
use std::sync::mpsc;
|
||||
|
||||
pub(super) struct MemoryClipboard {
|
||||
clipboard: Arc<str>,
|
||||
primary: Arc<str>,
|
||||
responses: mpsc::Sender<Response>,
|
||||
pub(super) frames: FrameRequester,
|
||||
}
|
||||
|
||||
impl ClipboardWorker {
|
||||
pub(crate) fn in_memory(frames: FrameRequester) -> Self {
|
||||
let (sender, responses) = mpsc::channel();
|
||||
let mut worker = Self::default();
|
||||
worker.backend = Backend::InMemory(MemoryClipboard {
|
||||
clipboard: Arc::default(),
|
||||
primary: Arc::default(),
|
||||
responses: sender,
|
||||
frames,
|
||||
});
|
||||
worker.responses = Some(responses);
|
||||
worker
|
||||
}
|
||||
|
||||
pub(crate) fn copied_text(&self, source: PasteSource) -> &str {
|
||||
let Backend::InMemory(clipboard) = &self.backend else {
|
||||
panic!("expected an in-memory clipboard");
|
||||
};
|
||||
clipboard.text(source)
|
||||
}
|
||||
}
|
||||
|
||||
impl MemoryClipboard {
|
||||
fn text(&self, source: PasteSource) -> &str {
|
||||
match source {
|
||||
PasteSource::Clipboard => &self.clipboard,
|
||||
PasteSource::Primary => &self.primary,
|
||||
}
|
||||
}
|
||||
|
||||
pub(super) fn handle(&mut self, request: Request) {
|
||||
match request {
|
||||
Request::WarmTextReader => return,
|
||||
Request::Copy {
|
||||
text,
|
||||
destination,
|
||||
setup,
|
||||
..
|
||||
} => {
|
||||
let result = setup.begin_delivery().map(|()| {
|
||||
if let Some(primary) = destination.primary_text(&text) {
|
||||
self.primary = Arc::clone(primary);
|
||||
}
|
||||
if destination == CopyDestination::Primary {
|
||||
CopyStatus::Unconfirmed
|
||||
} else {
|
||||
self.clipboard = text;
|
||||
CopyStatus::Confirmed
|
||||
}
|
||||
});
|
||||
self.responses
|
||||
.send(Response {
|
||||
result,
|
||||
terminal_sequence: None,
|
||||
})
|
||||
.unwrap();
|
||||
}
|
||||
Request::Read {
|
||||
source, response, ..
|
||||
} => response.send(Ok(self.text(source).to_owned())).unwrap(),
|
||||
}
|
||||
self.frames.schedule_frame();
|
||||
}
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
//! Blocked backends leave UI work and teardown independent of clipboard progress.
|
||||
//! Clipboard delivery, cancellation, and isolation across TUI sessions.
|
||||
|
||||
use super::*;
|
||||
use crate::clipboard_copy::CopyOutcome;
|
||||
@@ -13,6 +13,40 @@ use crossterm::event::KeyModifiers;
|
||||
use pretty_assertions::assert_eq;
|
||||
use std::time::Duration;
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_tuis_paste_their_own_clipboard_and_primary_selections() {
|
||||
let mut first = crate::tui::test_support::make_test_tui().unwrap();
|
||||
let mut second = crate::tui::test_support::make_test_tui().unwrap();
|
||||
let selection = crate::tui::SelectionCopy::on_select(
|
||||
/*clipboard*/ true, /*primary*/ true, /*clear_selection*/ false,
|
||||
);
|
||||
for (tui, markdown, plain) in [
|
||||
(&mut first, "**café**\n", "café\n"),
|
||||
(&mut second, "**other**", "other"),
|
||||
] {
|
||||
let mut redraws = crate::tui::test_support::record_frame_requests(tui);
|
||||
let (result, _owner) = tui.copy_selection(markdown, CopyFormat::Markdown, selection, plain);
|
||||
assert_eq!(result, Ok(CopyStatus::Pending(1)));
|
||||
assert!(redraws.try_recv().expect("completion redraw") <= Instant::now());
|
||||
assert_eq!(tui.clipboard.poll(), Some(&(1, Ok(CopyStatus::Confirmed))));
|
||||
}
|
||||
for (source, expected) in [
|
||||
(PasteSource::Clipboard, "**café**\n"),
|
||||
(PasteSource::Primary, "café\n"),
|
||||
] {
|
||||
let _owner = first
|
||||
.clipboard
|
||||
.read_text(source, first.frame_requester())
|
||||
.unwrap()
|
||||
.unwrap();
|
||||
first.clipboard.poll();
|
||||
assert_eq!(
|
||||
first.clipboard.take_text_result(),
|
||||
Some(Ok(expected.into()))
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test(start_paused = true)]
|
||||
async fn cloud_config_completion_does_not_wait_for_the_clipboard() {
|
||||
use crate::app::test_support::ClipboardHandoff;
|
||||
@@ -285,7 +319,7 @@ fn drop_waits_for_response_channel_disconnect() {
|
||||
let (requests, _incoming) = mpsc::channel();
|
||||
let (outgoing, responses) = mpsc::sync_channel(/*bound*/ 0);
|
||||
let mut worker = ClipboardWorker::default();
|
||||
worker.requests = Some(requests);
|
||||
worker.backend = Backend::Thread(requests);
|
||||
worker.responses = Some(responses);
|
||||
worker
|
||||
.copy(
|
||||
@@ -620,7 +654,7 @@ async fn cloud_handoff_keeps_an_owned_clipboard_read_until_completion_or_input()
|
||||
app.local_settings.transcript_mode = crate::transcript_mode::TranscriptMode::Owned;
|
||||
tui.set_owned_screen(shortcut.is_none()).unwrap();
|
||||
let (requests, incoming) = mpsc::channel();
|
||||
tui.clipboard.requests = Some(requests);
|
||||
tui.clipboard.backend = Backend::Thread(requests);
|
||||
|
||||
let (events_tx, events_rx) = tokio::sync::mpsc::unbounded_channel();
|
||||
if shortcut.is_some() {
|
||||
@@ -692,7 +726,7 @@ fn latest_primary_is_published_before_read_but_does_not_preempt_explicit_copy()
|
||||
let (requests, incoming) = mpsc::channel();
|
||||
let (outgoing, responses) = mpsc::channel();
|
||||
let mut worker = ClipboardWorker::default();
|
||||
worker.requests = Some(requests);
|
||||
worker.backend = Backend::Thread(requests);
|
||||
worker.responses = Some(responses);
|
||||
let complete = || {
|
||||
outgoing
|
||||
@@ -776,7 +810,7 @@ fn cancelling_owners_after_poll_drops_deferred_work_without_releasing_worker_ear
|
||||
let (requests, incoming) = mpsc::channel();
|
||||
let (outgoing, responses) = mpsc::channel();
|
||||
let mut worker = ClipboardWorker::default();
|
||||
worker.requests = Some(requests);
|
||||
worker.backend = Backend::Thread(requests);
|
||||
worker.responses = Some(responses);
|
||||
worker
|
||||
.copy("active".into(), CopyFormat::PlainText, frames.clone())
|
||||
|
||||
@@ -7,6 +7,7 @@ use ratatui::layout::Size;
|
||||
|
||||
use super::Tui;
|
||||
use super::terminal_stderr::TerminalStderrGuard;
|
||||
use crate::clipboard_copy::worker::ClipboardWorker;
|
||||
use crate::custom_terminal::Terminal;
|
||||
|
||||
pub(crate) fn record_frame_requests(
|
||||
@@ -29,9 +30,11 @@ pub(crate) fn make_test_tui_with_size(size: Size) -> io::Result<Tui> {
|
||||
Position { x: 0, y: 0 },
|
||||
);
|
||||
let stderr_guard = TerminalStderrGuard::install()?;
|
||||
Ok(Tui::new(
|
||||
let mut tui = Tui::new(
|
||||
terminal,
|
||||
/*enhanced_keys_supported*/ false,
|
||||
stderr_guard,
|
||||
))
|
||||
);
|
||||
tui.clipboard = ClipboardWorker::in_memory(tui.frame_requester());
|
||||
Ok(tui)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user