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
+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,