From a106a6e10b0cf16ace908a14bdf1b5390f5e89ea Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 14 Sep 2025 12:50:28 -0500 Subject: [PATCH] Support adding files through the VFS --- README.md | 6 +- src/components/Shakespeare/ChatPane.tsx | 52 ++++++- src/components/ui/file-attachment.test.tsx | 102 +++++++++++++ src/components/ui/file-attachment.tsx | 100 +++++++++++++ src/lib/fileUtils.test.ts | 157 +++++++++++++++++++++ src/lib/fileUtils.ts | 67 +++++++++ 6 files changed, 478 insertions(+), 6 deletions(-) create mode 100644 src/components/ui/file-attachment.test.tsx create mode 100644 src/components/ui/file-attachment.tsx create mode 100644 src/lib/fileUtils.test.ts create mode 100644 src/lib/fileUtils.ts diff --git a/README.md b/README.md index 1ffead42..f8bce56d 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,7 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we ## Features - **AI-Powered Development**: Chat with an AI assistant to build your Nostr website +- **File Attachments**: Attach files directly to chat messages for AI processing - **Project Management**: Create and manage multiple projects with sidebar navigation - **Real-time Editing**: Edit files directly in the browser with syntax highlighting - **File Explorer**: Browse and manage your project files @@ -15,8 +16,9 @@ Shakespeare is an AI chat application that allows users to build custom Nostr we 1. **Create a Project**: Enter a description of what you want to build in the prompt textarea 2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website -3. **Edit Code**: Switch to the code view to manually edit files if needed -4. **Preview**: View your website in the preview pane +3. **Attach Files**: Click the paperclip icon to attach files to your messages for AI analysis +4. **Edit Code**: Switch to the code view to manually edit files if needed +5. **Preview**: View your website in the preview pane ## Project Structure diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 6abd4b18..d6aff05a 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -5,6 +5,7 @@ import { Textarea } from '@/components/ui/textarea'; import { Skeleton } from '@/components/ui/skeleton'; import { CircularProgress } from '@/components/ui/circular-progress'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; +import { FileAttachment } from '@/components/ui/file-attachment'; import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; import { useFS } from '@/hooks/useFS'; @@ -36,6 +37,7 @@ import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { makeSystemPrompt } from '@/lib/system'; import { assistantContentEmpty } from '@/lib/ai-messages'; +import { saveFileToTmp } from '@/lib/fileUtils'; interface ChatPaneProps { projectId: string; @@ -67,6 +69,7 @@ export const ChatPane = forwardRef(({ const [input, setInput] = useState(''); const [systemPrompt, setSystemPrompt] = useState(''); const [showScrollToBottom, setShowScrollToBottom] = useState(false); + const [attachedFiles, setAttachedFiles] = useState([]); // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; @@ -274,12 +277,44 @@ export const ChatPane = forwardRef(({ } }, [messages, streamingMessage, isLoading]); - const handleSend = async () => { - if (!input.trim() || isLoading || !providerModel.trim()) return; + const handleFileSelect = (file: File) => { + setAttachedFiles(prev => [...prev, file]); + }; - const messageContent = input; + const handleFileRemove = (fileToRemove: File) => { + setAttachedFiles(prev => prev.filter(file => file !== fileToRemove)); + }; + + const handleSend = async () => { + if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return; + + let messageContent = input; const modelToUse = providerModel.trim(); + + // Process attached files + if (attachedFiles.length > 0) { + const filePromises = attachedFiles.map(async (file) => { + try { + const savedPath = await saveFileToTmp(fs, file); + return `File added to ${savedPath}`; + } catch (error) { + console.error('Failed to save file:', error); + return `Failed to save file: ${file.name}`; + } + }); + + const fileResults = await Promise.all(filePromises); + + // Append file information to the message + if (messageContent.trim()) { + messageContent += '\n\n' + fileResults.join('\n'); + } else { + messageContent = fileResults.join('\n'); + } + } + setInput(''); + setAttachedFiles([]); // Add model to recently used when sending a message addRecentlyUsedModel(modelToUse); @@ -464,6 +499,15 @@ export const ChatPane = forwardRef(({ {/* Bottom Controls Row */}
+ {/* File Attachment */} + + {/* Context Usage Wheel */} {contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && ( @@ -526,7 +570,7 @@ export const ChatPane = forwardRef(({ + + {selectedFiles.length > 0 && ( +
+ {selectedFiles.map((file, index) => ( +
+ + {file.name} + + {onFileRemove && ( + + )} +
+ ))} +
+ )} +
+ ); +} \ No newline at end of file diff --git a/src/lib/fileUtils.test.ts b/src/lib/fileUtils.test.ts new file mode 100644 index 00000000..b69db41d --- /dev/null +++ b/src/lib/fileUtils.test.ts @@ -0,0 +1,157 @@ +import { describe, it, expect, beforeEach } from 'vitest'; +import { generateUniqueFilename, saveFileToTmp } from './fileUtils'; +import type { JSRuntimeFS } from './JSRuntime'; + +// Mock filesystem for testing +class MockFS implements JSRuntimeFS { + private files = new Map(); + private directories = new Set(); + + constructor() { + this.directories.add('/'); + this.directories.add('/tmp'); + } + + async readFile(path: string): Promise; + async readFile(path: string, encoding: 'utf8'): Promise; + async readFile(path: string, encoding: string): Promise; + async readFile(path: string, encoding?: string): Promise { + const data = this.files.get(path); + if (!data) throw new Error(`File not found: ${path}`); + + if (encoding === 'utf8') { + return typeof data === 'string' ? data : new TextDecoder().decode(data); + } + + return data; + } + + async writeFile(path: string, data: string | Uint8Array): Promise { + this.files.set(path, data); + } + + async readdir(path: string): Promise; + async readdir(path: string, options: { withFileTypes: true }): Promise; + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise; + async readdir(_path: string, _options?: { withFileTypes?: boolean }): Promise { + if (_options?.withFileTypes) { + return []; + } + return []; + } + + async mkdir(path: string, _options?: { recursive?: boolean }): Promise { + this.directories.add(path); + } + + async stat(path: string) { + if (this.files.has(path)) { + return { + isDirectory: () => false, + isFile: () => true, + size: 100, + mtimeMs: Date.now() + }; + } + if (this.directories.has(path)) { + return { + isDirectory: () => true, + isFile: () => false, + size: 0, + mtimeMs: Date.now() + }; + } + throw new Error(`File not found: ${path}`); + } + + async lstat(path: string) { + return this.stat(path); + } + + async unlink(): Promise {} + async rmdir(): Promise {} + async rename(): Promise {} + async readlink(): Promise { return ''; } + async symlink(): Promise {} +} + +describe('fileUtils', () => { + let mockFS: MockFS; + + beforeEach(() => { + mockFS = new MockFS(); + }); + + describe('generateUniqueFilename', () => { + it('should return original filename if no conflict', async () => { + const result = await generateUniqueFilename(mockFS, '/tmp', 'test.txt'); + expect(result).toBe('test.txt'); + }); + + it('should add counter for conflicting filenames', async () => { + // Simulate existing files + await mockFS.writeFile('/tmp/test.txt', 'content'); + await mockFS.writeFile('/tmp/test_1.txt', 'content'); + + const result = await generateUniqueFilename(mockFS, '/tmp', 'test.txt'); + expect(result).toBe('test_2.txt'); + }); + + it('should handle files without extension', async () => { + await mockFS.writeFile('/tmp/README', 'content'); + + const result = await generateUniqueFilename(mockFS, '/tmp', 'README'); + expect(result).toBe('README_1'); + }); + + it('should handle multiple extensions correctly', async () => { + await mockFS.writeFile('/tmp/archive.tar.gz', 'content'); + + const result = await generateUniqueFilename(mockFS, '/tmp', 'archive.tar.gz'); + expect(result).toBe('archive.tar_1.gz'); + }); + }); + + describe('saveFileToTmp', () => { + it('should save file to /tmp directory', async () => { + const fileContent = 'Hello, world!'; + const arrayBuffer = new TextEncoder().encode(fileContent).buffer; + + // Create a mock File object with arrayBuffer method + const file = { + name: 'hello.txt', + arrayBuffer: async () => arrayBuffer + } as File; + + const savedPath = await saveFileToTmp(mockFS, file); + + expect(savedPath).toBe('/tmp/hello.txt'); + + // Verify file was actually saved + const savedContent = await mockFS.readFile('/tmp/hello.txt', 'utf8'); + expect(savedContent).toBe(fileContent); + }); + + it('should handle file deduplication', async () => { + // Create existing file + await mockFS.writeFile('/tmp/test.txt', 'existing'); + + const fileContent = 'new content'; + const arrayBuffer = new TextEncoder().encode(fileContent).buffer; + + // Create a mock File object with arrayBuffer method + const file = { + name: 'test.txt', + arrayBuffer: async () => arrayBuffer + } as File; + + const savedPath = await saveFileToTmp(mockFS, file); + + expect(savedPath).toBe('/tmp/test_1.txt'); + + // Verify new file was saved with unique name + const savedContent = await mockFS.readFile('/tmp/test_1.txt', 'utf8'); + expect(savedContent).toBe(fileContent); + }); + }); +}); \ No newline at end of file diff --git a/src/lib/fileUtils.ts b/src/lib/fileUtils.ts new file mode 100644 index 00000000..eb95460d --- /dev/null +++ b/src/lib/fileUtils.ts @@ -0,0 +1,67 @@ +import type { JSRuntimeFS } from '@/lib/JSRuntime'; + +/** + * Generate a unique filename by adding numbers if the file already exists + * @param fs - Filesystem instance + * @param directory - Directory to check for existing files + * @param filename - Original filename + * @returns Promise - Unique filename + */ +export async function generateUniqueFilename( + fs: JSRuntimeFS, + directory: string, + filename: string +): Promise { + // Ensure directory exists + try { + await fs.mkdir(directory, { recursive: true }); + } catch { + // Directory might already exist, continue + } + + // Parse filename and extension + const lastDotIndex = filename.lastIndexOf('.'); + const name = lastDotIndex === -1 ? filename : filename.slice(0, lastDotIndex); + const extension = lastDotIndex === -1 ? '' : filename.slice(lastDotIndex); + + let uniqueFilename = filename; + let counter = 1; + + // Keep checking for existing files and increment counter + while (true) { + const fullPath = `${directory}/${uniqueFilename}`; + + try { + await fs.stat(fullPath); + // File exists, try next number + uniqueFilename = `${name}_${counter}${extension}`; + counter++; + } catch { + // File doesn't exist, we can use this filename + break; + } + } + + return uniqueFilename; +} + +/** + * Save a file to the /tmp directory with deduplication + * @param fs - Filesystem instance + * @param file - File object to save + * @returns Promise - Full path where the file was saved + */ +export async function saveFileToTmp(fs: JSRuntimeFS, file: File): Promise { + const tmpDir = '/tmp'; + const uniqueFilename = await generateUniqueFilename(fs, tmpDir, file.name); + const fullPath = `${tmpDir}/${uniqueFilename}`; + + // Read file content as array buffer and convert to Uint8Array + const arrayBuffer = await file.arrayBuffer(); + const uint8Array = new Uint8Array(arrayBuffer); + + // Write file to filesystem + await fs.writeFile(fullPath, uint8Array); + + return fullPath; +} \ No newline at end of file