diff --git a/codex-rs/Cargo.lock b/codex-rs/Cargo.lock index 30b9c533f9..7f57c10c45 100644 --- a/codex-rs/Cargo.lock +++ b/codex-rs/Cargo.lock @@ -5505,6 +5505,7 @@ dependencies = [ "codex-utils-path", "codex-utils-path-uri", "codex-utils-plugins", + "codex-utils-process", "codex-utils-sandbox-summary", "codex-utils-sleep-inhibitor", "codex-utils-string", diff --git a/codex-rs/tui/Cargo.toml b/codex-rs/tui/Cargo.toml index c2db24728a..c79ea2a3df 100644 --- a/codex-rs/tui/Cargo.toml +++ b/codex-rs/tui/Cargo.toml @@ -80,6 +80,7 @@ codex-utils-home-dir = { workspace = true } codex-utils-oss = { workspace = true } codex-utils-path = { workspace = true } codex-utils-path-uri = { workspace = true } +codex-utils-process = { workspace = true } codex-utils-plugins = { workspace = true } codex-utils-sandbox-summary = { workspace = true } codex-utils-sleep-inhibitor = { workspace = true } diff --git a/codex-rs/tui/src/app/clipboard.rs b/codex-rs/tui/src/app/clipboard.rs index 911257de21..802d49ba3a 100644 --- a/codex-rs/tui/src/app/clipboard.rs +++ b/codex-rs/tui/src/app/clipboard.rs @@ -27,10 +27,13 @@ impl App { { return; } - // Finish paste before the next key, but never wait on the copy worker's lock. + // Do not read while the clipboard worker owns a copy or text paste. if tui.clipboard.is_busy() || self.pending_right_click_paste.is_some() { self.chat_widget .add_info_message("Clipboard busy; try again".into(), /*hint*/ None); + } else if crate::terminal_capabilities::needs_image_paste_worker() { + self.chat_widget + .start_image_paste(context, |frames| tui.clipboard.images.start(frames)); } else { match self.chat_widget.paste_image(context, text_fallback) { Ok(()) => {} @@ -56,6 +59,8 @@ impl App { } pub(super) fn finish_clipboard(&mut self, tui: &mut tui::Tui, event: &TuiEvent) { + self.chat_widget + .finish_image_paste(event, self.overlay.is_none()); let current = tui.is_owned_screen() && self.overlay.is_none(); if let Some(completion) = tui.clipboard.poll() { if let Some(characters) = self.chat_widget.finish_clipboard(completion, current) { diff --git a/codex-rs/tui/src/app/cloud_switch_wait.rs b/codex-rs/tui/src/app/cloud_switch_wait.rs index d8f5ec0c3a..1841efb1df 100644 --- a/codex-rs/tui/src/app/cloud_switch_wait.rs +++ b/codex-rs/tui/src/app/cloud_switch_wait.rs @@ -47,6 +47,8 @@ fn handle_cloud_switch_event( }; // Clipboard text is delivered on Draw after ordinary input invalidation and target checks. app.invalidate_right_click_paste(&event); + app.chat_widget + .finish_image_paste(&event, app.overlay.is_none()); if matches!(event, tui::TuiEvent::FocusLost | tui::TuiEvent::Resume) { for pane in app.sidebars.values_mut() { pane.cancel_hidden_document_primary(/*visible*/ false); @@ -175,12 +177,15 @@ async fn drain_cloud_switch_events( events: &mut (impl Stream + Unpin), progress: CloudSwitchProgress, ) -> ControlFlow<()> { - // The current draft owns paste keys and any clipboard text until adoption. + // Settle clipboard jobs that belong to the draft being carried into the next view. let settle_clipboard = matches!( progress, CloudSwitchProgress::Connecting(ClipboardHandoff::SettleBeforeNextView) ); - if settle_clipboard && app.pending_right_click_paste.is_some() { + if settle_clipboard + && (app.pending_right_click_paste.is_some() + || app.chat_widget.handoff_image_deadline().is_some()) + { tui.frame_requester().schedule_frame(); } loop { @@ -188,6 +193,7 @@ async fn drain_cloud_switch_events( app.pending_right_click_paste .as_ref() .and_then(|pending| tui.clipboard.text_read_deadline(&pending.request)) + .max(app.chat_widget.handoff_image_deadline()) } else { None }; @@ -225,7 +231,8 @@ pub(crate) async fn wait_for_cloud_switch( app.cancel_pending_key_chord(); show_cloud_switch_hint(app, progress); draw_cloud_switch(app, tui); - if app.pending_right_click_paste.is_some() { + if app.pending_right_click_paste.is_some() || app.chat_widget.handoff_image_deadline().is_some() + { // A completion frame can arrive between Cloud preparation phases. tui.frame_requester().schedule_frame(); } diff --git a/codex-rs/tui/src/app/session_lifecycle.rs b/codex-rs/tui/src/app/session_lifecycle.rs index 9d09827b3c..1f85001ce1 100644 --- a/codex-rs/tui/src/app/session_lifecycle.rs +++ b/codex-rs/tui/src/app/session_lifecycle.rs @@ -629,6 +629,7 @@ impl App { chat_widget.inherit_view_transition_key_guard(&mut self.chat_widget); chat_widget.fork_in_progress = self.chat_widget.fork_in_progress; self.pending_right_click_paste = None; + self.chat_widget.cancel_image_paste(); self.config_notification_test_pending = None; if !self.chat_widget.realtime_conversation_is_running() { self.retain_realtime_replay_state_before_replace(); diff --git a/codex-rs/tui/src/app/startup.rs b/codex-rs/tui/src/app/startup.rs index 7cd825e6ba..7895fe5806 100644 --- a/codex-rs/tui/src/app/startup.rs +++ b/codex-rs/tui/src/app/startup.rs @@ -2082,6 +2082,7 @@ See the Codex keymap documentation for supported actions and examples." }; // Let the pending terminal poll unwind while the app server shuts down. tui.pause_events(); + app.chat_widget.cancel_image_paste(); app.reconnect.cloud_resume = None; // Skip pending inference on exit. Give the fallback writes a bounded chance // to finish before closing the connections they use. diff --git a/codex-rs/tui/src/bottom_pane/chat_composer.rs b/codex-rs/tui/src/bottom_pane/chat_composer.rs index 89005aec82..160cd599d1 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer.rs @@ -14,6 +14,7 @@ //! search, or blocking view. The app reads clipboard text asynchronously and delivers a normal //! paste only while the same thread, draft, and cursor remain eligible. Intervening input or focus //! loss cancels the pending paste; a late clipboard result cannot overwrite newer input. +//! Pending WSL image pastes track disjoint edits, preserve selection and guard submission. //! The live voice strip renders after effort ignition, followed by the Astra sparkle when eligible. //! Owned transcripts keep persistent status below the composer and hints on a separate final row. //! Shortcut help opens a grouped action list above the composer and can switch to a keyboard. @@ -429,6 +430,7 @@ pub(super) mod composer_layout; mod draft_state; mod footer_state; mod history_search; +mod image_paste; mod inline_input; mod mouse; pub(crate) use mouse::ClipboardPasteTarget; @@ -816,6 +818,7 @@ impl ChatComposer { mode: FooterMode::ComposerEmpty, hint_override: None, flash: None, + image_submit_blocked: false, context_window_percent: None, context_window_used_tokens: None, context_window_hidden: false, @@ -1952,11 +1955,15 @@ impl ChatComposer { /// Insert an attachment placeholder and track it for the next submission. pub fn attach_image(&mut self, path: PathBuf) { + self.attach_image_at(path, self.draft.textarea.edit_target()); + } + + fn attach_image_at(&mut self, path: PathBuf, target: super::textarea::EditTarget) { self.dismiss_sparkle(); let started_edit = self.begin_direct_edit(); let elements_before = self.draft.textarea.element_payloads(); self.attachments - .attach_image(&mut self.draft.textarea, path); + .attach_image(&mut self.draft.textarea, path, target); self.reconcile_deleted_elements(elements_before); if started_edit { self.finish_edit(); @@ -3343,6 +3350,9 @@ impl ChatComposer { return (InputResult::None, true); } + if self.guard_pending_image() { + return (InputResult::None, true); + } if let Some(result) = self.handle_parent_owned_submission() { return result; } @@ -4014,6 +4024,11 @@ impl ChatComposer { if self.config.shell_commands_enabled && !self.draft.is_bash_mode && self.draft.textarea.text().starts_with('!') + && self + .draft + .textarea + .pending_image_target() + .is_none_or(|target| target.start() != 0) { self.draft.textarea.absorb_prompt_prefix(/*prefix_len*/ 1); self.draft.is_bash_mode = true; @@ -4065,6 +4080,7 @@ impl ChatComposer { if key_event.kind == KeyEventKind::Press && self.footer.hint_override.is_none() && self.toggle_shortcuts_keys.is_pressed(*key_event) + && self.draft.textarea.pending_image_target().is_none() && self.is_empty() && !self.is_in_paste_burst() { diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/attachment_state.rs b/codex-rs/tui/src/bottom_pane/chat_composer/attachment_state.rs index 7214e27546..9ed7247dea 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/attachment_state.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/attachment_state.rs @@ -13,6 +13,7 @@ use ratatui::text::Line; use super::InputResult; use crate::bottom_pane::LocalImageAttachment; +use crate::bottom_pane::textarea::EditTarget; use crate::bottom_pane::textarea::TextArea; use codex_protocol::models::local_image_label_text; use codex_protocol::user_input::TextElement; @@ -77,10 +78,15 @@ impl AttachmentState { self.relabel_local_images(textarea); } - pub(super) fn attach_image(&mut self, textarea: &mut TextArea, path: PathBuf) { + pub(super) fn attach_image( + &mut self, + textarea: &mut TextArea, + path: PathBuf, + target: EditTarget, + ) { let image_number = self.remote_image_urls.len() + self.local_images.len() + 1; let placeholder = local_image_label_text(image_number); - textarea.insert_element(&placeholder); + textarea.insert_image_at(target, &placeholder); self.local_images .push(LocalImageAttachment { placeholder, path }); } diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs b/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs index 7fe7fc2571..46f1864c78 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/footer_state.rs @@ -413,6 +413,7 @@ pub(super) struct FooterState { pub(super) mode: FooterMode, pub(super) hint_override: Option>, pub(super) flash: Option, + pub(super) image_submit_blocked: bool, pub(super) context_window_percent: Option, pub(super) context_window_used_tokens: Option, pub(super) context_window_hidden: bool, diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/image_paste.rs b/codex-rs/tui/src/bottom_pane/chat_composer/image_paste.rs new file mode 100644 index 0000000000..2df4688475 --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/chat_composer/image_paste.rs @@ -0,0 +1,32 @@ +//! Reserve an image's original insertion point without blocking subsequent draft edits. +//! The hint and submit guard follow the reservation until delivery or cancellation. + +use super::*; + +impl ChatComposer { + pub(crate) fn reserve_image_paste(&mut self, cancel: tokio_util::sync::CancellationToken) { + self.draft.textarea.reserve_image_paste(cancel); + self.footer.image_submit_blocked = false; + } + + pub(crate) fn image_paste_is_current(&self) -> bool { + self.history_search.is_none() + && self.draft.textarea.vim_query().is_none() + && self.draft.textarea.pending_image_target().is_some() + } + + pub(super) fn guard_pending_image(&mut self) -> bool { + self.footer.image_submit_blocked = self.draft.textarea.pending_image_target().is_some(); + self.footer.image_submit_blocked + } + + pub(crate) fn finish_image_paste(&mut self, path: tempfile::TempPath) { + self.flush_pending_paste_burst(); + let Some(target) = self.draft.textarea.pending_image_target() else { + return; + }; + let path = self.app_event_tx.pasted_images.register(path); + self.attach_image_at(path, target); + self.sync_popups(); + } +} diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/passive_hints.rs b/codex-rs/tui/src/bottom_pane/chat_composer/passive_hints.rs index 64b6b3ec9d..e2d4a16d12 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/passive_hints.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/passive_hints.rs @@ -6,6 +6,7 @@ //! in interaction priority order, then paint the surviving labels in reading order. use super::*; +use crate::bottom_pane::PASTE_REVIEW_HINT; use crate::bottom_pane::footer::goal_status_indicator_line; use crate::bottom_pane::footer::mode_indicator_line; use crate::line_truncation::line_width; @@ -250,6 +251,16 @@ pub(super) fn hint_area(area: Rect) -> Rect { impl ChatComposer { pub(super) fn passive_hints(&self, options: ComposerRenderOptions<'_>) -> Option { + let mut hints = Hints::default(); + if self.image_paste_is_current() && !options.footer.is_some_and(|f| f.is_interactive) { + let reminder = self + .footer + .image_submit_blocked + .then_some(PASTE_REVIEW_HINT); + let forms = reminder.into_iter().chain(["Paste pending."]); + hints.add(Action, forms.map(|text| text.dim().into())); + return Some(hints); + } let mode = self.footer_mode(); if options.footer.is_some() || self.custom_footer_height().is_some() @@ -260,7 +271,6 @@ impl ChatComposer { { return None; } - let mut hints = Hints::default(); hints.add(Shell, self.shell_mode_footer_line()); hints.add(Vim, self.vim_mode_indicator_span().map(Line::from)); let can_navigate = self.has_focus && self.draft.input_enabled && !self.popup_active(); diff --git a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs index 317ba3bbbe..404ff14f5e 100644 --- a/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs +++ b/codex-rs/tui/src/bottom_pane/chat_composer/slash_input.rs @@ -390,6 +390,9 @@ impl ChatComposer { .. } => { if let Some(sel) = popup.selected_item() { + if self.guard_pending_image() { + return (InputResult::None, true); + } if self.blocks_direct_input && mode == SlashPopupInputMode::Normal { let command_is_allowed = match &sel { CommandItem::Builtin(cmd) => { diff --git a/codex-rs/tui/src/bottom_pane/mod.rs b/codex-rs/tui/src/bottom_pane/mod.rs index 6da8e83df1..abb18d73e3 100644 --- a/codex-rs/tui/src/bottom_pane/mod.rs +++ b/codex-rs/tui/src/bottom_pane/mod.rs @@ -254,6 +254,8 @@ pub(crate) use selection_tabs::SelectionTab; /// Keeping a single value ensures Ctrl+C and Ctrl+D behave identically. pub(crate) const QUIT_SHORTCUT_TIMEOUT: Duration = Duration::from_secs(1); +pub(crate) const PASTE_REVIEW_HINT: &str = "Paste pending. Review the draft before sending."; + const PROMPT_TYPING_IDLE_DELAY: Duration = Duration::from_secs(1); /// Whether Ctrl+C/Ctrl+D require a second press to quit. @@ -2444,6 +2446,19 @@ impl BottomPane { } } + pub(crate) fn reserve_image_paste(&mut self, cancel: tokio_util::sync::CancellationToken) { + self.prepare_composer_clipboard_paste(); + self.composer.reserve_image_paste(cancel); + } + + pub(crate) fn image_paste_is_current(&self) -> bool { + !self.has_active_view() && self.composer.image_paste_is_current() + } + + pub(crate) fn finish_image_paste(&mut self, path: tempfile::TempPath) { + self.composer.finish_image_paste(path); + } + pub(crate) fn is_in_paste_burst(&self) -> bool { self.view_stack .last() diff --git a/codex-rs/tui/src/bottom_pane/textarea.rs b/codex-rs/tui/src/bottom_pane/textarea.rs index 361fc74358..d910c7bc56 100644 --- a/codex-rs/tui/src/bottom_pane/textarea.rs +++ b/codex-rs/tui/src/bottom_pane/textarea.rs @@ -1,5 +1,7 @@ //! The textarea owns editable composer text, placeholder elements, cursor/wrap state, and a //! single-entry kill buffer, including atomic ranges; rich payloads remain composer-owned. +//! A pending image reservation follows nonoverlapping edits with left affinity at its boundary; +//! overlapping edits and whole-buffer replacements invalidate it. //! Single-line inputs ignore line breaks and scroll horizontally. //! //! Whole-buffer replacement APIs intentionally rebuild only the visible draft state. They clear @@ -56,6 +58,7 @@ use unicode_segmentation::UnicodeSegmentation; mod editing; mod hyperlinks; mod mouse; +mod paste_anchor; pub(in crate::bottom_pane) mod register; mod single_line; mod vim; @@ -143,6 +146,7 @@ pub(crate) struct TextElementSnapshot { /// will appear to restore stale text from the user's perspective. #[derive(Debug)] pub(crate) struct TextArea { + paste_anchor: Option, prefix_insertion_revision: u64, text: String, single_line: bool, @@ -216,6 +220,7 @@ impl TextArea { pub fn new() -> Self { let defaults = RuntimeKeymap::defaults(); Self { + paste_anchor: None, text: String::new(), prefix_insertion_revision: 0, single_line: false, @@ -278,6 +283,7 @@ impl TextArea { } fn set_text_inner(&mut self, text: &str, elements: Option<&[UserTextElement]>) { + self.paste_anchor = None; let filtered = self.filter_line_breaks(text); let text = filtered.as_ref(); self.mouse_selection = None; @@ -486,6 +492,7 @@ impl TextArea { if pos == 0 && !text.is_empty() { self.prefix_insertion_revision = self.prefix_insertion_revision.wrapping_add(1); } + self.edit_paste_anchor(pos..pos, text.len()); self.text.insert_str(pos, text); self.wrap_cache.replace(None); if pos <= self.cursor_pos { @@ -523,6 +530,7 @@ impl TextArea { if start == 0 && !text.is_empty() { self.prefix_insertion_revision = self.prefix_insertion_revision.wrapping_add(1); } + self.edit_paste_anchor(range.clone(), text.len()); self.text.replace_range(range, text); self.wrap_cache.replace(None); self.preferred_col = None; @@ -1762,7 +1770,8 @@ impl TextArea { let inserted_len = new.len(); let diff = inserted_len as isize - removed_len as isize; - self.mouse_selection = None; + self.shift_selection_origin(end, diff); + self.edit_paste_anchor(range.clone(), new.len()); self.text.replace_range(range, new); self.wrap_cache.replace(None); self.preferred_col = None; diff --git a/codex-rs/tui/src/bottom_pane/textarea/editing.rs b/codex-rs/tui/src/bottom_pane/textarea/editing.rs index 6418c3f289..72b5402eba 100644 --- a/codex-rs/tui/src/bottom_pane/textarea/editing.rs +++ b/codex-rs/tui/src/bottom_pane/textarea/editing.rs @@ -9,7 +9,7 @@ use super::*; /// Vim Replace without a selection computes its overwrite span as it inserts each grapheme. #[derive(Debug, PartialEq, Eq)] pub(crate) struct EditTarget { - range: Range, + pub(super) range: Range, } impl EditTarget { diff --git a/codex-rs/tui/src/bottom_pane/textarea/editing_tests.rs b/codex-rs/tui/src/bottom_pane/textarea/editing_tests.rs index 8df7f7234d..163041975a 100644 --- a/codex-rs/tui/src/bottom_pane/textarea/editing_tests.rs +++ b/codex-rs/tui/src/bottom_pane/textarea/editing_tests.rs @@ -3,12 +3,37 @@ use crossterm::event::MouseButton; use crossterm::event::MouseEvent; use crossterm::event::MouseEventKind; use pretty_assertions::assert_eq; +use tokio_util::sync::CancellationToken; #[test] -fn target_replaces_forward_and_backward_selections() { - for (anchor, cursor) in [(1, 4), (4, 1)] { +fn editing_through_an_image_target_cancels_its_reservation() { + let cancel = CancellationToken::new(); + let mut textarea = TextArea::new(); + textarea.insert_str("before"); + textarea.set_cursor(/*pos*/ 3); + textarea.reserve_image_paste(cancel.clone()); + textarea.replace_range(1..4, "changed"); + assert!(cancel.is_cancelled()); + + // Completing a slash command turns the prefix around the anchor into one element. + let mut textarea = TextArea::new(); + textarea.insert_str("/pl"); + textarea.reserve_image_paste(CancellationToken::new()); + textarea.insert_str("an "); + textarea.add_element_range(0..5).unwrap(); + assert_eq!(textarea.pending_image_target(), None); + assert_eq!(textarea.text(), "/plan "); +} + +#[test] +fn target_replaces_forward_and_backward_selections_after_image_delivery() { + for (anchor, cursor, expected, prefix) in + [(1, 4, "a界[img]ef", "a"), (4, 1, "a[img]界ef", "a[img]")] + { let mut textarea = TextArea::new(); textarea.insert_str("abcdef"); + textarea.set_cursor(usize::from(cursor)); + textarea.reserve_image_paste(CancellationToken::new()); let area = Rect::new( /*x*/ 0, /*y*/ 0, /*width*/ 20, /*height*/ 2, ); @@ -28,10 +53,18 @@ fn target_replaces_forward_and_backward_selections() { state, )); } + textarea.insert_image_at(textarea.pending_image_target().unwrap(), "[i]"); + assert!(textarea.replace_element_payload("[i]", "[img]")); let target = textarea.edit_target(); - assert_eq!(&textarea.text()[..target.start()], "a"); + assert_eq!(&textarea.text()[..target.start()], prefix); + assert_eq!(textarea.cursor(), prefix.len() + usize::from(cursor - 1)); + textarea.reserve_image_paste(CancellationToken::new()); textarea.insert_str_at_target(target, "界"); - assert_eq!((textarea.text(), textarea.cursor()), ("a界ef", "a界".len())); + assert_eq!(textarea.pending_image_target(), None); + assert_eq!( + (textarea.text(), textarea.cursor()), + (expected, prefix.len() + "界".len()) + ); assert_eq!(textarea.mouse_selection_range(), None); } } diff --git a/codex-rs/tui/src/bottom_pane/textarea/mouse.rs b/codex-rs/tui/src/bottom_pane/textarea/mouse.rs index 4cbba8b006..b008735aa9 100644 --- a/codex-rs/tui/src/bottom_pane/textarea/mouse.rs +++ b/codex-rs/tui/src/bottom_pane/textarea/mouse.rs @@ -19,6 +19,18 @@ pub(super) struct MouseSelection { } impl TextArea { + // Relabeling an atomic element only moves endpoints on or beyond its trailing edge. + pub(super) fn shift_selection_origin(&mut self, from: usize, delta: isize) { + if let Some(selection) = &mut self.mouse_selection { + for pos in [&mut selection.origin.start, &mut selection.origin.end] { + if *pos >= from { + *pos = pos.saturating_add_signed(delta); + } + } + selection.pending_copy = None; + } + } + pub(in crate::bottom_pane) fn defer_copy(&mut self, id: u64) { if let Some(range) = self.mouse_selection_range() && let Some(selection) = &mut self.mouse_selection diff --git a/codex-rs/tui/src/bottom_pane/textarea/paste_anchor.rs b/codex-rs/tui/src/bottom_pane/textarea/paste_anchor.rs new file mode 100644 index 0000000000..3f6c63630d --- /dev/null +++ b/codex-rs/tui/src/bottom_pane/textarea/paste_anchor.rs @@ -0,0 +1,64 @@ +//! A pending image keeps its insertion boundary while later typing remains editable. +//! Edits through the reserved range cancel delivery. Disjoint selections follow their text. + +use super::*; +use tokio_util::sync::CancellationToken; + +#[derive(Debug)] +pub(super) struct PasteAnchor { + cancel: CancellationToken, + _cancel: tokio_util::sync::DropGuard, + range: Range, +} + +// An edit that starts at an empty anchor leaves it just before the edited text. +fn edit_offset(tracked: &Range, edit: &Range, inserted: usize) -> Option { + if tracked.end <= edit.start { + Some(0) + } else { + (edit.end <= tracked.start).then_some(inserted as isize - edit.len() as isize) + } +} + +impl TextArea { + /// Restore the newer caret and mouse gesture if delivery edits a disjoint range. + pub(crate) fn insert_image_at(&mut self, target: EditTarget, label: &str) { + let current = self.edit_target(); + let delta = + edit_offset(¤t.range, &target.range, label.len()).filter(|_| current != target); + let cursor = self.cursor_pos; + let selection = self.mouse_selection.take(); + self.insert_element_at_target(target, label); + if let Some(delta) = delta { + self.set_cursor(cursor.saturating_add_signed(delta)); + self.mouse_selection = selection; + self.shift_selection_origin(/*from*/ 0, delta); + } + } + + pub(crate) fn reserve_image_paste(&mut self, cancel: CancellationToken) { + self.paste_anchor = Some(PasteAnchor { + _cancel: cancel.clone().drop_guard(), + cancel, + range: self.edit_target().range, + }); + } + + pub(crate) fn pending_image_target(&self) -> Option { + let anchor = self.paste_anchor.as_ref()?; + let range = self.expand_range_to_element_boundaries(anchor.range.clone()); + (!anchor.cancel.is_cancelled() && range == anchor.range).then_some(EditTarget { range }) + } + + pub(super) fn edit_paste_anchor(&mut self, range: Range, inserted: usize) { + let Some(anchor) = &mut self.paste_anchor else { + return; + }; + if let Some(delta) = edit_offset(&anchor.range, &range, inserted) { + anchor.range = anchor.range.start.saturating_add_signed(delta) + ..anchor.range.end.saturating_add_signed(delta); + } else { + self.paste_anchor = None; + } + } +} diff --git a/codex-rs/tui/src/chatwidget.rs b/codex-rs/tui/src/chatwidget.rs index 25c1c5092e..c340f97a21 100644 --- a/codex-rs/tui/src/chatwidget.rs +++ b/codex-rs/tui/src/chatwidget.rs @@ -641,6 +641,7 @@ pub(crate) struct ChatWidget { pending_stream_consolidations: usize, /// Copy feedback is discarded with its originating conversation. pending_clipboard: Option, + pending_image_paste: Option, /// Legacy terminals report auto-repeat as new presses; suppress the burst after a slow paste. suppress_image_paste_until: Instant, copy_last_response_binding: Vec, diff --git a/codex-rs/tui/src/chatwidget/clipboard.rs b/codex-rs/tui/src/chatwidget/clipboard.rs index 8f8645f7e1..5cf5778bf0 100644 --- a/codex-rs/tui/src/chatwidget/clipboard.rs +++ b/codex-rs/tui/src/chatwidget/clipboard.rs @@ -4,6 +4,8 @@ use super::*; use crate::clipboard_copy::worker::CopyResult; use crate::clipboard_paste::PasteImageError; +use crate::clipboard_paste::image_job::ImageJob; +use crate::tui::TuiEvent; const IMAGE_PASTE_REPEAT_WINDOW: Duration = Duration::from_millis(/*millis*/ 250); @@ -22,7 +24,85 @@ pub(super) enum PendingCopy { Selection(u64), } +pub(super) struct PendingImagePaste { + job: ImageJob, + thread: Option, + context: ClipboardPasteContext, +} + impl ChatWidget { + pub(crate) fn cancel_image_paste(&mut self) { + if self.pending_image_paste.take().is_some() { + self.request_redraw(); + } + } + + pub(crate) fn start_image_paste( + &mut self, + context: ClipboardPasteContext, + read: impl FnOnce(FrameRequester) -> Result, + ) { + if self.pending_image_paste.is_some() + || self.has_active_view() + || !self.can_attach_clipboard_image(context) + { + return; + } + match read(self.frame_requester.clone()) { + Ok(job) => { + if context == ClipboardPasteContext::DraftHandoff { + self.bottom_pane.settle_before_handoff_image(); + } + self.bottom_pane.reserve_image_paste(job.cancel.clone()); + self.pending_image_paste = Some(PendingImagePaste { + job, + thread: self.thread_id, + context, + }); + self.request_redraw(); + } + Err(error) => self.add_error_message(format!("Failed to paste image: {error}")), + } + } + + pub(crate) fn finish_image_paste(&mut self, event: &TuiEvent, visible: bool) { + let Some(pending) = self.pending_image_paste.as_mut() else { + return; + }; + if !visible + || matches!(event, TuiEvent::FocusLost | TuiEvent::Resume) + || pending.thread != self.thread_id + || !self.bottom_pane.image_paste_is_current() + { + self.cancel_image_paste(); + return; + } + if !matches!(event, TuiEvent::Draw) { + return; + } + let Some(result) = pending.job.poll(&self.frame_requester) else { + return; + }; + let context = pending.context; + match result { + Ok(path) => { + if self.can_attach_clipboard_image(context) { + self.bottom_pane.finish_image_paste(path); + self.refresh_startup_recovery(); + } + } + Err(error) => self.add_error_message(format!("Failed to paste image: {error}")), + } + self.cancel_image_paste(); + } + + pub(crate) fn handoff_image_deadline(&self) -> Option { + self.pending_image_paste + .as_ref() + .filter(|paste| paste.context == ClipboardPasteContext::DraftHandoff) + .map(|paste| paste.job.deadline) + } + /// Recognize image paste shortcuts, including presses consumed by repeat suppression. pub(super) fn image_paste_key_action( &mut self, @@ -69,8 +149,6 @@ impl ChatWidget { text_fallback: Option, ) -> Result<(), PasteImageError> { let result = crate::clipboard_paste::paste_image_as_png(); - #[cfg(target_os = "linux")] - let result = result.or_else(crate::clipboard_paste::try_wsl_clipboard_fallback); self.suppress_image_paste_until = Instant::now() + IMAGE_PASTE_REPEAT_WINDOW; if context == ClipboardPasteContext::DraftHandoff && text_fallback.is_some() @@ -93,9 +171,7 @@ impl ChatWidget { pub(crate) fn show_paste_pending(&mut self) { self.bottom_pane.show_footer_flash( - "Paste pending. Review the draft before sending." - .dim() - .into(), + crate::bottom_pane::PASTE_REVIEW_HINT.dim().into(), Duration::from_secs(/*secs*/ 3), ); } @@ -165,3 +241,7 @@ impl ChatWidget { .finish_composer_copy(completion, composer_visible) } } + +#[cfg(test)] +#[path = "clipboard_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/chatwidget/clipboard_tests.rs b/codex-rs/tui/src/chatwidget/clipboard_tests.rs new file mode 100644 index 0000000000..25ae31fbac --- /dev/null +++ b/codex-rs/tui/src/chatwidget/clipboard_tests.rs @@ -0,0 +1,67 @@ +#![cfg(test)] + +use super::*; +use crate::chatwidget::tests::helpers::drain_insert_history; +use crate::chatwidget::tests::helpers::make_chatwidget_manual_with_sender; +use crate::chatwidget::tests::helpers::render_bottom_popup; +use crate::clipboard_paste::image_job::Progress; +use itertools::Itertools; +use pretty_assertions::assert_eq; + +fn pending(chat: &mut ChatWidget, deadline: Instant) -> std::sync::mpsc::Sender { + let (job, complete) = ImageJob::new(deadline); + chat.start_image_paste(ClipboardPasteContext::Composer, |_| Ok(job)); + complete +} + +#[tokio::test] +async fn image_job_typing_submission_timeout_and_stale_completion() { + let (mut chat, _sender, mut events, _ops) = make_chatwidget_manual_with_sender().await; + let hint = |chat: &ChatWidget| { + let view = render_bottom_popup(chat, /*width*/ 80); + view.lines().last().unwrap().trim().to_owned() + }; + chat.apply_external_edit("before ".into()); + let complete = pending(&mut chat, Instant::now() + Duration::from_secs(/*secs*/ 30)); + chat.handle_key_event(KeyCode::Char('x').into()); + chat.handle_key_event(KeyCode::Backspace.into()); + insta::assert_snapshot!(hint(&chat), @"Paste pending."); + chat.handle_key_event(KeyCode::Enter.into()); + insta::assert_snapshot!(hint(&chat), @"Paste pending. Review the draft before sending."); + chat.handle_paste("after".into()); + assert_eq!(chat.composer_text_with_pending(), "before after"); + let staged = tempfile::NamedTempFile::new().unwrap().into_temp_path(); + let accepted_path = staged.to_path_buf(); + complete.send(Progress::Writing(staged)).unwrap(); + complete.send(Progress::Done(Ok(()))).unwrap(); + chat.finish_image_paste(&TuiEvent::Draw, /*visible*/ true); + assert!(!hint(&chat).contains("Paste pending")); + assert_eq!(chat.composer_text_with_pending(), "before [Image #1]after"); + chat.handle_paste("!".into()); + assert_eq!(chat.composer_text_with_pending(), "before [Image #1]after!"); + + for event in [TuiEvent::FocusLost, TuiEvent::Draw] { + let complete = pending(&mut chat, Instant::now() + Duration::from_secs(/*secs*/ 30)); + assert_eq!(hint(&chat), "Paste pending."); + let staged = tempfile::NamedTempFile::new().unwrap().into_temp_path(); + let discarded_path = staged.to_path_buf(); + complete.send(Progress::Writing(staged)).unwrap(); + if matches!(event, TuiEvent::Draw) { + chat.apply_external_edit("new draft".into()); + } + chat.finish_image_paste(&event, /*visible*/ true); + assert!(complete.send(Progress::Done(Ok(()))).is_err()); + assert!(!hint(&chat).contains("Paste pending")); + assert!(!discarded_path.exists()); + } + + let _complete = pending(&mut chat, Instant::now()); + chat.finish_image_paste(&TuiEvent::Draw, /*visible*/ true); + assert!(!hint(&chat).contains("Paste pending")); + let messages = drain_insert_history(&mut events); + insta::assert_snapshot!(messages.iter().flatten().join("\n"), @"■ Failed to paste image: clipboard image read timed out"); + assert_eq!(chat.composer_text_with_pending(), "new draft"); + assert!(accepted_path.exists()); + chat.app_event_tx.pasted_images.clear(); + assert!(!accepted_path.exists()); +} diff --git a/codex-rs/tui/src/chatwidget/constructor.rs b/codex-rs/tui/src/chatwidget/constructor.rs index a1e571a254..2904c16506 100644 --- a/codex-rs/tui/src/chatwidget/constructor.rs +++ b/codex-rs/tui/src/chatwidget/constructor.rs @@ -209,6 +209,7 @@ impl ChatWidget { plan_stream_controller: None, pending_stream_consolidations: 0, pending_clipboard: None, + pending_image_paste: None, suppress_image_paste_until: Instant::now(), copy_last_response_binding, running_commands: HashMap::new(), diff --git a/codex-rs/tui/src/chatwidget/interaction.rs b/codex-rs/tui/src/chatwidget/interaction.rs index f638fa97b6..14372a1ef4 100644 --- a/codex-rs/tui/src/chatwidget/interaction.rs +++ b/codex-rs/tui/src/chatwidget/interaction.rs @@ -444,6 +444,17 @@ impl ChatWidget { KeyEventAction::None } + pub(super) fn can_attach_clipboard_image(&mut self, context: ClipboardPasteContext) -> bool { + if context == ClipboardPasteContext::DraftHandoff || self.current_model_supports_images() { + return true; + } + self.add_to_history(history_cell::new_warning_event( + self.image_inputs_not_supported_message(), + )); + self.request_redraw(); + false + } + /// Attach a local image, deferring model validation while the draft awaits its destination. /// /// Ordinary paste still checks the active model. Handoff only retains the attachment locally; @@ -453,11 +464,7 @@ impl ChatWidget { png: &[u8], context: ClipboardPasteContext, ) -> Result<(), PasteImageError> { - if context == ClipboardPasteContext::Composer && !self.current_model_supports_images() { - self.add_to_history(history_cell::new_warning_event( - self.image_inputs_not_supported_message(), - )); - self.request_redraw(); + if !self.can_attach_clipboard_image(context) { return Ok(()); } let path = self diff --git a/codex-rs/tui/src/chatwidget/tests/helpers.rs b/codex-rs/tui/src/chatwidget/tests/helpers.rs index 20cf621c77..c6d8267931 100644 --- a/codex-rs/tui/src/chatwidget/tests/helpers.rs +++ b/codex-rs/tui/src/chatwidget/tests/helpers.rs @@ -413,7 +413,7 @@ pub(crate) async fn make_chatwidget_manual_with_sender() -> ( (widget, app_event_tx, rx, op_rx) } -pub(super) fn drain_insert_history( +pub(in crate::chatwidget) fn drain_insert_history( rx: &mut tokio::sync::mpsc::UnboundedReceiver, ) -> Vec>> { drain_insert_history_with(rx, |cell| cell.display_lines(/*width*/ 80)) diff --git a/codex-rs/tui/src/clipboard_copy/worker.rs b/codex-rs/tui/src/clipboard_copy/worker.rs index e8d112b1a0..e139d27c1a 100644 --- a/codex-rs/tui/src/clipboard_copy/worker.rs +++ b/codex-rs/tui/src/clipboard_copy/worker.rs @@ -162,6 +162,7 @@ impl Backend { #[derive(Default)] pub(crate) struct ClipboardWorker { + pub(crate) images: crate::clipboard_paste::image_job::ImageWorker, backend: Backend, responses: Option>, pending: Option<(u64, Arc)>, @@ -174,7 +175,8 @@ pub(crate) struct ClipboardWorker { impl ClipboardWorker { pub(crate) fn is_busy(&self) -> bool { - self.pending.is_some() + self.images.is_reading() + || self.pending.is_some() || self .pending_read .as_ref() diff --git a/codex-rs/tui/src/clipboard_copy/wsl.rs b/codex-rs/tui/src/clipboard_copy/wsl.rs index 74bcf97c52..bce25d6a7f 100644 --- a/codex-rs/tui/src/clipboard_copy/wsl.rs +++ b/codex-rs/tui/src/clipboard_copy/wsl.rs @@ -140,12 +140,8 @@ fn command(executable: &std::path::Path, path: &std::ffi::OsStr) -> tokio::proce #[cfg(any(target_os = "linux", all(test, unix)))] fn shell_command(executable: &std::path::Path, path: &std::ffi::OsStr) -> tokio::process::Command { - // Spawn only the native shell here: directly spawning a Windows exe can block on WSL. - let mut command = tokio::process::Command::new("/bin/sh"); - command - .env("PATH", path) - .args(["-c", r#"exec "$@""#, "codex-wsl-copy"]) - .arg(executable); + let mut command = crate::command_output::wsl_command(executable); + command.env("PATH", path); command } @@ -245,20 +241,7 @@ async fn write_command( match result { Ok(status) => Ok(status), Err(error) => { - // Keep partially written stdin open until kill: PowerShell copies on EOF. - // If kill fails, still wait. Releasing the worker earlier could allow an old copy - // to overwrite a newer one. kill_on_drop alone does not guarantee reaping. - if let Some(pid) = child.id() { - // SAFETY: process_group(0) assigned the owned, unreaped child its own group. - // An installed adapter may have spawned its own writer. Stop the whole group. - unsafe { libc::killpg(pid as libc::pid_t, libc::SIGKILL) }; - } - let _ = child.start_kill(); - // wait() closes child.stdin itself, even if kill failed. Never give the - // writer EOF with partial input while waiting for it to stop. - let _stdin = child.stdin.take(); - child - .wait() + crate::command_output::stop_wsl_helper(&mut child) .await .map_err(|error| format!("failed to reap Windows clipboard writer: {error}"))?; Err(error) diff --git a/codex-rs/tui/src/clipboard_paste.rs b/codex-rs/tui/src/clipboard_paste.rs index 20486202ad..821abe0872 100644 --- a/codex-rs/tui/src/clipboard_paste.rs +++ b/codex-rs/tui/src/clipboard_paste.rs @@ -1,10 +1,14 @@ -//! Read and persist pasted images on the TUI host. Text reads run on the clipboard worker. +//! Read and persist pasted images on the TUI host. A pending image owns its temporary +//! file until the originating composer accepts it into the session's image registry. +pub(crate) mod image_job; #[cfg(target_os = "macos")] mod macos; pub(crate) mod text; #[cfg(windows)] mod windows; +#[cfg(target_os = "linux")] +mod wsl_image; use std::collections::HashMap; use std::path::Path; @@ -24,21 +28,36 @@ impl PastedImages { source: impl std::io::Read, suffix: &str, ) -> std::io::Result { - let mut tmp = Builder::new() + Ok(self.register(Self::stage(source, suffix, Ok)?)) + } + + // Hand off the cleanup guard before the possibly long write. A cancelled job drops it immediately. + fn stage( + source: impl std::io::Read, + suffix: &str, + own: impl FnOnce(tempfile::TempPath) -> std::io::Result, + ) -> std::io::Result { + let (mut tmp, path) = Builder::new() .prefix("codex-clipboard-") .suffix(suffix) - .tempfile()?; + .tempfile()? + .into_parts(); + let owned = own(path)?; if std::io::copy(&mut source.take(MAX_PASTED_IMAGE_BYTES + 1), &mut tmp)? > MAX_PASTED_IMAGE_BYTES { return Err(std::io::Error::other("image exceeds the 1 GiB input limit")); } - let path = tmp.path().to_path_buf(); + Ok(owned) + } + + pub(crate) fn register(&self, tmp: tempfile::TempPath) -> PathBuf { + let path = tmp.to_path_buf(); self.0 .lock() .unwrap_or_else(std::sync::PoisonError::into_inner) - .insert(path.clone(), tmp.into_temp_path()); - Ok(path) + .insert(path.clone(), tmp); + path } pub(crate) fn clear(&self) { @@ -71,6 +90,9 @@ pub enum PasteImageError { ImageReadFailed(String), EncodeFailed(String), IoError(String), + TimedOut, + #[cfg(target_os = "linux")] + Cancelled, } impl PasteImageError { @@ -87,11 +109,20 @@ impl std::fmt::Display for PasteImageError { PasteImageError::ImageReadFailed(msg) => write!(f, "could not read image: {msg}"), PasteImageError::EncodeFailed(msg) => write!(f, "could not encode image: {msg}"), PasteImageError::IoError(msg) => write!(f, "io error: {msg}"), + PasteImageError::TimedOut => write!(f, "clipboard image read timed out"), + #[cfg(target_os = "linux")] + PasteImageError::Cancelled => write!(f, "clipboard image paste cancelled"), } } } impl std::error::Error for PasteImageError {} +impl From for PasteImageError { + fn from(error: std::io::Error) -> Self { + Self::IoError(error.to_string()) + } +} + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum EncodedImageFormat { Png, @@ -204,8 +235,10 @@ pub fn paste_image_as_png() -> Result<(Vec, PastedImageInfo), PasteImageErro /// WSL can read the Windows clipboard even when arboard cannot. #[cfg(target_os = "linux")] -pub(crate) fn try_wsl_clipboard_fallback( +fn try_wsl_clipboard_fallback( error: PasteImageError, + deadline: std::time::Instant, + cancel: &tokio_util::sync::CancellationToken, ) -> Result<(Vec, PastedImageInfo), PasteImageError> { use PasteImageError::ClipboardUnavailable; use PasteImageError::NoImage; @@ -222,23 +255,26 @@ pub(crate) fn try_wsl_clipboard_fallback( tracing::debug!("attempting Windows PowerShell clipboard fallback"); // Return bytes so no Windows temp files are needed, even for a rejected paste. let script = r#"$img = Get-Clipboard -Format Image; if ($null -eq $img) { exit 1 }; $png = New-Object System.IO.MemoryStream; $img.Save($png, [System.Drawing.Imaging.ImageFormat]::Png); if ($png.Length -gt 1GB) { exit 1 }; $png.WriteTo([Console]::OpenStandardOutput())"#; + let runtime = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build()?; for cmd in ["powershell.exe", "pwsh", "powershell"] { - let Ok(output) = std::process::Command::new(cmd) - .args(["-NoProfile", "-Command", script]) - .output() + let mut command = crate::command_output::wsl_command(Path::new(cmd)); + command.args(["-NoProfile", "-Command", script]); + let Some(output) = runtime.block_on(wsl_image::read_command( + command, + deadline, + cancel, + MAX_PASTED_IMAGE_BYTES, + ))? else { continue; }; - if !output.status.success() { - continue; - } - let reader = image::ImageReader::with_format( - std::io::Cursor::new(&output.stdout), - image::ImageFormat::Png, - ); + let reader = + image::ImageReader::with_format(std::io::Cursor::new(&output), image::ImageFormat::Png); if let Ok((width, height)) = reader.into_dimensions() { return Ok(( - output.stdout, + output, PastedImageInfo { width, height, diff --git a/codex-rs/tui/src/clipboard_paste/image_job.rs b/codex-rs/tui/src/clipboard_paste/image_job.rs new file mode 100644 index 0000000000..3b0458ede2 --- /dev/null +++ b/codex-rs/tui/src/clipboard_paste/image_job.rs @@ -0,0 +1,132 @@ +//! One session-owned image reader survives chat switches, so an uninterruptible +//! native read cannot start a backlog. The draft owns cancellation and the file +//! to unlink, including while the worker still has it open for writing. + +use super::PasteImageError; +use super::PastedImages; +use crate::tui::FrameRequester; +use std::sync::mpsc; +use std::time::Duration; +use std::time::Instant; +use tempfile::TempPath; +use tokio_util::sync::CancellationToken; + +const TIMEOUT: Duration = Duration::from_secs(/*secs*/ 5); + +pub(crate) struct ImageJob { + pub(crate) cancel: CancellationToken, + pub(crate) deadline: Instant, + _cancel: tokio_util::sync::DropGuard, + response: mpsc::Receiver, + file: Option, +} + +pub(crate) enum Progress { + Writing(TempPath), + Done(Result<(), PasteImageError>), +} + +#[derive(Default)] +pub(crate) struct ImageWorker { + active: Option<(CancellationToken, mpsc::Receiver<()>)>, +} + +impl ImageWorker { + pub(crate) fn is_reading(&self) -> bool { + self.active.as_ref().is_some_and(|(cancel, done)| { + !cancel.is_cancelled() && matches!(done.try_recv(), Err(mpsc::TryRecvError::Empty)) + }) + } + + pub(crate) fn start(&mut self, frames: FrameRequester) -> Result { + if let Some((_, done)) = &self.active + && matches!(done.try_recv(), Err(mpsc::TryRecvError::Empty)) + { + return Err(PasteImageError::ClipboardUnavailable( + "image read is still busy".into(), + )); + } + let deadline = Instant::now() + TIMEOUT; + let (job, sender) = ImageJob::new(deadline); + let cancel = job.cancel.clone(); + let (running, done) = mpsc::channel(); + self.active = Some((cancel.clone(), done)); + frames.schedule_frame_in(TIMEOUT); + std::thread::Builder::new() + .name("clipboard-image".into()) + .spawn(move || { + let native = super::paste_image_as_png(); + #[cfg(target_os = "linux")] + let native = + native.or_else(|err| super::try_wsl_clipboard_fallback(err, deadline, &cancel)); + if cancel.is_cancelled() || Instant::now() >= deadline { + return; + } + let result = native.and_then(|(png, _)| { + PastedImages::stage(png.as_slice(), ".png", |path| { + sender + .send(Progress::Writing(path)) + .map_err(std::io::Error::other) + }) + .map_err(PasteImageError::from) + }); + drop(running); + if sender.send(Progress::Done(result)).is_ok() { + frames.schedule_frame(); + } + })?; + Ok(job) + } +} + +impl Drop for ImageWorker { + fn drop(&mut self) { + if let Some((cancel, done)) = &self.active { + cancel.cancel(); + // Allow subprocess cleanup on exit without waiting for a stuck native clipboard. + let _ = done.recv_timeout(Duration::from_millis(/*millis*/ 250)); + } + } +} + +impl ImageJob { + pub(crate) fn new(deadline: Instant) -> (Self, mpsc::Sender) { + let cancel = CancellationToken::new(); + let (sender, response) = mpsc::channel(); + let job = Self { + cancel: cancel.clone(), + deadline, + response, + file: None, + _cancel: cancel.drop_guard(), + }; + (job, sender) + } + + pub(crate) fn poll( + &mut self, + frames: &FrameRequester, + ) -> Option> { + if Instant::now() >= self.deadline { + return Some(Err(PasteImageError::TimedOut)); + } + frames.schedule_frame_in(self.deadline.saturating_duration_since(Instant::now())); + loop { + match self.response.try_recv() { + Ok(Progress::Writing(path)) => self.file = Some(path), + Ok(Progress::Done(Ok(()))) => { + return Some( + self.file + .take() + .ok_or_else(|| PasteImageError::IoError("missing image file".into())), + ); + } + Ok(Progress::Done(Err(err))) => return Some(Err(err)), + Err(mpsc::TryRecvError::Empty) => return None, + Err(mpsc::TryRecvError::Disconnected) => { + return Some(Err(PasteImageError::IoError("image worker stopped".into()))); + } + } + } + } +} diff --git a/codex-rs/tui/src/clipboard_paste/wsl_image.rs b/codex-rs/tui/src/clipboard_paste/wsl_image.rs new file mode 100644 index 0000000000..a310ddff90 --- /dev/null +++ b/codex-rs/tui/src/clipboard_paste/wsl_image.rs @@ -0,0 +1,57 @@ +//! Read raw PNG output using the caller's deadline for every PowerShell candidate. +//! Reap the helper on cancellation, including when its children inherit stdout. + +use super::PasteImageError; +use std::process::Stdio; +use std::time::Instant; +use tokio::io::AsyncReadExt; +use tokio_util::sync::CancellationToken; + +pub(super) async fn read_command( + mut command: tokio::process::Command, + deadline: Instant, + cancel: &CancellationToken, + limit: u64, +) -> Result>, PasteImageError> { + if Instant::now() >= deadline { + return Err(PasteImageError::TimedOut); + } + if cancel.is_cancelled() { + return Err(PasteImageError::Cancelled); + } + let mut child = command + .process_group(/*pgroup*/ 0) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::null()) + .kill_on_drop(/*kill_on_drop*/ true) + .spawn()?; + let read = async { + let mut stdout = child + .stdout + .take() + .ok_or_else(|| std::io::Error::other("missing clipboard pipe"))?; + let mut png = Vec::new(); + (&mut stdout).take(limit).read_to_end(&mut png).await?; + if png.len() as u64 == limit && stdout.read(&mut [0]).await? > 0 { + return Err(PasteImageError::IoError(format!( + "image exceeds the {limit}-byte input limit" + ))); + } + Ok(child.wait().await?.success().then_some(png)) + }; + let result = tokio::select! { + biased; + () = cancel.cancelled() => Err(PasteImageError::Cancelled), + () = tokio::time::sleep_until(deadline.into()) => Err(PasteImageError::TimedOut), + result = read => result, + }; + if result.is_err() { + crate::command_output::stop_wsl_helper(&mut child).await?; + } + result +} + +#[cfg(test)] +#[path = "wsl_image_tests.rs"] +mod tests; diff --git a/codex-rs/tui/src/clipboard_paste/wsl_image_tests.rs b/codex-rs/tui/src/clipboard_paste/wsl_image_tests.rs new file mode 100644 index 0000000000..d1701f1f66 --- /dev/null +++ b/codex-rs/tui/src/clipboard_paste/wsl_image_tests.rs @@ -0,0 +1,57 @@ +#![cfg(test)] + +use super::*; +use pretty_assertions::assert_eq; +use std::time::Duration; + +#[tokio::test] +async fn interrupted_reads_reap_the_provider() { + let dir = tempfile::tempdir().unwrap(); + for cause in [PasteImageError::TimedOut, PasteImageError::Cancelled] { + let path = dir.path().join(cause.to_string()); + let cancel = CancellationToken::new(); + let mut command = tokio::process::Command::new("/bin/sh"); + command + .args(["-c", r#"echo $$ > "$1"; exec sleep 30"#, "provider"]) + .arg(&path); + let deadline = Instant::now() + Duration::from_secs(/*secs*/ 2); + let observe = async { + loop { + if let Ok(text) = std::fs::read_to_string(&path) + && let Ok(pid) = text.trim().parse::() + { + if matches!(cause, PasteImageError::Cancelled) { + cancel.cancel(); + } + break pid; + } + tokio::task::yield_now().await; + } + }; + let (result, pid) = tokio::join!( + read_command(command, deadline, &cancel, /*limit*/ 1024), + observe + ); + assert_eq!(result.unwrap_err().to_string(), cause.to_string()); + assert!(!std::path::Path::new(&format!("/proc/{pid}")).exists()); + } +} + +#[tokio::test] +async fn binary_output_is_complete_or_rejected_at_the_limit() { + let file = tempfile::NamedTempFile::new().unwrap(); + let bytes = (0..=255_u8).cycle().take(16 * 1024).collect::>(); + std::fs::write(file.path(), &bytes).unwrap(); + let read = async |limit| { + let mut command = tokio::process::Command::new("cat"); + command.arg(file.path()); + let deadline = Instant::now() + Duration::from_secs(/*secs*/ 5); + read_command(command, deadline, &CancellationToken::new(), limit).await + }; + let size = bytes.len() as u64; + assert_eq!(read(size).await.unwrap(), Some(bytes)); + assert!(matches!( + read(size - 1).await, + Err(PasteImageError::IoError(_)) + )); +} diff --git a/codex-rs/tui/src/command_output.rs b/codex-rs/tui/src/command_output.rs index 5bedda5350..52321fddac 100644 --- a/codex-rs/tui/src/command_output.rs +++ b/codex-rs/tui/src/command_output.rs @@ -6,6 +6,31 @@ use std::process::Command; use std::time::Duration; use std::time::Instant; +/// Use a native shell so a stalled Windows executable launch happens in the child. +#[cfg(any(target_os = "linux", all(test, unix)))] +pub(crate) fn wsl_command(executable: &std::path::Path) -> tokio::process::Command { + let mut command = + tokio::process::Command::from(codex_utils_process::background_command("/bin/sh")); + command + .args(["-c", r#"exec "$@""#, "codex-wsl-clipboard"]) + .arg(executable); + command +} + +/// Stop a clipboard helper launched with process_group(0), including adapter children. +#[cfg(any(target_os = "linux", all(test, unix)))] +pub(crate) async fn stop_wsl_helper(child: &mut tokio::process::Child) -> std::io::Result<()> { + if let Some(pid) = child.id() { + // SAFETY: process_group(0) assigned the owned, unreaped child its own group. + unsafe { libc::killpg(pid as libc::pid_t, libc::SIGKILL) }; + } + let _ = child.start_kill(); + // wait() closes stdin. Hold the writer's pipe open so EOF cannot publish partial input. + let _stdin = child.stdin.take(); + child.wait().await?; + Ok(()) +} + const POLL_INTERVAL: Duration = Duration::from_millis(/*millis*/ 10); const MAX_OUTPUT_BYTES: u64 = 4096; diff --git a/codex-rs/tui/src/terminal_capabilities.rs b/codex-rs/tui/src/terminal_capabilities.rs index 21e1ad3b68..74e70d0f70 100644 --- a/codex-rs/tui/src/terminal_capabilities.rs +++ b/codex-rs/tui/src/terminal_capabilities.rs @@ -39,6 +39,11 @@ pub(crate) fn is_wsl_session() -> bool { false } +/// Image paste can invoke the Windows clipboard helper for this session. +pub(crate) fn needs_image_paste_worker() -> bool { + is_wsl_session() +} + pub(crate) fn is_ssh_session() -> bool { std::env::var_os("SSH_TTY").is_some() || std::env::var_os("SSH_CONNECTION").is_some() }