Skip to content

Commit 4cd104b

Browse files
committed
refactor: Store pasted images in memory as base64 data URLs
- Remove save_clipboard_image and cleanup_temp_images backend commands - Update FloatingPromptInput to store pasted images as data URLs in the prompt - Update ImagePreview component to handle both file paths and data URLs - Update extractImagePaths to properly handle quoted data URLs - Update handleRemoveImage to handle data URL removal This eliminates file system operations for pasted images and stores them directly in the prompt as base64 data URLs (e.g., @"data:image/png;base64,..."). Images are now fully self-contained within the session without creating temp files.
1 parent 2009601 commit 4cd104b

5 files changed

Lines changed: 52 additions & 145 deletions

File tree

src-tauri/src/commands/claude.rs

Lines changed: 0 additions & 97 deletions
Original file line numberDiff line numberDiff line change
@@ -922,104 +922,7 @@ pub async fn load_session_history(
922922
Ok(messages)
923923
}
924924

925-
/// Saves a clipboard image to a temporary location for a session
926-
///
927-
/// This command handles pasted images by saving them to a temp directory
928-
/// within the project structure, making them accessible for Claude.
929-
#[tauri::command]
930-
pub async fn save_clipboard_image(
931-
project_path: String,
932-
session_id: String,
933-
image_data: String, // Base64 encoded image data
934-
mime_type: String,
935-
) -> Result<String, String> {
936-
log::info!(
937-
"Saving clipboard image for session: {} in project: {}",
938-
session_id,
939-
project_path
940-
);
941925

942-
// Parse the base64 data (remove data URL prefix if present)
943-
let base64_data = if image_data.starts_with("data:") {
944-
image_data
945-
.split(',')
946-
.nth(1)
947-
.ok_or("Invalid data URL format")?
948-
} else {
949-
&image_data
950-
};
951-
952-
// Decode base64 to bytes
953-
use base64::Engine;
954-
let image_bytes = base64::engine::general_purpose::STANDARD
955-
.decode(base64_data)
956-
.map_err(|e| format!("Failed to decode base64 image: {}", e))?;
957-
958-
// Determine file extension from MIME type
959-
let extension = match mime_type.as_str() {
960-
"image/png" => "png",
961-
"image/jpeg" | "image/jpg" => "jpg",
962-
"image/gif" => "gif",
963-
"image/webp" => "webp",
964-
"image/svg+xml" => "svg",
965-
_ => "png", // Default to PNG
966-
};
967-
968-
// Create temp directory for the project if it doesn't exist
969-
let project_path_buf = PathBuf::from(&project_path);
970-
let temp_dir = project_path_buf.join(".claude_temp").join(&session_id);
971-
fs::create_dir_all(&temp_dir)
972-
.map_err(|e| format!("Failed to create temp directory: {}", e))?;
973-
974-
// Generate unique filename with timestamp
975-
let timestamp = SystemTime::now()
976-
.duration_since(SystemTime::UNIX_EPOCH)
977-
.unwrap_or_default()
978-
.as_millis();
979-
let filename = format!("pasted_image_{}.{}", timestamp, extension);
980-
let file_path = temp_dir.join(&filename);
981-
982-
// Write image to file
983-
fs::write(&file_path, image_bytes)
984-
.map_err(|e| format!("Failed to write image file: {}", e))?;
985-
986-
// Return the absolute path
987-
let absolute_path = file_path
988-
.canonicalize()
989-
.map_err(|e| format!("Failed to get absolute path: {}", e))?
990-
.to_string_lossy()
991-
.to_string();
992-
993-
log::info!("Saved clipboard image to: {}", absolute_path);
994-
Ok(absolute_path)
995-
}
996-
997-
/// Cleans up temporary images for a session
998-
///
999-
/// This command removes the temporary directory created for pasted images
1000-
/// when a session ends to avoid accumulating temporary files.
1001-
#[tauri::command]
1002-
pub async fn cleanup_temp_images(
1003-
project_path: String,
1004-
session_id: String,
1005-
) -> Result<(), String> {
1006-
log::info!(
1007-
"Cleaning up temp images for session: {} in project: {}",
1008-
session_id,
1009-
project_path
1010-
);
1011-
1012-
let project_path_buf = PathBuf::from(&project_path);
1013-
let temp_dir = project_path_buf.join(".claude_temp").join(&session_id);
1014-
1015-
if temp_dir.exists() {
1016-
fs::remove_dir_all(&temp_dir)
1017-
.map_err(|e| format!("Failed to remove temp directory: {}", e))?;
1018-
log::info!("Cleaned up temp directory: {}", temp_dir.display());
1019-
}
1020-
1021-
Ok(())
1022-
}
1023926

1024927
/// Execute a new interactive Claude Code session with streaming output
1025928
#[tauri::command]

src-tauri/src/main.rs

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -18,13 +18,13 @@ use commands::agents::{
1818
};
1919
use commands::claude::{
2020
cancel_claude_execution, check_auto_checkpoint, check_claude_version, cleanup_old_checkpoints,
21-
cleanup_temp_images, clear_checkpoint_manager, continue_claude_code, create_checkpoint, execute_claude_code,
21+
clear_checkpoint_manager, continue_claude_code, create_checkpoint, execute_claude_code,
2222
find_claude_md_files, fork_from_checkpoint, get_checkpoint_diff, get_checkpoint_settings,
2323
get_checkpoint_state_stats, get_claude_session_output, get_claude_settings, get_project_sessions,
2424
get_recently_modified_files, get_session_timeline, get_system_prompt, list_checkpoints,
2525
list_directory_contents, list_projects, list_running_claude_sessions, load_session_history,
2626
open_new_session, read_claude_md_file, restore_checkpoint, resume_claude_code,
27-
save_claude_md_file, save_claude_settings, save_clipboard_image, save_system_prompt, search_files,
27+
save_claude_md_file, save_claude_settings, save_system_prompt, search_files,
2828
track_checkpoint_message, track_session_messages, update_checkpoint_settings,
2929
get_hooks_config, update_hooks_config, validate_hook_command,
3030
ClaudeProcessState,
@@ -101,8 +101,6 @@ fn main() {
101101
find_claude_md_files,
102102
read_claude_md_file,
103103
save_claude_md_file,
104-
save_clipboard_image,
105-
cleanup_temp_images,
106104
load_session_history,
107105
execute_claude_code,
108106
continue_claude_code,

src/components/ClaudeCodeSession.tsx

Lines changed: 0 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,6 @@ import { api, type Session } from "@/lib/api";
2020
import { cn } from "@/lib/utils";
2121
import { open } from "@tauri-apps/plugin-dialog";
2222
import { listen, type UnlistenFn } from "@tauri-apps/api/event";
23-
import { invoke } from "@tauri-apps/api/core";
2423
import { StreamMessage } from "./StreamMessage";
2524
import { FloatingPromptInput, type FloatingPromptInputRef } from "./FloatingPromptInput";
2625
import { ErrorBoundary } from "./ErrorBoundary";
@@ -828,16 +827,6 @@ export const ClaudeCodeSession: React.FC<ClaudeCodeSessionProps> = ({
828827
api.clearCheckpointManager(effectiveSession.id).catch(err => {
829828
console.error("Failed to clear checkpoint manager:", err);
830829
});
831-
832-
// Clean up temporary images
833-
if (projectPath) {
834-
invoke('cleanup_temp_images', {
835-
projectPath,
836-
sessionId: effectiveSession.id
837-
}).catch((err: any) => {
838-
console.error("Failed to cleanup temp images:", err);
839-
});
840-
}
841830
}
842831
};
843832
}, [effectiveSession, projectPath]);

src/components/FloatingPromptInput.tsx

Lines changed: 37 additions & 30 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,6 @@ import { FilePicker } from "./FilePicker";
1919
import { ImagePreview } from "./ImagePreview";
2020
import { type FileEntry } from "@/lib/api";
2121
import { getCurrentWebviewWindow } from "@tauri-apps/api/webviewWindow";
22-
import { invoke } from "@tauri-apps/api/core";
2322

2423
interface FloatingPromptInputProps {
2524
/**
@@ -220,33 +219,39 @@ const FloatingPromptInputInner = (
220219

221220
// Helper function to check if a file is an image
222221
const isImageFile = (path: string): boolean => {
222+
// Check if it's a data URL
223+
if (path.startsWith('data:image/')) {
224+
return true;
225+
}
226+
// Otherwise check file extension
223227
const ext = path.split('.').pop()?.toLowerCase();
224228
return ['png', 'jpg', 'jpeg', 'gif', 'svg', 'webp', 'ico', 'bmp'].includes(ext || '');
225229
};
226230

227231
// Extract image paths from prompt text
228232
const extractImagePaths = (text: string): string[] => {
229-
console.log('[extractImagePaths] Input text:', text);
233+
console.log('[extractImagePaths] Input text length:', text.length);
230234

231235
// Updated regex to handle both quoted and unquoted paths
232-
// Pattern 1: @"path with spaces" - quoted paths
236+
// Pattern 1: @"path with spaces or data URLs" - quoted paths
233237
// Pattern 2: @path - unquoted paths (continues until @ or end)
234238
const quotedRegex = /@"([^"]+)"/g;
235239
const unquotedRegex = /@([^@\n\s]+)/g;
236240

237241
const pathsSet = new Set<string>(); // Use Set to ensure uniqueness
238242

239-
// First, extract quoted paths
243+
// First, extract quoted paths (including data URLs)
240244
let matches = Array.from(text.matchAll(quotedRegex));
241-
console.log('[extractImagePaths] Quoted matches:', matches.map(m => m[0]));
245+
console.log('[extractImagePaths] Quoted matches:', matches.length);
242246

243247
for (const match of matches) {
244248
const path = match[1]; // No need to trim, quotes preserve exact path
245-
console.log('[extractImagePaths] Processing quoted path:', path);
249+
console.log('[extractImagePaths] Processing quoted path:', path.startsWith('data:') ? 'data URL' : path);
246250

247-
// Convert relative path to absolute if needed
248-
const fullPath = path.startsWith('/') ? path : (projectPath ? `${projectPath}/${path}` : path);
249-
console.log('[extractImagePaths] Full path:', fullPath, 'Is image:', isImageFile(fullPath));
251+
// For data URLs, use as-is; for file paths, convert to absolute
252+
const fullPath = path.startsWith('data:')
253+
? path
254+
: (path.startsWith('/') ? path : (projectPath ? `${projectPath}/${path}` : path));
250255

251256
if (isImageFile(fullPath)) {
252257
pathsSet.add(fullPath);
@@ -256,25 +261,27 @@ const FloatingPromptInputInner = (
256261
// Remove quoted mentions from text to avoid double-matching
257262
let textWithoutQuoted = text.replace(quotedRegex, '');
258263

259-
// Then extract unquoted paths
264+
// Then extract unquoted paths (typically file paths)
260265
matches = Array.from(textWithoutQuoted.matchAll(unquotedRegex));
261-
console.log('[extractImagePaths] Unquoted matches:', matches.map(m => m[0]));
266+
console.log('[extractImagePaths] Unquoted matches:', matches.length);
262267

263268
for (const match of matches) {
264269
const path = match[1].trim();
270+
// Skip if it looks like a data URL fragment (shouldn't happen with proper quoting)
271+
if (path.includes('data:')) continue;
272+
265273
console.log('[extractImagePaths] Processing unquoted path:', path);
266274

267275
// Convert relative path to absolute if needed
268276
const fullPath = path.startsWith('/') ? path : (projectPath ? `${projectPath}/${path}` : path);
269-
console.log('[extractImagePaths] Full path:', fullPath, 'Is image:', isImageFile(fullPath));
270277

271278
if (isImageFile(fullPath)) {
272279
pathsSet.add(fullPath);
273280
}
274281
}
275282

276-
const uniquePaths = Array.from(pathsSet); // Convert Set back to Array
277-
console.log('[extractImagePaths] Final extracted paths (unique):', uniquePaths);
283+
const uniquePaths = Array.from(pathsSet);
284+
console.log('[extractImagePaths] Final extracted paths (unique):', uniquePaths.length);
278285
return uniquePaths;
279286
};
280287

@@ -479,7 +486,7 @@ const FloatingPromptInputInner = (
479486

480487
const handlePaste = async (e: React.ClipboardEvent) => {
481488
const items = e.clipboardData?.items;
482-
if (!items || !projectPath) return;
489+
if (!items) return;
483490

484491
for (const item of items) {
485492
if (item.type.startsWith('image/')) {
@@ -492,24 +499,13 @@ const FloatingPromptInputInner = (
492499
try {
493500
// Convert blob to base64
494501
const reader = new FileReader();
495-
reader.onload = async () => {
502+
reader.onload = () => {
496503
const base64Data = reader.result as string;
497504

498-
// Generate a session-specific ID for the image
499-
const sessionId = `paste-${Date.now()}`;
500-
501-
// Save the image via Tauri command
502-
const imagePath = await invoke<string>('save_clipboard_image', {
503-
projectPath,
504-
sessionId,
505-
imageData: base64Data,
506-
mimeType: item.type
507-
});
508-
509-
// Add the image path as a mention to the prompt
505+
// Add the base64 data URL directly to the prompt
510506
setPrompt(currentPrompt => {
511-
// Wrap path in quotes if it contains spaces
512-
const mention = imagePath.includes(' ') ? `@"${imagePath}"` : `@${imagePath}`;
507+
// Use the data URL directly as the image reference
508+
const mention = `@"${base64Data}"`;
513509
const newPrompt = currentPrompt + (currentPrompt.endsWith(' ') || currentPrompt === '' ? '' : ' ') + mention + ' ';
514510

515511
// Focus the textarea and move cursor to end
@@ -548,6 +544,17 @@ const FloatingPromptInputInner = (
548544
const handleRemoveImage = (index: number) => {
549545
// Remove the corresponding @mention from the prompt
550546
const imagePath = embeddedImages[index];
547+
548+
// For data URLs, we need to handle them specially since they're always quoted
549+
if (imagePath.startsWith('data:')) {
550+
// Simply remove the exact quoted data URL
551+
const quotedPath = `@"${imagePath}"`;
552+
const newPrompt = prompt.replace(quotedPath, '').trim();
553+
setPrompt(newPrompt);
554+
return;
555+
}
556+
557+
// For file paths, use the original logic
551558
const escapedPath = imagePath.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
552559
const escapedRelativePath = imagePath.replace(projectPath + '/', '').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
553560

src/components/ImagePreview.tsx

Lines changed: 13 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,16 @@ export const ImagePreview: React.FC<ImagePreviewProps> = ({
5656
onRemove(index);
5757
};
5858

59+
// Helper to get the image source - handles both file paths and data URLs
60+
const getImageSrc = (imagePath: string): string => {
61+
// If it's already a data URL, return as-is
62+
if (imagePath.startsWith('data:')) {
63+
return imagePath;
64+
}
65+
// Otherwise, convert the file path
66+
return convertFileSrc(imagePath);
67+
};
68+
5969
if (displayImages.length === 0) return null;
6070

6171
return (
@@ -83,7 +93,7 @@ export const ImagePreview: React.FC<ImagePreviewProps> = ({
8393
</div>
8494
) : (
8595
<img
86-
src={convertFileSrc(imagePath)}
96+
src={getImageSrc(imagePath)}
8797
alt={`Preview ${index + 1}`}
8898
className="w-full h-full object-cover"
8999
onError={() => handleImageError(index)}
@@ -131,7 +141,7 @@ export const ImagePreview: React.FC<ImagePreviewProps> = ({
131141
{selectedImageIndex !== null && (
132142
<div className="relative w-full h-full flex items-center justify-center p-4">
133143
<img
134-
src={convertFileSrc(displayImages[selectedImageIndex])}
144+
src={getImageSrc(displayImages[selectedImageIndex])}
135145
alt={`Full preview ${selectedImageIndex + 1}`}
136146
className="max-w-full max-h-full object-contain"
137147
onError={() => handleImageError(selectedImageIndex)}
@@ -164,4 +174,4 @@ export const ImagePreview: React.FC<ImagePreviewProps> = ({
164174
</Dialog>
165175
</>
166176
);
167-
};
177+
};

0 commit comments

Comments
 (0)