mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b21194fb0f |
No files matched your search
Generated
+3
-3
@@ -4668,9 +4668,9 @@
|
||||
}
|
||||
},
|
||||
"node_modules/caniuse-lite": {
|
||||
"version": "1.0.30001746",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz",
|
||||
"integrity": "sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==",
|
||||
"version": "1.0.30001716",
|
||||
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001716.tgz",
|
||||
"integrity": "sha512-49/c1+x3Kwz7ZIWt+4DvK3aMJy9oYXXG6/97JKsnjdCk/6n9vVyWL8NAwVt95Lwt9eigI10Hl782kDfZUUlRXw==",
|
||||
"dev": true,
|
||||
"funding": [
|
||||
{
|
||||
|
||||
+16
-19
@@ -16,7 +16,6 @@ import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
|
||||
@@ -74,24 +73,22 @@ export function App() {
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<ConsoleErrorProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleErrorProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -1,152 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { ReactNode } from 'react';
|
||||
import { ConsoleErrorProvider } from './ConsoleErrorProvider';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
|
||||
// Wrapper component for testing
|
||||
function TestWrapper({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<ConsoleErrorProvider>
|
||||
{children}
|
||||
</ConsoleErrorProvider>
|
||||
);
|
||||
}
|
||||
|
||||
describe('ConsoleErrorProvider', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
});
|
||||
|
||||
it('should provide initial state with no errors', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should update hasErrors when console error is added', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
|
||||
// Add an error message
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError);
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Test error message');
|
||||
});
|
||||
|
||||
it('should not update hasErrors for non-error messages', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add non-error messages
|
||||
act(() => {
|
||||
addConsoleMessage('log', 'Test log message');
|
||||
addConsoleMessage('warn', 'Test warning message');
|
||||
addConsoleMessage('info', 'Test info message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should update consoleError with latest error message', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add first error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'First error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: First error');
|
||||
|
||||
// Add second error - should update to show latest error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Second error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Second error');
|
||||
expect(result.current.consoleError?.logs).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should clear errors when clearErrors is called', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add error to set state
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
expect(result.current.consoleError).not.toBeNull();
|
||||
|
||||
// Clear errors
|
||||
act(() => {
|
||||
result.current.clearErrors();
|
||||
});
|
||||
|
||||
expect(result.current.hasErrors).toBe(false);
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
});
|
||||
|
||||
it('should dismiss console error when dismissConsoleError is called', async () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add error to create console error
|
||||
act(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError).not.toBeNull();
|
||||
|
||||
// Dismiss console error (this only clears the Quilly error, not the global state)
|
||||
act(() => {
|
||||
result.current.dismissConsoleError();
|
||||
});
|
||||
|
||||
expect(result.current.consoleError).toBeNull();
|
||||
// hasErrors should still be true since we only dismissed the Quilly display
|
||||
expect(result.current.hasErrors).toBe(true);
|
||||
});
|
||||
|
||||
it('should include all error messages in console error logs', () => {
|
||||
const { result } = renderHook(() => useConsoleError(), {
|
||||
wrapper: TestWrapper,
|
||||
});
|
||||
|
||||
// Add multiple errors and non-errors
|
||||
act(() => {
|
||||
addConsoleMessage('log', 'Log message');
|
||||
addConsoleMessage('error', 'First error');
|
||||
addConsoleMessage('warn', 'Warning message');
|
||||
addConsoleMessage('error', 'Second error');
|
||||
addConsoleMessage('info', 'Info message');
|
||||
addConsoleMessage('error', 'Third error');
|
||||
});
|
||||
|
||||
expect(result.current.consoleError?.message).toBe('Console error detected: Third error');
|
||||
expect(result.current.consoleError?.logs).toHaveLength(3);
|
||||
expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([
|
||||
'First error',
|
||||
'Second error',
|
||||
'Third error'
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,63 +0,0 @@
|
||||
import { useState, useEffect, useCallback, ReactNode } from 'react';
|
||||
import {
|
||||
addConsoleMessageListener,
|
||||
removeConsoleMessageListener,
|
||||
getHasConsoleErrors,
|
||||
getConsoleMessages,
|
||||
clearConsoleMessages,
|
||||
ProjectPreviewConsoleError
|
||||
} from '@/lib/consoleMessages';
|
||||
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
|
||||
|
||||
interface ConsoleErrorProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) {
|
||||
const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors());
|
||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||
|
||||
const updateState = useCallback(() => {
|
||||
const hasConsoleErrors = getHasConsoleErrors();
|
||||
setHasErrors(hasConsoleErrors);
|
||||
|
||||
if (hasConsoleErrors) {
|
||||
const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error');
|
||||
const latestError = errorMessages[errorMessages.length - 1];
|
||||
setConsoleError(new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${latestError.message}`,
|
||||
errorMessages
|
||||
));
|
||||
} else {
|
||||
setConsoleError(null);
|
||||
}
|
||||
}, []);
|
||||
|
||||
useEffect(() => {
|
||||
addConsoleMessageListener(updateState);
|
||||
updateState(); // Initial sync
|
||||
|
||||
return () => removeConsoleMessageListener(updateState);
|
||||
}, [updateState]);
|
||||
|
||||
const clearErrors = useCallback(() => {
|
||||
clearConsoleMessages();
|
||||
}, []);
|
||||
|
||||
const dismissConsoleError = useCallback(() => {
|
||||
setConsoleError(null);
|
||||
}, []);
|
||||
|
||||
const value = {
|
||||
hasErrors,
|
||||
consoleError,
|
||||
clearErrors,
|
||||
dismissConsoleError,
|
||||
};
|
||||
|
||||
return (
|
||||
<ConsoleErrorContext.Provider value={value}>
|
||||
{children}
|
||||
</ConsoleErrorContext.Provider>
|
||||
);
|
||||
}
|
||||
@@ -9,7 +9,7 @@ import { Label } from '@/components/ui/label';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
@@ -464,19 +464,26 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
|
||||
</div>
|
||||
|
||||
<div className="space-y-3">
|
||||
<Label className="text-sm font-medium">Payment Method</Label>
|
||||
<Tabs value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)} className="w-full">
|
||||
<TabsList className="grid w-full grid-cols-2">
|
||||
<TabsTrigger value="stripe" className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
Credit Card
|
||||
</TabsTrigger>
|
||||
<TabsTrigger value="lightning" className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4" />
|
||||
Lightning
|
||||
</TabsTrigger>
|
||||
</TabsList>
|
||||
</Tabs>
|
||||
<Label htmlFor="payment-method" className="text-sm font-medium">Payment Method</Label>
|
||||
<Select value={paymentMethod} onValueChange={(value: 'stripe' | 'lightning') => setPaymentMethod(value)}>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="stripe">
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditCard className="h-4 w-4" />
|
||||
Credit Card
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="lightning">
|
||||
<div className="flex items-center gap-2">
|
||||
<Zap className="h-4 w-4" />
|
||||
Lightning
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
|
||||
<Button
|
||||
|
||||
@@ -11,9 +11,6 @@ vi.mock('@/hooks/useLocalStorage');
|
||||
vi.mock('@/hooks/useProjectSessionStatus', () => ({
|
||||
useProjectSessionStatus: () => ({ hasRunningSessions: false })
|
||||
}));
|
||||
vi.mock('@/hooks/useDraftMessages', () => ({
|
||||
useDraftMessages: () => ({ hasDraft: () => false })
|
||||
}));
|
||||
vi.mock('react-router-dom', async (importOriginal) => {
|
||||
const actual = await importOriginal() as Record<string, unknown>;
|
||||
return {
|
||||
|
||||
@@ -1,14 +1,13 @@
|
||||
import React, { useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Pencil } from 'lucide-react';
|
||||
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } 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';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useDraftMessages } from '@/hooks/useDraftMessages';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import type { Project } from '@/lib/ProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
@@ -20,10 +19,9 @@ interface ProjectItemProps {
|
||||
isSelected: boolean;
|
||||
onSelect: (project: Project) => void;
|
||||
isFavorite?: boolean;
|
||||
hasDraft?: boolean;
|
||||
}
|
||||
|
||||
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite, hasDraft }) => {
|
||||
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
|
||||
const navigate = useNavigate();
|
||||
const { hasRunningSessions } = useProjectSessionStatus(project.id);
|
||||
|
||||
@@ -53,16 +51,10 @@ const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-between gap-2 flex-1 min-w-0">
|
||||
<div className="min-w-0 flex-1 flex items-center gap-2">
|
||||
<div className="min-w-0 flex-1 flex items-center">
|
||||
<h3 className="font-medium text-sm truncate">
|
||||
{project.name}
|
||||
</h3>
|
||||
{/* Draft indicator - only shown when project has draft */}
|
||||
{hasDraft && (
|
||||
<div className="flex-shrink-0 pointer-events-none">
|
||||
<Pencil className="h-3 w-3 text-sidebar-foreground opacity-60" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Star indicator - only shown when favorited */}
|
||||
@@ -101,7 +93,6 @@ export function ProjectSidebar({
|
||||
const queryClient = useQueryClient();
|
||||
const { data: projects = [], isLoading, error } = useProjects();
|
||||
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
|
||||
const { hasDraft } = useDraftMessages(); // Use without projectId for global access
|
||||
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
@@ -230,7 +221,6 @@ export function ProjectSidebar({
|
||||
isSelected={selectedProject?.id === project.id}
|
||||
onSelect={onSelectProject}
|
||||
isFavorite={favorites.includes(project.id)}
|
||||
hasDraft={hasDraft(project.id)}
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
|
||||
@@ -7,7 +7,7 @@ import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useState } from 'react';
|
||||
|
||||
export interface QuillyProps {
|
||||
|
||||
@@ -8,15 +8,13 @@ import { CircularProgress } from '@/components/ui/circular-progress';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Square, Loader2, ChevronDown, ArrowUp, Plus } from 'lucide-react';
|
||||
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useMessageQueue } from '@/hooks/useMessageQueue';
|
||||
import { useDraftMessages } from '@/hooks/useDraftMessages';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
@@ -36,8 +34,7 @@ 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 { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
@@ -87,11 +84,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
// Message queue for handling messages while AI is working
|
||||
const { queuedMessages, addToQueue, clearQueue, hasQueuedMessages, queueLength } = useMessageQueue(projectId);
|
||||
|
||||
// Draft messages for preserving input across project switches
|
||||
const { getDraft, saveDraft, clearDraft } = useDraftMessages(projectId);
|
||||
|
||||
// Determine which error to show - console error takes priority over AI errors
|
||||
const displayError = consoleError || aiError;
|
||||
@@ -138,12 +130,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
setAIError(null);
|
||||
}, [projectId, providerModel]);
|
||||
|
||||
// Load draft when switching projects
|
||||
useEffect(() => {
|
||||
const draft = getDraft();
|
||||
setInput(draft);
|
||||
}, [projectId, getDraft]);
|
||||
|
||||
// Initialize AI chat with tools
|
||||
const cwd = `/projects/${projectId}`;
|
||||
const customTools = useMemo(() => {
|
||||
@@ -271,64 +257,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||
|
||||
// Process queued messages when AI becomes available for this project
|
||||
const processQueuedMessages = useCallback(async () => {
|
||||
if (isLoading || !isConfigured || !providerModel.trim() || queuedMessages.length === 0) return;
|
||||
|
||||
const messagesToProcess = [...queuedMessages];
|
||||
// Clear the queue first to prevent re-processing
|
||||
clearQueue();
|
||||
|
||||
const modelToUse = providerModel.trim();
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
// Combine all queued messages into a single batch
|
||||
const allContentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
||||
|
||||
for (const queuedMessage of messagesToProcess) {
|
||||
// Add text content if present
|
||||
if (queuedMessage.content.trim()) {
|
||||
allContentParts.push({
|
||||
type: 'text',
|
||||
text: queuedMessage.content.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Process attached files for this message
|
||||
if (queuedMessage.attachedFiles.length > 0) {
|
||||
const filePromises = queuedMessage.attachedFiles.map(async (file) => {
|
||||
try {
|
||||
const savedPath = await saveFileToTmp(fs, file);
|
||||
return `Added file: ${savedPath}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
return `Failed to save file: ${file.name}`;
|
||||
}
|
||||
});
|
||||
|
||||
const fileResults = await Promise.all(filePromises);
|
||||
fileResults.forEach(fileResult => {
|
||||
allContentParts.push({
|
||||
type: 'text',
|
||||
text: fileResult
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Send all queued messages as a single batch
|
||||
if (allContentParts.length > 0) {
|
||||
const messageContent = allContentParts.length === 1 ? allContentParts[0].text : allContentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}
|
||||
}, [addRecentlyUsedModel, clearQueue, fs, isConfigured, isLoading, providerModel, queuedMessages, sendMessage]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!isLoading && hasQueuedMessages) {
|
||||
processQueuedMessages();
|
||||
}
|
||||
}, [isLoading, hasQueuedMessages, processQueuedMessages]);
|
||||
|
||||
// Calculate context usage percentage
|
||||
const currentModel = useMemo(() => {
|
||||
if (!providerModel.trim()) return null;
|
||||
@@ -483,6 +411,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
|
||||
if (isLoading || !providerModel.trim()) return;
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length === 0) return;
|
||||
|
||||
@@ -491,16 +421,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
};
|
||||
|
||||
const send = useCallback(async (input: string, attachedFiles: File[]) => {
|
||||
if ((!input.trim() && attachedFiles.length === 0)) return;
|
||||
|
||||
// If AI is loading, add to queue instead of sending immediately
|
||||
if (isLoading) {
|
||||
addToQueue(input, attachedFiles);
|
||||
setInput('');
|
||||
setAttachedFiles([]);
|
||||
clearDraft(); // Clear draft when message is queued
|
||||
return;
|
||||
}
|
||||
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
|
||||
|
||||
// If AI is not configured, show onboarding dialog
|
||||
if (!isConfigured) {
|
||||
@@ -551,7 +472,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
setInput('');
|
||||
setAttachedFiles([]);
|
||||
clearDraft(); // Clear draft when message is sent
|
||||
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
@@ -559,7 +479,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, addToQueue, clearDraft, fs, isConfigured, isLoading, providerModel, sendMessage]);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
await send(input, attachedFiles);
|
||||
@@ -752,160 +672,131 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
<div className="border-t p-4">
|
||||
{/* Chat Input Container */}
|
||||
<div
|
||||
className={`${hasQueuedMessages ? 'focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 rounded-2xl' : ''} transition-all`}
|
||||
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
}`}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
{/* Queued Messages Indicator */}
|
||||
{hasQueuedMessages && (
|
||||
<div className="w-full px-3 py-1 text-xs text-muted-foreground bg-muted/50 border border-input rounded-t-2xl text-left mb-0">
|
||||
{queueLength} message{queueLength > 1 ? 's' : ''} queued • will send when AI finishes
|
||||
</div>
|
||||
)}
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onFocus={handleTextareaFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: t('selectModelFirst')
|
||||
}
|
||||
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
disabled={isLoading || (isConfigured && !providerModel.trim())}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
height: 'auto',
|
||||
minHeight: '96px'
|
||||
}}
|
||||
onInput={(e) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
|
||||
}}
|
||||
/>
|
||||
|
||||
<div
|
||||
className={`flex flex-col border border-input bg-background shadow-sm transition-all ${hasQueuedMessages
|
||||
? 'rounded-b-2xl border-t-0'
|
||||
: 'rounded-2xl focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2'
|
||||
} ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''}`}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<Textarea
|
||||
value={input}
|
||||
onChange={(e) => {
|
||||
const newValue = e.target.value;
|
||||
setInput(newValue);
|
||||
saveDraft(newValue);
|
||||
}}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onFocus={handleTextareaFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: t('selectModelFirst')
|
||||
}
|
||||
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
disabled={isConfigured && !providerModel.trim()}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
height: 'auto',
|
||||
minHeight: '96px'
|
||||
}}
|
||||
onInput={(e) => {
|
||||
const target = e.target as HTMLTextAreaElement;
|
||||
target.style.height = 'auto';
|
||||
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
|
||||
}}
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="flex items-center gap-4 px-2 py-2">
|
||||
{/* File Attachment */}
|
||||
<FileAttachment
|
||||
onFileSelect={handleFileSelect}
|
||||
onFileRemove={handleFileRemove}
|
||||
selectedFiles={attachedFiles}
|
||||
disabled={isLoading}
|
||||
multiple={true}
|
||||
/>
|
||||
|
||||
{/* Bottom Controls Row */}
|
||||
<div className="flex items-center gap-4 px-2 py-2">
|
||||
{/* File Attachment */}
|
||||
<FileAttachment
|
||||
onFileSelect={handleFileSelect}
|
||||
onFileRemove={handleFileRemove}
|
||||
selectedFiles={attachedFiles}
|
||||
disabled={false}
|
||||
multiple={true}
|
||||
{/* Context Usage Wheel */}
|
||||
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="cursor-help">
|
||||
<CircularProgress
|
||||
value={contextUsagePercentage}
|
||||
size={20}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('contextUsage', {
|
||||
tokens: lastInputTokens.toLocaleString(),
|
||||
total: currentModel.contextLength.toLocaleString(),
|
||||
percentage: contextUsagePercentage.toFixed(1)
|
||||
})}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Cost Display */}
|
||||
{totalCost >= 0.01 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
|
||||
${totalCost.toFixed(2)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('totalCostSession')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Model Selector */}
|
||||
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
|
||||
<ModelSelector
|
||||
value={providerModel}
|
||||
onChange={setProviderModel}
|
||||
disabled={isLoading}
|
||||
placeholder={t('chooseModel')}
|
||||
open={isModelSelectorOpen}
|
||||
onOpenChange={setIsModelSelectorOpen}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Context Usage Wheel */}
|
||||
{contextUsagePercentage >= 10 && currentModel?.contextLength && lastInputTokens > 0 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="cursor-help">
|
||||
<CircularProgress
|
||||
value={contextUsagePercentage}
|
||||
size={20}
|
||||
strokeWidth={2}
|
||||
/>
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('contextUsage', {
|
||||
tokens: lastInputTokens.toLocaleString(),
|
||||
total: currentModel.contextLength.toLocaleString(),
|
||||
percentage: contextUsagePercentage.toFixed(1)
|
||||
})}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
{/* Send/Stop Button */}
|
||||
<div>
|
||||
{isLoading ? (
|
||||
<Button
|
||||
onClick={stopGeneration}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
|
||||
>
|
||||
<Square />
|
||||
</Button>
|
||||
) : (
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
|
||||
size="sm"
|
||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
||||
>
|
||||
<ArrowUp />
|
||||
</Button>
|
||||
)}
|
||||
|
||||
{/* Cost Display */}
|
||||
{totalCost >= 0.01 && (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<div className="text-xs text-muted-foreground px-2 py-1 bg-muted/50 rounded-md whitespace-nowrap cursor-help">
|
||||
${totalCost.toFixed(2)}
|
||||
</div>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<p>{t('totalCostSession')}</p>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
|
||||
{/* Model Selector */}
|
||||
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
|
||||
<ModelSelector
|
||||
value={providerModel}
|
||||
onChange={setProviderModel}
|
||||
disabled={isLoading}
|
||||
placeholder={t('chooseModel')}
|
||||
open={isModelSelectorOpen}
|
||||
onOpenChange={setIsModelSelectorOpen}
|
||||
/>
|
||||
</div>
|
||||
|
||||
{/* Send/Stop Button */}
|
||||
<div>
|
||||
{isLoading ? (
|
||||
<Button
|
||||
onClick={stopGeneration}
|
||||
size="sm"
|
||||
variant="ghost"
|
||||
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
|
||||
>
|
||||
<Square />
|
||||
</Button>
|
||||
) : (
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
|
||||
size="sm"
|
||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
||||
>
|
||||
{hasQueuedMessages ? <Plus /> : <ArrowUp />}
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
{hasQueuedMessages && (
|
||||
<TooltipContent>
|
||||
<p>{queueLength} message{queueLength > 1 ? 's' : ''} will send when AI finishes</p>
|
||||
</TooltipContent>
|
||||
)}
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
{/* Onboarding Dialog */}
|
||||
<OnboardingDialog
|
||||
open={showOnboarding}
|
||||
|
||||
@@ -3,8 +3,7 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
@@ -91,9 +90,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Use console error state from provider
|
||||
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
|
||||
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -457,7 +453,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}, [selectedFile, loadFileContent]);
|
||||
|
||||
// Reset selected file and navigation history when projectId changes
|
||||
const prevProjectIdRef = useRef<string>();
|
||||
useEffect(() => {
|
||||
setSelectedFile(null);
|
||||
setFileContent('');
|
||||
@@ -468,13 +463,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
setCurrentPath('/');
|
||||
setNavigationHistory(['/']);
|
||||
setHistoryIndex(0);
|
||||
|
||||
// Only clear console messages when projectId actually changes (not on initial mount)
|
||||
if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) {
|
||||
clearErrors();
|
||||
}
|
||||
prevProjectIdRef.current = projectId;
|
||||
}, [projectId, clearErrors]);
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
checkForBuiltProject();
|
||||
@@ -523,8 +512,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
|
||||
const messages = isOpen ? getConsoleMessages() : [];
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
@@ -535,7 +522,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}
|
||||
};
|
||||
|
||||
const messageCount = messages.length;
|
||||
const consoleMessages = getConsoleMessages();
|
||||
const messageCount = consoleMessages.length;
|
||||
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||
|
||||
return (
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
@@ -546,7 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
className="h-8 w-8 p-0 relative"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{hasConsoleErrors && (
|
||||
{hasErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
@@ -566,7 +555,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
messages.map((msg, index) => (
|
||||
consoleMessages.map((msg, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
|
||||
@@ -1,11 +0,0 @@
|
||||
import { createContext } from 'react';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
|
||||
export interface ConsoleErrorContextValue {
|
||||
hasErrors: boolean;
|
||||
consoleError: ProjectPreviewConsoleError | null;
|
||||
clearErrors: () => void;
|
||||
dismissConsoleError: () => void;
|
||||
}
|
||||
|
||||
export const ConsoleErrorContext = createContext<ConsoleErrorContextValue | undefined>(undefined);
|
||||
@@ -1,12 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { renderHook } from '@testing-library/react';
|
||||
import { useConsoleError } from './useConsoleError';
|
||||
|
||||
describe('useConsoleError', () => {
|
||||
it('should throw error when used outside ConsoleErrorProvider', () => {
|
||||
// Expect the hook to throw when not wrapped in provider
|
||||
expect(() => {
|
||||
renderHook(() => useConsoleError());
|
||||
}).toThrow('useConsoleError must be used within a ConsoleErrorProvider');
|
||||
});
|
||||
});
|
||||
@@ -1,16 +0,0 @@
|
||||
import { useContext } from 'react';
|
||||
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
|
||||
|
||||
/**
|
||||
* Hook to access console error state from the ConsoleErrorProvider.
|
||||
* Provides boolean error state and console error information for Quilly.
|
||||
*/
|
||||
export function useConsoleError() {
|
||||
const context = useContext(ConsoleErrorContext);
|
||||
|
||||
if (context === undefined) {
|
||||
throw new Error('useConsoleError must be used within a ConsoleErrorProvider');
|
||||
}
|
||||
|
||||
return context;
|
||||
}
|
||||
@@ -1,93 +0,0 @@
|
||||
import { useCallback, useState, useEffect } from 'react';
|
||||
|
||||
// Global drafts storage shared across all hook instances
|
||||
const globalDrafts = new Map<string, string>();
|
||||
|
||||
// Global listeners for draft changes
|
||||
const listeners = new Set<() => void>();
|
||||
|
||||
// Notify all listeners when drafts change
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach(listener => listener());
|
||||
};
|
||||
|
||||
/**
|
||||
* Hook to manage draft messages per project.
|
||||
* Drafts are stored in global memory and persist when switching between projects.
|
||||
* Drafts are cleared when messages are sent or queued.
|
||||
*
|
||||
* Can be used in two ways:
|
||||
* 1. With projectId - for managing drafts for a specific project
|
||||
* 2. Without projectId - for accessing global draft functionality (checking any project's drafts)
|
||||
*/
|
||||
export function useDraftMessages(projectId?: string) {
|
||||
// Use state to trigger re-renders when drafts change
|
||||
const [, forceUpdate] = useState(0);
|
||||
|
||||
// Register listener for draft changes
|
||||
useEffect(() => {
|
||||
const listener = () => forceUpdate(prev => prev + 1);
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
// Get draft for a specific project (or current project if projectId provided)
|
||||
const getDraft = useCallback((targetProjectId?: string): string => {
|
||||
const id = targetProjectId || projectId;
|
||||
if (!id) return '';
|
||||
return globalDrafts.get(id) || '';
|
||||
}, [projectId]);
|
||||
|
||||
// Save draft for a specific project (or current project if projectId provided)
|
||||
const saveDraft = useCallback((content: string, targetProjectId?: string) => {
|
||||
const id = targetProjectId || projectId;
|
||||
if (!id) return;
|
||||
|
||||
if (content.trim()) {
|
||||
globalDrafts.set(id, content);
|
||||
} else {
|
||||
// Clear draft if content is empty
|
||||
globalDrafts.delete(id);
|
||||
}
|
||||
notifyListeners();
|
||||
}, [projectId]);
|
||||
|
||||
// Clear draft for a specific project (or current project if projectId provided)
|
||||
const clearDraft = useCallback((targetProjectId?: string) => {
|
||||
const id = targetProjectId || projectId;
|
||||
if (!id) return;
|
||||
|
||||
globalDrafts.delete(id);
|
||||
notifyListeners();
|
||||
}, [projectId]);
|
||||
|
||||
// Check if a specific project has a draft (or current project if projectId provided)
|
||||
const hasDraft = useCallback((targetProjectId?: string): boolean => {
|
||||
const id = targetProjectId || projectId;
|
||||
if (!id) return false;
|
||||
|
||||
const draft = globalDrafts.get(id);
|
||||
return Boolean(draft && draft.trim());
|
||||
}, [projectId]);
|
||||
|
||||
// Get all projects that have drafts (global functionality)
|
||||
const getProjectsWithDrafts = useCallback((): string[] => {
|
||||
const projectsWithDrafts: string[] = [];
|
||||
globalDrafts.forEach((draft, id) => {
|
||||
if (draft && draft.trim()) {
|
||||
projectsWithDrafts.push(id);
|
||||
}
|
||||
});
|
||||
return projectsWithDrafts;
|
||||
}, []);
|
||||
|
||||
return {
|
||||
getDraft,
|
||||
saveDraft,
|
||||
clearDraft,
|
||||
hasDraft,
|
||||
getProjectsWithDrafts
|
||||
};
|
||||
}
|
||||
@@ -1,54 +0,0 @@
|
||||
import { useState, useCallback, useRef, useEffect } from 'react';
|
||||
|
||||
/**
|
||||
* Simple hook to manage a message queue per project.
|
||||
* Messages are only stored in memory and cleared when AI processes them.
|
||||
*/
|
||||
export function useMessageQueue(projectId: string) {
|
||||
// Use ref to store queues for all projects to persist across re-renders
|
||||
const queuesRef = useRef<Map<string, Array<{ content: string; attachedFiles: File[] }>>>(new Map());
|
||||
|
||||
// Local state for current project's queue to trigger re-renders
|
||||
const [currentQueue, setCurrentQueue] = useState<Array<{ content: string; attachedFiles: File[] }>>([]);
|
||||
|
||||
// Sync current queue with the ref when projectId changes
|
||||
useEffect(() => {
|
||||
const queue = queuesRef.current.get(projectId) || [];
|
||||
setCurrentQueue(queue);
|
||||
}, [projectId]);
|
||||
|
||||
const addToQueue = useCallback((content: string, attachedFiles: File[] = []) => {
|
||||
if (!content.trim() && attachedFiles.length === 0) return;
|
||||
|
||||
const currentProjectQueue = queuesRef.current.get(projectId) || [];
|
||||
const updatedQueue = [...currentProjectQueue, { content: content.trim(), attachedFiles }];
|
||||
|
||||
queuesRef.current.set(projectId, updatedQueue);
|
||||
setCurrentQueue(updatedQueue);
|
||||
}, [projectId]);
|
||||
|
||||
const clearQueue = useCallback(() => {
|
||||
queuesRef.current.set(projectId, []);
|
||||
setCurrentQueue([]);
|
||||
}, [projectId]);
|
||||
|
||||
const removeFromQueue = useCallback((index: number) => {
|
||||
const currentProjectQueue = queuesRef.current.get(projectId) || [];
|
||||
const updatedQueue = currentProjectQueue.filter((_, i) => i !== index);
|
||||
|
||||
queuesRef.current.set(projectId, updatedQueue);
|
||||
setCurrentQueue(updatedQueue);
|
||||
}, [projectId]);
|
||||
|
||||
const hasQueuedMessages = currentQueue.length > 0;
|
||||
const queueLength = currentQueue.length;
|
||||
|
||||
return {
|
||||
queuedMessages: currentQueue,
|
||||
addToQueue,
|
||||
clearQueue,
|
||||
removeFromQueue,
|
||||
hasQueuedMessages,
|
||||
queueLength
|
||||
};
|
||||
}
|
||||
@@ -64,13 +64,6 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
apiKeysURL: "https://console.x.ai",
|
||||
tosURL: "https://x.ai/legal",
|
||||
},
|
||||
{
|
||||
id: "deepseek",
|
||||
name: "Deepseek",
|
||||
baseURL: "https://api.deepseek.com/v1",
|
||||
apiKeysURL: "https://platform.deepseek.com/api_keys",
|
||||
tosURL: "https://cdn.deepseek.com/policies/en-US/deepseek-open-platform-terms-of-service.html",
|
||||
},
|
||||
];
|
||||
|
||||
// Helper function to get a specific preset by ID
|
||||
|
||||
@@ -16,15 +16,9 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
});
|
||||
|
||||
build.onResolve({ filter: /.*/ }, async (args) => {
|
||||
// Skip resolving paths from external URLs
|
||||
if (/^https?:\/\//.test(args.importer)) {
|
||||
return;
|
||||
}
|
||||
|
||||
let resolved: string;
|
||||
if (args.path.startsWith("/")) {
|
||||
resolved = args.path;
|
||||
} else if (args.path.startsWith("@/")) {
|
||||
|
||||
if (args.path.startsWith("@/")) {
|
||||
resolved = join(cwd, args.path.slice(2));
|
||||
} else if (args.kind === "entry-point") {
|
||||
resolved = join(cwd, args.path);
|
||||
@@ -34,12 +28,6 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
|
||||
return;
|
||||
}
|
||||
|
||||
// Security: prevent accessing files outside the project directory
|
||||
const projectDir = join(cwd, "..");
|
||||
if (resolved.startsWith("/") && !resolved.startsWith(projectDir)) {
|
||||
throw new Error(`Access to files outside the project directory is not allowed: ${resolved}`);
|
||||
}
|
||||
|
||||
// Vite query parameters https://vite.dev/guide/assets
|
||||
const [cleaned, query] = resolved.split("?");
|
||||
|
||||
|
||||
+16
-52
@@ -9,28 +9,14 @@ vi.mock('../esbuild', () => ({
|
||||
build: vi.fn(() => ({
|
||||
outputFiles: [
|
||||
{
|
||||
path: '/stdin-abc123.js',
|
||||
path: '/stdin.js',
|
||||
contents: new Uint8Array([1, 2, 3]),
|
||||
text: '',
|
||||
hash: 'abc123',
|
||||
},
|
||||
{
|
||||
path: '/stdin-def456.css',
|
||||
path: '/stdin.css',
|
||||
contents: new Uint8Array([4, 5, 6]),
|
||||
text: 'body { margin: 0; }',
|
||||
hash: 'def456',
|
||||
},
|
||||
],
|
||||
metafile: {
|
||||
outputs: {
|
||||
'stdin-abc123.js': {
|
||||
entryPoint: 'fs:/test/project/src/main.tsx',
|
||||
},
|
||||
'stdin-def456.css': {
|
||||
entryPoint: undefined,
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
})),
|
||||
}));
|
||||
@@ -66,25 +52,9 @@ describe('buildProject', () => {
|
||||
documentElement: {
|
||||
outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>',
|
||||
},
|
||||
querySelector: vi.fn((selector: string) => {
|
||||
if (selector === 'meta[http-equiv="content-security-policy"]') {
|
||||
// Return null for CSP meta tag (no CSP present in test)
|
||||
return null;
|
||||
}
|
||||
return {
|
||||
setAttribute: vi.fn(),
|
||||
getAttribute: vi.fn(),
|
||||
};
|
||||
}),
|
||||
scripts: [
|
||||
{
|
||||
getAttribute: vi.fn((attr: string) => {
|
||||
if (attr === 'src') return '/src/main.tsx';
|
||||
return null;
|
||||
}),
|
||||
type: 'module',
|
||||
},
|
||||
],
|
||||
querySelector: vi.fn(() => ({
|
||||
setAttribute: vi.fn(),
|
||||
})),
|
||||
head: {
|
||||
appendChild: vi.fn(),
|
||||
},
|
||||
@@ -163,13 +133,11 @@ describe('buildProject', () => {
|
||||
domParser: mockDOMParser,
|
||||
});
|
||||
|
||||
// Should include built files with hashed names
|
||||
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
// Should include built files
|
||||
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||
expect(result.files['index.html']).toBeDefined();
|
||||
|
||||
// CSS should be embedded in HTML, not as separate file
|
||||
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
|
||||
|
||||
// Public files should be copied to filesystem, not included in files object
|
||||
// Verify copyFiles was called for public directory
|
||||
expect(mockFS.stat).toHaveBeenCalledWith('/test/project/public');
|
||||
@@ -222,13 +190,11 @@ describe('buildProject', () => {
|
||||
domParser: mockDOMParser,
|
||||
});
|
||||
|
||||
// Should still include built files with hashed names
|
||||
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
// Should still include built files
|
||||
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||
expect(result.files['index.html']).toBeDefined();
|
||||
|
||||
// CSS should be embedded in HTML, not as separate file
|
||||
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
|
||||
|
||||
// Should not include any public files in bundle
|
||||
expect(Object.keys(result.files)).not.toContain('favicon.ico');
|
||||
|
||||
@@ -280,15 +246,13 @@ describe('buildProject', () => {
|
||||
domParser: mockDOMParser,
|
||||
});
|
||||
|
||||
// Should include built files with hashed names
|
||||
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
// Should include built files
|
||||
expect(result.files['main.js']).toEqual(new Uint8Array([1, 2, 3]));
|
||||
expect(result.files['main.css']).toEqual(new Uint8Array([4, 5, 6]));
|
||||
expect(result.files['index.html']).toBeDefined();
|
||||
|
||||
// CSS should be embedded in HTML, not as separate file
|
||||
expect(Object.keys(result.files)).not.toContain('stdin-def456.css');
|
||||
|
||||
// Should have exactly 2 files (stdin-abc123.js, index.html)
|
||||
expect(Object.keys(result.files)).toHaveLength(2);
|
||||
// Should have exactly 3 files (main.js, main.css, index.html)
|
||||
expect(Object.keys(result.files)).toHaveLength(3);
|
||||
|
||||
// Should try to copy public files but directory is empty
|
||||
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
|
||||
|
||||
+148
-86
@@ -1,7 +1,6 @@
|
||||
import { join } from "path-browserify";
|
||||
import { getEsbuild } from "@/lib/esbuild";
|
||||
import { copyFiles } from "@/lib/copyFiles";
|
||||
import { addDomainToCSP } from "@/lib/csp";
|
||||
import JSZip from "jszip";
|
||||
|
||||
import { shakespearePlugin } from "./shakespearePlugin";
|
||||
import { esmPlugin } from "./esmPlugin";
|
||||
@@ -34,51 +33,25 @@ async function bundle(
|
||||
);
|
||||
|
||||
const doc = domParser.parseFromString(indexHtmlText, "text/html");
|
||||
const entryPoints: string[] = [];
|
||||
const entryScripts: Record<string, HTMLScriptElement> = {};
|
||||
|
||||
// Find all module scripts with relative paths in index.html
|
||||
for (const script of doc.scripts) {
|
||||
const scriptSrc = script.getAttribute("src");
|
||||
|
||||
if (scriptSrc && script.type === "module" && /^[./]/.test(scriptSrc)) {
|
||||
const path = join(projectPath, scriptSrc);
|
||||
|
||||
// Files in the public directory take precedence over source files
|
||||
if (scriptSrc.startsWith("/")) {
|
||||
if (await fileExists(fs, join(projectPath, "public", scriptSrc))) {
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
entryPoints.push(path);
|
||||
entryScripts[path] = script;
|
||||
}
|
||||
}
|
||||
|
||||
// Enable Tailwind CSS if a config file is present
|
||||
for (const path of ["tailwind.config.ts", "tailwind.config.js"]) {
|
||||
if (await fileExists(fs, join(projectPath, path))) {
|
||||
entryPoints.push(`shakespeare:${path}`);
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
const results = await esbuild.build({
|
||||
entryPoints,
|
||||
stdin: {
|
||||
contents: `
|
||||
import "@/main.tsx";
|
||||
import tailwindConfig from "@/../tailwind.config.ts";
|
||||
import "https://esm.sh/tailwindcss-cdn@3";
|
||||
tailwind.config = tailwindConfig;
|
||||
`,
|
||||
loader: "tsx",
|
||||
},
|
||||
bundle: true,
|
||||
write: false,
|
||||
format: "esm",
|
||||
target,
|
||||
outdir: "/",
|
||||
jsx: "automatic",
|
||||
metafile: true,
|
||||
sourcemap: true,
|
||||
entryNames: "[name]-[hash]",
|
||||
chunkNames: "[name]-[hash]",
|
||||
assetNames: "[name]-[hash]",
|
||||
plugins: [
|
||||
shakespearePlugin(),
|
||||
shakespearePlugin(), // Takes precedence over esmPlugin
|
||||
fsPlugin(fs, `${projectPath}/src`),
|
||||
esmPlugin(JSON.parse(packageLockText), target),
|
||||
],
|
||||
@@ -90,40 +63,18 @@ async function bundle(
|
||||
const dist: Record<string, Uint8Array> = {};
|
||||
|
||||
for (const file of results.outputFiles) {
|
||||
const ext = file.path.split('.').pop();
|
||||
const filename = `${file.path.slice(1)}`;
|
||||
const entryPoint = results.metafile.outputs[filename]?.entryPoint?.replace(/^fs:/, '');
|
||||
const script = entryPoint ? entryScripts[entryPoint] : null;
|
||||
|
||||
if (script) {
|
||||
script.setAttribute("src", "/" + filename);
|
||||
dist[filename] = file.contents;
|
||||
} else if (ext === "js") {
|
||||
const script = document.createElement("script");
|
||||
script.type = "module";
|
||||
script.src = "/" + filename;
|
||||
doc.head.appendChild(script);
|
||||
dist[filename] = file.contents;
|
||||
} else if (ext === "css") {
|
||||
// Embed stylesheets as Tailwind CSS styles
|
||||
const style = doc.createElement("style");
|
||||
style.setAttribute("type", "text/tailwindcss");
|
||||
style.textContent = file.text;
|
||||
doc.head.appendChild(style);
|
||||
const relativePath = file.path.replace(/^\//, "");
|
||||
if (relativePath === "stdin.js") {
|
||||
dist["main.js"] = file.contents;
|
||||
} else if (relativePath === "stdin.css") {
|
||||
dist["main.css"] = file.contents;
|
||||
} else {
|
||||
dist[filename] = file.contents;
|
||||
dist[relativePath] = file.contents;
|
||||
}
|
||||
}
|
||||
|
||||
// Parse CSP and ensure esm.sh is allowed for necessary directives
|
||||
const cspMeta = doc.querySelector("meta[http-equiv=\"content-security-policy\"]");
|
||||
if (cspMeta) {
|
||||
const cspContent = cspMeta.getAttribute("content");
|
||||
if (cspContent) {
|
||||
const updatedCSP = updateCSPForEsmSh(cspContent);
|
||||
cspMeta.setAttribute("content", updatedCSP);
|
||||
}
|
||||
}
|
||||
// Update index.html with proper script and link tags
|
||||
updateIndexHtml(doc, dist);
|
||||
|
||||
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
|
||||
dist["index.html"] = new TextEncoder().encode(updatedHtml);
|
||||
@@ -138,8 +89,15 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
files: Record<string, Uint8Array>;
|
||||
outputPath: string;
|
||||
projectId?: string;
|
||||
}> {
|
||||
buildStats?: {
|
||||
totalTime: number;
|
||||
zipTime: number;
|
||||
zipFileCount: number;
|
||||
zipSize: number;
|
||||
};
|
||||
}> {
|
||||
const { fs, projectPath, outputPath = `${projectPath}/dist` } = options;
|
||||
const buildStartTime = performance.now();
|
||||
|
||||
// Check if we're in a valid project directory
|
||||
try {
|
||||
@@ -191,6 +149,14 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
// Expected format: /projects/{projectId}
|
||||
const projectId = projectPath.split('/').pop();
|
||||
|
||||
// Generate source code zip for Shakespeare cloning
|
||||
console.log('📦 Generating source code archive...');
|
||||
const zipStartTime = performance.now();
|
||||
const zipResult = await generateSourceCodeZip(fs, projectPath, outputPath);
|
||||
const zipEndTime = performance.now();
|
||||
const zipDuration = zipEndTime - zipStartTime;
|
||||
console.log(`✅ Source code archive created: ${zipResult.fileCount} files, ${(zipResult.zipSize / 1024).toFixed(2)}KB (${zipDuration.toFixed(2)}ms)`);
|
||||
|
||||
// Emit build completion event for PreviewPane to listen to
|
||||
if (projectId && typeof window !== 'undefined') {
|
||||
const buildCompleteEvent = new CustomEvent('buildComplete', {
|
||||
@@ -199,32 +165,128 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
|
||||
window.dispatchEvent(buildCompleteEvent);
|
||||
}
|
||||
|
||||
const buildEndTime = performance.now();
|
||||
const totalTime = buildEndTime - buildStartTime;
|
||||
console.log(`🚀 Build completed in ${totalTime.toFixed(2)}ms (${((zipDuration / totalTime) * 100).toFixed(1)}% spent on zip generation)`);
|
||||
|
||||
return {
|
||||
files: dist,
|
||||
outputPath,
|
||||
projectId,
|
||||
buildStats: {
|
||||
totalTime,
|
||||
zipTime: zipDuration,
|
||||
zipFileCount: zipResult.fileCount,
|
||||
zipSize: zipResult.zipSize,
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
|
||||
try {
|
||||
const stat = await fs.stat(path);
|
||||
return stat.isFile();
|
||||
} catch {
|
||||
return false;
|
||||
function updateIndexHtml(doc: Document, dist: Record<string, Uint8Array>): void {
|
||||
const entrypoint = doc.querySelector('script[src="/src/main.tsx"]');
|
||||
|
||||
if (!entrypoint) {
|
||||
throw new Error("No entrypoint script found in index.html");
|
||||
}
|
||||
|
||||
entrypoint.setAttribute("src", "/main.js");
|
||||
|
||||
const css = dist["main.css"];
|
||||
if (css) {
|
||||
const style = doc.createElement("style");
|
||||
style.setAttribute("type", "text/tailwindcss");
|
||||
style.textContent = new TextDecoder().decode(css);
|
||||
doc.head.appendChild(style);
|
||||
}
|
||||
}
|
||||
|
||||
/** Updates CSP to allow esm.sh for scripts, assets, fonts, and CSS */
|
||||
export function updateCSPForEsmSh(csp: string): string {
|
||||
const esmShDirectives = [
|
||||
'script-src', // For JavaScript modules
|
||||
'img-src', // For images
|
||||
'media-src', // For video/audio
|
||||
'font-src', // For fonts
|
||||
'style-src', // For CSS
|
||||
'connect-src' // For fetch/XHR requests to esm.sh
|
||||
];
|
||||
/**
|
||||
* Generate a source code zip file containing all project files for Shakespeare cloning
|
||||
*/
|
||||
async function generateSourceCodeZip(fs: JSRuntimeFS, projectPath: string, outputPath: string): Promise<{ fileCount: number, zipSize: number }> {
|
||||
const zip = new JSZip();
|
||||
const fileCount = { count: 0 };
|
||||
|
||||
// Recursively add all files from project directory, excluding unwanted files
|
||||
await addDirectoryToZip(fs, zip, projectPath, '', projectPath, fileCount);
|
||||
|
||||
// Generate and save zip directly to the dist folder
|
||||
const zipBuffer = await zip.generateAsync({ type: 'uint8array' });
|
||||
await fs.writeFile(`${outputPath}/sourcecode.zip`, zipBuffer);
|
||||
|
||||
return { fileCount: fileCount.count, zipSize: zipBuffer.length };
|
||||
}
|
||||
|
||||
return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives);
|
||||
/**
|
||||
* Recursively add a directory and its contents to a zip file
|
||||
*/
|
||||
async function addDirectoryToZip(
|
||||
fs: JSRuntimeFS,
|
||||
zip: JSZip,
|
||||
dirPath: string,
|
||||
relativePath: string,
|
||||
projectPath: string,
|
||||
fileCount: { count: number }
|
||||
): Promise<void> {
|
||||
try {
|
||||
const entries = await fs.readdir(dirPath);
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullEntryPath = `${dirPath}/${entry}`;
|
||||
const relativeEntryPath = `${relativePath}/${entry}`;
|
||||
|
||||
// Skip excluded files and directories
|
||||
if (shouldExcludeFromZip(entry)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const stat = await fs.stat(fullEntryPath);
|
||||
|
||||
if (stat.isFile()) {
|
||||
const content = await fs.readFile(fullEntryPath, 'utf8');
|
||||
zip.file(relativeEntryPath, content);
|
||||
fileCount.count++;
|
||||
} else if (stat.isDirectory()) {
|
||||
await addDirectoryToZip(fs, zip, fullEntryPath, relativeEntryPath, projectPath, fileCount);
|
||||
}
|
||||
} catch {
|
||||
// Skip files that can't be read
|
||||
continue;
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Directory can't be read, skip it
|
||||
return;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file or directory should be excluded from the source code zip
|
||||
*/
|
||||
function shouldExcludeFromZip(name: string): boolean {
|
||||
const excludePatterns = [
|
||||
'node_modules',
|
||||
'dist',
|
||||
'.git',
|
||||
'.env',
|
||||
'.env.local',
|
||||
'.env.development',
|
||||
'.env.production',
|
||||
'sourcecode.zip', // Don't include the zip in itself
|
||||
'.DS_Store',
|
||||
'Thumbs.db',
|
||||
'*.log',
|
||||
'.vscode',
|
||||
'.idea'
|
||||
];
|
||||
|
||||
return excludePatterns.some(pattern => {
|
||||
if (pattern.includes('*')) {
|
||||
// Simple wildcard matching
|
||||
const regex = new RegExp(pattern.replace('*', '.*'));
|
||||
return regex.test(name);
|
||||
}
|
||||
return name === pattern;
|
||||
});
|
||||
}
|
||||
@@ -10,26 +10,6 @@ export function shakespearePlugin(): Plugin {
|
||||
name: "shakespeare",
|
||||
|
||||
setup(build) {
|
||||
// Handle Tailwind CSS configuration files
|
||||
build.onResolve({ filter: /^shakespeare:tailwind\.config\.(js|ts)$/ }, (args) => {
|
||||
return {
|
||||
path: args.path,
|
||||
namespace: "shakespeare-tailwind",
|
||||
};
|
||||
});
|
||||
|
||||
build.onLoad({ filter: /.*/, namespace: "shakespeare-tailwind" }, async (args) => {
|
||||
const { pathname } = new URL(args.path);
|
||||
return {
|
||||
contents: `
|
||||
import tailwindConfig from "@/../${pathname}";
|
||||
import "https://esm.sh/tailwindcss-cdn@3";
|
||||
tailwind.config = tailwindConfig;
|
||||
`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
|
||||
// Handle "sonner" imports with a dummy API
|
||||
build.onResolve({ filter: /^sonner$/ }, (args) => {
|
||||
return {
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import {
|
||||
addConsoleMessage,
|
||||
clearConsoleMessages,
|
||||
getConsoleMessages,
|
||||
getHasConsoleErrors,
|
||||
addConsoleMessageListener,
|
||||
removeConsoleMessageListener,
|
||||
ProjectPreviewConsoleError
|
||||
} from './consoleMessages';
|
||||
|
||||
describe('Console Messages System', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
});
|
||||
|
||||
describe('addConsoleMessage', () => {
|
||||
it('should add messages to the global store', () => {
|
||||
addConsoleMessage('log', 'Test log message');
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
|
||||
const messages = getConsoleMessages();
|
||||
expect(messages).toHaveLength(2);
|
||||
expect(messages[0]).toEqual({ level: 'log', message: 'Test log message' });
|
||||
expect(messages[1]).toEqual({ level: 'error', message: 'Test error message' });
|
||||
});
|
||||
|
||||
it('should update error state when error message is added', () => {
|
||||
expect(getHasConsoleErrors()).toBe(false);
|
||||
|
||||
addConsoleMessage('log', 'Log message');
|
||||
expect(getHasConsoleErrors()).toBe(false);
|
||||
|
||||
addConsoleMessage('error', 'Error message');
|
||||
expect(getHasConsoleErrors()).toBe(true);
|
||||
});
|
||||
|
||||
it('should notify listeners when messages are added', () => {
|
||||
const listener = vi.fn();
|
||||
addConsoleMessageListener(listener);
|
||||
|
||||
addConsoleMessage('error', 'First error');
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
|
||||
addConsoleMessage('error', 'Second error');
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
|
||||
removeConsoleMessageListener(listener);
|
||||
});
|
||||
});
|
||||
|
||||
describe('getConsoleMessages', () => {
|
||||
it('should return a copy of messages array', () => {
|
||||
addConsoleMessage('info', 'Test message');
|
||||
|
||||
const messages1 = getConsoleMessages();
|
||||
const messages2 = getConsoleMessages();
|
||||
|
||||
expect(messages1).toEqual(messages2);
|
||||
expect(messages1).not.toBe(messages2); // Different array instances
|
||||
});
|
||||
|
||||
it('should return empty array when no messages', () => {
|
||||
const messages = getConsoleMessages();
|
||||
expect(messages).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
describe('clearConsoleMessages', () => {
|
||||
it('should clear all messages and reset error state', () => {
|
||||
addConsoleMessage('error', 'Error message');
|
||||
addConsoleMessage('log', 'Log message');
|
||||
|
||||
expect(getConsoleMessages()).toHaveLength(2);
|
||||
expect(getHasConsoleErrors()).toBe(true);
|
||||
|
||||
clearConsoleMessages();
|
||||
|
||||
expect(getConsoleMessages()).toHaveLength(0);
|
||||
expect(getHasConsoleErrors()).toBe(false);
|
||||
});
|
||||
|
||||
it('should notify listeners when messages are cleared', () => {
|
||||
const listener = vi.fn();
|
||||
addConsoleMessageListener(listener);
|
||||
|
||||
addConsoleMessage('error', 'Error message');
|
||||
expect(listener).toHaveBeenCalledTimes(1);
|
||||
|
||||
clearConsoleMessages();
|
||||
expect(listener).toHaveBeenCalledTimes(2);
|
||||
|
||||
removeConsoleMessageListener(listener);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Message Listeners', () => {
|
||||
it('should add and remove listeners correctly', () => {
|
||||
const listener1 = vi.fn();
|
||||
const listener2 = vi.fn();
|
||||
|
||||
addConsoleMessageListener(listener1);
|
||||
addConsoleMessageListener(listener2);
|
||||
|
||||
addConsoleMessage('error', 'Test error');
|
||||
|
||||
expect(listener1).toHaveBeenCalledTimes(1);
|
||||
expect(listener2).toHaveBeenCalledTimes(1);
|
||||
|
||||
removeConsoleMessageListener(listener1);
|
||||
clearConsoleMessages();
|
||||
|
||||
expect(listener1).toHaveBeenCalledTimes(1); // Only called once (not for clear)
|
||||
expect(listener2).toHaveBeenCalledTimes(2); // Called for both add and clear
|
||||
|
||||
removeConsoleMessageListener(listener2);
|
||||
});
|
||||
|
||||
it('should handle listener errors gracefully', () => {
|
||||
const faultyListener = vi.fn(() => {
|
||||
throw new Error('Listener error');
|
||||
});
|
||||
const workingListener = vi.fn();
|
||||
|
||||
addConsoleMessageListener(faultyListener);
|
||||
addConsoleMessageListener(workingListener);
|
||||
|
||||
// Should not throw despite faulty listener
|
||||
expect(() => {
|
||||
addConsoleMessage('error', 'Test error');
|
||||
}).not.toThrow();
|
||||
|
||||
expect(faultyListener).toHaveBeenCalled();
|
||||
expect(workingListener).toHaveBeenCalled();
|
||||
|
||||
removeConsoleMessageListener(faultyListener);
|
||||
removeConsoleMessageListener(workingListener);
|
||||
});
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,65 +0,0 @@
|
||||
/**
|
||||
* Global console message storage and state management.
|
||||
* This module handles the core console message system that the AI tool reads from.
|
||||
*/
|
||||
|
||||
export interface ConsoleMessage {
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
// Global console messages storage
|
||||
const consoleMessages: ConsoleMessage[] = [];
|
||||
const listeners: Array<() => void> = [];
|
||||
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach(listener => {
|
||||
try {
|
||||
listener();
|
||||
} catch (err) {
|
||||
console.warn('Console message listener failed:', err);
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
consoleMessages.push({ level, message });
|
||||
notifyListeners();
|
||||
};
|
||||
|
||||
export const addConsoleMessageListener = (listener: () => void) => {
|
||||
listeners.push(listener);
|
||||
};
|
||||
|
||||
export const removeConsoleMessageListener = (listener: () => void) => {
|
||||
const index = listeners.indexOf(listener);
|
||||
if (index > -1) {
|
||||
listeners.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
export const getHasConsoleErrors = (): boolean => {
|
||||
return consoleMessages.some(msg => msg.level === 'error');
|
||||
};
|
||||
|
||||
export const getConsoleMessages = (): ConsoleMessage[] => {
|
||||
return [...consoleMessages];
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
consoleMessages.length = 0;
|
||||
notifyListeners();
|
||||
};
|
||||
@@ -1,145 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import {
|
||||
parseCSP,
|
||||
stringifyCSP,
|
||||
addSourceToDirective,
|
||||
addDomainToCSP,
|
||||
type CSPDirectives
|
||||
} from './csp';
|
||||
|
||||
describe('parseCSP', () => {
|
||||
it('should parse basic CSP with multiple directives', () => {
|
||||
const csp = "default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *";
|
||||
const result = parseCSP(csp);
|
||||
|
||||
expect(result).toEqual({
|
||||
'default-src': ["'self'"],
|
||||
'script-src': ["'self'", "'unsafe-inline'"],
|
||||
'img-src': ['*']
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle directives without sources', () => {
|
||||
const csp = "upgrade-insecure-requests; block-all-mixed-content";
|
||||
const result = parseCSP(csp);
|
||||
|
||||
expect(result).toEqual({
|
||||
'upgrade-insecure-requests': [],
|
||||
'block-all-mixed-content': []
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle empty or whitespace-only CSP', () => {
|
||||
expect(parseCSP('')).toEqual({});
|
||||
expect(parseCSP(' ')).toEqual({});
|
||||
expect(parseCSP(';;;')).toEqual({});
|
||||
});
|
||||
|
||||
it('should handle extra whitespace and semicolons', () => {
|
||||
const csp = " default-src 'self' ; script-src 'self' ; ";
|
||||
const result = parseCSP(csp);
|
||||
|
||||
expect(result).toEqual({
|
||||
'default-src': ["'self'"],
|
||||
'script-src': ["'self'"]
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('stringifyCSP', () => {
|
||||
it('should convert directives back to CSP string', () => {
|
||||
const directives: CSPDirectives = {
|
||||
'default-src': ["'self'"],
|
||||
'script-src': ["'self'", "'unsafe-inline'"],
|
||||
'img-src': ['*']
|
||||
};
|
||||
|
||||
const result = stringifyCSP(directives);
|
||||
expect(result).toBe("default-src 'self'; script-src 'self' 'unsafe-inline'; img-src *");
|
||||
});
|
||||
|
||||
it('should handle directives without sources', () => {
|
||||
const directives: CSPDirectives = {
|
||||
'upgrade-insecure-requests': [],
|
||||
'default-src': ["'self'"]
|
||||
};
|
||||
|
||||
const result = stringifyCSP(directives);
|
||||
expect(result).toBe("upgrade-insecure-requests; default-src 'self'");
|
||||
});
|
||||
|
||||
it('should handle empty directives object', () => {
|
||||
expect(stringifyCSP({})).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('addSourceToDirective', () => {
|
||||
it('should add new source to existing sources', () => {
|
||||
const sources = ["'self'", "'unsafe-inline'"];
|
||||
const result = addSourceToDirective(sources, 'https://example.com');
|
||||
|
||||
expect(result).toEqual(["'self'", "'unsafe-inline'", 'https://example.com']);
|
||||
});
|
||||
|
||||
it('should not duplicate existing sources', () => {
|
||||
const sources = ["'self'", 'https://example.com'];
|
||||
const result = addSourceToDirective(sources, 'https://example.com');
|
||||
|
||||
expect(result).toEqual(["'self'", 'https://example.com']);
|
||||
});
|
||||
|
||||
it('should replace none with new source', () => {
|
||||
const sources = ["'none'"];
|
||||
const result = addSourceToDirective(sources, 'https://example.com');
|
||||
|
||||
expect(result).toEqual(['https://example.com']);
|
||||
});
|
||||
|
||||
it('should replace none even with other sources present', () => {
|
||||
const sources = ["'self'", "'none'", "'unsafe-inline'"];
|
||||
const result = addSourceToDirective(sources, 'https://example.com');
|
||||
|
||||
expect(result).toEqual(["'self'", 'https://example.com', "'unsafe-inline'"]);
|
||||
});
|
||||
|
||||
it('should handle empty sources array', () => {
|
||||
const sources: string[] = [];
|
||||
const result = addSourceToDirective(sources, 'https://example.com');
|
||||
|
||||
expect(result).toEqual(['https://example.com']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('addDomainToCSP', () => {
|
||||
it('should add domain to specified directives', () => {
|
||||
const csp = "default-src 'self'; script-src 'self'; img-src 'self'";
|
||||
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']);
|
||||
|
||||
expect(result).toContain('script-src \'self\' https://cdn.example.com');
|
||||
expect(result).toContain('img-src \'self\' https://cdn.example.com');
|
||||
expect(result).toContain('default-src \'self\''); // unchanged
|
||||
});
|
||||
|
||||
it('should not modify directives that do not exist', () => {
|
||||
const csp = "default-src 'self'";
|
||||
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src', 'img-src']);
|
||||
|
||||
expect(result).toBe("default-src 'self'");
|
||||
});
|
||||
|
||||
it('should handle multiple domains being added', () => {
|
||||
const csp = "script-src 'self'";
|
||||
let result = addDomainToCSP(csp, 'https://cdn1.example.com', ['script-src']);
|
||||
result = addDomainToCSP(result, 'https://cdn2.example.com', ['script-src']);
|
||||
|
||||
expect(result).toBe("script-src 'self' https://cdn1.example.com https://cdn2.example.com");
|
||||
});
|
||||
|
||||
it('should replace none in specified directives', () => {
|
||||
const csp = "default-src 'self'; script-src 'none'; img-src 'self'";
|
||||
const result = addDomainToCSP(csp, 'https://cdn.example.com', ['script-src']);
|
||||
|
||||
expect(result).toContain('script-src https://cdn.example.com');
|
||||
expect(result).toContain('img-src \'self\''); // unchanged
|
||||
});
|
||||
});
|
||||
@@ -1,87 +0,0 @@
|
||||
/**
|
||||
* Content Security Policy (CSP) utilities for managing and updating CSP directives
|
||||
*/
|
||||
|
||||
export interface CSPDirectives {
|
||||
[directive: string]: string[];
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a CSP string into a structured format
|
||||
*/
|
||||
export function parseCSP(csp: string): CSPDirectives {
|
||||
const directives: CSPDirectives = {};
|
||||
|
||||
// Split by semicolon and parse each directive
|
||||
csp.split(';').forEach(directive => {
|
||||
const trimmed = directive.trim();
|
||||
if (!trimmed) return;
|
||||
|
||||
const parts = trimmed.split(/\s+/);
|
||||
const directiveName = parts[0];
|
||||
const sources = parts.slice(1);
|
||||
|
||||
directives[directiveName] = sources;
|
||||
});
|
||||
|
||||
return directives;
|
||||
}
|
||||
|
||||
/**
|
||||
* Converts CSP directives back to a string format
|
||||
*/
|
||||
export function stringifyCSP(directives: CSPDirectives): string {
|
||||
const directiveStrings: string[] = [];
|
||||
|
||||
Object.entries(directives).forEach(([directiveName, sources]) => {
|
||||
if (sources.length > 0) {
|
||||
directiveStrings.push(`${directiveName} ${sources.join(' ')}`);
|
||||
} else {
|
||||
directiveStrings.push(directiveName);
|
||||
}
|
||||
});
|
||||
|
||||
return directiveStrings.join('; ');
|
||||
}
|
||||
|
||||
/**
|
||||
* Adds a source to a CSP directive, handling special cases
|
||||
*/
|
||||
export function addSourceToDirective(sources: string[], newSource: string): string[] {
|
||||
// Don't add if already present
|
||||
if (sources.includes(newSource)) {
|
||||
return sources;
|
||||
}
|
||||
|
||||
// If 'none' is present, replace it with the new source
|
||||
if (sources.includes("'none'")) {
|
||||
const noneIndex = sources.indexOf("'none'");
|
||||
const newSources = [...sources];
|
||||
newSources[noneIndex] = newSource;
|
||||
return newSources;
|
||||
}
|
||||
|
||||
// Add to existing sources
|
||||
return [...sources, newSource];
|
||||
}
|
||||
|
||||
/**
|
||||
* Updates CSP directives to allow a specific domain for multiple directive types
|
||||
*/
|
||||
export function addDomainToCSP(
|
||||
csp: string,
|
||||
domain: string,
|
||||
directiveTypes: string[]
|
||||
): string {
|
||||
const directives = parseCSP(csp);
|
||||
|
||||
// Add domain to each relevant directive if it exists
|
||||
directiveTypes.forEach(directiveName => {
|
||||
const sources = directives[directiveName];
|
||||
if (sources) {
|
||||
directives[directiveName] = addSourceToDirective(sources, domain);
|
||||
}
|
||||
});
|
||||
|
||||
return stringifyCSP(directives);
|
||||
}
|
||||
@@ -1,6 +1,12 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool';
|
||||
import { addConsoleMessage, clearConsoleMessages } from '@/lib/consoleMessages';
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import {
|
||||
ReadConsoleMessagesTool,
|
||||
addConsoleMessage,
|
||||
clearConsoleMessages,
|
||||
ProjectPreviewConsoleError,
|
||||
addErrorListener,
|
||||
removeErrorListener
|
||||
} from './ReadConsoleMessagesTool';
|
||||
|
||||
describe('ReadConsoleMessagesTool', () => {
|
||||
beforeEach(() => {
|
||||
@@ -57,43 +63,106 @@ describe('ReadConsoleMessagesTool', () => {
|
||||
|
||||
expect(result).toBe('No console messages found for level: debug.');
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle all filter levels', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
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);
|
||||
|
||||
// Test each filter level
|
||||
const errorResult = await tool.execute({ filter: 'error' });
|
||||
expect(errorResult).toContain('[ERROR] Network request failed');
|
||||
|
||||
const warnResult = await tool.execute({ filter: 'warn' });
|
||||
expect(warnResult).toContain('[WARN] Deprecated API used');
|
||||
|
||||
const logResult = await tool.execute({ filter: 'log' });
|
||||
expect(logResult).toContain('[LOG] App started');
|
||||
|
||||
const infoResult = await tool.execute({ filter: 'info' });
|
||||
expect(infoResult).toContain('[INFO] User logged in');
|
||||
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);
|
||||
});
|
||||
});
|
||||
|
||||
it('should format messages correctly', async () => {
|
||||
describe('Console Error Listeners', () => {
|
||||
beforeEach(() => {
|
||||
clearConsoleMessages();
|
||||
addConsoleMessage('error', 'Test error with special chars: <>&"');
|
||||
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toContain('[ERROR] Test error with special chars: <>&"');
|
||||
});
|
||||
|
||||
it('should handle limit correctly', async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
it('should trigger error listener when console error is added', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
|
||||
// Limit should return only the most recent messages
|
||||
const limitedResult = await tool.execute({ limit: 2 });
|
||||
expect(limitedResult).toContain('Found 2 console messages');
|
||||
// Add an error message
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
|
||||
// No limit should return all messages
|
||||
const allResult = await tool.execute({});
|
||||
expect(allResult).toContain('Found 4 console messages');
|
||||
// Wait a bit for the listener to be called
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
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'
|
||||
})
|
||||
])
|
||||
})
|
||||
);
|
||||
|
||||
removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
it('should not trigger error listener for non-error messages', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
|
||||
// Add non-error messages
|
||||
addConsoleMessage('log', 'Test log message');
|
||||
addConsoleMessage('warn', 'Test warning message');
|
||||
addConsoleMessage('info', 'Test info message');
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
|
||||
removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
it('should remove error listener correctly', async () => {
|
||||
const errorListener = vi.fn();
|
||||
addErrorListener(errorListener);
|
||||
removeErrorListener(errorListener);
|
||||
|
||||
// Add an error message
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle listener errors gracefully', async () => {
|
||||
const faultyListener = vi.fn(() => {
|
||||
throw new Error('Listener error');
|
||||
});
|
||||
const workingListener = vi.fn();
|
||||
|
||||
addErrorListener(faultyListener);
|
||||
addErrorListener(workingListener);
|
||||
|
||||
// Should not throw despite faulty listener
|
||||
expect(() => {
|
||||
addConsoleMessage('error', 'Test error message');
|
||||
}).not.toThrow();
|
||||
|
||||
// Wait a bit
|
||||
await new Promise(resolve => setTimeout(resolve, 10));
|
||||
|
||||
expect(faultyListener).toHaveBeenCalled();
|
||||
expect(workingListener).toHaveBeenCalled();
|
||||
|
||||
removeErrorListener(faultyListener);
|
||||
removeErrorListener(workingListener);
|
||||
});
|
||||
});
|
||||
@@ -1,5 +1,9 @@
|
||||
import { Tool } from './Tool';
|
||||
import { getConsoleMessages } from '@/lib/consoleMessages';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export interface ReadConsoleMessagesParams {
|
||||
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
||||
@@ -7,30 +11,87 @@ export interface ReadConsoleMessagesParams {
|
||||
}
|
||||
|
||||
/**
|
||||
* AI tool for reading console messages from the project preview.
|
||||
* This tool allows AI assistants to access console logs for debugging assistance.
|
||||
* 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;
|
||||
}
|
||||
}
|
||||
|
||||
// Simple global console messages storage
|
||||
const consoleMessages: ConsoleMessage[] = [];
|
||||
const errorListeners: Array<(error: ProjectPreviewConsoleError) => void> = [];
|
||||
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
const consoleMessage: ConsoleMessage = {
|
||||
level,
|
||||
message,
|
||||
};
|
||||
|
||||
consoleMessages.push(consoleMessage);
|
||||
|
||||
// If this is an error, notify listeners
|
||||
if (level === 'error') {
|
||||
const error = new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${message}`,
|
||||
consoleMessages.filter(msg => msg.level === 'error')
|
||||
);
|
||||
|
||||
errorListeners.forEach(listener => {
|
||||
try {
|
||||
listener(error);
|
||||
} catch (err) {
|
||||
console.warn('Error listener failed:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const getConsoleMessages = (): ConsoleMessage[] => {
|
||||
return [...consoleMessages];
|
||||
};
|
||||
|
||||
export const addErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
errorListeners.push(listener);
|
||||
};
|
||||
|
||||
export const removeErrorListener = (listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
const index = errorListeners.indexOf(listener);
|
||||
if (index > -1) {
|
||||
errorListeners.splice(index, 1);
|
||||
}
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
consoleMessages.length = 0;
|
||||
};
|
||||
|
||||
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||
const { filter = 'all', limit } = params;
|
||||
|
||||
let messages = getConsoleMessages()
|
||||
.filter(msg => filter === 'all' || msg.level === filter);
|
||||
// Filter and limit messages in one chain
|
||||
const filteredMessages = getConsoleMessages()
|
||||
.filter(msg => filter === 'all' || msg.level === filter)
|
||||
.slice(limit && limit > 0 ? -limit : 0);
|
||||
|
||||
if (limit && limit > 0) {
|
||||
messages = messages.slice(-limit);
|
||||
}
|
||||
|
||||
if (messages.length === 0) {
|
||||
if (filteredMessages.length === 0) {
|
||||
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||
}
|
||||
|
||||
const formatted = messages
|
||||
const formattedMessages = filteredMessages
|
||||
.map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`)
|
||||
.join('\n');
|
||||
|
||||
const suffix = filter !== 'all' ? ` (level: ${filter})` : '';
|
||||
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}:\n\n${formatted}`;
|
||||
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.';
|
||||
|
||||
@@ -16,8 +16,6 @@ export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI
|
||||
|
||||
if (tool.inputSchema) {
|
||||
functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema);
|
||||
} else {
|
||||
functionDef.parameters = {};
|
||||
}
|
||||
|
||||
return {
|
||||
|
||||
@@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -29,9 +29,7 @@ export function ProjectView() {
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
|
||||
// Use console error state from provider
|
||||
const { consoleError, dismissConsoleError, clearErrors } = useConsoleError();
|
||||
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
|
||||
|
||||
const projectsManager = useProjectsManager();
|
||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||
@@ -50,13 +48,14 @@ export function ProjectView() {
|
||||
const projectData = await projectsManager.getProject(projectId);
|
||||
setProject(projectData);
|
||||
// Clear console messages and error state when switching projects
|
||||
clearErrors();
|
||||
clearConsoleMessages();
|
||||
setConsoleError(null);
|
||||
} catch (error) {
|
||||
console.error('Failed to load project:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectId, projectsManager, clearErrors]);
|
||||
}, [projectId, projectsManager]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProject();
|
||||
@@ -82,6 +81,16 @@ export function ProjectView() {
|
||||
}
|
||||
}, [isPreviewable, mobileView, activeTab]);
|
||||
|
||||
// Global console error listener (always active regardless of current tab)
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
setConsoleError(error);
|
||||
};
|
||||
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, []);
|
||||
|
||||
const handleNewChat = () => {
|
||||
// Reset to chat view on mobile when starting new chat
|
||||
if (isMobile) {
|
||||
@@ -104,7 +113,7 @@ export function ProjectView() {
|
||||
};
|
||||
|
||||
const handleDismissConsoleError = () => {
|
||||
dismissConsoleError();
|
||||
setConsoleError(null);
|
||||
};
|
||||
|
||||
const handleProjectDeleted = async () => {
|
||||
|
||||
@@ -13,7 +13,6 @@ export default defineConfig(() => ({
|
||||
react(),
|
||||
],
|
||||
build: {
|
||||
sourcemap: true,
|
||||
rollupOptions: {
|
||||
output: {
|
||||
manualChunks(id) {
|
||||
|
||||
Reference in new issue
Block a user