From 6f4aa264ebf81988753adde21a2220f60dbba11c Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 03:55:34 +0000 Subject: [PATCH 01/11] merge in from upstream and resolve conflict --- AGENTS.md | 78 +++++- src/components/ProjectSidebar.tsx | 43 ++- src/components/ZipImportDialog.tsx | 408 +++++++++++++++++++++++++++++ src/lib/ProjectsManager.ts | 156 +++++++++++ src/pages/Index.tsx | 7 + 5 files changed, 689 insertions(+), 3 deletions(-) create mode 100644 src/components/ZipImportDialog.tsx diff --git a/AGENTS.md b/AGENTS.md index 6d787bd4..6b387b7b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -160,6 +160,80 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - **TanStack Query**: For data fetching, caching, and state management - **TypeScript**: For type-safe JavaScript development +## Project Import + +Shakespeare supports importing existing projects from ZIP files through the main interface: + +### ZIP Import Feature + +- **Location**: Available in the sidebar under the "New Project" expand menu, below "Import Repository" +- **Function**: Upload ZIP files containing project source code with drag & drop support +- **Auto-setup**: Automatically extracts files, sets up Git repository, and creates project structure +- **Drag & Drop**: Intuitive drag and drop interface with click-to-browse fallback +- **Custom IDs**: Option to specify custom project ID or auto-generate from filename +- **Project Overwrite**: Allows overwriting existing projects with clear warnings and confirmation +- **Error Handling**: Validates ZIP files and provides clear error messages +- **Progress Tracking**: Shows import progress with visual feedback + +### ZIP Import Process + +1. Click the "New Project" button in the sidebar +2. Click the dropdown arrow (▼) to expand the menu +3. Select "Import ZIP File" from the dropdown options +4. **Upload Methods**: + - **Drag & Drop**: Drag your ZIP file directly onto the drop zone + - **Click to Browse**: Click the drop zone to open file selector +5. Review the selected file (name and size displayed) +6. Optionally specify a custom project ID (auto-generated from filename if empty) +7. **Overwrite Detection**: If project ID already exists, warning appears with option to overwrite +8. **Overwrite Confirmation**: Detailed confirmation dialog explains what will be preserved/deleted +9. Click "Import Project" or "Overwrite Project" to begin the import process +10. Wait for the import to complete (progress bar shows extraction and setup) +11. The imported project will be automatically available in the project list + +### ZIP File Requirements + +- Must be a valid ZIP archive +- Can contain any project structure (React, Node.js, static sites, etc.) +- Directory structure is preserved during import +- Maximum recommended file size: 50MB +- Existing `.git` directories are preserved if present +- New Git repository is initialized if no `.git` directory exists +- `.ai/` directory is automatically created for Shakespeare functionality + +### Project Overwrite Feature + +When importing a project with an ID that already exists: + +**What Gets Preserved:** +- **Git History**: All existing commits and repository history are maintained +- **AI Chat History**: All chat sessions and conversation data are preserved +- **Project Settings**: Configuration and metadata remain intact + +**What Gets Replaced:** +- **All Project Files**: Every file in the project directory is replaced with ZIP contents +- **Directory Structure**: New directory structure from ZIP replaces existing structure +- **Git Commit**: New commit is created documenting the overwrite action + +**Confirmation Process:** +1. Clear warning appears when duplicate project ID is detected +2. Detailed confirmation dialog lists exactly what will happen +3. User must explicitly confirm the overwrite action +4. Process cannot be undone once confirmed + +**Use Cases:** +- **Project Updates**: Import newer version of existing project +- **Template Refresh**: Update project with latest template changes +- **Migration**: Move project from different development environment + +### Integration with Existing Features + +- **Project Management**: Imported projects appear alongside AI-created projects +- **Git Integration**: Preserves existing Git history or initializes new repository +- **AI Chat**: Full AI assistance available for imported projects +- **File Operations**: All file operations work normally with imported projects +- **Build System**: Projects can be built and deployed normally + ## Project Structure - `/src/components/`: UI components including NostrProvider for Nostr integration @@ -168,6 +242,8 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog) - `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection) - `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane) + - `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options + - `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files - Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments - `/src/hooks/`: Custom hooks including: - `useNostr`: Core Nostr protocol integration @@ -182,7 +258,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - `useSessionManager`: Access session management for AI chat sessions - `useGitStatus`: Real-time Git repository status monitoring - `useProjects`: Project management and CRUD operations - - `useProjectsManager`: Advanced project operations (creation, cloning, building) + - `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import) - `useTheme`: Theme management - `useToast`: Toast notifications - `useLocalStorage`: Persistent local storage diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index a99d2c7d..ba4567fe 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -1,7 +1,7 @@ -import React, { useEffect } from 'react'; +import React, { useEffect, useState } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react'; +import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Skeleton } from '@/components/ui/skeleton'; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu'; @@ -9,6 +9,9 @@ import { useProjects } from '@/hooks/useProjects'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; import { useLocalStorage } from '@/hooks/useLocalStorage'; import { useIsMobile } from '@/hooks/useIsMobile'; +import { ZipImportDialog } from '@/components/ZipImportDialog'; +import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useToast } from '@/hooks/useToast'; import type { Project } from '@/lib/ProjectsManager'; import { cn } from '@/lib/utils'; import { useQueryClient } from '@tanstack/react-query'; @@ -92,6 +95,9 @@ export function ProjectSidebar({ const queryClient = useQueryClient(); const { data: projects = [], isLoading, error } = useProjects(); const [favorites] = useLocalStorage('project-favorites', []); + const projectsManager = useProjectsManager(); + const { toast } = useToast(); + const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); const isMobile = useIsMobile(); const navigate = useNavigate(); @@ -117,6 +123,25 @@ export function ProjectSidebar({ } }; + const handleImportZip = async (file: File, customId?: string, overwrite = false) => { + try { + // Import project from zip file + const project = await projectsManager.importProjectFromZip(file, customId, overwrite); + + // Show success toast + toast({ + title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully", + description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`, + }); + + // Navigate to the imported project + navigate(`/project/${project.id}`); + } catch (error) { + console.error('Failed to import project:', error); + throw error; // Re-throw to let the dialog handle the error display + } + }; + useEffect(() => { queryClient.invalidateQueries({ queryKey: ['projects'] }); }, [favorites, queryClient]); @@ -186,6 +211,13 @@ export function ProjectSidebar({ {t('importRepository')} + setIsZipDialogOpen(true)} + className="flex items-center gap-2 w-full" + > + + Import ZIP File + @@ -248,6 +280,13 @@ export function ProjectSidebar({ + + {/* ZIP Import Dialog */} + ); } \ No newline at end of file diff --git a/src/components/ZipImportDialog.tsx b/src/components/ZipImportDialog.tsx new file mode 100644 index 00000000..35a8f7ff --- /dev/null +++ b/src/components/ZipImportDialog.tsx @@ -0,0 +1,408 @@ +import React, { useState, useRef, useCallback, useEffect } from 'react'; +import { Button } from '@/components/ui/button'; +import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; +import { Progress } from '@/components/ui/progress'; +import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog'; +import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react'; +import { useProjects } from '@/hooks/useProjects'; +import { cn } from '@/lib/utils'; + +interface ZipImportDialogProps { + onImport: (file: File, customId?: string, overwrite?: boolean) => Promise; + disabled?: boolean; + className?: string; + open?: boolean; + onOpenChange?: (open: boolean) => void; +} + +export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) { + // Use controlled state if props are provided, otherwise use internal state + const [internalIsOpen, setInternalIsOpen] = useState(false); + const isOpen = open !== undefined ? open : internalIsOpen; + const setIsOpen = onOpenChange || setInternalIsOpen; + const [selectedFile, setSelectedFile] = useState(null); + const [customId, setCustomId] = useState(''); + const [isImporting, setIsImporting] = useState(false); + const [importProgress, setImportProgress] = useState(0); + const [error, setError] = useState(null); + const [isDragOver, setIsDragOver] = useState(false); + const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null); + const [showOverwriteDialog, setShowOverwriteDialog] = useState(false); + const fileInputRef = useRef(null); + const { data: projects = [] } = useProjects(); + + const handleFileSelect = (file: File) => { + // Only accept zip files + if (!file.name.toLowerCase().endsWith('.zip')) { + setError('Please select a ZIP file'); + return; + } + + setSelectedFile(file); + setError(null); + + // Auto-generate custom ID from file name + const baseName = file.name.replace(/\.zip$/i, ''); + const generatedId = baseName + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + setCustomId(generatedId); + }; + + // Check for existing project when custom ID changes + useEffect(() => { + if (customId && projects.length > 0) { + const existing = projects.find(project => project.id === customId); + setExistingProject(existing || null); + } else { + setExistingProject(null); + } + }, [customId, projects]); + + // Drag and drop handlers + const handleDragOver = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(true); + }, []); + + const handleDragLeave = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(false); + }, []); + + const handleDrop = useCallback((e: React.DragEvent) => { + e.preventDefault(); + setIsDragOver(false); + + const files = Array.from(e.dataTransfer.files); + if (files.length > 0) { + handleFileSelect(files[0]); + } + }, []); + + const handleDragOverDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(true); + }, []); + + const handleDragLeaveDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(false); + }, []); + + const handleDropDialog = useCallback((e: React.DragEvent) => { + e.preventDefault(); + e.stopPropagation(); + setIsDragOver(false); + + const files = Array.from(e.dataTransfer.files); + if (files.length > 0) { + handleFileSelect(files[0]); + } + }, []); + + const handleClickUpload = () => { + fileInputRef.current?.click(); + }; + + const handleFileRemove = () => { + setSelectedFile(null); + setCustomId(''); + setError(null); + }; + + const handleImport = async (overwrite = false) => { + if (!selectedFile) return; + + setIsImporting(true); + setImportProgress(0); + setError(null); + + try { + // Simulate progress for better UX + const progressInterval = setInterval(() => { + setImportProgress(prev => Math.min(prev + 10, 90)); + }, 200); + + await onImport(selectedFile, customId || undefined, overwrite); + + clearInterval(progressInterval); + setImportProgress(100); + + // Close dialog after a short delay + setTimeout(() => { + setIsOpen(false); + setSelectedFile(null); + setCustomId(''); + setImportProgress(0); + setExistingProject(null); + }, 1000); + } catch (err) { + setError(err instanceof Error ? err.message : 'Failed to import project'); + setImportProgress(0); + } finally { + setIsImporting(false); + } + }; + + const handleImportWithOverwriteCheck = async () => { + if (!selectedFile || !customId) return; + + // Check if project with this ID already exists + try { + // This would ideally be passed as a prop or through context + // For now, we'll assume the parent will handle the check and pass existing project info + if (existingProject) { + setShowOverwriteDialog(true); + } else { + await handleImport(false); + } + } catch (error) { + console.error('Error checking existing project:', error); + await handleImport(false); + } + }; + + const confirmOverwrite = async () => { + setShowOverwriteDialog(false); + await handleImport(true); + }; + + const handleClose = () => { + if (!isImporting) { + setIsOpen(false); + setSelectedFile(null); + setCustomId(''); + setError(null); + setImportProgress(0); + } + }; + + return ( + <> + + + + + + + + + + Import Project from ZIP + + + Upload a ZIP file containing your project source code to import it into Shakespeare. + + + +
+ {!isImporting && ( + <> + {/* Drag and Drop Area */} +
+ { + const files = e.target.files; + if (files && files.length > 0) { + handleFileSelect(files[0]); + } + }} + accept=".zip" + className="hidden" + disabled={isImporting} + /> + +
+
+ {selectedFile ? ( + + ) : ( + + )} +
+ +
+ {selectedFile ? ( +
+

+ {selectedFile.name} +

+

+ {(selectedFile.size / 1024 / 1024).toFixed(2)} MB +

+ +
+ ) : ( +
+

+ Drop your ZIP file here or click to browse +

+

+ Supports ZIP files up to 50MB +

+
+ )} +
+
+
+ + {/* Error Display */} + {error && ( +
+ + {error} +
+ )} + + {/* Custom Project ID */} +
+ + setCustomId(e.target.value)} + placeholder="project-name" + className="w-full px-3 py-2 text-sm border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2" + disabled={isImporting} + /> +

+ Auto-generated from filename. Only use lowercase letters, numbers, and hyphens. +

+ {existingProject && ( +
+ + A project with this ID already exists. You can choose to overwrite it. +
+ )} +
+ + {/* Import Button */} +
+ + +
+ + )} + + {/* Import Progress */} + {isImporting && ( +
+
+
+ Importing project... +
+ +

+ Extracting files and setting up project... +

+
+ )} + + {/* Success State */} + {!isImporting && importProgress === 100 && ( +
+ + + + Project imported successfully! +
+ )} +
+
+
+ + {/* Overwrite Confirmation Dialog */} + + + + + + Overwrite Existing Project + + +

+ A project with the ID "{customId}" already exists. + Overwriting it will: +

+
    +
  • Delete all existing files in the project
  • +
  • Replace them with files from the ZIP archive
  • +
  • Preserve Git history if it exists
  • +
  • Keep AI chat history and session data
  • +
+

+ This action cannot be undone. Are you sure you want to continue? +

+
+
+ + Cancel + + Yes, Overwrite Project + + +
+
+ + ); +} \ No newline at end of file diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 91af47ab..817abd2a 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -1,4 +1,5 @@ import { Buffer } from 'buffer'; +import JSZip from 'jszip'; import { Git } from '@/lib/git'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; @@ -91,6 +92,161 @@ export class ProjectsManager { return project; } + async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise { + // Generate a project ID based on the zip file name or use custom ID + const baseName = zipFile.name.replace(/\.zip$/i, ''); + const id = customId || await this.generateUniqueProjectId(baseName); + + const projectPath = `${this.dir}/${id}`; + const projectExists = await this.projectExists(id); + + // Check if project with this ID already exists when not overwriting + if (projectExists && !overwrite) { + throw new Error(`Project with ID "${id}" already exists`); + } + + try { + // Create project directory (or ensure it exists for overwrite) + await this.fs.mkdir(projectPath, { recursive: true }); + + // If overwriting, delete existing files except .ai directory and .git directory + if (projectExists && overwrite) { + const existingFiles = await this.getAllFiles(projectPath); + for (const file of existingFiles) { + // Preserve .ai directory and .git directory + if (!file.startsWith('.ai/') && !file.startsWith('.git/')) { + try { + await this.fs.unlink(`${projectPath}/${file}`); + } catch { + // Ignore deletion errors + } + } + } + } + + // Read the zip file + const arrayBuffer = await zipFile.arrayBuffer(); + const zip = await JSZip.loadAsync(arrayBuffer); + + // Extract all files from the zip + const files = Object.keys(zip.files); + + for (const filePath of files) { + const zipEntry = zip.files[filePath]; + + // Skip directories (they end with / in JSZip) + if (zipEntry.dir) { + // Create the directory structure + const dirPath = `${projectPath}/${filePath}`; + await this.fs.mkdir(dirPath, { recursive: true }); + continue; + } + + // Extract file content + const content = await zipEntry.async('uint8array'); + const fullPath = `${projectPath}/${filePath}`; + + // Ensure parent directory exists + const dirPath = fullPath.split('/').slice(0, -1).join('/'); + if (dirPath) { + await this.fs.mkdir(dirPath, { recursive: true }); + } + + // Write the file (this will overwrite existing files) + await this.fs.writeFile(fullPath, content); + } + + // Get filesystem stats for timestamps + const stats = await this.fs.stat(projectPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + // Initialize git repository if there's no .git directory + try { + await this.fs.stat(`${projectPath}/.git`); + + // If git exists and we're overwriting, stage the new files + if (overwrite) { + const projectFiles = await this.getAllFiles(projectPath); + for (const file of projectFiles) { + // Skip .git directory and .ai directory + if (!file.startsWith('.git/') && !file.startsWith('.ai/')) { + try { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } catch { + // Ignore git add errors for files that might be gitignored + } + } + } + + // Make commit for the overwrite + await this.git.commit({ + dir: projectPath, + message: `Overwrite project from ${zipFile.name}`, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + }); + } + } catch { + // No .git directory found, initialize new repository + await this.git.init({ + dir: projectPath, + defaultBranch: 'main', + }); + + // Add all files to git (excluding .ai directory) + const projectFiles = await this.getAllFiles(projectPath); + for (const file of projectFiles) { + // Skip .git directory and .ai directory + if (!file.startsWith('.git/') && !file.startsWith('.ai/')) { + await this.git.add({ + dir: projectPath, + filepath: file, + }); + } + } + + // Make initial commit + await this.git.commit({ + dir: projectPath, + message: `Import project from ${zipFile.name}`, + author: { + name: 'shakespeare.diy', + email: 'assistant@shakespeare.diy', + }, + }); + } + + // Create .ai/history directory + try { + await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true }); + } catch { + // Directory might already exist + } + + return { + id, + name: this.formatProjectName(id), + path: projectPath, + lastModified: timestamp, + }; + } catch (error) { + // Clean up on error (only if this was a new project creation) + if (!projectExists) { + try { + await this.deleteDirectory(projectPath); + } catch { + // Ignore cleanup errors + } + } + throw error; + } + } + async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise { const id = customId || await this.generateUniqueProjectId(name); diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index d8f3b6d6..430c1228 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -115,11 +115,18 @@ export default function Index() { navigate(`/project/${project.id}?${searchParams.toString()}`); } catch (error) { console.error('Failed to create project:', error); + toast({ + title: "Project Creation Failed", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); } finally { setIsCreating(false); } }; + + const headerContent = null; return ( From f4ccc2d924a9b0ad3423c48252edc8db9ec180c0 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 05:47:17 +0000 Subject: [PATCH 02/11] refactors --- src/components/ProjectSidebar.tsx | 4 +- src/components/ZipImportDialog.test.tsx | 203 ++++++++++++++++++++++++ src/components/ZipImportDialog.tsx | 63 +++----- src/lib/ProjectsManager.test.ts | 96 ++++++++++- src/lib/ProjectsManager.ts | 26 ++- src/pages/Index.tsx | 2 + 6 files changed, 349 insertions(+), 45 deletions(-) create mode 100644 src/components/ZipImportDialog.test.tsx diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index ba4567fe..3d6782a0 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -123,10 +123,10 @@ export function ProjectSidebar({ } }; - const handleImportZip = async (file: File, customId?: string, overwrite = false) => { + const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { try { // Import project from zip file - const project = await projectsManager.importProjectFromZip(file, customId, overwrite); + const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); // Show success toast toast({ diff --git a/src/components/ZipImportDialog.test.tsx b/src/components/ZipImportDialog.test.tsx new file mode 100644 index 00000000..19ecadbe --- /dev/null +++ b/src/components/ZipImportDialog.test.tsx @@ -0,0 +1,203 @@ +import { describe, it, expect, vi, beforeEach } from 'vitest'; +import { render, screen, fireEvent, waitFor } from '@testing-library/react'; +import { ZipImportDialog } from './ZipImportDialog'; +import { TestApp } from '@/test/TestApp'; + +// Mock the useProjects hook +const mockProjects = [ + { id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() } +]; + +vi.mock('@/hooks/useProjects', () => ({ + useProjects: () => ({ + data: mockProjects, + isLoading: false, + error: null + }) +})); + +describe('ZipImportDialog', () => { + const mockOnImport = vi.fn(); + const defaultProps = { + onImport: mockOnImport, + disabled: false + }; + + beforeEach(() => { + mockOnImport.mockClear(); + vi.clearAllMocks(); + }); + + it('renders dialog trigger button', () => { + render( + + + + ); + + expect(screen.getByText('Import ZIP')).toBeInTheDocument(); + }); + + it('opens dialog when trigger is clicked', async () => { + render( + + + + ); + + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + await waitFor(() => { + expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument(); + }); + }); + + it('processes file selection without displaying project ID', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file + const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + await waitFor(() => { + // Verify that the file name is displayed (from the file selection area) + expect(screen.getByText('my-project.zip')).toBeInTheDocument(); + // Verify that Project ID label is not displayed + expect(screen.queryByText('Project ID')).not.toBeInTheDocument(); + }); + }); + + it('shows overwrite warning when project ID already exists', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file that will generate an existing project ID + const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + await waitFor(() => { + expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument(); + expect(screen.getByText('Overwrite Project')).toBeInTheDocument(); + }); + }); + + it('calls onImport with correct parameters when import button is clicked', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file + const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + // Wait for file to be processed + await waitFor(() => { + expect(screen.getByText('new-project.zip')).toBeInTheDocument(); + }); + + // Click import button + const importButton = screen.getByText('Import Project'); + fireEvent.click(importButton); + + await waitFor(() => { + expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project"); + }); + }); + + it('shows overwrite confirmation dialog when overwrite button is clicked', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Create a mock file that will generate an existing project ID + const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' }); + + // Find the hidden file input by ref + const fileInput = document.querySelector('input[type="file"][accept=".zip"]'); + + if (fileInput) { + fireEvent.change(fileInput, { target: { files: [file] } }); + } + + // Wait for overwrite button to appear + await waitFor(() => { + expect(screen.getByText('Overwrite Project')).toBeInTheDocument(); + }); + + // Click overwrite button + const overwriteButton = screen.getByText('Overwrite Project'); + fireEvent.click(overwriteButton); + + // Check for overwrite confirmation dialog + await waitFor(() => { + expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument(); + // Use a more flexible matcher for the text that might be split across elements + const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent'); + if (dialogContent) { + expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists'); + } + }, { timeout: 2000 }); + }); + + it('does not show project ID input field (simplified interface)', async () => { + render( + + + + ); + + // Open dialog + const triggerButton = screen.getByText('Import ZIP'); + fireEvent.click(triggerButton); + + // Check that there's no input field for project ID + expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument(); + expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument(); + }); +}); \ No newline at end of file diff --git a/src/components/ZipImportDialog.tsx b/src/components/ZipImportDialog.tsx index 35a8f7ff..5f6a3436 100644 --- a/src/components/ZipImportDialog.tsx +++ b/src/components/ZipImportDialog.tsx @@ -8,7 +8,7 @@ import { useProjects } from '@/hooks/useProjects'; import { cn } from '@/lib/utils'; interface ZipImportDialogProps { - onImport: (file: File, customId?: string, overwrite?: boolean) => Promise; + onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise; disabled?: boolean; className?: string; open?: boolean; @@ -21,7 +21,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o const isOpen = open !== undefined ? open : internalIsOpen; const setIsOpen = onOpenChange || setInternalIsOpen; const [selectedFile, setSelectedFile] = useState(null); - const [customId, setCustomId] = useState(''); + const [generatedId, setGeneratedId] = useState(''); const [isImporting, setIsImporting] = useState(false); const [importProgress, setImportProgress] = useState(0); const [error, setError] = useState(null); @@ -41,24 +41,24 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o setSelectedFile(file); setError(null); - // Auto-generate custom ID from file name + // Auto-generate ID from file name const baseName = file.name.replace(/\.zip$/i, ''); - const generatedId = baseName + const id = baseName .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); - setCustomId(generatedId); + setGeneratedId(id); }; - // Check for existing project when custom ID changes + // Check for existing project when generated ID changes useEffect(() => { - if (customId && projects.length > 0) { - const existing = projects.find(project => project.id === customId); + if (generatedId && projects.length > 0) { + const existing = projects.find(project => project.id === generatedId); setExistingProject(existing || null); } else { setExistingProject(null); } - }, [customId, projects]); + }, [generatedId, projects]); // Drag and drop handlers const handleDragOver = useCallback((e: React.DragEvent) => { @@ -110,7 +110,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o const handleFileRemove = () => { setSelectedFile(null); - setCustomId(''); + setGeneratedId(''); setError(null); }; @@ -127,7 +127,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o setImportProgress(prev => Math.min(prev + 10, 90)); }, 200); - await onImport(selectedFile, customId || undefined, overwrite); + await onImport(selectedFile, overwrite, generatedId); clearInterval(progressInterval); setImportProgress(100); @@ -136,7 +136,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o setTimeout(() => { setIsOpen(false); setSelectedFile(null); - setCustomId(''); + setGeneratedId(''); setImportProgress(0); setExistingProject(null); }, 1000); @@ -149,7 +149,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o }; const handleImportWithOverwriteCheck = async () => { - if (!selectedFile || !customId) return; + if (!selectedFile || !generatedId) return; // Check if project with this ID already exists try { @@ -175,7 +175,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o if (!isImporting) { setIsOpen(false); setSelectedFile(null); - setCustomId(''); + setGeneratedId(''); setError(null); setImportProgress(0); } @@ -290,30 +290,13 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o )} - {/* Custom Project ID */} -
- - setCustomId(e.target.value)} - placeholder="project-name" - className="w-full px-3 py-2 text-sm border border-input rounded-md bg-background focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2" - disabled={isImporting} - /> -

- Auto-generated from filename. Only use lowercase letters, numbers, and hyphens. -

- {existingProject && ( -
- - A project with this ID already exists. You can choose to overwrite it. -
- )} -
+ {/* Overwrite Warning */} + {existingProject && ( +
+ + A project with this ID already exists. You can choose to overwrite it. +
+ )} {/* Import Button */}
@@ -322,7 +305,7 @@ export function ZipImportDialog({ onImport, disabled = false, className, open, o - + {!isControlled && ( + + + + )} Date: Sat, 20 Sep 2025 06:14:16 +0000 Subject: [PATCH 04/11] Restore mobile back buttons and clean up branch - Restore mobile back buttons in AboutSettings and DataSettings pages - Remove extra empty lines in Index.tsx - Ensure compatibility with origin/main changes - All tests pass and build succeeds This resolves conflicts where the zipImport branch had incorrectly removed mobile navigation features that were added in origin/main. --- src/pages/AboutSettings.tsx | 49 +++++++++++++++++++++++++++++-------- src/pages/DataSettings.tsx | 47 +++++++++++++++++++++++++++-------- src/pages/Index.tsx | 2 -- 3 files changed, 76 insertions(+), 22 deletions(-) diff --git a/src/pages/AboutSettings.tsx b/src/pages/AboutSettings.tsx index 837cab14..296ee731 100644 --- a/src/pages/AboutSettings.tsx +++ b/src/pages/AboutSettings.tsx @@ -1,13 +1,17 @@ import { useState, useEffect } from 'react'; +import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Info, ExternalLink, Loader2, AlertTriangle } from 'lucide-react'; +import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; +import { useIsMobile } from '@/hooks/useIsMobile'; export function AboutSettings() { const { t } = useTranslation(); + const navigate = useNavigate(); + const isMobile = useIsMobile(); const [license, setLicense] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); @@ -39,15 +43,40 @@ export function AboutSettings() { return (
-
-

- - {t('aboutShakespeare')} -

-

- {t('aboutShakespeareDescription')} -

-
+ {isMobile && ( +
+ +
+

+ + {t('aboutShakespeare')} +

+

+ {t('aboutShakespeareDescription')} +

+
+
+ )} + + {!isMobile && ( +
+

+ + {t('aboutShakespeare')} +

+

+ {t('aboutShakespeareDescription')} +

+
+ )}
{/* Project Information */} diff --git a/src/pages/DataSettings.tsx b/src/pages/DataSettings.tsx index 568a22c3..ef439a26 100644 --- a/src/pages/DataSettings.tsx +++ b/src/pages/DataSettings.tsx @@ -1,13 +1,14 @@ import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Download, Trash2, AlertTriangle, Loader2, Database, Info } from 'lucide-react'; +import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { Progress } from '@/components/ui/progress'; import { useToast } from '@/hooks/useToast'; import { useFS } from '@/hooks/useFS'; +import { useIsMobile } from '@/hooks/useIsMobile'; import JSZip from 'jszip'; interface StorageUsageDetails { @@ -32,6 +33,7 @@ export function DataSettings() { const { toast } = useToast(); const { fs } = useFS(); const navigate = useNavigate(); + const isMobile = useIsMobile(); // Format bytes to human readable format const formatBytes = (bytes: number): string => { @@ -196,15 +198,40 @@ export function DataSettings() { return (
-
-

- - {t('dataSettings')} -

-

- {t('dataSettingsDescriptionLong')} -

-
+ {isMobile && ( +
+ +
+

+ + {t('dataSettings')} +

+

+ {t('dataSettingsDescriptionLong')} +

+
+
+ )} + + {!isMobile && ( +
+

+ + {t('dataSettings')} +

+

+ {t('dataSettingsDescriptionLong')} +

+
+ )}
{/* Storage Information */} diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 8e6bec0b..0c99ee16 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -127,8 +127,6 @@ export default function Index() { } }; - - const headerContent = null; return ( From 6d4964858053af8082bee6364960f8dd2b4c196e Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 06:34:45 +0000 Subject: [PATCH 05/11] simplify agents.md entry --- AGENTS.md | 74 ------------------------------------------------------- 1 file changed, 74 deletions(-) diff --git a/AGENTS.md b/AGENTS.md index 6b387b7b..d4cf2f37 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -160,80 +160,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3. - **TanStack Query**: For data fetching, caching, and state management - **TypeScript**: For type-safe JavaScript development -## Project Import - -Shakespeare supports importing existing projects from ZIP files through the main interface: - -### ZIP Import Feature - -- **Location**: Available in the sidebar under the "New Project" expand menu, below "Import Repository" -- **Function**: Upload ZIP files containing project source code with drag & drop support -- **Auto-setup**: Automatically extracts files, sets up Git repository, and creates project structure -- **Drag & Drop**: Intuitive drag and drop interface with click-to-browse fallback -- **Custom IDs**: Option to specify custom project ID or auto-generate from filename -- **Project Overwrite**: Allows overwriting existing projects with clear warnings and confirmation -- **Error Handling**: Validates ZIP files and provides clear error messages -- **Progress Tracking**: Shows import progress with visual feedback - -### ZIP Import Process - -1. Click the "New Project" button in the sidebar -2. Click the dropdown arrow (▼) to expand the menu -3. Select "Import ZIP File" from the dropdown options -4. **Upload Methods**: - - **Drag & Drop**: Drag your ZIP file directly onto the drop zone - - **Click to Browse**: Click the drop zone to open file selector -5. Review the selected file (name and size displayed) -6. Optionally specify a custom project ID (auto-generated from filename if empty) -7. **Overwrite Detection**: If project ID already exists, warning appears with option to overwrite -8. **Overwrite Confirmation**: Detailed confirmation dialog explains what will be preserved/deleted -9. Click "Import Project" or "Overwrite Project" to begin the import process -10. Wait for the import to complete (progress bar shows extraction and setup) -11. The imported project will be automatically available in the project list - -### ZIP File Requirements - -- Must be a valid ZIP archive -- Can contain any project structure (React, Node.js, static sites, etc.) -- Directory structure is preserved during import -- Maximum recommended file size: 50MB -- Existing `.git` directories are preserved if present -- New Git repository is initialized if no `.git` directory exists -- `.ai/` directory is automatically created for Shakespeare functionality - -### Project Overwrite Feature - -When importing a project with an ID that already exists: - -**What Gets Preserved:** -- **Git History**: All existing commits and repository history are maintained -- **AI Chat History**: All chat sessions and conversation data are preserved -- **Project Settings**: Configuration and metadata remain intact - -**What Gets Replaced:** -- **All Project Files**: Every file in the project directory is replaced with ZIP contents -- **Directory Structure**: New directory structure from ZIP replaces existing structure -- **Git Commit**: New commit is created documenting the overwrite action - -**Confirmation Process:** -1. Clear warning appears when duplicate project ID is detected -2. Detailed confirmation dialog lists exactly what will happen -3. User must explicitly confirm the overwrite action -4. Process cannot be undone once confirmed - -**Use Cases:** -- **Project Updates**: Import newer version of existing project -- **Template Refresh**: Update project with latest template changes -- **Migration**: Move project from different development environment - -### Integration with Existing Features - -- **Project Management**: Imported projects appear alongside AI-created projects -- **Git Integration**: Preserves existing Git history or initializes new repository -- **AI Chat**: Full AI assistance available for imported projects -- **File Operations**: All file operations work normally with imported projects -- **Build System**: Projects can be built and deployed normally - ## Project Structure - `/src/components/`: UI components including NostrProvider for Nostr integration From 797984c5d32e0dadd7ff964ce23be0f86a58531d Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 06:38:53 +0000 Subject: [PATCH 06/11] Revert "Restore mobile back buttons and clean up branch" This reverts commit 4d6bc91650b9f2f60bb0161b29dfdd434680c399. --- src/pages/AboutSettings.tsx | 49 ++++++++----------------------------- src/pages/DataSettings.tsx | 47 ++++++++--------------------------- src/pages/Index.tsx | 2 ++ 3 files changed, 22 insertions(+), 76 deletions(-) diff --git a/src/pages/AboutSettings.tsx b/src/pages/AboutSettings.tsx index 296ee731..837cab14 100644 --- a/src/pages/AboutSettings.tsx +++ b/src/pages/AboutSettings.tsx @@ -1,17 +1,13 @@ import { useState, useEffect } from 'react'; -import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react'; +import { Info, ExternalLink, Loader2, AlertTriangle } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; -import { useIsMobile } from '@/hooks/useIsMobile'; export function AboutSettings() { const { t } = useTranslation(); - const navigate = useNavigate(); - const isMobile = useIsMobile(); const [license, setLicense] = useState(null); const [isLoading, setIsLoading] = useState(true); const [error, setError] = useState(null); @@ -43,40 +39,15 @@ export function AboutSettings() { return (
- {isMobile && ( -
- -
-

- - {t('aboutShakespeare')} -

-

- {t('aboutShakespeareDescription')} -

-
-
- )} - - {!isMobile && ( -
-

- - {t('aboutShakespeare')} -

-

- {t('aboutShakespeareDescription')} -

-
- )} +
+

+ + {t('aboutShakespeare')} +

+

+ {t('aboutShakespeareDescription')} +

+
{/* Project Information */} diff --git a/src/pages/DataSettings.tsx b/src/pages/DataSettings.tsx index ef439a26..568a22c3 100644 --- a/src/pages/DataSettings.tsx +++ b/src/pages/DataSettings.tsx @@ -1,14 +1,13 @@ import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } from 'lucide-react'; +import { Download, Trash2, AlertTriangle, Loader2, Database, Info } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { Progress } from '@/components/ui/progress'; import { useToast } from '@/hooks/useToast'; import { useFS } from '@/hooks/useFS'; -import { useIsMobile } from '@/hooks/useIsMobile'; import JSZip from 'jszip'; interface StorageUsageDetails { @@ -33,7 +32,6 @@ export function DataSettings() { const { toast } = useToast(); const { fs } = useFS(); const navigate = useNavigate(); - const isMobile = useIsMobile(); // Format bytes to human readable format const formatBytes = (bytes: number): string => { @@ -198,40 +196,15 @@ export function DataSettings() { return (
- {isMobile && ( -
- -
-

- - {t('dataSettings')} -

-

- {t('dataSettingsDescriptionLong')} -

-
-
- )} - - {!isMobile && ( -
-

- - {t('dataSettings')} -

-

- {t('dataSettingsDescriptionLong')} -

-
- )} +
+

+ + {t('dataSettings')} +

+

+ {t('dataSettingsDescriptionLong')} +

+
{/* Storage Information */} diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 0c99ee16..8e6bec0b 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -127,6 +127,8 @@ export default function Index() { } }; + + const headerContent = null; return ( From 57e12261af2cb20d1853fdbd36b61cd696203dd7 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 06:39:11 +0000 Subject: [PATCH 07/11] clean up index spaces --- src/pages/Index.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 8e6bec0b..0c99ee16 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -127,8 +127,6 @@ export default function Index() { } }; - - const headerContent = null; return ( From 588e32a43dbf4e251019cf0f469351432a1650cb Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 06:52:47 +0000 Subject: [PATCH 08/11] remove custom id logic --- src/components/ProjectSidebar.tsx | 4 ++-- src/lib/ProjectsManager.test.ts | 8 ++++---- src/lib/ProjectsManager.ts | 28 +++++++++++++--------------- src/pages/Index.tsx | 9 +++------ 4 files changed, 22 insertions(+), 27 deletions(-) diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 3d6782a0..03be8a67 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -123,10 +123,10 @@ export function ProjectSidebar({ } }; - const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { + const handleImportZip = async (file: File, overwrite = false) => { try { // Import project from zip file - const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); + const project = await projectsManager.importProjectFromZip(file, overwrite); // Show success toast toast({ diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 3ae4deef..75b3494d 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -211,8 +211,8 @@ describe('ProjectsManager', () => { // Replace git instance Object.assign(projectsManager, { git: mockGit }); - // Create a mock ZIP file with different name - const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' }); + // Create a mock ZIP file with same name to trigger overwrite + const zipFile = new File(['test content'], 'my-project.zip', { type: 'application/zip' }); // Mock arrayBuffer method Object.defineProperty(zipFile, 'arrayBuffer', { @@ -221,7 +221,7 @@ describe('ProjectsManager', () => { }); // Import with overwrite - const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true); + const project = await projectsManager.importProjectFromZip(zipFile, true); // Should preserve original project name expect(project.name).toBe('my-project'); @@ -254,7 +254,7 @@ describe('ProjectsManager', () => { }); // Import without overwrite - const project = await projectsManager.importProjectFromZip(zipFile, undefined, false); + const project = await projectsManager.importProjectFromZip(zipFile, false); // Should use formatted name from ID expect(project.name).toBe('new-project'); diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 79963a49..68e34f5f 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -38,8 +38,8 @@ export class ProjectsManager { } } - async createProject(name: string, customId?: string): Promise { - const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 }); + async createProject(name: string): Promise { + const project = await this.cloneProject(name, GIT_TEMPLATE_URL, { depth: 1 }); try { await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true }); @@ -92,21 +92,24 @@ export class ProjectsManager { return project; } - async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise { - // Generate a project ID based on the zip file name or use custom ID + async importProjectFromZip(zipFile: File, overwrite = false): Promise { + // Generate a project ID based on the zip file name const baseName = zipFile.name.replace(/\.zip$/i, ''); const generatedId = baseName .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); + // Check if a project with the generated ID already exists + const existingProjectExists = await this.projectExists(generatedId); + // Determine the project ID to use let id: string; - if (customId) { - // Use the provided custom ID (for overwrite scenarios) - id = customId; + if (overwrite && existingProjectExists) { + // Use the existing project ID for overwrite + id = generatedId; } else { - // If no custom ID, generate a unique ID (for new projects) + // Generate a unique ID for new projects id = await this.generateUniqueProjectId(generatedId); } @@ -269,13 +272,8 @@ export class ProjectsManager { } } - async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise { - const id = customId || await this.generateUniqueProjectId(name); - - // Check if project with this ID already exists when using custom ID - if (customId && await this.projectExists(id)) { - throw new Error(`Project with ID "${id}" already exists`); - } + async cloneProject(name: string, repoUrl: string, options?: { depth?: number }): Promise { + const id = await this.generateUniqueProjectId(name); const projectPath = `${this.dir}/${id}`; diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 0c99ee16..acb2e47a 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -26,7 +26,7 @@ export default function Index() { const navigate = useNavigate(); const projectsManager = useProjectsManager(); const { fs } = useFS(); - const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId(); + const { isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId(); const { settings, addRecentlyUsedModel } = useAISettings(); const { toast } = useToast(); const [providerModel, setProviderModel] = useState(() => { @@ -91,14 +91,11 @@ export default function Index() { setIsCreating(true); try { - // Use AI to generate project ID - const projectId = await generateProjectId(providerModel, prompt.trim()); - // Add model to recently used when creating project with AI addRecentlyUsedModel(providerModel.trim()); - // Create project with AI-generated ID - const project = await projectsManager.createProject(prompt.trim(), projectId); + // Create project + const project = await projectsManager.createProject(prompt.trim()); // Store the initial message in chat history using DotAI const dotAI = new DotAI(fs, `/projects/${project.id}`); From adeb3bf53f154ecb4acea964839ef4b9f29a2930 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Sat, 20 Sep 2025 06:57:24 +0000 Subject: [PATCH 09/11] Revert "remove custom id logic" This reverts commit 588e32a43dbf4e251019cf0f469351432a1650cb. --- src/components/ProjectSidebar.tsx | 4 ++-- src/lib/ProjectsManager.test.ts | 8 ++++---- src/lib/ProjectsManager.ts | 28 +++++++++++++++------------- src/pages/Index.tsx | 9 ++++++--- 4 files changed, 27 insertions(+), 22 deletions(-) diff --git a/src/components/ProjectSidebar.tsx b/src/components/ProjectSidebar.tsx index 03be8a67..3d6782a0 100644 --- a/src/components/ProjectSidebar.tsx +++ b/src/components/ProjectSidebar.tsx @@ -123,10 +123,10 @@ export function ProjectSidebar({ } }; - const handleImportZip = async (file: File, overwrite = false) => { + const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { try { // Import project from zip file - const project = await projectsManager.importProjectFromZip(file, overwrite); + const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); // Show success toast toast({ diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 75b3494d..3ae4deef 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -211,8 +211,8 @@ describe('ProjectsManager', () => { // Replace git instance Object.assign(projectsManager, { git: mockGit }); - // Create a mock ZIP file with same name to trigger overwrite - const zipFile = new File(['test content'], 'my-project.zip', { type: 'application/zip' }); + // Create a mock ZIP file with different name + const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' }); // Mock arrayBuffer method Object.defineProperty(zipFile, 'arrayBuffer', { @@ -221,7 +221,7 @@ describe('ProjectsManager', () => { }); // Import with overwrite - const project = await projectsManager.importProjectFromZip(zipFile, true); + const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true); // Should preserve original project name expect(project.name).toBe('my-project'); @@ -254,7 +254,7 @@ describe('ProjectsManager', () => { }); // Import without overwrite - const project = await projectsManager.importProjectFromZip(zipFile, false); + const project = await projectsManager.importProjectFromZip(zipFile, undefined, false); // Should use formatted name from ID expect(project.name).toBe('new-project'); diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 68e34f5f..79963a49 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -38,8 +38,8 @@ export class ProjectsManager { } } - async createProject(name: string): Promise { - const project = await this.cloneProject(name, GIT_TEMPLATE_URL, { depth: 1 }); + async createProject(name: string, customId?: string): Promise { + const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 }); try { await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true }); @@ -92,24 +92,21 @@ export class ProjectsManager { return project; } - async importProjectFromZip(zipFile: File, overwrite = false): Promise { - // Generate a project ID based on the zip file name + async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise { + // Generate a project ID based on the zip file name or use custom ID const baseName = zipFile.name.replace(/\.zip$/i, ''); const generatedId = baseName .toLowerCase() .replace(/[^a-z0-9]+/g, '-') .replace(/^-+|-+$/g, ''); - // Check if a project with the generated ID already exists - const existingProjectExists = await this.projectExists(generatedId); - // Determine the project ID to use let id: string; - if (overwrite && existingProjectExists) { - // Use the existing project ID for overwrite - id = generatedId; + if (customId) { + // Use the provided custom ID (for overwrite scenarios) + id = customId; } else { - // Generate a unique ID for new projects + // If no custom ID, generate a unique ID (for new projects) id = await this.generateUniqueProjectId(generatedId); } @@ -272,8 +269,13 @@ export class ProjectsManager { } } - async cloneProject(name: string, repoUrl: string, options?: { depth?: number }): Promise { - const id = await this.generateUniqueProjectId(name); + async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise { + const id = customId || await this.generateUniqueProjectId(name); + + // Check if project with this ID already exists when using custom ID + if (customId && await this.projectExists(id)) { + throw new Error(`Project with ID "${id}" already exists`); + } const projectPath = `${this.dir}/${id}`; diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index acb2e47a..0c99ee16 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -26,7 +26,7 @@ export default function Index() { const navigate = useNavigate(); const projectsManager = useProjectsManager(); const { fs } = useFS(); - const { isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId(); + const { generateProjectId, isLoading: isGeneratingId, isConfigured: isAIConfigured } = useAIProjectId(); const { settings, addRecentlyUsedModel } = useAISettings(); const { toast } = useToast(); const [providerModel, setProviderModel] = useState(() => { @@ -91,11 +91,14 @@ export default function Index() { setIsCreating(true); try { + // Use AI to generate project ID + const projectId = await generateProjectId(providerModel, prompt.trim()); + // Add model to recently used when creating project with AI addRecentlyUsedModel(providerModel.trim()); - // Create project - const project = await projectsManager.createProject(prompt.trim()); + // Create project with AI-generated ID + const project = await projectsManager.createProject(prompt.trim(), projectId); // Store the initial message in chat history using DotAI const dotAI = new DotAI(fs, `/projects/${project.id}`); From ce4a6022702248657f2d2269788258f7aad5b3a3 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 25 Sep 2025 02:42:46 +0000 Subject: [PATCH 10/11] Add check to verify extracted zip paths are within project directory. --- src/lib/ProjectsManager.test.ts | 77 +++++++++++++++++++++++++++++++ src/lib/ProjectsManager.ts | 82 +++++++++++++++++++++++++++++---- src/pages/Index.tsx | 3 +- 3 files changed, 151 insertions(+), 11 deletions(-) diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 87b041e5..85cf1253 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -361,6 +361,83 @@ describe('ProjectsManager', () => { expect(project.name).toBe('new-project'); expect(project.id).toBe('new-project'); }); + + it('should prevent zip slip attacks during import', async () => { + await projectsManager.init(); + + // Mock the git methods + const mockGit = { + init: vi.fn(), + clone: vi.fn(), + add: vi.fn(), + commit: vi.fn(), + getConfig: vi.fn(), + getAllFiles: vi.fn().mockResolvedValue([]), + } as Partial; + + // Replace git instance + Object.assign(projectsManager, { git: mockGit }); + + // Create a mock ZIP file that would try to escape the project directory + const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' }); + + // Mock JSZip to simulate a malicious ZIP with path traversal + const JSZip = await import('jszip'); + + const mockLoadAsync = vi.fn().mockResolvedValue({ + files: { + '../../../etc/passwd': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])) + }, + '../../outside.txt': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])) + }, + 'safe-file.txt': { + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])) + } + } + }); + + vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync); + + // Mock arrayBuffer method + Object.defineProperty(zipFile, 'arrayBuffer', { + value: () => Promise.resolve(new ArrayBuffer(0)), + writable: false + }); + + // Spy on console.warn to check for security warnings + const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); + + try { + // Import the malicious ZIP + const project = await projectsManager.importProjectFromZip(zipFile, undefined, false); + + // Should have completed successfully (safe files extracted) + expect(project).toBeDefined(); + + // Should have logged a security warning about skipped files + expect(consoleSpy).toHaveBeenCalledWith( + expect.stringContaining('Skipped 2 files due to security concerns'), + ['../../../etc/passwd', '../../outside.txt'] + ); + + // Verify that only safe files would be written (check writeFile calls) + const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || []; + const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) => + call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt') + ); + expect(maliciousPaths).toHaveLength(0); + + } finally { + // Restore mocks + consoleSpy.mockRestore(); + vi.restoreAllMocks(); + } + }); }); describe('renameProject', () => { diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index f6faa22b..2bc8bd3d 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -154,32 +154,41 @@ export class ProjectsManager { const arrayBuffer = await zipFile.arrayBuffer(); const zip = await JSZip.loadAsync(arrayBuffer); - // Extract all files from the zip - const files = Object.keys(zip.files); + // Extract all files from the zip with security validation + const extractedFiles: string[] = []; + const skippedFiles: string[] = []; - for (const filePath of files) { - const zipEntry = zip.files[filePath]; + for (const [relativePath, zipEntry] of Object.entries(zip.files)) { + // Validate the extraction path is within the project directory + const extractPath = this.join(projectPath, relativePath); + + if (!this.isPathWithinProject(extractPath, projectPath)) { + skippedFiles.push(relativePath); + continue; + } - // Skip directories (they end with / in JSZip) if (zipEntry.dir) { // Create the directory structure - const dirPath = `${projectPath}/${filePath}`; - await this.fs.mkdir(dirPath, { recursive: true }); + await this.fs.mkdir(extractPath, { recursive: true }); continue; } // Extract file content const content = await zipEntry.async('uint8array'); - const fullPath = `${projectPath}/${filePath}`; // Ensure parent directory exists - const dirPath = fullPath.split('/').slice(0, -1).join('/'); + const dirPath = extractPath.split('/').slice(0, -1).join('/'); if (dirPath) { await this.fs.mkdir(dirPath, { recursive: true }); } // Write the file (this will overwrite existing files) - await this.fs.writeFile(fullPath, content); + await this.fs.writeFile(extractPath, content); + extractedFiles.push(relativePath); + } + + if (skippedFiles.length > 0) { + console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project direcotry:`, skippedFiles); } // Get filesystem stats for timestamps @@ -580,4 +589,57 @@ export class ProjectsManager { return files; } + + /** + * Safe path join that normalizes the result to prevent directory traversal + */ + private join(...paths: string[]): string { + // Simple path joining with normalization + const joined = paths.join('/').replace(/\/+/g, '/'); + + // Normalize path separators and resolve .. and . components + const parts = joined.split('/').filter(part => part !== ''); + const normalized: string[] = []; + + for (const part of parts) { + if (part === '..') { + normalized.pop(); + } else if (part !== '.') { + normalized.push(part); + } + } + + return '/' + normalized.join('/'); + } + + /** + * Check if a path is within the project directory + */ + private isPathWithinProject(extractPath: string, projectPath: string): boolean { + // Normalize both paths + const normalizedExtractPath = this.normalize(extractPath); + const normalizedProjectPath = this.normalize(projectPath); + + // Check if the extract path starts with the project path + return normalizedExtractPath.startsWith(normalizedProjectPath + '/') || + normalizedExtractPath === normalizedProjectPath; + } + + /** + * Normalize a path by resolving . and .. components + */ + private normalize(path: string): string { + const parts = path.split('/').filter(part => part !== ''); + const normalized: string[] = []; + + for (const part of parts) { + if (part === '..') { + normalized.pop(); + } else if (part !== '.') { + normalized.push(part); + } + } + + return '/' + normalized.join('/'); + } } \ No newline at end of file diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 85c8e8ac..a0c39678 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -261,12 +261,13 @@ export default function Index() { navigate(`/project/${project.id}?${searchParams.toString()}`); } catch (error) { console.error('Failed to create project:', error); - checkForKeyFailure(error) || + if (!checkForKeyFailure(error)) { toast({ title: "Project Creation Failed", description: error instanceof Error ? error.message : "An unexpected error occurred", variant: "destructive", }); + } } finally { setIsCreating(false); } From ad5902cdc66e09cfd4e5babc036c536459bd4f77 Mon Sep 17 00:00:00 2001 From: Chad Curtis Date: Thu, 25 Sep 2025 02:48:32 +0000 Subject: [PATCH 11/11] test fix --- src/lib/ProjectsManager.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index 85cf1253..f823c200 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -421,7 +421,7 @@ describe('ProjectsManager', () => { // Should have logged a security warning about skipped files expect(consoleSpy).toHaveBeenCalledWith( - expect.stringContaining('Skipped 2 files due to security concerns'), + expect.stringContaining('Skipped 2 files due to resolving to paths outside the project direcotry:'), ['../../../etc/passwd', '../../outside.txt'] );