Compare commits

..
Author SHA1 Message Date
sam e5368fa5f7 keep the prompt queueing feature, but lose the UI for viewing stacked messages 2025-10-03 17:18:08 +07:00
sam e8220e0dae Merge branch 'main' into ui/38-ability-to-type-in-chat-box-when-shakespeare-is-working 2025-10-03 17:07:14 +07:00
Alex Gleason 388afd0b16 Enable sourcemap in Shakespeare itself 2025-10-02 17:59:29 -05:00
Alex Gleason 5f2faaad61 Fix xAI tool definitions
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/57
2025-10-02 17:57:36 -05:00
Alex Gleason aaf30db257 Add DeepSeek as a preset provider
Fixes https://gitlab.com/soapbox-pub/shakespeare/-/issues/58
2025-10-02 17:46:08 -05:00
Alex Gleason d4c775828f Fix build tests 2025-10-02 17:36:42 -05:00
Alex Gleason cbf85313af Enable sourcemap, fix output filenames 2025-10-02 17:30:12 -05:00
Alex Gleason 0b7f9cd2cb Update browserlist 2025-10-02 16:24:14 -05:00
Alex Gleason e0620bcca0 Merge branch 'consoleFramev4' into 'main'
Refactor console error to be provider level, simplifying console message/error tracking

See merge request soapbox-pub/shakespeare!48
2025-10-02 21:21:58 +00:00
Chad Curtis 97f5481ec7 Only clear console messages when project actually changes. 2025-10-02 20:58:56 +00:00
Alex Gleason 225c90f556 Surgically add esm.sh to existing CSP of index.html 2025-10-02 15:43:27 -05:00
Chad Curtis 51ce9c61ef Remove spurrious migration comment. 2025-10-02 20:30:02 +00:00
Alex Gleason c72170f19c Build by actually mimicking Vite's handling of index.html 2025-10-02 15:26:27 -05:00
Chad Curtis 111ab724e5 Remove and simplify some logic. 2025-10-02 20:15:30 +00:00
Chad Curtis 23c3cead89 Move non-tool logic out of tool file. 2025-10-02 20:09:09 +00:00
Chad Curtis 945c4209e8 Remove frivilous UI updates. 2025-10-02 20:02:16 +00:00
Chad Curtis 7574085213 Refactor console error to be provider level, tracking error via boolean rather than full logs as state. 2025-10-02 19:58:53 +00:00
Alex Gleason 3fba26ddb7 Switch payment method to a tabbed UI instead of dropdown 2025-10-01 17:24:22 -05:00
Alex Gleason bbcc56c800 Fix ModelSelector test 2025-10-01 17:13:23 -05:00
Alex Gleason cb794b5719 We do a little discord coding 2025-10-01 17:08:31 -05:00
Alex Gleason 931733ba16 Add warning to model selector if a free model is chosen 2025-10-01 16:38:16 -05:00
shakespeare.diy 52fe76c9c6 Improve README: Add 🎭 emoji, website link, edit button, and license 2025-09-30 20:00:08 -05:00
sam 4782d72129 lint 2025-09-29 21:53:32 +07:00
sam 8cf013e7e4 wip drafts showing in sidebar 2025-09-29 21:36:50 +07:00
sam 87cc79bda8 wip drafts 2025-09-29 20:44:58 +07:00
sam 8f2623f02d per project message queue 2025-09-29 18:05:01 +07:00
sam 24af13c330 send all queued messages together 2025-09-29 17:58:25 +07:00
sam 362880a3f4 focus ring outwith the queued message indicator 2025-09-29 17:41:37 +07:00
sam 2d3fd550fb show indicator for queued messages between new message composer and current chat to convey visual hierarchy of message flow 2025-09-29 17:22:41 +07:00
sam fc33179adc wip queue messages while the model works 2025-09-29 17:17:02 +07:00
33 changed files with 1900 additions and 717 deletions

No files matched your search

+29 -76
View File
@@ -1,85 +1,38 @@
# Shakespeare - AI-Powered Nostr Website Builder
# Shakespeare 🎭
Shakespeare is an AI chat application that allows users to build custom Nostr websites through natural language conversation. Simply describe what you want to build, and AI will help you create it.
[![Edit with Shakespeare](https://shakespeare.diy/badge.svg)](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git)
AI-powered Nostr website builder. Describe what you want to build, and AI helps you create it.
https://shakespeare.diy
## Features
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
- **Project Management**: Create and manage multiple projects with sidebar navigation
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
- **File Explorer**: Browse and manage your project files
- **Project Preview**: Preview your website as you build it
- **Template Cloning**: Start from a pre-configured Nostr template
- **AI Chat**: Build websites through natural conversation
- **File Attachments**: Drag & drop files or paste images
- **Live Preview**: See changes in real-time
- **Code Editor**: Edit files with syntax highlighting
- **Git Integration**: Full version control with credential management
- **Nostr Ready**: Built-in Nostr protocol support
## Quick Start
1. **Describe** your project in the textarea
2. **Chat** with AI to build features
3. **Preview** your website instantly
4. **Deploy** with one click
## Tech Stack
- React 18 + TypeScript
- Vite + TailwindCSS
- shadcn/ui + Nostrify
- LightningFS + isomorphic-git
## Getting Started
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename"
4. **Edit Code**: Switch to the code view to manually edit files if needed
5. **Preview**: View your website in the preview pane
Visit the homepage, enter your project idea, and start building with AI assistance.
## Project Structure
## License
Each project includes:
- React 18 with TypeScript
- Vite for building
- TailwindCSS for styling
- Nostrify for Nostr integration
- shadcn/ui components
## AI Capabilities
The AI assistant can:
- Read and write project files
- Add new components and pages
- Configure Nostr functionality
- Build the project
- Search through files
- Provide project structure overview
- Add and remove npm packages
- Install dependencies and dev dependencies
## Usage
1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
3. **File Explorer**: Navigate your project files in the code view
4. **File Editor**: Edit files with syntax highlighting and save changes
## Git Integration
Shakespeare includes full Git functionality with credential management:
### Features
- **Version Control**: Full Git repository support with commit history and branch management
- **Global Credentials**: Configure Git credentials once and use them across all projects
- **Automatic Matching**: Credentials are automatically matched to repository origins
- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers
- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB
### Setting Up Git Credentials
1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option
2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider
3. **Enter Token**: Use your username and personal access token for authentication
4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories
### Repository Operations
- **Push/Pull**: Sync changes with remote repositories using configured credentials
- **Status Monitoring**: Real-time Git status with file changes and sync information
- **Commit History**: View commit history and repository information
- **Branch Management**: Work with different branches and track remote changes
## Development
Built with:
- React 18
- TypeScript
- Vite
- TailwindCSS
- shadcn/ui
- LightningFS for filesystem
- isomorphic-git for template cloning
AGPLv3
+3 -3
View File
@@ -4668,9 +4668,9 @@
}
},
"node_modules/caniuse-lite": {
"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==",
"version": "1.0.30001746",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001746.tgz",
"integrity": "sha512-eA7Ys/DGw+pnkWWSE/id29f2IcPHVoE8wxtvE5JdvD2V28VTDPy1yEeo11Guz0sJ4ZeGRcm3uaTcAqK1LXaphA==",
"dev": true,
"funding": [
{
+19 -16
View File
@@ -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 { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
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>
<ConsoleErrorProvider>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<GitSettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
</FSProvider>
</AppProvider>
</QueryClientProvider>
@@ -0,0 +1,152 @@
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'
]);
});
});
+63
View File
@@ -0,0 +1,63 @@
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>
);
}
+14 -21
View File
@@ -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 { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Tabs, TabsList, TabsTrigger } from '@/components/ui/tabs';
import { useToast } from '@/hooks/useToast';
import { createAIClient } from '@/lib/ai-client';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -464,26 +464,19 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</div>
<div className="space-y-3">
<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>
<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>
</div>
<Button
+230 -5
View File
@@ -1,5 +1,7 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Decimal } from 'decimal.js';
import { TestApp } from '@/test/TestApp';
import { ModelSelector } from './ModelSelector';
@@ -12,6 +14,10 @@ vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: vi.fn(),
}));
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: vi.fn(),
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
@@ -22,9 +28,11 @@ vi.mock('react-router-dom', async (importOriginal) => {
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseProviderModels = vi.mocked(useProviderModels);
const mockUseIsMobile = vi.mocked(useIsMobile);
describe('ModelSelector', () => {
const mockOnChange = vi.fn();
@@ -41,7 +49,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
mockUseProviderModels.mockReturnValue({
@@ -50,6 +58,8 @@ describe('ModelSelector', () => {
error: null,
refetch: vi.fn(),
});
mockUseIsMobile.mockReturnValue(false);
});
it('hides recently used section when less than 5 models and all recently used are available', async () => {
@@ -77,7 +87,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -124,7 +134,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -173,7 +183,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -216,7 +226,7 @@ describe('ModelSelector', () => {
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
});
render(
@@ -237,4 +247,219 @@ describe('ModelSelector', () => {
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
});
it('shows caution icon for free models', async () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
const paidModel = {
fullId: 'provider1/paid-model',
provider: 'provider1',
id: 'paid-model',
pricing: {
prompt: new Decimal('0.01'),
completion: new Decimal('0.02'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel, paidModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
// Test with free model selected
const { rerender } = render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
// Should show caution icon for free model
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
// Test with paid model selected
rerender(
<TestApp>
<ModelSelector value="provider1/paid-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for paid model
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon when no model is selected', () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon when no model is selected
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon for models without pricing information', () => {
const modelWithoutPricing = {
fullId: 'provider1/unknown-pricing',
provider: 'provider1',
id: 'unknown-pricing',
// No pricing property
};
mockUseProviderModels.mockReturnValue({
models: [modelWithoutPricing],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-pricing" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for models without pricing info
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('shows tooltip when hovering over caution icon', async () => {
const user = userEvent.setup();
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionIcon = screen.getByTestId('triangle-alert');
expect(cautionIcon).toBeInTheDocument();
// Hover over the caution icon
await user.hover(cautionIcon);
// Wait for tooltip to appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
});
it('makes caution icon tappable on mobile with click-to-toggle tooltip', async () => {
const user = userEvent.setup();
mockUseIsMobile.mockReturnValue(true);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Free model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile
// Click to open tooltip - just verify the click works without errors
await user.click(cautionButton);
// Tooltip should appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
// The button should still be clickable (no errors)
await user.click(cautionButton);
expect(cautionButton).toBeInTheDocument();
});
it('makes caution icon not focusable on desktop', () => {
mockUseIsMobile.mockReturnValue(false);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Free model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop
});
});
+243 -152
View File
@@ -1,14 +1,16 @@
import { useState, useMemo } from 'react';
import { useState, useMemo, useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
interface ModelSelectorProps {
@@ -32,6 +34,7 @@ export function ModelSelector({
}: ModelSelectorProps) {
const { t } = useTranslation();
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
// Use controlled state if provided, otherwise use local state
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
@@ -42,6 +45,7 @@ export function ModelSelector({
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const isMobile = useIsMobile();
const defaultPlaceholder = t('selectOrEnterModel');
@@ -82,9 +86,43 @@ export function ModelSelector({
return !allRecentlyUsedAreAvailable;
}, [recentlyUsedModels, models]);
// Check if the current model is free
const isCurrentModelFree = useMemo(() => {
if (!value) return false;
const currentModel = models.find(model => model.fullId === value);
if (!currentModel?.pricing) return false;
return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0);
}, [value, models]);
// Don't auto-initialize with recently used models
// Let the parent component handle initialization
// Close tooltip when clicking outside on mobile
useEffect(() => {
if (!isMobile || !isTooltipOpen) return;
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
const target = event.target as Element;
// Check if the click is outside the tooltip and trigger
if (!target.closest('[data-radix-tooltip-content]') &&
!target.closest('[data-radix-tooltip-trigger]') &&
!target.closest('[data-testid="triangle-alert"]')) {
setIsTooltipOpen(false);
}
};
// Add both click and touch event listeners
document.addEventListener('click', handleClickOutside, true);
document.addEventListener('touchstart', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
document.removeEventListener('touchstart', handleClickOutside, true);
};
}, [isMobile, isTooltipOpen]);
const handleSelect = (selectedValue: string) => {
if (selectedValue === '__custom__') {
setIsCustomInput(true);
@@ -125,169 +163,222 @@ export function ModelSelector({
if (isCustomInput) {
return (
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
<TooltipProvider>
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
</TooltipProvider>
);
}
return (
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
className
)}
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end">
<Command>
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList className="max-h-[300px]">
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</CommandEmpty>
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem>
))}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
<TooltipProvider>
<div className={cn("flex justify-end gap-0.5", className)}>
{isCurrentModelFree && (
<Tooltip
open={isMobile ? isTooltipOpen : undefined}
onOpenChange={isMobile ? setIsTooltipOpen : undefined}
delayDuration={isMobile ? 0 : 700}
disableHoverableContent={isMobile}
>
<TooltipTrigger asChild>
<button
type="button"
className="inline-flex items-center p-0 rounded-none border-0 bg-transparent hover:bg-transparent focus:bg-transparent active:bg-transparent focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 focus:border-0 active:outline-none"
aria-label="Free model warning"
tabIndex={isMobile ? 0 : -1}
onClick={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : undefined}
onTouchStart={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
} : undefined}
onTouchEnd={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : undefined}
style={{
WebkitTapHighlightColor: 'transparent',
outline: 'none',
border: 'none',
boxShadow: 'none'
}}
>
<TriangleAlert className="h-3 w-3 text-amber-500 flex-shrink-0" data-testid="triangle-alert" />
</button>
</TooltipTrigger>
<TooltipContent
side="top"
sideOffset={4}
className="max-w-xs text-center"
avoidCollisions={true}
collisionPadding={8}
>
<p>You are using a free model. For better results, switch to a paid model.</p>
</TooltipContent>
</Tooltip>
)}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0"
)}
disabled={disabled}
>
<span className="truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0" align="end">
<Command>
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList className="max-h-[300px]">
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</div>
</CommandGroup>
)}
</CommandEmpty>
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => (
<CommandItem
key={model}
value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem>
))}
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</CommandGroup>
)}
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
</CommandItem>
))}
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandGroup>
{isConfigured && (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
))}
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
</TooltipProvider>
);
}
+3
View File
@@ -11,6 +11,9 @@ 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 {
+13 -3
View File
@@ -1,13 +1,14 @@
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 } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Pencil } 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';
@@ -19,9 +20,10 @@ interface ProjectItemProps {
isSelected: boolean;
onSelect: (project: Project) => void;
isFavorite?: boolean;
hasDraft?: boolean;
}
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite }) => {
const ProjectItem: React.FC<ProjectItemProps> = ({ project, isSelected, onSelect, isFavorite, hasDraft }) => {
const navigate = useNavigate();
const { hasRunningSessions } = useProjectSessionStatus(project.id);
@@ -51,10 +53,16 @@ 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">
<div className="min-w-0 flex-1 flex items-center gap-2">
<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 */}
@@ -93,6 +101,7 @@ 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();
@@ -221,6 +230,7 @@ export function ProjectSidebar({
isSelected={selectedProject?.id === project.id}
onSelect={onSelectProject}
isFavorite={favorites.includes(project.id)}
hasDraft={hasDraft(project.id)}
/>
))}
</div>
+1 -1
View File
@@ -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/tools/ReadConsoleMessagesTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { useState } from 'react';
export interface QuillyProps {
+228 -120
View File
@@ -8,13 +8,15 @@ 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 } from 'lucide-react';
import { Square, Loader2, ChevronDown, ArrowUp, Plus } 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';
@@ -34,7 +36,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, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool';
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
@@ -84,6 +87,11 @@ 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;
@@ -130,6 +138,12 @@ 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(() => {
@@ -257,6 +271,64 @@ 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;
@@ -411,8 +483,6 @@ 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;
@@ -421,7 +491,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
};
const send = useCallback(async (input: string, attachedFiles: File[]) => {
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
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 AI is not configured, show onboarding dialog
if (!isConfigured) {
@@ -472,6 +551,7 @@ 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);
@@ -479,7 +559,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, fs, isConfigured, isLoading, providerModel, sendMessage]);
}, [addRecentlyUsedModel, addToQueue, clearDraft, fs, isConfigured, isLoading, providerModel, sendMessage]);
const handleSend = useCallback(async () => {
await send(input, attachedFiles);
@@ -672,132 +752,160 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="border-t p-4">
{/* Chat Input Container */}
<div
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}
className={`${hasQueuedMessages ? 'focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 rounded-2xl' : ''} transition-all`}
>
<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';
}}
/>
{/* 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>
)}
{/* 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}
<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';
}}
/>
{/* 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}
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
open={isModelSelectorOpen}
onOpenChange={setIsModelSelectorOpen}
{/* 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}
/>
</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>
) : (
<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>
{/* 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>
{/* 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}
+18 -7
View File
@@ -3,7 +3,8 @@ 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/tools/ReadConsoleMessagesTool';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
@@ -90,6 +91,9 @@ 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();
@@ -453,6 +457,7 @@ 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('');
@@ -463,7 +468,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
setCurrentPath('/');
setNavigationHistory(['/']);
setHistoryIndex(0);
}, [projectId]);
// Only clear console messages when projectId actually changes (not on initial mount)
if (prevProjectIdRef.current && prevProjectIdRef.current !== projectId) {
clearErrors();
}
prevProjectIdRef.current = projectId;
}, [projectId, clearErrors]);
useEffect(() => {
checkForBuiltProject();
@@ -512,6 +523,8 @@ 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);
@@ -522,9 +535,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
};
const consoleMessages = getConsoleMessages();
const messageCount = consoleMessages.length;
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
const messageCount = messages.length;
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
@@ -535,7 +546,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
className="h-8 w-8 p-0 relative"
>
<Bug className="h-4 w-4" />
{hasErrors && (
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
@@ -555,7 +566,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>
) : (
consoleMessages.map((msg, index) => (
messages.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"
+11
View File
@@ -0,0 +1,11 @@
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);
+12
View File
@@ -0,0 +1,12 @@
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');
});
});
+16
View File
@@ -0,0 +1,16 @@
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;
}
+93
View File
@@ -0,0 +1,93 @@
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
};
}
+54
View File
@@ -0,0 +1,54 @@
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
};
}
+7
View File
@@ -64,6 +64,13 @@ 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
+14 -2
View File
@@ -16,9 +16,15 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin {
});
build.onResolve({ filter: /.*/ }, async (args) => {
let resolved: string;
// Skip resolving paths from external URLs
if (/^https?:\/\//.test(args.importer)) {
return;
}
if (args.path.startsWith("@/")) {
let resolved: string;
if (args.path.startsWith("/")) {
resolved = args.path;
} else if (args.path.startsWith("@/")) {
resolved = join(cwd, args.path.slice(2));
} else if (args.kind === "entry-point") {
resolved = join(cwd, args.path);
@@ -28,6 +34,12 @@ 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("?");
+52 -16
View File
@@ -9,14 +9,28 @@ vi.mock('../esbuild', () => ({
build: vi.fn(() => ({
outputFiles: [
{
path: '/stdin.js',
path: '/stdin-abc123.js',
contents: new Uint8Array([1, 2, 3]),
text: '',
hash: 'abc123',
},
{
path: '/stdin.css',
path: '/stdin-def456.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,
},
},
},
})),
})),
}));
@@ -52,9 +66,25 @@ describe('buildProject', () => {
documentElement: {
outerHTML: '<html><head></head><body><script src="/src/main.tsx"></script></body></html>',
},
querySelector: vi.fn(() => ({
setAttribute: vi.fn(),
})),
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',
},
],
head: {
appendChild: vi.fn(),
},
@@ -133,11 +163,13 @@ describe('buildProject', () => {
domParser: mockDOMParser,
});
// 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]));
// Should include built files with hashed names
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
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');
@@ -190,11 +222,13 @@ describe('buildProject', () => {
domParser: mockDOMParser,
});
// 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]));
// Should still include built files with hashed names
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
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');
@@ -246,13 +280,15 @@ describe('buildProject', () => {
domParser: mockDOMParser,
});
// 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]));
// Should include built files with hashed names
expect(result.files['stdin-abc123.js']).toEqual(new Uint8Array([1, 2, 3]));
expect(result.files['index.html']).toBeDefined();
// Should have exactly 3 files (main.js, main.css, index.html)
expect(Object.keys(result.files)).toHaveLength(3);
// 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 try to copy public files but directory is empty
expect(copyFiles).toHaveBeenCalledWith(mockFS, mockFS, '/test/project/public', '/test/project/dist');
+86 -31
View File
@@ -1,5 +1,7 @@
import { join } from "path-browserify";
import { getEsbuild } from "@/lib/esbuild";
import { copyFiles } from "@/lib/copyFiles";
import { addDomainToCSP } from "@/lib/csp";
import { shakespearePlugin } from "./shakespearePlugin";
import { esmPlugin } from "./esmPlugin";
@@ -32,25 +34,51 @@ 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({
stdin: {
contents: `
import "@/main.tsx";
import tailwindConfig from "@/../tailwind.config.ts";
import "https://esm.sh/tailwindcss-cdn@3";
tailwind.config = tailwindConfig;
`,
loader: "tsx",
},
entryPoints,
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(), // Takes precedence over esmPlugin
shakespearePlugin(),
fsPlugin(fs, `${projectPath}/src`),
esmPlugin(JSON.parse(packageLockText), target),
],
@@ -62,18 +90,40 @@ async function bundle(
const dist: Record<string, Uint8Array> = {};
for (const file of results.outputFiles) {
const relativePath = file.path.replace(/^\//, "");
if (relativePath === "stdin.js") {
dist["main.js"] = file.contents;
} else if (relativePath === "stdin.css") {
dist["main.css"] = file.contents;
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);
} else {
dist[relativePath] = file.contents;
dist[filename] = file.contents;
}
}
// Update index.html with proper script and link tags
updateIndexHtml(doc, dist);
// 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);
}
}
const updatedHtml = "<!DOCTYPE html>\n" + doc.documentElement.outerHTML;
dist["index.html"] = new TextEncoder().encode(updatedHtml);
@@ -156,20 +206,25 @@ export async function buildProject(options: BuildProjectOptions): Promise<{
};
}
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");
async function fileExists(fs: JSRuntimeFS, path: string): Promise<boolean> {
try {
const stat = await fs.stat(path);
return stat.isFile();
} catch {
return false;
}
}
entrypoint.setAttribute("src", "/main.js");
/** 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
];
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);
}
return addDomainToCSP(csp, 'https://esm.sh', esmShDirectives);
}
+20
View File
@@ -10,6 +10,26 @@ 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 {
+155
View File
@@ -0,0 +1,155 @@
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);
});
});
});
+65
View File
@@ -0,0 +1,65 @@
/**
* 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();
};
+145
View File
@@ -0,0 +1,145 @@
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
});
});
+87
View File
@@ -0,0 +1,87 @@
/**
* 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);
}
+12 -73
View File
@@ -908,16 +908,15 @@ export class Git {
'#d': [nostrURI.d],
};
// Always prioritize git.shakespeare.diy
const shakespeareRelayUrl = 'wss://git.shakespeare.diy/';
const otherGitRelays = [
const gitRelays = new Set<string>([
'wss://git.shakespeare.diy/',
'wss://relay.ngit.dev/',
'wss://relay.nostr.band/', // General purpose relay as fallback
];
]);
let events: NostrEvent[] = [];
// Try the specified relay first if provided
// Try the specified relay first, then fall back to known Git relays
if (nostrURI.relay) {
try {
events = await this.nostr.relay(nostrURI.relay).query([filter], { signal: AbortSignal.timeout(1000) });
@@ -925,30 +924,11 @@ export class Git {
console.error(`Error querying relay ${nostrURI.relay}: ${error}`);
}
}
// If no events from specified relay, try git.shakespeare.diy first
if (!events.length) {
try {
console.log(`Trying git.shakespeare.diy first...`);
events = await this.nostr.relay(shakespeareRelayUrl).query([filter], { signal: AbortSignal.timeout(3000) });
if (events.length > 0) {
console.log(`✓ Found events on ${shakespeareRelayUrl}`);
}
events = await this.nostr.group([...gitRelays]).query([filter], { signal: AbortSignal.timeout(5000) });
} catch (error) {
console.error(`Error querying ${shakespeareRelayUrl}: ${error}`);
}
}
// If still no events, try other git relays
if (!events.length) {
try {
console.log(`Trying other git relays: ${otherGitRelays.join(', ')}`);
events = await this.nostr.group(otherGitRelays).query([filter], { signal: AbortSignal.timeout(5000) });
if (events.length > 0) {
console.log(`✓ Found events on fallback relays`);
}
} catch (error) {
console.error(`Error querying fallback relays: ${error}`);
console.error(`Error querying group relays: ${error}`);
}
}
if (!events.length) {
@@ -1410,24 +1390,13 @@ export class Git {
}
}
// Ensure git.shakespeare.diy is always included and prioritized
const shakespeareRelay = 'wss://git.shakespeare.diy/';
// Remove git.shakespeare.diy from relayUrls if it exists (to avoid duplicates)
const filteredRelayUrls = relayUrls.filter(url => url !== shakespeareRelay);
// Always prioritize git.shakespeare.diy by putting it first
relayUrls.unshift(shakespeareRelay);
// If no relays specified in announcement, use default git-focused relays
if (filteredRelayUrls.length === 0 && relayUrls.length === 1) {
if (relayUrls.length === 0) {
relayUrls.push(
'wss://git.shakespeare.diy/',
'wss://relay.ngit.dev/',
'wss://relay.nostr.band/'
);
} else {
// Add back the other relays after git.shakespeare.diy
relayUrls.push(...filteredRelayUrls);
}
// Get current repository state
@@ -1448,42 +1417,12 @@ export class Git {
// Publish the state event to Nostr relays
console.log(`Publishing repository state to ${relayUrls.length} relays`);
// Always publish to git.shakespeare.diy first
const shakespeareRelayUrl = 'wss://git.shakespeare.diy/';
const otherRelays = relayUrls.filter(url => url !== shakespeareRelayUrl);
try {
// Publish to git.shakespeare.diy first
console.log(`Publishing to ${shakespeareRelayUrl} first...`);
await this.nostr.relay(shakespeareRelayUrl).event(stateEvent);
console.log(`✓ Repository state published to ${shakespeareRelayUrl} successfully`);
// Then publish to other relays
if (otherRelays.length > 0) {
console.log(`Publishing to ${otherRelays.length} additional relays...`);
try {
await this.nostr.group(otherRelays).event(stateEvent);
console.log('✓ Repository state published to additional relays successfully');
} catch (error) {
console.warn('Failed to publish repository state to some additional relays:', error);
// Continue even if publishing to additional relays fails
}
}
console.log('✓ Nostr push completed successfully');
await this.nostr.group(relayUrls).event(stateEvent);
console.log('✓ Repository state published to Nostr successfully');
} catch (error) {
console.error('Failed to publish repository state to git.shakespeare.diy:', error);
// If git.shakespeare.diy fails, still try to publish to other relays as fallback
if (otherRelays.length > 0) {
console.log(`Attempting to publish to ${otherRelays.length} fallback relays...`);
try {
await this.nostr.group(otherRelays).event(stateEvent);
console.log('✓ Repository state published to fallback relays successfully');
} catch (fallbackError) {
console.warn('Failed to publish repository state to fallback relays:', fallbackError);
}
}
// Don't throw here - continue with Git push even if Nostr publishing fails
console.warn('Failed to publish repository state to some relays:', error);
// Continue with Git push even if Nostr publishing partially fails
}
// Push to each clone URL
+32 -101
View File
@@ -1,12 +1,6 @@
import { describe, it, expect, beforeEach, vi } from 'vitest';
import {
ReadConsoleMessagesTool,
addConsoleMessage,
clearConsoleMessages,
ProjectPreviewConsoleError,
addErrorListener,
removeErrorListener
} from './ReadConsoleMessagesTool';
import { describe, it, expect, beforeEach } from 'vitest';
import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool';
import { addConsoleMessage, clearConsoleMessages } from '@/lib/consoleMessages';
describe('ReadConsoleMessagesTool', () => {
beforeEach(() => {
@@ -63,106 +57,43 @@ describe('ReadConsoleMessagesTool', () => {
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);
it('should handle all filter levels', async () => {
const tool = new ReadConsoleMessagesTool();
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);
// 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');
});
});
describe('Console Error Listeners', () => {
beforeEach(() => {
it('should format messages correctly', async () => {
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 trigger error listener when console error is added', async () => {
const errorListener = vi.fn();
addErrorListener(errorListener);
it('should handle limit correctly', async () => {
const tool = new ReadConsoleMessagesTool();
// Add an error message
addConsoleMessage('error', 'Test error message');
// Limit should return only the most recent messages
const limitedResult = await tool.execute({ limit: 2 });
expect(limitedResult).toContain('Found 2 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);
// No limit should return all messages
const allResult = await tool.execute({});
expect(allResult).toContain('Found 4 console messages');
});
});
+13 -74
View File
@@ -1,9 +1,5 @@
import { Tool } from './Tool';
export interface ConsoleMessage {
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
message: string;
}
import { getConsoleMessages } from '@/lib/consoleMessages';
export interface ReadConsoleMessagesParams {
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
@@ -11,87 +7,30 @@ export interface ReadConsoleMessagesParams {
}
/**
* Custom error class for project preview console errors
* AI tool for reading console messages from the project preview.
* This tool allows AI assistants to access console logs for debugging assistance.
*/
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;
// Filter and limit messages in one chain
const filteredMessages = getConsoleMessages()
.filter(msg => filter === 'all' || msg.level === filter)
.slice(limit && limit > 0 ? -limit : 0);
let messages = getConsoleMessages()
.filter(msg => filter === 'all' || msg.level === filter);
if (filteredMessages.length === 0) {
if (limit && limit > 0) {
messages = messages.slice(-limit);
}
if (messages.length === 0) {
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
}
const formattedMessages = filteredMessages
const formatted = messages
.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}`;
const suffix = filter !== 'all' ? ` (level: ${filter})` : '';
return `Found ${messages.length} console message${messages.length !== 1 ? 's' : ''}${suffix}:\n\n${formatted}`;
}
description = 'Read console messages from the project preview. Can filter by level and limit results.';
+2
View File
@@ -16,6 +16,8 @@ export function toolToOpenAI<TParams>(name: string, tool: Tool<TParams>): OpenAI
if (tool.inputSchema) {
functionDef.parameters = zodSchemaToJsonSchema(tool.inputSchema);
} else {
functionDef.parameters = {};
}
return {
+7 -16
View File
@@ -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 { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool';
import { useConsoleError } from '@/hooks/useConsoleError';
export function ProjectView() {
const { projectId } = useParams<{ projectId: string }>();
@@ -29,7 +29,9 @@ export function ProjectView() {
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
const [isAILoading, setIsAILoading] = useState(false);
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
// Use console error state from provider
const { consoleError, dismissConsoleError, clearErrors } = useConsoleError();
const projectsManager = useProjectsManager();
const chatPaneRef = useRef<ChatPaneRef>(null);
@@ -48,14 +50,13 @@ export function ProjectView() {
const projectData = await projectsManager.getProject(projectId);
setProject(projectData);
// Clear console messages and error state when switching projects
clearConsoleMessages();
setConsoleError(null);
clearErrors();
} catch (error) {
console.error('Failed to load project:', error);
} finally {
setIsLoading(false);
}
}, [projectId, projectsManager]);
}, [projectId, projectsManager, clearErrors]);
useEffect(() => {
loadProject();
@@ -81,16 +82,6 @@ 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) {
@@ -113,7 +104,7 @@ export function ProjectView() {
};
const handleDismissConsoleError = () => {
setConsoleError(null);
dismissConsoleError();
};
const handleProjectDeleted = async () => {
+1
View File
@@ -13,6 +13,7 @@ export default defineConfig(() => ({
react(),
],
build: {
sourcemap: true,
rollupOptions: {
output: {
manualChunks(id) {