import React, { useRef, memo } from 'react'; import { RiAttachment2, RiCloseLine, RiComputerLine, RiFileImageLine, RiFileLine, RiFilePdfLine, RiHardDrive3Line } from '@remixicon/react'; import { useSessionStore, type AttachedFile } from '@/stores/useSessionStore'; import { useUIStore } from '@/stores/useUIStore'; import { toast } from 'sonner'; import { cn } from '@/lib/utils'; import { Tooltip, TooltipTrigger, TooltipContent } from '@/components/ui/tooltip'; import { useIsVSCodeRuntime } from '@/hooks/useRuntimeAPIs'; import type { ToolPopupContent } from './message/types'; export const FileAttachmentButton = memo(() => { const fileInputRef = useRef(null); const { addAttachedFile } = useSessionStore(); const { isMobile } = useUIStore(); const isVSCodeRuntime = useIsVSCodeRuntime(); const buttonSizeClass = isMobile ? 'h-9 w-9' : 'h-7 w-7'; const iconSizeClass = isMobile ? 'h-5 w-5' : 'h-[18px] w-[18px]'; const attachFiles = async (files: FileList | File[]) => { let attachedCount = 0; for (let i = 0; i < files.length; i++) { const file = files[i]; const sizeBefore = useSessionStore.getState().attachedFiles.length; try { await addAttachedFile(file); const sizeAfter = useSessionStore.getState().attachedFiles.length; if (sizeAfter > sizeBefore) { attachedCount++; } } catch (error) { console.error('File attach failed', error); toast.error(error instanceof Error ? error.message : 'Failed to attach file'); } } if (attachedCount > 0) { toast.success(`Attached ${attachedCount} file${attachedCount > 1 ? 's' : ''}`); } }; const handleFileSelect = async (e: React.ChangeEvent) => { const files = e.target.files; if (!files) return; await attachFiles(files); if (fileInputRef.current) { fileInputRef.current.value = ''; } }; const handleVSCodePick = async () => { try { const response = await fetch('/api/vscode/pick-files'); const data = await response.json(); const picked = Array.isArray(data?.files) ? data.files : []; const skipped = Array.isArray(data?.skipped) ? data.skipped : []; if (skipped.length > 0) { const summary = skipped.map((s: { name?: string; reason?: string }) => `${s?.name || 'file'}: ${s?.reason || 'skipped'}`).join('\n'); toast.error(`Some files were skipped:\n${summary}`); } const asFiles = picked .map((file: { name: string; mimeType?: string; dataUrl?: string }) => { if (!file?.dataUrl) return null; try { const [meta, base64] = file.dataUrl.split(','); const mime = file.mimeType || (meta?.match(/data:(.*);base64/)?.[1] || 'application/octet-stream'); if (!base64) return null; const binary = atob(base64); const bytes = new Uint8Array(binary.length); for (let i = 0; i < binary.length; i++) { bytes[i] = binary.charCodeAt(i); } const blob = new Blob([bytes], { type: mime }); return new File([blob], file.name || 'file', { type: mime }); } catch (err) { console.error('Failed to decode VS Code picked file', err); return null; } }) .filter(Boolean) as File[]; if (asFiles.length > 0) { await attachFiles(asFiles); } } catch (error) { console.error('VS Code file pick failed', error); toast.error(error instanceof Error ? error.message : 'Failed to pick files in VS Code'); } }; return ( <> ); }); interface FileChipProps { file: AttachedFile; onRemove: () => void; } const FileChip = memo(({ file, onRemove }: FileChipProps) => { const getFileIcon = () => { if (file.mimeType.startsWith('image/')) { return ; } if (file.mimeType.includes('text') || file.mimeType.includes('code')) { return ; } if (file.mimeType.includes('json') || file.mimeType.includes('xml')) { return ; } return ; }; const formatFileSize = (bytes: number) => { if (bytes < 1024) return bytes + ' B'; if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(1) + ' KB'; return (bytes / (1024 * 1024)).toFixed(1) + ' MB'; }; const extractFilename = (path: string): string => { const normalized = path.replace(/\\/g, '/'); const parts = normalized.split('/'); const filename = parts[parts.length - 1]; return filename || path; }; const displayName = extractFilename(file.filename); return (
{}
{file.source === 'server' ? ( ) : ( )}
{getFileIcon()} {displayName} ({formatFileSize(file.size)})
); }); export const AttachedFilesList = memo(() => { const { attachedFiles, removeAttachedFile } = useSessionStore(); if (attachedFiles.length === 0) return null; return (
Attached: {attachedFiles.map((file) => ( removeAttachedFile(file.id)} /> ))}
); }); interface FilePart { type: string; mime?: string; url?: string; filename?: string; size?: number; } interface MessageFilesDisplayProps { files: FilePart[]; onShowPopup?: (content: ToolPopupContent) => void; } export const MessageFilesDisplay = memo(({ files, onShowPopup }: MessageFilesDisplayProps) => { const fileItems = files.filter(f => f.type === 'file' && (f.mime || f.url)); const extractFilename = (path?: string): string => { if (!path) return 'Unnamed file'; const normalized = path.replace(/\\/g, '/'); const parts = normalized.split('/'); return parts[parts.length - 1] || path; }; const getFileIcon = (mimeType?: string) => { if (!mimeType) return ; if (mimeType.startsWith('image/')) { return ; } if (mimeType.includes('text') || mimeType.includes('code')) { return ; } if (mimeType.includes('json') || mimeType.includes('xml')) { return ; } return ; }; const imageFiles = fileItems.filter(f => f.mime?.startsWith('image/') && f.url); const otherFiles = fileItems.filter(f => !f.mime?.startsWith('image/')); const handleImageClick = React.useCallback((file: { filename?: string; mime?: string; size?: number; url?: string }) => { if (!onShowPopup || !file?.url) { return; } const filename = extractFilename(file.filename) || 'Image'; const popupPayload: ToolPopupContent = { open: true, title: filename, content: '', metadata: { tool: 'image-preview', filename, mime: file.mime, size: file.size, }, image: { url: file.url, mimeType: file.mime, filename, }, }; onShowPopup(popupPayload); }, [onShowPopup]); if (fileItems.length === 0) return null; return (
{} {otherFiles.length > 0 && (
{otherFiles.map((file, index) => (
{getFileIcon(file.mime)} {extractFilename(file.filename)}
))}
)} {} {imageFiles.length > 0 && (
{imageFiles.map((file, index) => { const filename = extractFilename(file.filename) || 'Image'; return ( {filename} ); })}
)}
); });