mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 00:03:35 +00:00
Compare commits
43
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f09f1436ae | ||
|
|
374d2804ad | ||
|
|
c0f906ae7e | ||
|
|
92e2ac1ce5 | ||
|
|
e81fb33ffe | ||
|
|
9a65d5d086 | ||
|
|
61d5a5fefc | ||
|
|
75e961d281 | ||
|
|
93e992f128 | ||
|
|
7ab30af944 | ||
|
|
6296fc4366 | ||
|
|
147c7cdf3a | ||
|
|
18a276a44e | ||
|
|
a20bbfdf29 | ||
|
|
980cb60f1b | ||
|
|
2956c86f88 | ||
|
|
c46077af67 | ||
|
|
ad5902cdc6 | ||
|
|
ce4a602270 | ||
|
|
5e352e60e9 | ||
|
|
37147a69d4 | ||
|
|
4f9d3ae1d1 | ||
|
|
fdfdcb4b16 | ||
|
|
50e16e1b57 | ||
|
|
662f95d35d | ||
|
|
458eec0e27 | ||
|
|
74e472338d | ||
|
|
2b5e3013ff | ||
|
|
951eefb7b8 | ||
|
|
a68d37452b | ||
|
|
c8653e67dc | ||
|
|
660f25656c | ||
|
|
804efb4d23 | ||
|
|
8108407478 | ||
|
|
adeb3bf53f | ||
|
|
588e32a43d | ||
|
|
57e12261af | ||
|
|
797984c5d3 | ||
|
|
6d49648580 | ||
|
|
4d6bc91650 | ||
|
|
2fdf8a3740 | ||
|
|
f4ccc2d924 | ||
|
|
6f4aa264eb |
No files matched your search
@@ -51,6 +51,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
@@ -168,6 +169,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 +185,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
|
||||
|
||||
+19
-16
@@ -16,6 +16,7 @@ import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleProvider } from '@/contexts/ConsoleContext';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
|
||||
@@ -73,22 +74,24 @@ export function App() {
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
<ConsoleProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -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<string[]>('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, overwrite = false, projectId?: string) => {
|
||||
try {
|
||||
// Import project from zip file
|
||||
const project = await projectsManager.importProjectFromZip(file, projectId, 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({
|
||||
<GitBranch className="h-4 w-4" />
|
||||
{t('importRepository')}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setIsZipDialogOpen(true)}
|
||||
className="flex items-center gap-2 w-full"
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP File
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
@@ -248,6 +280,13 @@ export function ProjectSidebar({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ZipImportDialog
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -7,6 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
import { useState } from 'react';
|
||||
|
||||
export interface QuillyProps {
|
||||
@@ -14,6 +15,7 @@ export interface QuillyProps {
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
providerModel: string;
|
||||
}
|
||||
|
||||
@@ -25,7 +27,7 @@ interface ErrorBody {
|
||||
};
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, providerModel }: QuillyProps) {
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
const { provider } = parseProviderModel(providerModel, settings.providers);
|
||||
@@ -33,6 +35,20 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, provi
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error): ErrorBody => {
|
||||
// Handle Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
|
||||
action: {
|
||||
label: 'Help fix errors',
|
||||
onClick: () => {
|
||||
onRequestConsoleErrorHelp?.(error);
|
||||
onDismiss();
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Handle OpenAI API errors with specific error codes
|
||||
if (error instanceof OpenAI.APIError) {
|
||||
switch (error.code) {
|
||||
|
||||
@@ -34,6 +34,8 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useConsole, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
@@ -74,6 +76,22 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
|
||||
// Get console functionality early so it can be used in useEffect
|
||||
const { messagesRef: consoleMessagesRef, addErrorListener, removeErrorListener } = useConsole();
|
||||
|
||||
// Console error handling
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
// Only show console errors if there's no existing AI error
|
||||
if (!aiError) {
|
||||
setAIError(error);
|
||||
}
|
||||
};
|
||||
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, [aiError, addErrorListener, removeErrorListener]);
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
@@ -123,6 +141,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
read_console_messages: new ReadConsoleMessagesTool(() => consoleMessagesRef.current),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
@@ -134,7 +153,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId]);
|
||||
}, [fs, git, cwd, user, projectId, consoleMessagesRef]);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
@@ -187,6 +206,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onAIError,
|
||||
});
|
||||
|
||||
// Handle console error help requests
|
||||
const handleConsoleErrorHelp = useCallback(() => {
|
||||
sendMessage('Read the console messages and fix any errors present.', providerModel);
|
||||
}, [sendMessage, providerModel]);
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||
|
||||
@@ -596,6 +620,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onDismiss={() => setAIError(null)}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
)}
|
||||
|
||||
@@ -3,12 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages';
|
||||
import { useConsole, type ConsoleMessage } from '@/contexts/ConsoleContext';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
@@ -18,7 +18,12 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
@@ -66,7 +71,6 @@ interface JSONRPCResponse {
|
||||
id: number;
|
||||
}
|
||||
|
||||
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
@@ -78,12 +82,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
|
||||
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { messages: consoleMessages } = useConsoleMessages();
|
||||
const { addMessage: addConsoleMessage, messages: consoleMessages } = useConsole();
|
||||
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -211,12 +216,12 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
normalizedLevel = params.level as ConsoleMessage['level'];
|
||||
}
|
||||
|
||||
// Add to global console messages
|
||||
// Add to console messages
|
||||
addConsoleMessage(normalizedLevel, params.message);
|
||||
|
||||
// Log to parent console for debugging with appropriate level
|
||||
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
|
||||
}, []);
|
||||
}, [addConsoleMessage]);
|
||||
|
||||
const handleUpdateNavigationState = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
@@ -303,8 +308,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const { params, id } = request;
|
||||
const { request: fetchRequest } = params;
|
||||
|
||||
|
||||
|
||||
try {
|
||||
// Parse the URL and validate origin
|
||||
const url = new URL(fetchRequest.url);
|
||||
@@ -368,9 +371,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// For non-static assets, try SPA fallback to index.html
|
||||
|
||||
}
|
||||
|
||||
// SPA fallback: serve index.html for non-file requests (SPA routing)
|
||||
@@ -393,8 +393,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
});
|
||||
} catch {
|
||||
// Even index.html doesn't exist
|
||||
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
@@ -503,98 +501,101 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
};
|
||||
|
||||
const ConsoleDropdown = () => {
|
||||
const getLevelColor = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return 'text-red-500';
|
||||
case 'warn': return 'text-yellow-500';
|
||||
case 'info': return 'text-blue-500';
|
||||
case 'debug': return 'text-gray-500';
|
||||
default: return 'text-gray-400';
|
||||
}
|
||||
};
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
|
||||
const getLevelIcon = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return '!';
|
||||
case 'warn': return '⚠';
|
||||
case 'info': return 'ℹ';
|
||||
case 'debug': return '🔍';
|
||||
default: return '•';
|
||||
}
|
||||
};
|
||||
|
||||
const clearConsole = () => {
|
||||
clearConsoleMessages();
|
||||
};
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
// Create a formatted string with all message details
|
||||
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
|
||||
|
||||
await navigator.clipboard.writeText(formattedMessage);
|
||||
setCopiedMessageId(msg.id);
|
||||
|
||||
// Reset the copied state after 2 seconds
|
||||
setTimeout(() => {
|
||||
setCopiedMessageId(null);
|
||||
}, 2000);
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
setCopiedMessageIndex(index);
|
||||
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// consoleMessages is now available from the hook
|
||||
const messageCount = consoleMessages.length;
|
||||
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 relative hover:bg-accent hover:text-accent-foreground transition-colors"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{consoleMessages.some(msg => msg.level === 'error') && (
|
||||
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
|
||||
{hasErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
|
||||
<div className="flex items-center justify-between p-2 border-b">
|
||||
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
|
||||
<Button variant="ghost" size="sm" onClick={clearConsole}>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
|
||||
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
|
||||
{consoleMessages.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground text-sm py-4">
|
||||
No console messages
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
|
||||
sideOffset={4}
|
||||
>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||
<div className="py-2 px-1 space-y-0">
|
||||
{messageCount === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
consoleMessages.map((msg) => (
|
||||
consoleMessages.map((msg, index) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between w-full">
|
||||
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copyMessageToClipboard(msg)}
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
|
||||
>
|
||||
{copiedMessageId === msg.id ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
<div className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||
msg.level === 'error' ? "text-destructive" :
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
)}>
|
||||
{msg.message}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||
>
|
||||
{copiedMessageIndex === index ? (
|
||||
<Check className="h-2 w-2 text-success" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
|
||||
>
|
||||
<X className="h-5 w-5 text-muted-foreground" />
|
||||
</button>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -613,7 +614,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuContent align="end" className="w-48 sm:w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
|
||||
@@ -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(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens dialog when trigger is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
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(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// 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(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// 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(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// 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(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// 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(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// 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();
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,397 @@
|
||||
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, overwrite?: boolean, projectId?: string) => Promise<void>;
|
||||
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<File | null>(null);
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
|
||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(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 ID from file name
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setGeneratedId(id);
|
||||
};
|
||||
|
||||
// Check for existing project when generated ID changes
|
||||
useEffect(() => {
|
||||
if (generatedId && projects.length > 0) {
|
||||
const existing = projects.find(project => project.id === generatedId);
|
||||
setExistingProject(existing || null);
|
||||
} else {
|
||||
setExistingProject(null);
|
||||
}
|
||||
}, [generatedId, 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);
|
||||
setGeneratedId('');
|
||||
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, overwrite, generatedId);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
|
||||
// Close dialog after a short delay
|
||||
setTimeout(() => {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
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 || !generatedId) 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);
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
// (no open/onOpenChange props provided)
|
||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn("gap-2", className)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent
|
||||
className="sm:max-w-md"
|
||||
onDragOver={handleDragOverDialog}
|
||||
onDragLeave={handleDragLeaveDialog}
|
||||
onDrop={handleDropDialog}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Project from ZIP
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Upload a ZIP file containing your project source code to import it into Shakespeare.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{!isImporting && (
|
||||
<>
|
||||
{/* Drag and Drop Area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||
)}
|
||||
onClick={handleClickUpload}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}}
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
disabled={isImporting}
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
<FileText className="h-8 w-8 text-green-600" />
|
||||
) : (
|
||||
<Upload className="h-8 w-8 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-green-600">
|
||||
{selectedFile.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop your ZIP file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Supports ZIP files up to 50MB
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Overwrite Warning */}
|
||||
{existingProject && (
|
||||
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
A project with this ID already exists. You can choose to overwrite it.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!selectedFile || !generatedId || isImporting}
|
||||
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{existingProject ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Overwrite Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Project
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Import Progress */}
|
||||
{isImporting && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||
Importing project...
|
||||
</div>
|
||||
<Progress value={importProgress} className="w-full" />
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Extracting files and setting up project...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success State */}
|
||||
{!isImporting && importProgress === 100 && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
Project imported successfully!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Overwrite Confirmation Dialog */}
|
||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||
Overwrite Existing Project
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-2">
|
||||
<p>
|
||||
A project with the ID "<strong>{generatedId}</strong>" already exists.
|
||||
Overwriting it will:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in the project</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
<p className="text-amber-600 font-medium">
|
||||
This action cannot be undone. Are you sure you want to continue?
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmOverwrite}
|
||||
className="bg-amber-600 hover:bg-amber-700"
|
||||
>
|
||||
Yes, Overwrite Project
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { ConsoleProvider, useConsole } from './ConsoleContext';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
|
||||
|
||||
// Test wrapper component
|
||||
function TestWrapper({ children }: { children: React.ReactNode }) {
|
||||
return <ConsoleProvider>{children}</ConsoleProvider>;
|
||||
}
|
||||
|
||||
describe('ConsoleContext', () => {
|
||||
it('should provide console functionality', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
expect(result.current.messages).toEqual([]);
|
||||
expect(result.current.messagesRef.current).toEqual([]);
|
||||
expect(typeof result.current.addMessage).toBe('function');
|
||||
expect(typeof result.current.clearMessages).toBe('function');
|
||||
expect(typeof result.current.addErrorListener).toBe('function');
|
||||
expect(typeof result.current.removeErrorListener).toBe('function');
|
||||
});
|
||||
|
||||
it('should add and retrieve messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test log message');
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(2);
|
||||
expect(result.current.messagesRef.current).toHaveLength(2);
|
||||
expect(result.current.messages[0]).toEqual({
|
||||
level: 'log',
|
||||
message: 'Test log message',
|
||||
});
|
||||
expect(result.current.messagesRef.current[0]).toEqual({
|
||||
level: 'log',
|
||||
message: 'Test log message',
|
||||
});
|
||||
expect(result.current.messages[1]).toEqual({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
});
|
||||
expect(result.current.messagesRef.current[1]).toEqual({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test message');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(1);
|
||||
expect(result.current.messagesRef.current).toHaveLength(1);
|
||||
|
||||
act(() => {
|
||||
result.current.clearMessages();
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(0);
|
||||
expect(result.current.messagesRef.current).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should trigger error listener when error message is added', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||
expect(errorListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Console error detected: Test error message',
|
||||
logs: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
}),
|
||||
]),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should not trigger error listener for non-error messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test log message');
|
||||
result.current.addMessage('warn', 'Test warning message');
|
||||
result.current.addMessage('info', 'Test info message');
|
||||
});
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should remove error listener correctly', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
result.current.removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle listener errors gracefully', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const faultyListener = vi.fn(() => {
|
||||
throw new Error('Listener error');
|
||||
});
|
||||
const workingListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(faultyListener);
|
||||
result.current.addErrorListener(workingListener);
|
||||
});
|
||||
|
||||
// Should not throw despite faulty listener
|
||||
expect(() => {
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
expect(faultyListener).toHaveBeenCalled();
|
||||
expect(workingListener).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should throw error when used outside provider', () => {
|
||||
expect(() => {
|
||||
renderHook(() => useConsole());
|
||||
}).toThrow('useConsole must be used within a ConsoleProvider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProjectPreviewConsoleError', () => {
|
||||
it('should create error with console logs', () => {
|
||||
const logs = [{ level: 'error' as const, message: 'Test error' }];
|
||||
const error = new ProjectPreviewConsoleError('Test message', logs);
|
||||
|
||||
expect(error.message).toBe('Test message');
|
||||
expect(error.name).toBe('ProjectPreviewConsoleError');
|
||||
expect(error.logs).toEqual(logs);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import React, { createContext, useContext, useState, useCallback, useRef, ReactNode } from 'react';
|
||||
|
||||
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export { ProjectPreviewConsoleError };
|
||||
|
||||
interface ConsoleContextType {
|
||||
messages: ConsoleMessage[];
|
||||
messagesRef: React.MutableRefObject<ConsoleMessage[]>;
|
||||
addMessage: (level: ConsoleMessage['level'], message: string) => void;
|
||||
clearMessages: () => void;
|
||||
addErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
|
||||
removeErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
|
||||
}
|
||||
|
||||
const ConsoleContext = createContext<ConsoleContextType | undefined>(undefined);
|
||||
|
||||
export function useConsole(): ConsoleContextType {
|
||||
const context = useContext(ConsoleContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useConsole must be used within a ConsoleProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface ConsoleProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ConsoleProvider({ children }: ConsoleProviderProps) {
|
||||
const [messages, setMessages] = useState<ConsoleMessage[]>([]);
|
||||
const messagesRef = useRef<ConsoleMessage[]>([]);
|
||||
const [errorListeners, setErrorListeners] = useState<Array<(error: ProjectPreviewConsoleError) => void>>([]);
|
||||
|
||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
||||
const consoleMessage: ConsoleMessage = {
|
||||
level,
|
||||
message,
|
||||
};
|
||||
|
||||
// Update both state and ref
|
||||
const newMessages = [...messagesRef.current, consoleMessage];
|
||||
messagesRef.current = newMessages;
|
||||
setMessages(newMessages);
|
||||
|
||||
// If this is an error, notify listeners
|
||||
if (level === 'error') {
|
||||
const error = new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${message}`,
|
||||
newMessages.filter(msg => msg.level === 'error')
|
||||
);
|
||||
|
||||
errorListeners.forEach(listener => {
|
||||
try {
|
||||
listener(error);
|
||||
} catch (err) {
|
||||
console.warn('Error listener failed:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [errorListeners]);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
messagesRef.current = [];
|
||||
}, []);
|
||||
|
||||
const addErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
setErrorListeners(prev => [...prev, listener]);
|
||||
}, []);
|
||||
|
||||
const removeErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
setErrorListeners(prev => prev.filter(l => l !== listener));
|
||||
}, []);
|
||||
|
||||
const value: ConsoleContextType = {
|
||||
messages,
|
||||
messagesRef,
|
||||
addMessage,
|
||||
clearMessages,
|
||||
addErrorListener,
|
||||
removeErrorListener,
|
||||
};
|
||||
|
||||
return (
|
||||
<ConsoleContext.Provider value={value}>
|
||||
{children}
|
||||
</ConsoleContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -1,79 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
id: number;
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
// Global state for console messages
|
||||
let globalConsoleMessages: ConsoleMessage[] = [];
|
||||
const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set();
|
||||
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach(listener => listener([...globalConsoleMessages]));
|
||||
};
|
||||
|
||||
export const useConsoleMessages = () => {
|
||||
const [messages, setMessages] = useState<ConsoleMessage[]>(globalConsoleMessages);
|
||||
|
||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(), // Ensure uniqueness
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const getErrorsSince = useCallback((timestamp: number) => {
|
||||
return globalConsoleMessages.filter(
|
||||
msg => msg.level === 'error' && msg.timestamp > timestamp
|
||||
);
|
||||
}, []);
|
||||
|
||||
// Subscribe to global state changes
|
||||
useEffect(() => {
|
||||
const listener = (newMessages: ConsoleMessage[]) => {
|
||||
setMessages(newMessages);
|
||||
};
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
addMessage,
|
||||
clearMessages,
|
||||
getErrorsSince,
|
||||
};
|
||||
};
|
||||
|
||||
// Export functions for external use (like PreviewPane)
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(),
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
};
|
||||
@@ -14,6 +14,27 @@ const createMockNostr = (): NPool => ({
|
||||
close: vi.fn(),
|
||||
}) as unknown as NPool;
|
||||
|
||||
// Mock JSZip
|
||||
vi.mock('jszip', () => ({
|
||||
default: class MockJSZip {
|
||||
files: Record<string, { dir: boolean; async: () => Uint8Array }> = {};
|
||||
|
||||
static async loadAsync(buffer: ArrayBuffer) {
|
||||
const instance = new MockJSZip();
|
||||
// Add a mock file entry
|
||||
instance.files['package.json'] = {
|
||||
dir: false,
|
||||
async: () => new Uint8Array(buffer)
|
||||
};
|
||||
return instance;
|
||||
}
|
||||
|
||||
async file(name: string) {
|
||||
return this.files[name];
|
||||
}
|
||||
}
|
||||
}));
|
||||
|
||||
// Mock filesystem for testing
|
||||
class MockFS implements JSRuntimeFS {
|
||||
private files: Map<string, string | Uint8Array> = new Map();
|
||||
@@ -269,6 +290,156 @@ describe('ProjectsManager', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('importProjectFromZip', () => {
|
||||
it('should preserve original project name when overwriting', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create an existing project with a specific name
|
||||
await fs.mkdir('/projects/my-project');
|
||||
await fs.mkdir('/projects/my-project/.git');
|
||||
await fs.writeFile('/projects/my-project/package.json', '{"name": "original-name"}');
|
||||
|
||||
// Mock the git methods to simulate existing project
|
||||
const mockGit = {
|
||||
init: vi.fn(),
|
||||
clone: vi.fn(),
|
||||
add: vi.fn(),
|
||||
commit: vi.fn(),
|
||||
getConfig: vi.fn(),
|
||||
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// 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' });
|
||||
|
||||
// Mock arrayBuffer method
|
||||
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||
writable: false
|
||||
});
|
||||
|
||||
// Import with overwrite
|
||||
const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true);
|
||||
|
||||
// Should preserve original project name
|
||||
expect(project.name).toBe('my-project');
|
||||
expect(project.id).toBe('my-project');
|
||||
});
|
||||
|
||||
it('should use new project name when not overwriting', 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(['package.json']),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Create a mock ZIP file
|
||||
const zipFile = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Mock arrayBuffer method
|
||||
Object.defineProperty(zipFile, 'arrayBuffer', {
|
||||
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
|
||||
writable: false
|
||||
});
|
||||
|
||||
// Import without overwrite
|
||||
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
|
||||
|
||||
// Should use formatted name from ID
|
||||
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<import('./git').Git>;
|
||||
|
||||
// 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 resolving to paths outside the project direcotry:'),
|
||||
['../../../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', () => {
|
||||
it('should rename a project directory', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
+258
-1
@@ -1,6 +1,8 @@
|
||||
import { Buffer } from 'buffer';
|
||||
import type { Git } from '@/lib/git';
|
||||
import JSZip from 'jszip';
|
||||
import { Git } from '@/lib/git';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { ensurePersistentStorage } from '@/lib/persistentStorage';
|
||||
|
||||
// Polyfill Buffer for browser
|
||||
if (typeof window !== 'undefined') {
|
||||
@@ -92,9 +94,203 @@ export class ProjectsManager {
|
||||
},
|
||||
});
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||
// 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, '');
|
||||
|
||||
// Determine the project ID to use
|
||||
let id: string;
|
||||
if (customId) {
|
||||
// Use the provided custom ID (for overwrite scenarios)
|
||||
id = customId;
|
||||
} else {
|
||||
// If no custom ID, generate a unique ID (for new projects)
|
||||
id = await this.generateUniqueProjectId(generatedId);
|
||||
}
|
||||
|
||||
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`);
|
||||
}
|
||||
|
||||
// Get original project name if overwriting, otherwise use formatted name
|
||||
let projectName: string;
|
||||
if (overwrite && projectExists) {
|
||||
const existingProject = await this.getProject(id);
|
||||
projectName = existingProject?.name || this.formatProjectName(id);
|
||||
} else {
|
||||
projectName = this.formatProjectName(id);
|
||||
}
|
||||
|
||||
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 with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
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;
|
||||
}
|
||||
|
||||
if (zipEntry.dir) {
|
||||
// Create the directory structure
|
||||
await this.fs.mkdir(extractPath, { recursive: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
// Extract file content
|
||||
const content = await zipEntry.async('uint8array');
|
||||
|
||||
// Ensure parent directory exists
|
||||
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(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
|
||||
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: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
} 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: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create .ai/history directory
|
||||
try {
|
||||
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name: projectName,
|
||||
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<Project> {
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
@@ -119,6 +315,14 @@ export class ProjectsManager {
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Automatically request persistent storage after project cloning
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project cloning if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project cloning:', error);
|
||||
}
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
@@ -402,4 +606,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('/');
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ConsoleMessage } from '@/contexts/ConsoleContext';
|
||||
|
||||
/**
|
||||
* Custom error class for project preview console errors
|
||||
*/
|
||||
export class ProjectPreviewConsoleError extends Error {
|
||||
public readonly logs: ConsoleMessage[];
|
||||
|
||||
constructor(message: string, logs: ConsoleMessage[]) {
|
||||
super(message);
|
||||
this.name = 'ProjectPreviewConsoleError';
|
||||
this.logs = logs;
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Data cleared successfully',
|
||||
dataClearedDescription: 'All local data has been removed. Redirecting to homepage...',
|
||||
failedToClearData: 'Failed to clear data',
|
||||
persistData: 'Persist Data',
|
||||
persistDataDescription: 'Request persistent storage to prevent data loss when browser storage is low. This helps protect your projects and settings.',
|
||||
persistentStorageGranted: 'Persistent storage granted',
|
||||
persistentStorageGrantedDescription: 'Your browser will now protect your data from automatic cleanup.',
|
||||
persistentStorageAlreadyGranted: 'Persistent storage already granted',
|
||||
persistentStorageAlreadyGrantedDescription: 'Your data is already protected from automatic cleanup.',
|
||||
persistentStorageDenied: 'Persistent storage request denied',
|
||||
persistentStorageDeniedDescription: 'Your browser declined the request. Data may still be cleared automatically when storage is low.',
|
||||
persistentStorageNotSupported: 'Persistent storage not supported',
|
||||
persistentStorageNotSupportedDescription: 'Your browser does not support persistent storage requests.',
|
||||
failedToRequestPersistentStorage: 'Failed to request persistent storage',
|
||||
|
||||
// 404 Page
|
||||
pageNotFound: 'Oops! Page not found',
|
||||
@@ -534,6 +545,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Dados limpos com sucesso',
|
||||
dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...',
|
||||
failedToClearData: 'Falha ao limpar dados',
|
||||
persistData: 'Persistir Dados',
|
||||
persistDataDescription: 'Solicitar armazenamento persistente para evitar perda de dados quando o armazenamento do navegador estiver baixo. Isso ajuda a proteger seus projetos e configurações.',
|
||||
persistentStorageGranted: 'Armazenamento persistente concedido',
|
||||
persistentStorageGrantedDescription: 'Seu navegador agora protegerá seus dados da limpeza automática.',
|
||||
persistentStorageAlreadyGranted: 'Armazenamento persistente já concedido',
|
||||
persistentStorageAlreadyGrantedDescription: 'Seus dados já estão protegidos da limpeza automática.',
|
||||
persistentStorageDenied: 'Solicitação de armazenamento persistente negada',
|
||||
persistentStorageDeniedDescription: 'Seu navegador recusou a solicitação. Os dados ainda podem ser limpos automaticamente quando o armazenamento estiver baixo.',
|
||||
persistentStorageNotSupported: 'Armazenamento persistente não suportado',
|
||||
persistentStorageNotSupportedDescription: 'Seu navegador não suporta solicitações de armazenamento persistente.',
|
||||
failedToRequestPersistentStorage: 'Falha ao solicitar armazenamento persistente',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Sobre o Shakespeare',
|
||||
@@ -836,6 +858,17 @@ const resources = {
|
||||
dataClearedSuccessfully: '数据清除成功',
|
||||
dataClearedDescription: '所有本地数据已删除。正在重定向到主页...',
|
||||
failedToClearData: '清除数据失败',
|
||||
persistData: '持久化数据',
|
||||
persistDataDescription: '请求持久存储以防止浏览器存储不足时数据丢失。这有助于保护您的项目和设置。',
|
||||
persistentStorageGranted: '已授予持久存储',
|
||||
persistentStorageGrantedDescription: '您的浏览器现在将保护您的数据免受自动清理。',
|
||||
persistentStorageAlreadyGranted: '已授予持久存储',
|
||||
persistentStorageAlreadyGrantedDescription: '您的数据已受到保护,不会被自动清理。',
|
||||
persistentStorageDenied: '持久存储请求被拒绝',
|
||||
persistentStorageDeniedDescription: '您的浏览器拒绝了请求。当存储不足时,数据仍可能被自动清理。',
|
||||
persistentStorageNotSupported: '不支持持久存储',
|
||||
persistentStorageNotSupportedDescription: '您的浏览器不支持持久存储请求。',
|
||||
failedToRequestPersistentStorage: '请求持久存储失败',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: '关于Shakespeare',
|
||||
@@ -1138,6 +1171,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'An share bayanai cikin nasara',
|
||||
dataClearedDescription: 'An cire duk bayanan gida. Ana turawa zuwa shafin gida...',
|
||||
failedToClearData: 'Ya gaza share bayanai',
|
||||
persistData: 'Kiyaye Bayanai',
|
||||
persistDataDescription: 'Nemi ajiyar bayanai ta dindindin don hana asarar bayanai lokacin da ajiyar burauzar ta ragu. Wannan yana taimakawa wajen kare ayyukan ku da saitunan.',
|
||||
persistentStorageGranted: 'An ba da ajiyar ta dindindin',
|
||||
persistentStorageGrantedDescription: 'Burauzar ku yanzu za ta kare bayananku daga share mai sarrafa kansa.',
|
||||
persistentStorageAlreadyGranted: 'An riga an ba da ajiyar ta dindindin',
|
||||
persistentStorageAlreadyGrantedDescription: 'An riga an kare bayananku daga share mai sarrafa kansa.',
|
||||
persistentStorageDenied: 'An ki neman ajiyar ta dindindin',
|
||||
persistentStorageDeniedDescription: 'Burauzar ku ta ki bukatar. Ana iya share bayanai ta atomatik lokacin da ajiya ta ragu.',
|
||||
persistentStorageNotSupported: 'Ba a goyan bayan ajiyar ta dindindin ba',
|
||||
persistentStorageNotSupportedDescription: 'Burauzar ku ba ta goyan bayan bukatun ajiyar ta dindindin ba.',
|
||||
failedToRequestPersistentStorage: 'Ya gaza neman ajiyar ta dindindin',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Game da Shakespeare',
|
||||
@@ -1440,6 +1484,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Data ti nu ni aṣeyọri',
|
||||
dataClearedDescription: 'Gbogbo data agbegbe ti yọ kuro. N ṣe atunṣe si oju-iwe ile...',
|
||||
failedToClearData: 'O kuna lati nu data',
|
||||
persistData: 'Fi Data Pamọ',
|
||||
persistDataDescription: 'Beere ibi ipamọ ti o wa nigbagbogbo lati yago fun isonu data nigbati ibi ipamọ aṣawakiri ba kere. Eyi ṣe iranlọwọ lati daabobo awọn iṣẹ akanṣe ati awọn eto rẹ.',
|
||||
persistentStorageGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni',
|
||||
persistentStorageGrantedDescription: 'Aṣawakiri rẹ yoo daabobo data rẹ lati imukuro adaṣe.',
|
||||
persistentStorageAlreadyGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni tẹlẹ',
|
||||
persistentStorageAlreadyGrantedDescription: 'Data rẹ ti wa ni aabo lati imukuro adaṣe.',
|
||||
persistentStorageDenied: 'Ibeere ibi ipamọ ti o wa nigbagbogbo ti kọ',
|
||||
persistentStorageDeniedDescription: 'Aṣawakiri rẹ ti kọ ibeere naa. Data le tun jẹ imukuro adaṣe nigbati ibi ipamọ ba kere.',
|
||||
persistentStorageNotSupported: 'Ibi ipamọ ti o wa nigbagbogbo ko ni atilẹyin',
|
||||
persistentStorageNotSupportedDescription: 'Aṣawakiri rẹ ko ni atilẹyin awọn ibeere ibi ipamọ ti o wa nigbagbogbo.',
|
||||
failedToRequestPersistentStorage: 'O kuna lati beere ibi ipamọ ti o wa nigbagbogbo',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Nipa Shakespeare',
|
||||
@@ -1737,6 +1792,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Ehichapụrụ data nke ọma',
|
||||
dataClearedDescription: 'Ewepụrụ data mpaghara niile. Na-atụgharị gaa na ibe ụlọ...',
|
||||
failedToClearData: 'O dara ihichapụ data',
|
||||
persistData: 'Chekwaa Data Ogologo Oge',
|
||||
persistDataDescription: 'Rịọ nchekwa na-adịgide adịgide iji gbochie mfu data mgbe nchekwa browser dị ala. Nke a na-enyere aka ichebe ọrụ gị na ntọala.',
|
||||
persistentStorageGranted: 'Enyere nchekwa na-adịgide adịgide',
|
||||
persistentStorageGrantedDescription: 'Browser gị ga-echebe data gị ugbu a site na nhicha akpaaka.',
|
||||
persistentStorageAlreadyGranted: 'Enyerela nchekwa na-adịgide adịgide',
|
||||
persistentStorageAlreadyGrantedDescription: 'Echebeela data gị site na nhicha akpaaka.',
|
||||
persistentStorageDenied: 'Ajụrụ arịrịọ nchekwa na-adịgide adịgide',
|
||||
persistentStorageDeniedDescription: 'Browser gị jụrụ arịrịọ ahụ. Enwere ike ihichapụ data akpaaka mgbe nchekwa dị ala.',
|
||||
persistentStorageNotSupported: 'Akwadoghị nchekwa na-adịgide adịgide',
|
||||
persistentStorageNotSupportedDescription: 'Browser gị akwadoghị arịrịọ nchekwa na-adịgide adịgide.',
|
||||
failedToRequestPersistentStorage: 'O dara ịrịọ nchekwa na-adịgide adịgide',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Gbasara Shakespeare',
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Utility functions for managing persistent storage in the browser
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks if persistent storage is supported by the browser
|
||||
*/
|
||||
export function isPersistentStorageSupported(): boolean {
|
||||
return 'storage' in navigator && 'persist' in navigator.storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if persistent storage is already granted
|
||||
*/
|
||||
export async function isPersistentStorageGranted(): Promise<boolean> {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return await navigator.storage.persisted();
|
||||
} catch (error) {
|
||||
console.warn('Failed to check persistent storage status:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests persistent storage from the browser
|
||||
* Returns true if granted, false if denied or not supported
|
||||
*/
|
||||
export async function requestPersistentStorage(): Promise<boolean> {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
console.warn('Persistent storage is not supported in this browser');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if already granted
|
||||
const alreadyGranted = await isPersistentStorageGranted();
|
||||
if (alreadyGranted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Request persistent storage
|
||||
const granted = await navigator.storage.persist();
|
||||
return granted;
|
||||
} catch (error) {
|
||||
console.warn('Failed to request persistent storage:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically requests persistent storage if not already granted
|
||||
* This is intended to be called silently after project creation/cloning
|
||||
* Returns true if persistent storage is available (either already granted or newly granted)
|
||||
*/
|
||||
export async function ensurePersistentStorage(): Promise<boolean> {
|
||||
try {
|
||||
// Check if already granted
|
||||
const alreadyGranted = await isPersistentStorageGranted();
|
||||
if (alreadyGranted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only request if supported
|
||||
if (!isPersistentStorageSupported()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Silently request persistent storage
|
||||
const granted = await requestPersistentStorage();
|
||||
|
||||
if (granted) {
|
||||
console.log('Persistent storage granted automatically');
|
||||
} else {
|
||||
console.log('Persistent storage request denied or failed');
|
||||
}
|
||||
|
||||
return granted;
|
||||
} catch (error) {
|
||||
console.warn('Failed to ensure persistent storage:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets current storage usage information
|
||||
*/
|
||||
export async function getStorageInfo(): Promise<{
|
||||
quota: number;
|
||||
usage: number;
|
||||
usageDetails?: Record<string, number>;
|
||||
} | null> {
|
||||
if (!('storage' in navigator)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const estimate = await navigator.storage.estimate();
|
||||
return {
|
||||
quota: estimate.quota || 0,
|
||||
usage: estimate.usage || 0,
|
||||
usageDetails: (estimate as StorageEstimate & { usageDetails?: Record<string, number> }).usageDetails,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('Failed to get storage information:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool';
|
||||
import { ConsoleMessage, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
|
||||
describe('ReadConsoleMessagesTool', () => {
|
||||
let mockMessages: ConsoleMessage[];
|
||||
let getMessages: () => ConsoleMessage[];
|
||||
|
||||
beforeEach(() => {
|
||||
// Set up test messages
|
||||
mockMessages = [
|
||||
{ level: 'log', message: 'App started' },
|
||||
{ level: 'warn', message: 'Deprecated API used' },
|
||||
{ level: 'error', message: 'Network request failed' },
|
||||
{ level: 'info', message: 'User logged in' },
|
||||
];
|
||||
getMessages = () => mockMessages;
|
||||
});
|
||||
|
||||
it('should return all messages by default', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toContain('Found 4 console messages');
|
||||
expect(result).toContain('[LOG] App started');
|
||||
expect(result).toContain('[WARN] Deprecated API used');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
});
|
||||
|
||||
it('should filter messages by level', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ filter: 'error' });
|
||||
|
||||
expect(result).toContain('Found 1 console message (level: error)');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should limit number of messages', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ limit: 2 });
|
||||
|
||||
expect(result).toContain('Found 2 console messages');
|
||||
// Should get the last 2 messages
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should handle no messages found', async () => {
|
||||
const emptyGetMessages = () => [];
|
||||
const tool = new ReadConsoleMessagesTool(emptyGetMessages);
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toBe('No console messages found.');
|
||||
});
|
||||
|
||||
it('should handle no messages found with filter', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ filter: 'debug' });
|
||||
|
||||
expect(result).toBe('No console messages found for level: debug.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProjectPreviewConsoleError', () => {
|
||||
it('should create error with console logs', () => {
|
||||
const logs = [
|
||||
{ level: 'error' as const, message: 'Test error' }
|
||||
];
|
||||
const error = new ProjectPreviewConsoleError('Test message', logs);
|
||||
|
||||
expect(error.message).toBe('Test message');
|
||||
expect(error.name).toBe('ProjectPreviewConsoleError');
|
||||
expect(error.logs).toEqual(logs);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// Console error listener tests are now handled by the ConsoleContext
|
||||
// These tests should be moved to a separate ConsoleContext test file
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Tool } from './Tool';
|
||||
|
||||
export interface ReadConsoleMessagesParams {
|
||||
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
||||
constructor(private getMessages: () => import('@/contexts/ConsoleContext').ConsoleMessage[]) {}
|
||||
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||
const { filter = 'all', limit } = params;
|
||||
|
||||
// Filter and limit messages in one chain
|
||||
const filteredMessages = this.getMessages()
|
||||
.filter(msg => filter === 'all' || msg.level === filter)
|
||||
.slice(limit && limit > 0 ? -limit : 0);
|
||||
|
||||
if (filteredMessages.length === 0) {
|
||||
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||
}
|
||||
|
||||
const formattedMessages = filteredMessages
|
||||
.map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`)
|
||||
.join('\n');
|
||||
|
||||
const plural = filteredMessages.length !== 1 ? 's' : '';
|
||||
const levelInfo = filter !== 'all' ? ` (level: ${filter})` : '';
|
||||
|
||||
return `Found ${filteredMessages.length} console message${plural}${levelInfo}:\n\n${formattedMessages}`;
|
||||
}
|
||||
|
||||
description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
||||
}
|
||||
@@ -17,6 +17,9 @@ describe('DataSettings', () => {
|
||||
// Check for description
|
||||
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
|
||||
|
||||
// Check for Persist Data section
|
||||
expect(screen.getByText('Persist Data')).toBeInTheDocument();
|
||||
|
||||
// Check for Export Files section
|
||||
expect(screen.getByText('Export Files')).toBeInTheDocument();
|
||||
expect(screen.getByText('Export All Files')).toBeInTheDocument();
|
||||
@@ -26,13 +29,17 @@ describe('DataSettings', () => {
|
||||
expect(screen.getByRole('button', { name: /clear all data/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows export and clear buttons', () => {
|
||||
it('shows persist data toggle, export and clear buttons', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<DataSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Persist storage toggle should be visible
|
||||
const persistToggle = screen.getByRole('switch');
|
||||
expect(persistToggle).toBeInTheDocument();
|
||||
|
||||
// Export button should be visible
|
||||
const exportButton = screen.getByRole('button', { name: /export all files/i });
|
||||
expect(exportButton).toBeInTheDocument();
|
||||
|
||||
+103
-12
@@ -1,14 +1,21 @@
|
||||
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, ArrowLeft, Shield } 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 { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
requestPersistentStorage,
|
||||
getStorageInfo
|
||||
} from '@/lib/persistentStorage';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface StorageUsageDetails {
|
||||
@@ -28,8 +35,10 @@ export function DataSettings() {
|
||||
const { t } = useTranslation();
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [isClearing, setIsClearing] = useState(false);
|
||||
const [isRequestingPersistent, setIsRequestingPersistent] = useState(false);
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
@@ -44,27 +53,29 @@ export function DataSettings() {
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
// Load storage information
|
||||
// Load storage information and persistent status
|
||||
useEffect(() => {
|
||||
const loadStorageInfo = async () => {
|
||||
try {
|
||||
// Check if StorageManager API is available
|
||||
if (!('storage' in navigator)) {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
setStorageError('StorageManager API is not available in this browser');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get storage estimate
|
||||
const estimate = await navigator.storage.estimate();
|
||||
const info = await getStorageInfo();
|
||||
if (info) {
|
||||
setStorageInfo({
|
||||
quota: info.quota,
|
||||
usage: info.usage,
|
||||
usageDetails: info.usageDetails as StorageUsageDetails,
|
||||
});
|
||||
}
|
||||
|
||||
// Extract usage details safely
|
||||
const usageDetails: StorageUsageDetails | undefined = (estimate as StorageEstimate & { usageDetails?: StorageUsageDetails }).usageDetails;
|
||||
|
||||
setStorageInfo({
|
||||
quota: estimate.quota || 0,
|
||||
usage: estimate.usage || 0,
|
||||
usageDetails,
|
||||
});
|
||||
// Check if storage is persistent
|
||||
const persistent = await isPersistentStorageGranted();
|
||||
setIsPersistent(persistent);
|
||||
} catch (error) {
|
||||
console.error('Failed to get storage information:', error);
|
||||
setStorageError(error instanceof Error ? error.message : 'Failed to get storage information');
|
||||
@@ -149,6 +160,63 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handlePersistentStorageToggle = async (checked: boolean) => {
|
||||
// If trying to turn off, we can't actually do that - just ignore
|
||||
if (!checked) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRequestingPersistent(true);
|
||||
try {
|
||||
// Check if persist method is available
|
||||
if (!isPersistentStorageSupported()) {
|
||||
toast({
|
||||
title: t('persistentStorageNotSupported'),
|
||||
description: t('persistentStorageNotSupportedDescription'),
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if already persistent
|
||||
const alreadyPersistent = await isPersistentStorageGranted();
|
||||
if (alreadyPersistent) {
|
||||
setIsPersistent(true);
|
||||
toast({
|
||||
title: t('persistentStorageAlreadyGranted'),
|
||||
description: t('persistentStorageAlreadyGrantedDescription'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Request persistent storage
|
||||
const granted = await requestPersistentStorage();
|
||||
|
||||
if (granted) {
|
||||
setIsPersistent(true);
|
||||
toast({
|
||||
title: t('persistentStorageGranted'),
|
||||
description: t('persistentStorageGrantedDescription'),
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: t('persistentStorageDenied'),
|
||||
description: t('persistentStorageDeniedDescription'),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to request persistent storage:', error);
|
||||
toast({
|
||||
title: t('failedToRequestPersistentStorage'),
|
||||
description: error instanceof Error ? error.message : t('error'),
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsRequestingPersistent(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearAllData = async () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -268,6 +336,29 @@ export function DataSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Persist Data */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5" />
|
||||
{t('persistData')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('persistDataDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-start">
|
||||
<Switch
|
||||
id="persistent-storage"
|
||||
checked={isPersistent === true}
|
||||
onCheckedChange={handlePersistentStorageToggle}
|
||||
disabled={isRequestingPersistent || isPersistent === null}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Export Files */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
+7
-2
@@ -15,7 +15,6 @@ import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
@@ -262,7 +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);
|
||||
}
|
||||
|
||||
@@ -16,9 +16,9 @@ import { ActionsMenu } from '@/components/ActionsMenu';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { useConsole } from '@/contexts/ConsoleContext';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -29,10 +29,12 @@ export function ProjectView() {
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
|
||||
const projectsManager = useProjectsManager();
|
||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const { clearMessages: clearConsoleMessages } = useConsole();
|
||||
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
|
||||
@@ -45,12 +47,14 @@ export function ProjectView() {
|
||||
try {
|
||||
const projectData = await projectsManager.getProject(projectId);
|
||||
setProject(projectData);
|
||||
// Clear console messages when switching projects
|
||||
clearConsoleMessages();
|
||||
} catch (error) {
|
||||
console.error('Failed to load project:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectId, projectsManager]);
|
||||
}, [projectId, projectsManager, clearConsoleMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProject();
|
||||
|
||||
+16
-13
@@ -7,6 +7,7 @@ import NostrProvider from '@/components/NostrProvider';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleProvider } from '@/contexts/ConsoleContext';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
@@ -43,19 +44,21 @@ export function TestApp({ children }: TestAppProps) {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
|
||||
<FSProvider fs={fs}>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
<NostrProvider>
|
||||
<SessionManagerProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
</SessionManagerProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
<ConsoleProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
<NostrProvider>
|
||||
<SessionManagerProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
</SessionManagerProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</ConsoleProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
Reference in new issue
Block a user