Clean up unused TUI image paste files on exit (#64382)

## Why

Pasting an image or an image file path could leave a temporary copy on disk
even if the image never reached the app server. Drafts still need those
copies during the session, and saved turns can reference them after exit.

## What changed

Track pasted-image copies for the lifetime of the TUI session, including
across backend switches and reconnects. Delete the remaining tracked copies
on exit. Preserve copies when a turn is admitted or when a lost response
leaves admission uncertain.

Check model support before writing a clipboard image for an ordinary
composer paste. In WSL, read PNG bytes from PowerShell's standard output
so the fallback uses the same cleanup path.

## Testing

Extend paste tests to verify that a copied image survives changes to the
source file and a change of event sender, and that cleanup removes the
copy while preserving the source. Verify that queueing a submission still
leaves the copy eligible for cleanup.

GitOrigin-RevId: 36d51af242901306be0ff319949d26a01ca71200
This commit is contained in:
Eric Traut
2026-11-27 20:36:59 +00:00
committed by copyberry
parent 045a11fe2c
commit e2e7dabd45
13 changed files with 155 additions and 126 deletions
+3 -1
View File
@@ -520,7 +520,9 @@ impl App {
self.agents_overview.pending_usage = None;
self.reset_agents_overview_usage_for_backend_switch();
self.agents_overview.usage_disabled = false;
self.app_event_tx = AppEventSender::new(self.app_event_tx.app_event_tx.clone());
self.app_event_tx = self
.app_event_tx
.new_scope(self.app_event_tx.app_event_tx.clone());
self.app_server_backend_id = Some(destination.backend_id());
self.app_server_target = target;
self.refresh_transcript_document_links();
+1 -1
View File
@@ -457,7 +457,7 @@ impl App {
// Old request handles stay attached to the dead connection. Rotating the event channel
// prevents their late completions from submitting follow-up operations on the new one.
let (tx, rx) = mpsc::unbounded_channel();
self.app_event_tx = AppEventSender::new(tx);
self.app_event_tx = self.app_event_tx.new_scope(tx);
self.app_server_backend_id = Some(session.backend_id());
*app_event_rx = rx;
self.pending_thread_switch_resets = 0;
+2
View File
@@ -2056,6 +2056,8 @@ See the Codex keymap documentation for supported actions and examples."
{
tracing::warn!(error = %err, "failed to finish background server restart during exit");
}
// Background callbacks can retain event senders after the input loop exits.
app.app_event_tx.pasted_images.clear();
// Keep the alternate screen active until the outer guard restores both keyboard stacks.
let exit_reason = match exit_reason_result {
Ok(exit_reason) => {
@@ -82,6 +82,19 @@ pub(super) async fn try_submit_user_turn(
start_settings,
)
.await;
// A lost response can still mean the server accepted the paths. Only leave
// copies registered for cleanup when we know the turn was not admitted.
if !matches!(
&result,
Err(UserMessageSubmissionFailure::Preflight(_) | UserMessageSubmissionFailure::Rejected(_))
| Ok((UserMessageAdmission::Queued(_), _))
) {
for item in items {
if let codex_app_server_protocol::UserInput::LocalImage { path, .. } = item {
app.app_event_tx.pasted_images.keep(path);
}
}
}
if active != original_active
&& let Some(channel) = app.thread_event_channels.get(&thread_id)
{
+11
View File
@@ -25,6 +25,7 @@ use crate::session_log;
#[derive(Clone, Debug)]
pub(crate) struct AppEventSender {
pub app_event_tx: UnboundedSender<AppEvent>,
pub(crate) pasted_images: Arc<crate::clipboard_paste::PastedImages>,
pub(crate) voice_only: Arc<AtomicBool>,
}
@@ -33,6 +34,16 @@ impl AppEventSender {
Self {
app_event_tx,
voice_only: Arc::default(),
pasted_images: Arc::default(),
}
}
/// Reset callback routing without invalidating drafts from the same TUI session.
pub(crate) fn new_scope(&self, app_event_tx: UnboundedSender<AppEvent>) -> Self {
Self {
app_event_tx,
voice_only: Arc::default(),
pasted_images: self.pasted_images.clone(),
}
}
@@ -15,7 +15,7 @@ use crate::clipboard_paste::normalize_pasted_path;
use crate::clipboard_paste::pasted_image_format;
impl ChatComposer {
fn copy_pasted_image_path(pasted: &str) -> std::io::Result<Option<PathBuf>> {
fn copy_pasted_image_path(&self, pasted: &str) -> std::io::Result<Option<PathBuf>> {
use std::io::Seek;
#[cfg(unix)]
use std::os::unix::fs::OpenOptionsExt;
@@ -60,7 +60,10 @@ impl ChatComposer {
return Err(std::io::Error::other("image exceeds the 1 GiB input limit"));
}
file.rewind()?;
crate::clipboard_paste::persist_pasted_image(file, &suffix).map(Some)
self.app_event_tx
.pasted_images
.copy(file, &suffix)
.map(Some)
}
Err(err) => {
tracing::trace!("ERR: {err}");
@@ -300,7 +303,7 @@ impl ChatComposer {
let image = if (2..=LARGE_PASTE_CHAR_THRESHOLD).contains(&char_count)
&& self.image_paste_enabled()
{
match Self::copy_pasted_image_path(&pasted) {
match self.copy_pasted_image_path(&pasted) {
Ok(image) => image,
Err(error) => {
self.draft.paste_burst.clear_after_explicit_paste();
@@ -222,9 +222,16 @@ fn pasting_filepath_attaches_image() {
panic!("expected one image attachment");
};
let expected = std::fs::read(&tmp_path).unwrap();
std::fs::remove_file(&tmp_path).unwrap();
std::fs::write(&tmp_path, b"changed").unwrap();
assert_eq!(std::fs::read(attachment).unwrap(), expected);
std::fs::remove_file(attachment).unwrap();
let next = composer
.app_event_tx
.new_scope(composer.app_event_tx.app_event_tx.clone());
drop(composer);
assert_eq!(std::fs::read(attachment).unwrap(), expected);
next.pasted_images.clear();
assert!(!attachment.exists());
assert_eq!(std::fs::read(tmp_path).unwrap(), b"changed");
}
#[cfg(unix)]
-1
View File
@@ -221,7 +221,6 @@ use crate::bottom_pane::SelectionItem;
use crate::bottom_pane::SelectionViewParams;
use crate::bottom_pane::custom_prompt_view::CustomPromptView;
use crate::bottom_pane::popup_consts::standard_popup_hint_line;
use crate::clipboard_paste::paste_image_to_temp_png;
use crate::collaboration_modes;
use crate::diff_render::display_path_for;
use crate::exec_cell::ExecCell;
+5 -4
View File
@@ -64,7 +64,9 @@ impl ChatWidget {
context: ClipboardPasteContext,
text_fallback: Option<KeyCode>,
) -> Result<(), PasteImageError> {
let result = paste_image_to_temp_png();
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()
@@ -75,15 +77,14 @@ impl ChatWidget {
// Settle typing before capturing the asynchronous text target.
self.bottom_pane.prepare_composer_clipboard_paste();
}
let (path, info) = result?;
let (png, info) = result?;
tracing::debug!(
"pasted image size={}x{} format={}",
info.width,
info.height,
info.encoded_format.label()
);
self.attach_image(path, context);
Ok(())
self.attach_clipboard_image(&png, context)
}
pub(crate) fn show_paste_pending(&mut self) {
+1 -1
View File
@@ -36,7 +36,7 @@ impl ChatWidget {
session_telemetry,
} = common;
// Keep asynchronous widget callbacks scoped separately from the app and other widgets.
let app_event_tx = AppEventSender::new(app_event_tx.app_event_tx);
let app_event_tx = app_event_tx.new_scope(app_event_tx.app_event_tx.clone());
let model = model.filter(|m| !m.trim().is_empty());
let mut config = config;
config.model = model.clone();
+17 -2
View File
@@ -6,6 +6,7 @@ use crate::activation_key_guard::ActivationKeySuppression;
use crate::bottom_pane::BottomPaneView;
use crate::clipboard_copy::CopyStatus;
use crate::clipboard_copy::worker::CopyResult;
use crate::clipboard_paste::PasteImageError;
/// An input action the app must finish before processing the next key.
#[derive(Debug)]
@@ -440,14 +441,28 @@ impl ChatWidget {
///
/// Ordinary paste still checks the active model. Handoff only retains the attachment locally;
/// submission validates the destination model and backend before admission.
pub(crate) fn attach_image(&mut self, path: PathBuf, context: ClipboardPasteContext) {
pub(super) fn attach_clipboard_image(
&mut self,
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();
return;
return Ok(());
}
let path = self
.app_event_tx
.pasted_images
.copy(png, ".png")
.map_err(|err| PasteImageError::IoError(err.to_string()))?;
self.attach_image(path, context);
Ok(())
}
pub(crate) fn attach_image(&mut self, path: PathBuf, context: ClipboardPasteContext) {
tracing::info!("attach_image path={path:?}");
if context == ClipboardPasteContext::DraftHandoff && !self.has_active_view() {
self.bottom_pane.settle_before_handoff_image();
@@ -540,6 +540,10 @@ async fn handoff_image_survives_model_rejection_and_submission_failure() {
}
set_test_model_catalog(&mut source, models);
source.sync_image_paste_enabled();
source
.attach_clipboard_image(b"image", crate::chatwidget::ClipboardPasteContext::Composer)
.unwrap();
assert!(source.composer_draft_snapshot().local_images.is_empty());
let path = PathBuf::from("image.png");
let action = source.handle_restricted_key(
KeyEvent::new(KeyCode::Char('v'), KeyModifiers::ALT),
@@ -633,8 +637,8 @@ async fn local_clipboard_image_does_not_turn_a_held_bang_into_a_shell_command()
let KeyEventAction::PasteImage { context, .. } = paste else {
panic!("expected a clipboard image request");
};
let image_path = PathBuf::from("image.png");
chat.attach_image(image_path.clone(), context);
chat.attach_clipboard_image(b"image", context).unwrap();
let image_path = chat.bottom_pane.composer_local_image_paths()[0].clone();
chat.handle_key_event(KeyCode::Enter.into());
let draft = chat.bottom_pane.composer_recovery_snapshot();
@@ -654,6 +658,10 @@ async fn local_clipboard_image_does_not_turn_a_held_bang_into_a_shell_command()
let Op::UserTurn { items, .. } = next_submit_op(&mut operations) else {
panic!("expected submitted user turn");
};
assert_eq!(std::fs::read(&image_path).unwrap(), b"image");
// Queueing the operation alone must not make the copy permanent.
chat.app_event_tx.pasted_images.clear();
assert!(!image_path.exists());
let placeholder = "[Image #1]";
assert_eq!(
items,
+77 -109
View File
@@ -6,27 +6,62 @@ pub(crate) mod text;
#[cfg(windows)]
mod windows;
use std::collections::HashMap;
use std::path::Path;
use std::path::PathBuf;
use std::sync::Mutex;
use tempfile::Builder;
pub(crate) const MAX_PASTED_IMAGE_BYTES: u64 = 1024 * 1024 * 1024;
pub(crate) fn persist_pasted_image(
source: impl std::io::Read,
suffix: &str,
) -> std::io::Result<PathBuf> {
let mut tmp = Builder::new()
.prefix("codex-clipboard-")
.suffix(suffix)
.tempfile()?;
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"));
/// Hold unsent copies for the TUI session, including drafts restored by path.
#[derive(Debug, Default)]
pub(crate) struct PastedImages(Mutex<HashMap<PathBuf, tempfile::TempPath>>);
impl PastedImages {
pub(crate) fn copy(
&self,
source: impl std::io::Read,
suffix: &str,
) -> std::io::Result<PathBuf> {
let mut tmp = Builder::new()
.prefix("codex-clipboard-")
.suffix(suffix)
.tempfile()?;
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();
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.insert(path.clone(), tmp.into_temp_path());
Ok(path)
}
pub(crate) fn clear(&self) {
self.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.clear();
}
// The app server and saved turns can still reference a submitted path after exit.
pub(crate) fn keep(&self, path: &Path) {
let copy = self
.0
.lock()
.unwrap_or_else(std::sync::PoisonError::into_inner)
.remove(path);
if let Some(copy) = copy
&& let Err(mut err) = copy.keep()
{
err.path.disable_cleanup(/*disable_cleanup*/ true);
tracing::warn!("Failed to persist submitted image: {}", err.error);
}
}
let (_, path) = tmp.keep().map_err(|error| error.error)?;
Ok(path)
}
#[derive(Debug, Clone)]
@@ -167,39 +202,11 @@ pub fn paste_image_as_png() -> Result<(Vec<u8>, PastedImageInfo), PasteImageErro
))
}
/// Convenience: write to a temp file and return its path + info.
#[cfg(not(target_os = "android"))]
pub fn paste_image_to_temp_png() -> Result<(PathBuf, PastedImageInfo), PasteImageError> {
// First attempt: read image from system clipboard via arboard (native paths or image data).
match paste_image_as_png() {
Ok((png, info)) => {
let path = persist_pasted_image(png.as_slice(), ".png")
.map_err(|e| PasteImageError::IoError(e.to_string()))?;
Ok((path, info))
}
Err(e) => {
#[cfg(target_os = "linux")]
{
try_wsl_clipboard_fallback(&e).or(Err(e))
}
#[cfg(not(target_os = "linux"))]
{
Err(e)
}
}
}
}
/// Attempt WSL fallback for clipboard image paste.
///
/// If clipboard is unavailable (common under WSL because arboard cannot access
/// the Windows clipboard), attempt a WSL fallback that calls PowerShell on the
/// Windows side to write the clipboard image to a temporary file, then return
/// the corresponding WSL path.
/// WSL can read the Windows clipboard even when arboard cannot.
#[cfg(target_os = "linux")]
fn try_wsl_clipboard_fallback(
error: &PasteImageError,
) -> Result<(PathBuf, PastedImageInfo), PasteImageError> {
pub(crate) fn try_wsl_clipboard_fallback(
error: PasteImageError,
) -> Result<(Vec<u8>, PastedImageInfo), PasteImageError> {
use PasteImageError::ClipboardUnavailable;
use PasteImageError::NoImage;
@@ -209,77 +216,38 @@ fn try_wsl_clipboard_fallback(
ClipboardUnavailable(_) | NoImage(_) | PasteImageError::ImageReadFailed(_)
)
{
return Err(error.clone());
return Err(error);
}
tracing::debug!("attempting Windows PowerShell clipboard fallback");
let Some(win_path) = try_dump_windows_clipboard_image() else {
return Err(error.clone());
};
tracing::debug!("powershell produced path: {}", win_path);
let Some(mapped_path) = convert_windows_path_to_wsl(&win_path) else {
return Err(error.clone());
};
let Ok((w, h)) = image::image_dimensions(&mapped_path) else {
return Err(error.clone());
};
// Return the mapped path directly without copying.
// The file will be read and base64-encoded during serialization.
Ok((
mapped_path,
PastedImageInfo {
width: w,
height: h,
encoded_format: EncodedImageFormat::Png,
},
))
}
/// Try to call a Windows PowerShell command (several common names) to save the
/// clipboard image to a temporary PNG and return the Windows path to that file.
/// Returns None if no command succeeded or no image was present.
#[cfg(target_os = "linux")]
fn try_dump_windows_clipboard_image() -> Option<String> {
// Powershell script: save image from clipboard to a temp png and print the path.
// Force UTF-8 output to avoid encoding issues between powershell.exe (UTF-16LE default)
// and pwsh (UTF-8 default).
let script = r#"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8; $img = Get-Clipboard -Format Image; if ($img -ne $null) { $p=[System.IO.Path]::GetTempFileName(); $p = [System.IO.Path]::ChangeExtension($p,'png'); $img.Save($p,[System.Drawing.Imaging.ImageFormat]::Png); Write-Output $p } else { exit 1 }"#;
// 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())"#;
for cmd in ["powershell.exe", "pwsh", "powershell"] {
match std::process::Command::new(cmd)
let Ok(output) = std::process::Command::new(cmd)
.args(["-NoProfile", "-Command", script])
.output()
{
// Executing PowerShell command
Ok(output) => {
if output.status.success() {
// Decode as UTF-8 (forced by the script above).
let win_path = String::from_utf8_lossy(&output.stdout).trim().to_string();
if !win_path.is_empty() {
tracing::debug!("{} saved clipboard image to {}", cmd, win_path);
return Some(win_path);
}
} else {
tracing::debug!("{} returned non-zero status", cmd);
}
}
Err(err) => {
tracing::debug!("{} not executable: {}", cmd, err);
}
else {
continue;
};
if !output.status.success() {
continue;
}
let reader = image::ImageReader::with_format(
std::io::Cursor::new(&output.stdout),
image::ImageFormat::Png,
);
if let Ok((width, height)) = reader.into_dimensions() {
return Ok((
output.stdout,
PastedImageInfo {
width,
height,
encoded_format: EncodedImageFormat::Png,
},
));
}
}
None
}
#[cfg(target_os = "android")]
pub fn paste_image_to_temp_png() -> Result<(PathBuf, PastedImageInfo), PasteImageError> {
// Keep error consistent with paste_image_as_png.
Err(PasteImageError::ClipboardUnavailable(
"clipboard image paste is unsupported on Android".into(),
))
Err(error)
}
/// Normalize pasted text for a single-line search query.