Compare commits

..
Author SHA1 Message Date
Chad Curtis e5ca49962e Reset iframe browser history on project change. 2025-09-25 03:15:51 +00:00
Chad Curtis f5c5684ac8 Merge branch 'main' of gitlab.com:soapbox-pub/act2 into navigationBar 2025-09-25 03:13:32 +00:00
Chad Curtis 6a72711aa0 Fix force re-render on url change in preview pane. 2025-09-25 03:13:04 +00:00
Chad Curtis 1ed4a5abd4 Properly block actions based on build status 2025-09-25 02:56:01 +00:00
Alex Gleason db57619bca Allow refilling Shakespeare credits from Quilly 2025-09-24 21:55:28 -05:00
Chad Curtis 0f4075ce38 Merge in from upstream and resolve conflicts 2025-09-25 02:53:08 +00:00
Alex Gleason ec5d84d3f7 Disconnect Quilly from console errors temporarily 2025-09-24 21:23:31 -05:00
Alex Gleason 0b949d55b9 Remove Quilly tests (for now) 2025-09-24 21:14:41 -05:00
Alex Gleason 25f14ee2b3 Clean up Quilly 2025-09-24 21:06:52 -05:00
Alex Gleason 7057c34f01 Consolidate action logic into Quilly 2025-09-24 20:53:24 -05:00
Alex Gleason d932f05d04 Make Quilly intercept actual Error objects 2025-09-24 20:19:20 -05:00
Alex Gleason e9f8e99ac5 Surface AI Errors to ChatPane 2025-09-24 20:00:02 -05:00
Chad Curtis 41d7d7834d a bit more janitorial work 2025-09-21 06:52:56 +00:00
Chad Curtis 785f75a39a remove cruft path 2025-09-21 06:48:03 +00:00
Chad Curtis 8e3cc67ce2 cleanup current logic 2025-09-21 06:47:23 +00:00
Chad Curtis fae90cc85e refresh functionality fix 2025-09-21 06:08:18 +00:00
Chad Curtis 2ed44e43f7 v3 2025-09-21 06:08:18 +00:00
Chad Curtis 53cf844fd6 v2 navigation 2025-09-21 06:08:18 +00:00
Chad Curtis 6aa36b6738 v1 navigation 2025-09-21 06:08:18 +00:00
22 changed files with 737 additions and 1754 deletions

No files matched your search

+1 -3
View File
@@ -168,8 +168,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `/src/components/ai/`: AI-related components (GitCommit, GitHistoryDialog)
- `/src/components/comments/`: Comment system components (Comment, CommentForm, CommentsSection)
- `/src/components/Shakespeare/`: Core Shakespeare editor components (ChatPane, FileEditor, FileTree, PreviewPane)
- `/src/components/ProjectSidebar.tsx`: Sidebar component containing project list and import options
- `/src/components/ZipImportDialog.tsx`: Dialog component for importing projects from ZIP files
- Zap components: `ZapButton`, `ZapDialog`, `WalletModal` for Lightning payments
- `/src/hooks/`: Custom hooks including:
- `useNostr`: Core Nostr protocol integration
@@ -184,7 +182,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useSessionManager`: Access session management for AI chat sessions
- `useGitStatus`: Real-time Git repository status monitoring
- `useProjects`: Project management and CRUD operations
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
- `useProjectsManager`: Advanced project operations (creation, cloning, building)
- `useTheme`: Theme management
- `useToast`: Toast notifications
- `useLocalStorage`: Persistent local storage
+30
View File
@@ -148,6 +148,36 @@ consistent handling of both text and binary data across the messaging protocol.
**Result:** None (notification only, no response expected)
### Navigation Methods
#### `navigate`
**Purpose:** Navigate iframe to a new URL within the same origin
**Parameters:** `url` (string) - Target URL (must be same origin)
**Result:** None (notification only)
#### `refresh`
**Purpose:** Refresh/reload the current page in the iframe
**Parameters:** None
**Result:** None (notification only)
#### `goBack`
**Purpose:** Navigate back in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `goForward`
**Purpose:** Navigate forward in the iframe's history
**Parameters:** None
**Result:** None (notification only)
#### `updateNavigationState`
**Purpose:** Update parent about iframe's current navigation state
**Parameters:**
- `currentUrl` (string) - Current URL of the iframe
- `canGoBack` (boolean) - Whether iframe can go back in history
- `canGoForward` (boolean) - Whether iframe can go forward in history
**Result:** None (notification only)
## Implementation
### Parent Page
+29 -1
View File
@@ -136,7 +136,27 @@ The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
- Parent responds with serialized HTTP responses
- ServiceWorker creates Response objects and returns them to the client app
3. **Content Replacement:**
3. **SPA Routing Support:**
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
- This allows the SPA's client-side router to handle the route properly
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
4. **Semantic Path Navigation:**
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
- Parent displays semantic path while iframe remains on base URL
- SPA's client-side router handles navigation internally without page reloads
- This prevents 404 errors from literal path navigation
5. **SPA Navigation Tracking:**
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
- Navigation state includes semantic path, back/forward capability, and history tracking
- Parent can display current semantic path and enable proper back/forward navigation controls
6. **Content Replacement:**
- Main thread requests `/` from parent via JSON-RPC fetch
- Replaces its own content with the site index
- Site runs normally, with all requests handled by SW via JSON-RPC
@@ -322,6 +342,14 @@ function handleRequest(fetchRequest) {
- Check that JSON-RPC messages are properly formatted
- Ensure iframe has appropriate sandbox permissions
### SPA routes don't work
- Ensure the parent page serves the correct `index.html` for the root path `/`
- Check that the SPA's client-side router is properly configured
- Verify that navigation requests are being detected correctly by the ServiceWorker
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
## Development
To modify the system:
+227 -1
View File
@@ -13,6 +13,11 @@ class JSONRPCClient {
setupMessageListener() {
window.addEventListener("message", (event) => {
// Only accept messages from parent window for security
if (event.source !== window.parent) {
return;
}
const message = event.data;
// Check if this is a response to our own request or a ServiceWorker request
if (message.jsonrpc === "2.0" && message.id !== undefined) {
@@ -148,19 +153,202 @@ class ConsoleInterceptor {
}
}
// Navigation Handler - manages iframe navigation and history
class NavigationHandler {
constructor() {
// Get initial path from window property or default to root
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
this.setupMessageListener();
this.setupHistoryListeners();
this.overrideHistoryMethods();
this.updateNavigationState();
}
// Extract semantic path from URL or string
extractSemanticPath(urlOrString) {
try {
const url = typeof urlOrString === 'string'
? new URL(urlOrString, window.location.origin)
: urlOrString;
return url.pathname + url.search + url.hash;
} catch {
return window.location.pathname + window.location.search + window.location.hash;
}
}
setupMessageListener() {
window.addEventListener("message", (event) => {
// Only accept messages from parent window for security
if (event.source !== window.parent) {
return;
}
const message = event.data;
if (message.jsonrpc === "2.0") {
switch (message.method) {
case "navigate":
this.handleNavigate(message.params.url);
break;
case "refresh":
this.handleRefresh();
break;
case "goBack":
this.handleGoBack();
break;
case "goForward":
this.handleGoForward();
break;
}
}
});
}
setupHistoryListeners() {
// Listen for popstate events (back/forward navigation)
window.addEventListener('popstate', () => {
this.currentSemanticPath = this.extractSemanticPath(window.location);
this.updateNavigationState();
});
// Listen for hash changes
window.addEventListener('hashchange', () => {
this.currentSemanticPath = this.extractSemanticPath(window.location);
this.updateNavigationState();
});
}
overrideHistoryMethods() {
// Override history.pushState and history.replaceState to detect SPA navigation
this.originalPushState = window.history.pushState;
this.originalReplaceState = window.history.replaceState;
window.history.pushState = (...args) => {
const result = this.originalPushState.apply(window.history, args);
// Extract semantic path from URL argument or use current location
const semanticPath = args[2]
? this.extractSemanticPath(args[2])
: this.extractSemanticPath(window.location);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
return result;
};
window.history.replaceState = (...args) => {
const result = this.originalReplaceState.apply(window.history, args);
const semanticPath = args[2]
? this.extractSemanticPath(args[2])
: this.extractSemanticPath(window.location);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
return result;
};
}
handleNavigate(url) {
try {
// Validate URL - must be same origin
const targetUrl = new URL(url, window.location.origin);
if (targetUrl.origin !== window.location.origin) {
console.error('Navigation to different origin not allowed:', url);
return;
}
const semanticPath = this.extractSemanticPath(targetUrl);
this.currentSemanticPath = semanticPath;
this.updateNavigationState();
// Trigger SPA navigation
window.history.pushState({}, '', semanticPath);
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
} catch (error) {
console.error('Invalid navigation URL:', url, error);
}
}
handleRefresh() {
// Store current semantic path for reload
const currentPath = this.currentSemanticPath || '/';
// Save the current path to sessionStorage so it persists across reload
try {
sessionStorage.setItem('iframe_initial_path', currentPath);
} catch (error) {
console.warn('Failed to store initial path in sessionStorage:', error);
}
// Actually reload the iframe to get a fresh SPA instance
window.location.reload();
}
handleGoBack() {
window.history.back();
}
handleGoForward() {
window.history.forward();
}
updateNavigationState() {
// Use tracked semantic path, fallback to current location if needed
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
const state = {
currentUrl: semanticPath,
canGoBack: false, // Let parent handle history tracking
canGoForward: false // Let parent handle history tracking
};
// Send navigation state to parent
try {
window.parent.postMessage({
jsonrpc: "2.0",
method: "updateNavigationState",
params: state
}, "*");
} catch (error) {
console.error('Failed to send navigation state:', error);
}
}
}
// Main Fetch Client
class FetchClient {
constructor() {
this.rpcClient = new JSONRPCClient();
this.consoleInterceptor = new ConsoleInterceptor();
this.navigationHandler = new NavigationHandler();
this.init();
}
// Ensure SPA navigates to initial path after document is loaded
ensureInitialNavigation() {
// Wait for the SPA to initialize, then navigate to the initial path
setTimeout(() => {
const initialPath = window.__IFRAME_INITIAL_PATH__;
if (initialPath && initialPath !== '/') {
const currentPath = window.location.pathname + window.location.search + window.location.hash;
// If we're not already at the initial path, navigate there
if (currentPath !== initialPath) {
this.navigationHandler.handleNavigate(initialPath);
}
}
}, 150); // Give SPA more time to initialize
}
async init() {
try {
await this.setupServiceWorker();
await this.loadSiteIndex();
} catch (error) {
console.error("FetchClient: Initialization failed:", error);
this.showError("Failed to initialize fetch client", error);
}
}
@@ -212,6 +400,20 @@ class FetchClient {
}
async loadSiteIndex() {
// Check if we have a stored initial path from a refresh
let initialPath = '/';
try {
const storedPath = sessionStorage.getItem('iframe_initial_path');
if (storedPath) {
initialPath = storedPath;
// Clear the stored path after using it
sessionStorage.removeItem('iframe_initial_path');
}
} catch (error) {
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
}
const serializedRequest = {
url: `${location.origin}/`,
method: "GET",
@@ -232,10 +434,33 @@ class FetchClient {
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
const text = new TextDecoder().decode(bytes);
// Set the initial path on window before replacing the document
// This will be available to the NavigationHandler when it initializes
if (initialPath && initialPath !== '/') {
window.__IFRAME_INITIAL_PATH__ = initialPath;
}
this.replaceDocument(text);
}
replaceDocument(htmlContent) {
console.log("replaceDocument: Starting...");
// Restore the initial path from sessionStorage before replacing document
let initialPath = '/';
try {
const storedPath = sessionStorage.getItem('spa_initial_path');
if (storedPath) {
initialPath = storedPath;
sessionStorage.removeItem('spa_initial_path');
console.log('replaceDocument: Restored initial path:', initialPath);
// Set it on window for the new document
window.__IFRAME_INITIAL_PATH__ = initialPath;
}
} catch (error) {
console.warn('replaceDocument: Failed to restore initial path:', error);
}
// Create a new document from the HTML content
const parser = new DOMParser();
const newDoc = parser.parseFromString(htmlContent, "text/html");
@@ -266,7 +491,8 @@ class FetchClient {
document.body.appendChild(newScript);
});
console.log("Document replaced with site content");
// Ensure initial navigation after document is loaded
this.ensureInitialNavigation();
}
showError(message, error) {
+60 -14
View File
@@ -68,23 +68,37 @@ async function requestViaJSONRPC(request) {
return new Promise(async (resolve, reject) => {
const id = ++requestIdCounter;
// Serialize the fetch request
let body = null;
if (request.body) {
try {
// Convert body to Uint8Array then base64 encode
const bytes = await request.bytes();
body = btoa(String.fromCharCode(...bytes));
} catch (error) {
reject(new Error(`Failed to serialize request body: ${error.message}`));
return;
// Check if request is a plain object or Request object
let url, method, headers, body;
if (request instanceof Request) {
// Handle Request object
url = request.url;
method = request.method;
headers = Object.fromEntries(request.headers.entries());
if (request.body) {
try {
// Convert body to Uint8Array then base64 encode
const bytes = await request.bytes();
body = btoa(String.fromCharCode(...bytes));
} catch (error) {
reject(new Error(`Failed to serialize request body: ${error.message}`));
return;
}
}
} else {
// Handle plain request object
url = request.url;
method = request.method || 'GET';
headers = request.headers || {};
body = request.body || null;
}
const serializedRequest = {
url: request.url,
method: request.method,
headers: Object.fromEntries(request.headers.entries()),
url: url,
method: method,
headers: headers,
body: body,
};
@@ -109,7 +123,7 @@ async function requestViaJSONRPC(request) {
setTimeout(() => {
if (pendingRequests.has(id)) {
pendingRequests.delete(id);
reject(new Error(`Timeout requesting: ${request.url}`));
reject(new Error(`Timeout requesting: ${url}`));
}
}, 10000);
});
@@ -134,6 +148,38 @@ self.addEventListener("fetch", (event) => {
return;
}
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
if (url.pathname.startsWith("/_iframe-client/") ||
url.pathname === "/favicon.ico" ||
url.pathname === "/manifest.webmanifest") {
return;
}
// For SPA routes, check if this is a navigation request (HTML page request)
// But first check if we need to load the iframe client (this happens during refresh)
if (event.request.mode === "navigate" &&
(event.request.headers.get("accept") || "").includes("text/html")) {
// Check if this is a request for the iframe client itself
// We need to serve the iframe client HTML first, which will then load the SPA
if (url.pathname !== "/") {
// Redirect to root to load the iframe client, which will then navigate to the target path
const response = Response.redirect(new URL("/", event.request.url).href, 302);
event.respondWith(response);
return;
}
// This is a request for the root path, serve the site's index.html via JSON-RPC
const rootRequest = {
url: new URL("/", event.request.url).href,
method: event.request.method,
headers: Object.fromEntries(event.request.headers.entries()),
body: event.request.body
};
event.respondWith(handleRequest(rootRequest));
return;
}
// Handle all other requests through JSON-RPC communication
event.respondWith(handleRequest(event.request));
});
+2 -41
View File
@@ -1,7 +1,7 @@
import React, { useEffect, useState } from 'react';
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, FileArchive } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
@@ -9,9 +9,6 @@ import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
@@ -95,9 +92,6 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const projectsManager = useProjectsManager();
const { toast } = useToast();
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const isMobile = useIsMobile();
const navigate = useNavigate();
@@ -123,25 +117,6 @@ export function ProjectSidebar({
}
};
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
try {
// Import project from zip file
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
// Show success toast
toast({
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
});
// Navigate to the imported project
navigate(`/project/${project.id}`);
} catch (error) {
console.error('Failed to import project:', error);
throw error; // Re-throw to let the dialog handle the error display
}
};
useEffect(() => {
queryClient.invalidateQueries({ queryKey: ['projects'] });
}, [favorites, queryClient]);
@@ -211,13 +186,6 @@ export function ProjectSidebar({
<GitBranch className="h-4 w-4" />
{t('importRepository')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setIsZipDialogOpen(true)}
className="flex items-center gap-2 w-full"
>
<FileArchive className="h-4 w-4" />
Import ZIP File
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
@@ -280,13 +248,6 @@ export function ProjectSidebar({
</Button>
</div>
</div>
{/* ZIP Import Dialog */}
<ZipImportDialog
onImport={handleImportZip}
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
</div>
);
}
+152
View File
@@ -0,0 +1,152 @@
import OpenAI from 'openai';
import { useNavigate } from 'react-router-dom';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { QuillySVG } from '@/components/ui/QuillySVG';
import { useAISettings } from '@/hooks/useAISettings';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from './CreditsDialog';
import { useState } from 'react';
export interface QuillyProps {
error: Error;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
providerModel: string;
}
interface ErrorBody {
message: string;
action?: {
label: string;
onClick: () => void;
};
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, providerModel }: QuillyProps) {
const navigate = useNavigate();
const { settings } = useAISettings();
const { provider } = parseProviderModel(providerModel, settings.providers);
const credits = useAICredits(provider);
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error): ErrorBody => {
// Handle OpenAI API errors with specific error codes
if (error instanceof OpenAI.APIError) {
switch (error.code) {
case 'invalid_api_key':
case 'invalid_request_error':
return {
message: 'Authentication error: Please check your API key in AI settings.',
action: {
label: 'Check API key',
onClick: () => navigate('/settings/ai'),
}
};
case 'insufficient_quota': {
if (credits.data) {
return {
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
action: {
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}
};
} else {
return {
message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
action: {
label: 'Check AI settings',
onClick: () => navigate('/settings/ai'),
}
};
}
}
case 'rate_limit_exceeded':
return {
message: 'Rate limit exceeded. Please wait a moment before trying again.',
};
case 'model_not_found':
return {
message: 'The selected AI model is not available. Please choose a different model.',
action: {
label: 'Choose model',
onClick: onOpenModelSelector,
},
};
case 'context_length_exceeded':
return {
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
action: {
label: 'New chat',
onClick: onNewChat,
},
};
case 'server_error':
case 'service_unavailable':
return {
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
};
default:
return {
message: `AI service error: ${error.message}`,
};
}
}
// Default fallback
return {
message: error.message
? `AI service error: ${error.message}`
: 'Sorry, I encountered an unexpected error. Please try again.',
};
};
const { message, action } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
<div className="flex items-start gap-2">
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
<div className="flex-1 min-w-0">
<div className="space-y-1">
<h4 className="font-semibold text-primary">
Pardon the interruption
</h4>
<p className="text-sm text-muted-foreground">
{message}
{' '}
{action && (
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
)}
</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={onDismiss}
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
<CreditsDialog
open={showCreditsDialog}
onOpenChange={setShowCreditsDialog}
provider={provider}
/>
</div>
);
}
@@ -1,313 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen, fireEvent, act } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { ChatPane } from './ChatPane';
// Mock the AI settings hook to return configured state
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
isConfigured: true,
settings: {
providers: [],
recentlyUsedModels: ['gpt-4'],
},
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
updateSettings: vi.fn(),
}),
}));
// Mock other hooks
vi.mock('@/hooks/useFS', () => ({
useFS: () => ({
fs: {},
}),
}));
vi.mock('@/hooks/useCurrentUser', () => ({
useCurrentUser: () => ({
user: null,
metadata: null,
}),
}));
vi.mock('@/hooks/useKeepAlive', () => ({
useKeepAlive: () => ({
updateMetadata: vi.fn(),
}),
}));
vi.mock('@/hooks/useAIChat', () => ({
useAIChat: () => ({
messages: [],
streamingMessage: null,
isLoading: false,
totalCost: 0,
lastInputTokens: 0,
sendMessage: vi.fn(),
startGeneration: vi.fn(),
stopGeneration: vi.fn(),
startNewSession: vi.fn(),
}),
}));
vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: () => ({
models: [
{
fullId: 'gpt-4',
contextLength: 8192,
},
],
}),
}));
vi.mock('@/hooks/useToast', () => ({
useToast: () => ({
toast: vi.fn(),
}),
}));
describe('ChatPane', () => {
describe('Placeholder switching', () => {
it('shows "Please select a model" placeholder when providerModel is empty', () => {
// Create a test that doesn't require modifying mocks
// Instead, we'll test the existing behavior which shows the placeholder when configured
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
expect(textarea).toBeInTheDocument();
});
it('shows "Ask me to add features" placeholder when providerModel is set', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
expect(textarea).toBeInTheDocument();
});
});
describe('Drag and drop functionality', () => {
it('handles dropping a single valid file', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const validFile = new File(['test content'], 'test.txt', { type: 'text/plain' });
// Simulate drag and drop events
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.dragOver(chatContainer, {
dataTransfer: { files: [validFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.drop(chatContainer, {
dataTransfer: { files: [validFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Verify the drop was handled (no errors thrown)
expect(chatContainer).toBeInTheDocument();
});
it('handles dropping multiple valid files', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const files = [
new File(['content1'], 'file1.txt', { type: 'text/plain' }),
new File(['content2'], 'file2.txt', { type: 'text/plain' }),
];
// Simulate drag and drop events
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.dragOver(chatContainer, {
dataTransfer: { files },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.drop(chatContainer, {
dataTransfer: { files },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Verify the drop was handled (no errors thrown)
expect(chatContainer).toBeInTheDocument();
});
it('handles dropping an unsupported file type', () => {
// Test that the drop handler exists and doesn't throw errors
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const unsupportedFile = new File(['malicious content'], 'virus.exe', { type: 'application/x-executable' });
// Simulate drag and drop events - should not throw errors
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.dragOver(chatContainer, {
dataTransfer: { files: [unsupportedFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
fireEvent.drop(chatContainer, {
dataTransfer: { files: [unsupportedFile] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Test passes if no errors are thrown during drop
expect(chatContainer).toBeInTheDocument();
});
it('adds visual drag-over state during drag operations', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const chatContainer = screen.getByPlaceholderText(/Ask me to add features/).closest('div')?.parentElement;
expect(chatContainer).toBeInTheDocument();
const _file = new File(['test content'], 'test.txt', { type: 'text/plain' });
// Simulate drag enter - should not throw errors
act(() => {
if (chatContainer) {
fireEvent.dragEnter(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
});
}
});
// Test passes if no errors are thrown during drag operations
expect(chatContainer).toBeInTheDocument();
// Simulate drag leave
act(() => {
if (chatContainer) {
fireEvent.dragLeave(chatContainer, {
dataTransfer: { files: [] },
preventDefault: vi.fn(),
stopPropagation: vi.fn(),
relatedTarget: null, // Simulate leaving the container
});
}
});
// Test passes if no errors are thrown during drag operations
expect(chatContainer).toBeInTheDocument();
});
});
it('handles image paste from clipboard', async () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
const textarea = screen.getByPlaceholderText(/Ask me to add features/);
expect(textarea).toBeInTheDocument();
// Create a mock image file
const imageFile = new File(['fake-image-data'], 'test.png', {
type: 'image/png',
});
// Create mock clipboard data
const mockClipboardItem = {
type: 'image/png',
getAsFile: () => imageFile,
} as DataTransferItem;
const mockClipboardData = {
items: [mockClipboardItem],
length: 1,
} as unknown as DataTransfer;
// Fire the paste event on the textarea using fireEvent
fireEvent.paste(textarea, {
clipboardData: mockClipboardData,
});
// The file should be added to the attached files
// We can't easily test the internal state, but we can verify the event was handled
// without throwing an error
expect(textarea).toBeInTheDocument();
});
it('renders welcome message when no messages exist', () => {
render(
<TestApp>
<ChatPane projectId="test-project" />
</TestApp>
);
expect(screen.getByText('Welcome to Shakespeare')).toBeInTheDocument();
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
});
});
+32 -93
View File
@@ -8,7 +8,7 @@ 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, X } from 'lucide-react';
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
import { useAISettings } from '@/hooks/useAISettings';
import { useFS } from '@/hooks/useFS';
import { useCurrentUser } from '@/hooks/useCurrentUser';
@@ -39,58 +39,13 @@ import { Tool } from '@/lib/tools/Tool';
import OpenAI from 'openai';
import { saveFileToTmp } from '@/lib/fileUtils';
import { useGit } from '@/hooks/useGit';
import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection';
import { QuillySVG } from '@/components/ui/QuillySVG';
function ChatIntervention({
message,
onDismiss,
action,
}: {
message: string;
onDismiss: () => void;
action?: { label: string; onClick: () => void };
}) {
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
<div className="flex items-start gap-2">
<QuillySVG className="h-20 px-2 flex-shrink-0" fillColor="hsl(var(--primary))" />
<div className="flex-1 min-w-0">
<div className="space-y-1">
<h4 className="font-semibold text-primary">
Pardon the interruption
</h4>
<p className="text-sm text-muted-foreground">
{message}
{' '}
{action && (
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
)}
</p>
</div>
</div>
<Button
variant="ghost"
size="sm"
onClick={onDismiss}
className="h-5 w-5 p-0 hover:text-foreground/70 hover:bg-transparent flex-shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
);
}
import { Quilly } from '@/components/Quilly';
// Clean interfaces now handled by proper hooks
interface ChatPaneProps {
projectId: string;
onNewChat?: () => void;
onBuild?: () => void;
onNewChat: () => void;
onFirstInteraction?: () => void;
onLoadingChange?: (isLoading: boolean) => void;
isLoading?: boolean;
@@ -103,8 +58,7 @@ export interface ChatPaneRef {
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
projectId,
onNewChat: _onNewChat,
onBuild: _onBuild,
onNewChat,
onFirstInteraction,
onLoadingChange,
isLoading: externalIsLoading,
@@ -118,6 +72,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [scrolledProjects] = useState(() => new Set<string>());
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
// Use external state if provided, otherwise default to false
const isBuildLoading = externalIsBuildLoading || false;
@@ -137,6 +92,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}, [providerModel, settings.recentlyUsedModels]);
// Reset error state when navigating between projects and switching models
useEffect(() => {
setAIError(null);
}, [projectId, providerModel]);
const [searchParams, setSearchParams] = useSearchParams();
const { fs } = useFS();
const { git } = useGit();
@@ -204,6 +164,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
updateMetadata(title, description);
}, [updateMetadata]);
// Handle AI errors from the SessionManager
const onAIError = useCallback((error: Error) => {
setAIError(error);
}, []);
const {
messages,
streamingMessage,
@@ -219,6 +184,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
tools,
customTools,
onUpdateMetadata,
onAIError,
});
// Use external loading state if provided, otherwise use internal state
@@ -267,19 +233,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
setIsModelSelectorOpen(true);
}, []);
// Function to suggest error fix
// Clean alert hooks with proper interfaces
const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector);
const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading);
// Scroll to bottom when alerts appear
// Scroll to bottom when AI error occurs
useEffect(() => {
if (aiModelAlert.hasError || consoleAlert.hasError) {
setTimeout(() => {
scrollToBottom();
}, 50);
}
}, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]);
scrollToBottom();
}, [aiError, scrollToBottom]);
// Check for autostart parameter and trigger AI generation
useEffect(() => {
@@ -425,6 +382,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// If configured but no model selected, don't proceed
if (!providerModel.trim()) return;
setAIError(null);
const modelToUse = providerModel.trim();
// Build message content as text parts
@@ -467,14 +426,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
// Add model to recently used when sending a message
addRecentlyUsedModel(modelToUse);
try {
// 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);
} catch (error) {
console.error('AI chat error:', error);
// Error handling is done in the useAIChat hook and SessionManager
}
// 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]);
const handleSend = useCallback(async () => {
@@ -543,10 +497,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
}), [internalStartNewSession]);
const suggestErrorFix = useCallback(async (errorMessage: string) => {
await send(errorMessage, attachedFiles);
}, [send, attachedFiles]);
return (
<div className="h-full flex flex-col relative">
@@ -639,27 +589,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
</div>
)}
{/* AI Model Alert */}
{aiModelAlert.hasError && (
<ChatIntervention
message={aiModelAlert.errorMessage || ''}
onDismiss={aiModelAlert.dismiss}
action={aiModelAlert.action}
{/* AI Error Alert */}
{aiError && (
<Quilly
error={aiError}
onDismiss={() => setAIError(null)}
onNewChat={onNewChat}
onOpenModelSelector={openModelSelector}
providerModel={providerModel}
/>
)}
{/* Console Error Alert */}
{consoleAlert.hasError && (
<ChatIntervention
message={`Console ${consoleAlert.errorCount === 1 ? 'error' : 'errors'} detected in your app. Would you like me to help fix ${consoleAlert.errorCount === 1 ? 'it' : 'them'}?`}
onDismiss={consoleAlert.dismiss}
action={{
label: `Fix ${consoleAlert.errorCount === 1 ? 'error' : 'errors'}`,
onClick: () => suggestErrorFix(consoleAlert.errorSummary || '')
}}
/>
)}
</div>
</div>
+128 -62
View File
@@ -166,67 +166,23 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
}, [projectId, projectsManager]);
const refreshIframe = useCallback(() => {
// Legacy refresh function for build completion events
const refreshIframeLegacy = useCallback(() => {
if (iframeRef.current) {
// Force reload the iframe by updating its src
iframeRef.current.src = '/';
// Use a small timeout to ensure the src is cleared before setting it back
setTimeout(() => {
if (iframeRef.current) {
iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}${currentPath}`;
iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}/`;
}
}, 10);
}
}, [currentPath, projectId]);
const navigateToPath = useCallback((path: string) => {
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
setCurrentPath(path);
// Update navigation history
const newHistory = navigationHistory.slice(0, historyIndex + 1);
newHistory.push(path);
setNavigationHistory(newHistory);
setHistoryIndex(newHistory.length - 1);
}
}, [projectId, navigationHistory, historyIndex]);
const goBack = useCallback(() => {
if (historyIndex > 0) {
const newIndex = historyIndex - 1;
const path = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
}
}, [historyIndex, navigationHistory, projectId]);
const goForward = useCallback(() => {
if (historyIndex < navigationHistory.length - 1) {
const newIndex = historyIndex + 1;
const path = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(path);
if (iframeRef.current) {
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
const newUrl = `${baseUrl}${path}`;
iframeRef.current.src = newUrl;
}
}
}, [historyIndex, navigationHistory, projectId]);
}, [projectId]);
const sendResponse = useCallback((message: JSONRPCResponse) => {
if (iframeRef.current?.contentWindow) {
console.log(`Sending response to iframe:`, message);
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
@@ -262,11 +218,92 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
}, []);
const handleUpdateNavigationState = useCallback((message: {
jsonrpc: '2.0';
method: 'updateNavigationState';
params: {
currentUrl: string;
canGoBack: boolean;
canGoForward: boolean;
};
}) => {
const { params } = message;
try {
// params.currentUrl is now just a semantic path (e.g., "/about", "/contact?param=value#section")
const path = params.currentUrl;
setCurrentPath(path);
// Update navigation history if this is a new navigation
// But only if it's different from current path (avoid duplicates)
if (path !== navigationHistory[historyIndex]) {
const newHistory = navigationHistory.slice(0, historyIndex + 1);
newHistory.push(path);
setNavigationHistory(newHistory);
setHistoryIndex(newHistory.length - 1);
}
} catch (error) {
console.error('Failed to handle navigation state:', params.currentUrl, error);
}
}, [historyIndex, navigationHistory]);
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
if (iframeRef.current?.contentWindow) {
const message = {
jsonrpc: '2.0',
method,
params: params || {},
id: Date.now()
};
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
}
}, [projectId]);
const navigateIframe = useCallback((url: string) => {
// Send semantic path directly (e.g., "/about", "/contact")
// The iframe's NavigationHandler will handle this as semantic navigation
sendNavigationCommand('navigate', { url });
}, [sendNavigationCommand]);
const refreshIframe = useCallback(() => {
sendNavigationCommand('refresh');
}, [sendNavigationCommand]);
const goBackIframe = useCallback(() => {
if (historyIndex > 0) {
// Move back in history
const newIndex = historyIndex - 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const goForwardIframe = useCallback(() => {
if (historyIndex < navigationHistory.length - 1) {
// Move forward in history
const newIndex = historyIndex + 1;
const targetPath = navigationHistory[newIndex];
setHistoryIndex(newIndex);
setCurrentPath(targetPath);
// Tell iframe to navigate to this path
sendNavigationCommand('navigate', { url: targetPath });
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
console.log(`Preview iframe requesting: ${fetchRequest.url}`);
try {
// Parse the URL and validate origin
@@ -290,6 +327,9 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const path = url.pathname;
const filePath = path;
// Skip SPA fallback for static assets (files with extensions)
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
// SPA routing: try to serve the exact file first
try {
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
@@ -310,11 +350,30 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
});
return;
} catch {
// File not found, try SPA fallback to index.html
console.log(`File not found: ${filePath}, trying index.html fallback`);
// For static assets, return 404 immediately
if (isStaticAsset) {
sendResponse({
jsonrpc: '2.0',
result: {
status: 404,
statusText: 'Not Found',
headers: {
'Content-Type': 'text/plain',
},
body: encodeBase64(`Static asset not found: ${path}`),
},
id
});
return;
}
// For non-static assets, try SPA fallback to index.html
}
// SPA fallback: serve index.html for non-file requests
// SPA fallback: serve index.html for non-file requests (SPA routing)
try {
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
console.log(`Serving index.html fallback for: ${path}`);
@@ -334,7 +393,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
});
} catch {
// Even index.html doesn't exist
console.log(`No files found, returning 404 for: ${path}`);
sendResponse({
jsonrpc: '2.0',
@@ -379,12 +438,14 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
handleUpdateNavigationState(message);
}
};
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleConsoleMessage, projectId]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]);
useEffect(() => {
if (selectedFile) {
@@ -392,11 +453,16 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
}, [selectedFile, loadFileContent]);
// Reset selected file when projectId changes
// Reset selected file and navigation history when projectId changes
useEffect(() => {
setSelectedFile(null);
setFileContent('');
setMobileCodeView('explorer');
// Reset navigation history and state
setCurrentPath('/');
setNavigationHistory(['/']);
setHistoryIndex(0);
}, [projectId]);
useEffect(() => {
@@ -410,13 +476,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
console.log('Build completed for project, refreshing preview');
// Check for built project and refresh iframe
checkForBuiltProject();
refreshIframe();
refreshIframeLegacy();
}
};
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
}, [projectId, checkForBuiltProject, refreshIframe]);
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
const handleFileSelect = (filePath: string) => {
setSelectedFile(filePath);
@@ -583,10 +649,10 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<div className="h-12 flex items-center w-full">
<BrowserAddressBar
currentPath={currentPath}
onNavigate={hasBuiltProject ? navigateToPath : undefined}
onNavigate={hasBuiltProject ? navigateIframe : undefined}
onRefresh={hasBuiltProject ? refreshIframe : undefined}
onBack={hasBuiltProject ? goBack : undefined}
onForward={hasBuiltProject ? goForward : undefined}
onBack={hasBuiltProject ? goBackIframe : undefined}
onForward={hasBuiltProject ? goForwardIframe : undefined}
canGoBack={hasBuiltProject && historyIndex > 0}
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
extraContent={(
@@ -613,7 +679,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
{hasBuiltProject ? (
<iframe
ref={iframeRef}
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
className="w-full h-full border-0"
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
-203
View File
@@ -1,203 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import { ZipImportDialog } from './ZipImportDialog';
import { TestApp } from '@/test/TestApp';
// Mock the useProjects hook
const mockProjects = [
{ id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() }
];
vi.mock('@/hooks/useProjects', () => ({
useProjects: () => ({
data: mockProjects,
isLoading: false,
error: null
})
}));
describe('ZipImportDialog', () => {
const mockOnImport = vi.fn();
const defaultProps = {
onImport: mockOnImport,
disabled: false
};
beforeEach(() => {
mockOnImport.mockClear();
vi.clearAllMocks();
});
it('renders dialog trigger button', () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
});
it('opens dialog when trigger is clicked', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
await waitFor(() => {
expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument();
});
});
it('processes file selection without displaying project ID', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file
const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
await waitFor(() => {
// Verify that the file name is displayed (from the file selection area)
expect(screen.getByText('my-project.zip')).toBeInTheDocument();
// Verify that Project ID label is not displayed
expect(screen.queryByText('Project ID')).not.toBeInTheDocument();
});
});
it('shows overwrite warning when project ID already exists', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file that will generate an existing project ID
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
await waitFor(() => {
expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument();
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
});
});
it('calls onImport with correct parameters when import button is clicked', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file
const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
// Wait for file to be processed
await waitFor(() => {
expect(screen.getByText('new-project.zip')).toBeInTheDocument();
});
// Click import button
const importButton = screen.getByText('Import Project');
fireEvent.click(importButton);
await waitFor(() => {
expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project");
});
});
it('shows overwrite confirmation dialog when overwrite button is clicked', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Create a mock file that will generate an existing project ID
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
// Find the hidden file input by ref
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
if (fileInput) {
fireEvent.change(fileInput, { target: { files: [file] } });
}
// Wait for overwrite button to appear
await waitFor(() => {
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
});
// Click overwrite button
const overwriteButton = screen.getByText('Overwrite Project');
fireEvent.click(overwriteButton);
// Check for overwrite confirmation dialog
await waitFor(() => {
expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument();
// Use a more flexible matcher for the text that might be split across elements
const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent');
if (dialogContent) {
expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists');
}
}, { timeout: 2000 });
});
it('does not show project ID input field (simplified interface)', async () => {
render(
<TestApp>
<ZipImportDialog {...defaultProps} />
</TestApp>
);
// Open dialog
const triggerButton = screen.getByText('Import ZIP');
fireEvent.click(triggerButton);
// Check that there's no input field for project ID
expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument();
expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument();
});
});
-397
View File
@@ -1,397 +0,0 @@
import React, { useState, useRef, useCallback, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
import { Progress } from '@/components/ui/progress';
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react';
import { useProjects } from '@/hooks/useProjects';
import { cn } from '@/lib/utils';
interface ZipImportDialogProps {
onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise<void>;
disabled?: boolean;
className?: string;
open?: boolean;
onOpenChange?: (open: boolean) => void;
}
export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) {
// Use controlled state if props are provided, otherwise use internal state
const [internalIsOpen, setInternalIsOpen] = useState(false);
const isOpen = open !== undefined ? open : internalIsOpen;
const setIsOpen = onOpenChange || setInternalIsOpen;
const [selectedFile, setSelectedFile] = useState<File | null>(null);
const [generatedId, setGeneratedId] = useState('');
const [isImporting, setIsImporting] = useState(false);
const [importProgress, setImportProgress] = useState(0);
const [error, setError] = useState<string | null>(null);
const [isDragOver, setIsDragOver] = useState(false);
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
const fileInputRef = useRef<HTMLInputElement>(null);
const { data: projects = [] } = useProjects();
const handleFileSelect = (file: File) => {
// Only accept zip files
if (!file.name.toLowerCase().endsWith('.zip')) {
setError('Please select a ZIP file');
return;
}
setSelectedFile(file);
setError(null);
// Auto-generate ID from file name
const baseName = file.name.replace(/\.zip$/i, '');
const id = baseName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
setGeneratedId(id);
};
// Check for existing project when generated ID changes
useEffect(() => {
if (generatedId && projects.length > 0) {
const existing = projects.find(project => project.id === generatedId);
setExistingProject(existing || null);
} else {
setExistingProject(null);
}
}, [generatedId, projects]);
// Drag and drop handlers
const handleDragOver = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(true);
}, []);
const handleDragLeave = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
}, []);
const handleDrop = useCallback((e: React.DragEvent) => {
e.preventDefault();
setIsDragOver(false);
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
handleFileSelect(files[0]);
}
}, []);
const handleDragOverDialog = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(true);
}, []);
const handleDragLeaveDialog = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
}, []);
const handleDropDialog = useCallback((e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
const files = Array.from(e.dataTransfer.files);
if (files.length > 0) {
handleFileSelect(files[0]);
}
}, []);
const handleClickUpload = () => {
fileInputRef.current?.click();
};
const handleFileRemove = () => {
setSelectedFile(null);
setGeneratedId('');
setError(null);
};
const handleImport = async (overwrite = false) => {
if (!selectedFile) return;
setIsImporting(true);
setImportProgress(0);
setError(null);
try {
// Simulate progress for better UX
const progressInterval = setInterval(() => {
setImportProgress(prev => Math.min(prev + 10, 90));
}, 200);
await onImport(selectedFile, overwrite, generatedId);
clearInterval(progressInterval);
setImportProgress(100);
// Close dialog after a short delay
setTimeout(() => {
setIsOpen(false);
setSelectedFile(null);
setGeneratedId('');
setImportProgress(0);
setExistingProject(null);
}, 1000);
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to import project');
setImportProgress(0);
} finally {
setIsImporting(false);
}
};
const handleImportWithOverwriteCheck = async () => {
if (!selectedFile || !generatedId) return;
// Check if project with this ID already exists
try {
// This would ideally be passed as a prop or through context
// For now, we'll assume the parent will handle the check and pass existing project info
if (existingProject) {
setShowOverwriteDialog(true);
} else {
await handleImport(false);
}
} catch (error) {
console.error('Error checking existing project:', error);
await handleImport(false);
}
};
const confirmOverwrite = async () => {
setShowOverwriteDialog(false);
await handleImport(true);
};
const handleClose = () => {
if (!isImporting) {
setIsOpen(false);
setSelectedFile(null);
setGeneratedId('');
setError(null);
setImportProgress(0);
}
};
// Only render DialogTrigger if this component is being used in uncontrolled mode
// (no open/onOpenChange props provided)
const isControlled = open !== undefined && onOpenChange !== undefined;
return (
<>
<Dialog open={isOpen} onOpenChange={setIsOpen}>
{!isControlled && (
<DialogTrigger asChild>
<Button
variant="outline"
disabled={disabled}
className={cn("gap-2", className)}
>
<FileArchive className="h-4 w-4" />
Import ZIP
</Button>
</DialogTrigger>
)}
<DialogContent
className="sm:max-w-md"
onDragOver={handleDragOverDialog}
onDragLeave={handleDragLeaveDialog}
onDrop={handleDropDialog}
>
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Upload className="h-5 w-5" />
Import Project from ZIP
</DialogTitle>
<DialogDescription>
Upload a ZIP file containing your project source code to import it into Shakespeare.
</DialogDescription>
</DialogHeader>
<div className="space-y-4">
{!isImporting && (
<>
{/* Drag and Drop Area */}
<div
className={cn(
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
selectedFile && "border-green-500/50 bg-green-500/5"
)}
onClick={handleClickUpload}
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
>
<input
ref={fileInputRef}
type="file"
onChange={(e) => {
const files = e.target.files;
if (files && files.length > 0) {
handleFileSelect(files[0]);
}
}}
accept=".zip"
className="hidden"
disabled={isImporting}
/>
<div className="space-y-3">
<div className="flex justify-center">
{selectedFile ? (
<FileText className="h-8 w-8 text-green-600" />
) : (
<Upload className="h-8 w-8 text-muted-foreground" />
)}
</div>
<div>
{selectedFile ? (
<div className="space-y-1">
<p className="text-sm font-medium text-green-600">
{selectedFile.name}
</p>
<p className="text-xs text-muted-foreground">
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
</p>
<button
onClick={(e) => {
e.stopPropagation();
handleFileRemove();
}}
className="text-xs text-destructive hover:underline"
>
Remove file
</button>
</div>
) : (
<div className="space-y-1">
<p className="text-sm font-medium">
Drop your ZIP file here or click to browse
</p>
<p className="text-xs text-muted-foreground">
Supports ZIP files up to 50MB
</p>
</div>
)}
</div>
</div>
</div>
{/* Error Display */}
{error && (
<div className="flex items-center gap-2 text-sm text-destructive">
<AlertCircle className="h-4 w-4" />
{error}
</div>
)}
{/* Overwrite Warning */}
{existingProject && (
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
<AlertCircle className="h-3 w-3" />
A project with this ID already exists. You can choose to overwrite it.
</div>
)}
{/* Import Button */}
<div className="flex justify-end gap-2 pt-4">
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
Cancel
</Button>
<Button
onClick={handleImportWithOverwriteCheck}
disabled={!selectedFile || !generatedId || isImporting}
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
>
{existingProject ? (
<>
<Trash2 className="mr-2 h-4 w-4" />
Overwrite Project
</>
) : (
<>
<Upload className="mr-2 h-4 w-4" />
Import Project
</>
)}
</Button>
</div>
</>
)}
{/* Import Progress */}
{isImporting && (
<div className="space-y-3">
<div className="flex items-center gap-2 text-sm">
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
Importing project...
</div>
<Progress value={importProgress} className="w-full" />
<p className="text-xs text-muted-foreground text-center">
Extracting files and setting up project...
</p>
</div>
)}
{/* Success State */}
{!isImporting && importProgress === 100 && (
<div className="flex items-center gap-2 text-sm text-green-600">
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
</svg>
Project imported successfully!
</div>
)}
</div>
</DialogContent>
</Dialog>
{/* Overwrite Confirmation Dialog */}
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
<AlertDialogContent>
<AlertDialogHeader>
<AlertDialogTitle className="flex items-center gap-2">
<AlertCircle className="h-5 w-5 text-amber-600" />
Overwrite Existing Project
</AlertDialogTitle>
<AlertDialogDescription className="space-y-2">
<p>
A project with the ID "<strong>{generatedId}</strong>" already exists.
Overwriting it will:
</p>
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
<li><strong>Delete all existing files</strong> in the project</li>
<li><strong>Replace them with files</strong> from the ZIP archive</li>
<li><strong>Preserve Git history</strong> if it exists</li>
<li><strong>Keep AI chat history</strong> and session data</li>
</ul>
<p className="text-amber-600 font-medium">
This action cannot be undone. Are you sure you want to continue?
</p>
</AlertDialogDescription>
</AlertDialogHeader>
<AlertDialogFooter>
<AlertDialogCancel>Cancel</AlertDialogCancel>
<AlertDialogAction
onClick={confirmOverwrite}
className="bg-amber-600 hover:bg-amber-700"
>
Yes, Overwrite Project
</AlertDialogAction>
</AlertDialogFooter>
</AlertDialogContent>
</AlertDialog>
</>
);
}
@@ -81,4 +81,21 @@ describe('BrowserAddressBar', () => {
expect(onForward).toHaveBeenCalled();
expect(onRefresh).toHaveBeenCalled();
});
it('updates input value when currentPath prop changes', () => {
const { rerender } = render(<BrowserAddressBar currentPath="/" />);
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
expect(input).toHaveValue('/');
// Re-render with new currentPath
rerender(<BrowserAddressBar currentPath="/about" />);
expect(input).toHaveValue('/about');
// Re-render with another path
rerender(<BrowserAddressBar currentPath="/contact" />);
expect(input).toHaveValue('/contact');
});
});
+6 -1
View File
@@ -1,4 +1,4 @@
import { useState } from 'react';
import { useState, useEffect } from 'react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
@@ -30,6 +30,11 @@ export function BrowserAddressBar({
}: BrowserAddressBarProps) {
const [inputValue, setInputValue] = useState(currentPath);
// Update input value when currentPath changes (e.g., when iframe navigates)
useEffect(() => {
setInputValue(currentPath);
}, [currentPath]);
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
if (!onNavigate) return;
+25 -7
View File
@@ -12,6 +12,7 @@ interface UseAIChatSessionOptions {
customTools?: Record<string, Tool<unknown>>;
maxSteps?: number;
onUpdateMetadata?: (title: string, description: string) => void;
onAIError?: (error: Error) => void;
}
interface StreamingMessage {
@@ -30,7 +31,8 @@ export function useAIChat({
tools = {},
customTools = {},
maxSteps = 50,
onUpdateMetadata
onUpdateMetadata,
onAIError
}: UseAIChatSessionOptions) {
const sessionManager = useSessionManager();
const { isConfigured } = useAISettings();
@@ -113,14 +115,30 @@ export function useAIChat({
// Actions
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
}, [projectId, sessionManager, initSession]);
try {
await initSession();
await sessionManager.sendMessage(projectId, content, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
onAIError(error);
} else {
console.error('AI chat error:', error);
}
}
}, [projectId, sessionManager, initSession, onAIError]);
const startGeneration = useCallback(async (providerModel: string) => {
await initSession();
await sessionManager.startGeneration(projectId, providerModel);
}, [projectId, sessionManager, initSession]);
try {
await initSession();
await sessionManager.startGeneration(projectId, providerModel);
} catch (error) {
if (onAIError && error instanceof Error) {
onAIError(error);
} else {
console.error('AI chat error:', error);
}
}
}, [projectId, sessionManager, initSession, onAIError]);
const stopGeneration = useCallback(() => {
sessionManager.stopGeneration(projectId);
-153
View File
@@ -1,153 +0,0 @@
import { useState, useCallback, useMemo } from 'react';
import type { AIMessage } from '@/lib/SessionManager';
import { useConsoleMessages } from './useConsoleMessages';
export interface ConsoleErrorAlert {
hasError: boolean;
errorSummary: string | null;
errorCount: number;
dismiss: () => void;
}
export const useConsoleErrorAlert = (
aiMessages: AIMessage[],
isBuilding?: boolean,
isLoading?: boolean
): ConsoleErrorAlert => {
const { messages } = useConsoleMessages();
const [dismissedErrorSummary, setDismissedErrorSummary] = useState<string>('');
const { hasError, errorSummary, errorCount } = useMemo(() => {
// Don't show alerts while building or AI is working
if (isBuilding || isLoading) {
return { hasError: false, errorSummary: null, errorCount: 0 };
}
// Find the timestamp of the last AI assistant message
// Since AIMessage doesn't have timestamps, we'll use a different approach:
// Only show errors if there are any errors at all and no recent user activity
const lastMessage = aiMessages[aiMessages.length - 1];
const isLastMessageFromAssistant = lastMessage?.role === 'assistant';
// Only show console errors if the last message was from assistant (AI just responded)
if (!isLastMessageFromAssistant) {
return { hasError: false, errorSummary: null, errorCount: 0 };
}
// Get recent errors (last 10 seconds worth to catch errors from recent AI actions)
const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago
const recentErrors = messages.filter(msg =>
msg.level === 'error' &&
msg.timestamp > recentTimeThreshold
);
if (recentErrors.length === 0) {
return { hasError: false, errorSummary: null, errorCount: 0 };
}
// Just return the raw error messages, no formatting
const summary = recentErrors.slice(-3).map(e => e.message).join('\n');
return {
hasError: dismissedErrorSummary !== summary,
errorSummary: summary,
errorCount: recentErrors.length
};
}, [messages, dismissedErrorSummary, aiMessages, isBuilding, isLoading]);
const dismiss = useCallback(() => {
if (errorSummary) {
setDismissedErrorSummary(errorSummary);
}
}, [errorSummary]);
return {
hasError,
errorSummary,
errorCount,
dismiss
};
};
export interface AIModelErrorAlert {
hasError: boolean;
errorMessage: string | null;
errorType: 'warn' | 'error' | null;
action?: { label: string; onClick: () => void };
dismiss: () => void;
}
export const useAIModelErrorAlert = (
messages: AIMessage[],
onNewChat?: () => void,
onChangeModel?: () => void
): AIModelErrorAlert => {
const [dismissedAlertKey, setDismissedAlertKey] = useState<string>('');
const { hasError, errorMessage, errorType, action } = useMemo(() => {
const lastMessage = messages[messages.length - 1];
// Only show AI model alerts if the last message is from the assistant
// This ensures we don't show stale alerts when user continues the conversation
if (!lastMessage || lastMessage.role !== 'assistant') {
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
}
const content = typeof lastMessage.content === 'string' ? lastMessage.content : '';
// Define error patterns with actions
const errorPatterns = [
{
test: (content: string) => /AI service error: 422/.test(content) || /Provider returned error/.test(content),
type: 'error' as const,
message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.',
action: onChangeModel ? { label: 'Change model', onClick: onChangeModel } : undefined
},
{
test: (content: string) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content),
type: 'warn' as const,
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
action: onNewChat ? { label: 'New chat', onClick: onNewChat } : undefined
},
{
test: (content: string) => /rate limit/i.test(content) || /too many requests/i.test(content),
type: 'warn' as const,
message: 'You\'re sending requests too quickly. Please wait a moment before trying again.'
}
];
for (const pattern of errorPatterns) {
if (pattern.test(content)) {
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
const alertKey = `${pattern.message}_${messageContent.slice(0, 50)}_${Date.now()}`;
return {
hasError: dismissedAlertKey !== alertKey,
errorMessage: pattern.message,
errorType: pattern.type,
action: pattern.action,
alertKey
};
}
}
return { hasError: false, errorMessage: null, errorType: null, action: undefined };
}, [messages, dismissedAlertKey, onNewChat, onChangeModel]);
const dismiss = useCallback(() => {
const lastMessage = messages[messages.length - 1];
if (errorMessage && lastMessage) {
const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content);
const alertKey = `${errorMessage}_${messageContent.slice(0, 50)}_${Date.now()}`;
setDismissedAlertKey(alertKey);
}
}, [errorMessage, messages]);
return {
hasError,
errorMessage,
errorType,
action,
dismiss
};
};
-171
View File
@@ -14,27 +14,6 @@ const createMockNostr = (): NPool => ({
close: vi.fn(),
}) as unknown as NPool;
// Mock JSZip
vi.mock('jszip', () => ({
default: class MockJSZip {
files: Record<string, { dir: boolean; async: () => Uint8Array }> = {};
static async loadAsync(buffer: ArrayBuffer) {
const instance = new MockJSZip();
// Add a mock file entry
instance.files['package.json'] = {
dir: false,
async: () => new Uint8Array(buffer)
};
return instance;
}
async file(name: string) {
return this.files[name];
}
}
}));
// Mock filesystem for testing
class MockFS implements JSRuntimeFS {
private files: Map<string, string | Uint8Array> = new Map();
@@ -290,156 +269,6 @@ describe('ProjectsManager', () => {
});
});
describe('importProjectFromZip', () => {
it('should preserve original project name when overwriting', async () => {
await projectsManager.init();
// Create an existing project with a specific name
await fs.mkdir('/projects/my-project');
await fs.mkdir('/projects/my-project/.git');
await fs.writeFile('/projects/my-project/package.json', '{"name": "original-name"}');
// Mock the git methods to simulate existing project
const mockGit = {
init: vi.fn(),
clone: vi.fn(),
add: vi.fn(),
commit: vi.fn(),
getConfig: vi.fn(),
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Create a mock ZIP file with different name
const zipFile = new File(['test content'], 'different-name.zip', { type: 'application/zip' });
// Mock arrayBuffer method
Object.defineProperty(zipFile, 'arrayBuffer', {
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
writable: false
});
// Import with overwrite
const project = await projectsManager.importProjectFromZip(zipFile, 'my-project', true);
// Should preserve original project name
expect(project.name).toBe('my-project');
expect(project.id).toBe('my-project');
});
it('should use new project name when not overwriting', async () => {
await projectsManager.init();
// Mock the git methods
const mockGit = {
init: vi.fn(),
clone: vi.fn(),
add: vi.fn(),
commit: vi.fn(),
getConfig: vi.fn(),
getAllFiles: vi.fn().mockResolvedValue(['package.json']),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Create a mock ZIP file
const zipFile = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
// Mock arrayBuffer method
Object.defineProperty(zipFile, 'arrayBuffer', {
value: () => Promise.resolve(new TextEncoder().encode('test content').buffer),
writable: false
});
// Import without overwrite
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
// Should use formatted name from ID
expect(project.name).toBe('new-project');
expect(project.id).toBe('new-project');
});
it('should prevent zip slip attacks during import', async () => {
await projectsManager.init();
// Mock the git methods
const mockGit = {
init: vi.fn(),
clone: vi.fn(),
add: vi.fn(),
commit: vi.fn(),
getConfig: vi.fn(),
getAllFiles: vi.fn().mockResolvedValue([]),
} as Partial<import('./git').Git>;
// Replace git instance
Object.assign(projectsManager, { git: mockGit });
// Create a mock ZIP file that would try to escape the project directory
const zipFile = new File(['malicious content'], 'malicious.zip', { type: 'application/zip' });
// Mock JSZip to simulate a malicious ZIP with path traversal
const JSZip = await import('jszip');
const mockLoadAsync = vi.fn().mockResolvedValue({
files: {
'../../../etc/passwd': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
},
'../../outside.txt': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
},
'safe-file.txt': {
dir: false,
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
}
}
});
vi.spyOn(JSZip.default, 'loadAsync').mockImplementation(mockLoadAsync);
// Mock arrayBuffer method
Object.defineProperty(zipFile, 'arrayBuffer', {
value: () => Promise.resolve(new ArrayBuffer(0)),
writable: false
});
// Spy on console.warn to check for security warnings
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
try {
// Import the malicious ZIP
const project = await projectsManager.importProjectFromZip(zipFile, undefined, false);
// Should have completed successfully (safe files extracted)
expect(project).toBeDefined();
// Should have logged a security warning about skipped files
expect(consoleSpy).toHaveBeenCalledWith(
expect.stringContaining('Skipped 2 files due to resolving to paths outside the project direcotry:'),
['../../../etc/passwd', '../../outside.txt']
);
// Verify that only safe files would be written (check writeFile calls)
const writeFileCalls = (fs.writeFile as unknown as { mock?: { calls: [string, unknown][] } }).mock?.calls || [];
const maliciousPaths = writeFileCalls.filter((call: [string, unknown]) =>
call[0].includes('../') || call[0].includes('etc/passwd') || call[0].includes('outside.txt')
);
expect(maliciousPaths).toHaveLength(0);
} finally {
// Restore mocks
consoleSpy.mockRestore();
vi.restoreAllMocks();
}
});
});
describe('renameProject', () => {
it('should rename a project directory', async () => {
await projectsManager.init();
+1 -241
View File
@@ -1,6 +1,5 @@
import { Buffer } from 'buffer';
import JSZip from 'jszip';
import { Git } from '@/lib/git';
import type { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
// Polyfill Buffer for browser
@@ -96,192 +95,6 @@ export class ProjectsManager {
return project;
}
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
// Generate a project ID based on the zip file name or use custom ID
const baseName = zipFile.name.replace(/\.zip$/i, '');
const generatedId = baseName
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-')
.replace(/^-+|-+$/g, '');
// Determine the project ID to use
let id: string;
if (customId) {
// Use the provided custom ID (for overwrite scenarios)
id = customId;
} else {
// If no custom ID, generate a unique ID (for new projects)
id = await this.generateUniqueProjectId(generatedId);
}
const projectPath = `${this.dir}/${id}`;
const projectExists = await this.projectExists(id);
// Check if project with this ID already exists when not overwriting
if (projectExists && !overwrite) {
throw new Error(`Project with ID "${id}" already exists`);
}
// Get original project name if overwriting, otherwise use formatted name
let projectName: string;
if (overwrite && projectExists) {
const existingProject = await this.getProject(id);
projectName = existingProject?.name || this.formatProjectName(id);
} else {
projectName = this.formatProjectName(id);
}
try {
// Create project directory (or ensure it exists for overwrite)
await this.fs.mkdir(projectPath, { recursive: true });
// If overwriting, delete existing files except .ai directory and .git directory
if (projectExists && overwrite) {
const existingFiles = await this.getAllFiles(projectPath);
for (const file of existingFiles) {
// Preserve .ai directory and .git directory
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
try {
await this.fs.unlink(`${projectPath}/${file}`);
} catch {
// Ignore deletion errors
}
}
}
}
// Read the zip file
const arrayBuffer = await zipFile.arrayBuffer();
const zip = await JSZip.loadAsync(arrayBuffer);
// Extract all files from the zip with security validation
const extractedFiles: string[] = [];
const skippedFiles: string[] = [];
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
// Validate the extraction path is within the project directory
const extractPath = this.join(projectPath, relativePath);
if (!this.isPathWithinProject(extractPath, projectPath)) {
skippedFiles.push(relativePath);
continue;
}
if (zipEntry.dir) {
// Create the directory structure
await this.fs.mkdir(extractPath, { recursive: true });
continue;
}
// Extract file content
const content = await zipEntry.async('uint8array');
// Ensure parent directory exists
const dirPath = extractPath.split('/').slice(0, -1).join('/');
if (dirPath) {
await this.fs.mkdir(dirPath, { recursive: true });
}
// Write the file (this will overwrite existing files)
await this.fs.writeFile(extractPath, content);
extractedFiles.push(relativePath);
}
if (skippedFiles.length > 0) {
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project direcotry:`, skippedFiles);
}
// Get filesystem stats for timestamps
const stats = await this.fs.stat(projectPath);
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
// Initialize git repository if there's no .git directory
try {
await this.fs.stat(`${projectPath}/.git`);
// If git exists and we're overwriting, stage the new files
if (overwrite) {
const projectFiles = await this.getAllFiles(projectPath);
for (const file of projectFiles) {
// Skip .git directory and .ai directory
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
try {
await this.git.add({
dir: projectPath,
filepath: file,
});
} catch {
// Ignore git add errors for files that might be gitignored
}
}
}
// Make commit for the overwrite
await this.git.commit({
dir: projectPath,
message: `Overwrite project from ${zipFile.name}`,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
}
} catch {
// No .git directory found, initialize new repository
await this.git.init({
dir: projectPath,
defaultBranch: 'main',
});
// Add all files to git (excluding .ai directory)
const projectFiles = await this.getAllFiles(projectPath);
for (const file of projectFiles) {
// Skip .git directory and .ai directory
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
await this.git.add({
dir: projectPath,
filepath: file,
});
}
}
// Make initial commit
await this.git.commit({
dir: projectPath,
message: `Import project from ${zipFile.name}`,
author: {
name: 'shakespeare.diy',
email: '[email protected]',
},
});
}
// Create .ai/history directory
try {
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
} catch {
// Directory might already exist
}
return {
id,
name: projectName,
path: projectPath,
lastModified: timestamp,
};
} catch (error) {
// Clean up on error (only if this was a new project creation)
if (!projectExists) {
try {
await this.deleteDirectory(projectPath);
} catch {
// Ignore cleanup errors
}
}
throw error;
}
}
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
@@ -589,57 +402,4 @@ export class ProjectsManager {
return files;
}
/**
* Safe path join that normalizes the result to prevent directory traversal
*/
private join(...paths: string[]): string {
// Simple path joining with normalization
const joined = paths.join('/').replace(/\/+/g, '/');
// Normalize path separators and resolve .. and . components
const parts = joined.split('/').filter(part => part !== '');
const normalized: string[] = [];
for (const part of parts) {
if (part === '..') {
normalized.pop();
} else if (part !== '.') {
normalized.push(part);
}
}
return '/' + normalized.join('/');
}
/**
* Check if a path is within the project directory
*/
private isPathWithinProject(extractPath: string, projectPath: string): boolean {
// Normalize both paths
const normalizedExtractPath = this.normalize(extractPath);
const normalizedProjectPath = this.normalize(projectPath);
// Check if the extract path starts with the project path
return normalizedExtractPath.startsWith(normalizedProjectPath + '/') ||
normalizedExtractPath === normalizedProjectPath;
}
/**
* Normalize a path by resolving . and .. components
*/
private normalize(path: string): string {
const parts = path.split('/').filter(part => part !== '');
const normalized: string[] = [];
for (const part of parts) {
if (part === '..') {
normalized.pop();
} else if (part !== '.') {
normalized.push(part);
}
}
return '/' + normalized.join('/');
}
}
+22
View File
@@ -95,4 +95,26 @@ describe('SessionManager', () => {
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
}
});
it('should throw service errors instead of adding them to message history', async () => {
const projectId = 'test-project';
const tools = {};
const customTools = {};
// Load a session
await sessionManager.loadSession(projectId, tools, customTools);
// Add a user message to enable generation
await sessionManager.addMessage(projectId, { role: 'user', content: 'test message' });
// Attempt to start generation with invalid provider - should throw error instead of adding to messages
await expect(
sessionManager.startGeneration(projectId, 'invalid-provider/invalid-model')
).rejects.toThrow('Provider "invalid-provider" not found');
// Verify that no error message was added to the conversation
const updatedSession = sessionManager.getSession(projectId);
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
expect(updatedSession?.messages[0].role).toBe('user');
});
});
+3 -15
View File
@@ -404,25 +404,13 @@ export class SessionManager {
} catch (error) {
console.error('AI generation error:', error);
// Handle different error types
// Handle user cancellation
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
return; // User cancelled
}
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
const errorMsg = error?.message || '';
if (error?.name === 'TypeError' && errorMsg.includes('fetch')) {
errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
} else if (errorMsg.includes('API key')) {
errorMessage = 'Authentication error: Please check your API key in AI settings.';
} else if (errorMsg.includes('rate limit')) {
errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
} else if (errorMsg) {
errorMessage = `AI service error: ${errorMsg}`;
}
await this.addMessage(projectId, { role: 'assistant', content: errorMessage });
// Re-throw service errors to be handled at the UI level
throw error;
} finally {
if (session) {
session.isLoading = false;
+2 -7
View File
@@ -15,6 +15,7 @@ import { parseProviderModel } from '@/lib/parseProviderModel';
import type { AIMessage } from '@/lib/SessionManager';
import { saveFileToTmp } from '@/lib/fileUtils';
import type OpenAI from 'openai';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { ModelSelector } from '@/components/ModelSelector';
@@ -261,13 +262,7 @@ export default function Index() {
navigate(`/project/${project.id}?${searchParams.toString()}`);
} catch (error) {
console.error('Failed to create project:', error);
if (!checkForKeyFailure(error)) {
toast({
title: "Project Creation Failed",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
}
checkForKeyFailure(error);
} finally {
setIsCreating(false);
}
-31
View File
@@ -14,7 +14,6 @@ import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react';
import { useNavigate } from 'react-router-dom';
import { ActionsMenu } from '@/components/ActionsMenu';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useKeepAlive } from '@/hooks/useKeepAlive';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { StarButton } from '@/components/StarButton';
@@ -40,20 +39,6 @@ export function ProjectView() {
const build = useBuildProject(projectId!);
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
// Keep-alive functionality to prevent tab throttling during AI processing
const { updateMetadata } = useKeepAlive({
enabled: isAILoading || build.isPending,
title: 'Shakespeare',
artist: project ? `Working on ${project.name}...` : 'Working...',
artwork: [
{
src: '/favicon.png',
sizes: '512x512',
type: 'image/png'
}
]
});
const loadProject = useCallback(async () => {
if (!projectId) return;
@@ -91,20 +76,6 @@ export function ProjectView() {
}
}, [isPreviewable, mobileView, activeTab]);
const runBuild = async () => {
if (build.isPending || !project) return;
updateMetadata('Shakespeare', `Building ${project.name}...`);
await build.mutateAsync(undefined, {
onSuccess(result) {
console.log('Project built:', result);
},
onError(error) {
console.error('Build failed:', error);
},
});
};
const handleNewChat = () => {
// Reset to chat view on mobile when starting new chat
if (isMobile) {
@@ -234,7 +205,6 @@ export function ProjectView() {
ref={chatPaneRef}
projectId={project.id}
onNewChat={handleNewChat}
onBuild={runBuild}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}
@@ -414,7 +384,6 @@ export function ProjectView() {
ref={chatPaneRef}
projectId={project.id}
onNewChat={handleNewChat}
onBuild={runBuild}
onFirstInteraction={handleFirstInteraction}
onLoadingChange={handleAILoadingChange}
isLoading={isAILoading}