mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 16:03:34 +00:00
Compare commits
50
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
f09f1436ae | ||
|
|
374d2804ad | ||
|
|
c0f906ae7e | ||
|
|
92e2ac1ce5 | ||
|
|
e81fb33ffe | ||
|
|
9a65d5d086 | ||
|
|
61d5a5fefc | ||
|
|
75e961d281 | ||
|
|
93e992f128 | ||
|
|
7ab30af944 | ||
|
|
6296fc4366 | ||
|
|
147c7cdf3a | ||
|
|
18a276a44e | ||
|
|
a20bbfdf29 | ||
|
|
980cb60f1b | ||
|
|
2956c86f88 | ||
|
|
c46077af67 | ||
|
|
e5ca49962e | ||
|
|
f5c5684ac8 | ||
|
|
6a72711aa0 | ||
|
|
1ed4a5abd4 | ||
|
|
db57619bca | ||
|
|
0f4075ce38 | ||
|
|
37147a69d4 | ||
|
|
ec5d84d3f7 | ||
|
|
0b949d55b9 | ||
|
|
25f14ee2b3 | ||
|
|
7057c34f01 | ||
|
|
d932f05d04 | ||
|
|
e9f8e99ac5 | ||
|
|
4f9d3ae1d1 | ||
|
|
fdfdcb4b16 | ||
|
|
50e16e1b57 | ||
|
|
662f95d35d | ||
|
|
458eec0e27 | ||
|
|
74e472338d | ||
|
|
2b5e3013ff | ||
|
|
951eefb7b8 | ||
|
|
a68d37452b | ||
|
|
c8653e67dc | ||
|
|
660f25656c | ||
|
|
804efb4d23 | ||
|
|
8108407478 | ||
|
|
41d7d7834d | ||
|
|
785f75a39a | ||
|
|
8e3cc67ce2 | ||
|
|
fae90cc85e | ||
|
|
2ed44e43f7 | ||
|
|
53cf844fd6 | ||
|
|
6aa36b6738 |
No files matched your search
@@ -51,6 +51,7 @@ Shakespeare provides AI agents with specialized tools for project development (n
|
||||
- **NostrReadNipsIndexTool**: Read the full list of NIPs, kinds, and tags
|
||||
- **NostrFetchEventTool**: Fetch Nostr events using NIP-19 identifiers
|
||||
- **NostrGenerateKindTool**: Generate unused Nostr event kind numbers
|
||||
- **ReadConsoleMessagesTool**: Read console messages from project preview with filtering capabilities
|
||||
|
||||
#### Shell Commands
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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
@@ -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));
|
||||
});
|
||||
|
||||
+19
-16
@@ -16,6 +16,7 @@ import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleProvider } from '@/contexts/ConsoleContext';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
|
||||
@@ -73,22 +74,24 @@ export function App() {
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
<ConsoleProvider>
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<SessionManagerProvider>
|
||||
<TooltipProvider>
|
||||
<Toaster />
|
||||
<Suspense>
|
||||
<AppRouter />
|
||||
</Suspense>
|
||||
</TooltipProvider>
|
||||
</SessionManagerProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</ConsoleProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
@@ -0,0 +1,168 @@
|
||||
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 { ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
import { useState } from 'react';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
providerModel: string;
|
||||
}
|
||||
|
||||
interface ErrorBody {
|
||||
message: string;
|
||||
action?: {
|
||||
label: string;
|
||||
onClick: () => void;
|
||||
};
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, 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 Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
|
||||
action: {
|
||||
label: 'Help fix errors',
|
||||
onClick: () => {
|
||||
onRequestConsoleErrorHelp?.(error);
|
||||
onDismiss();
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
// Handle OpenAI API errors with specific error codes
|
||||
if (error instanceof OpenAI.APIError) {
|
||||
switch (error.code) {
|
||||
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();
|
||||
});
|
||||
});
|
||||
@@ -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';
|
||||
@@ -34,63 +34,20 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool';
|
||||
import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { useConsole, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
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 +60,7 @@ export interface ChatPaneRef {
|
||||
|
||||
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
projectId,
|
||||
onNewChat: _onNewChat,
|
||||
onBuild: _onBuild,
|
||||
onNewChat,
|
||||
onFirstInteraction,
|
||||
onLoadingChange,
|
||||
isLoading: externalIsLoading,
|
||||
@@ -118,6 +74,23 @@ 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);
|
||||
|
||||
// Get console functionality early so it can be used in useEffect
|
||||
const { messagesRef: consoleMessagesRef, addErrorListener, removeErrorListener } = useConsole();
|
||||
|
||||
// Console error handling
|
||||
useEffect(() => {
|
||||
const handleConsoleError = (error: ProjectPreviewConsoleError) => {
|
||||
// Only show console errors if there's no existing AI error
|
||||
if (!aiError) {
|
||||
setAIError(error);
|
||||
}
|
||||
};
|
||||
|
||||
addErrorListener(handleConsoleError);
|
||||
return () => removeErrorListener(handleConsoleError);
|
||||
}, [aiError, addErrorListener, removeErrorListener]);
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
@@ -137,6 +110,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();
|
||||
@@ -163,6 +141,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
shell: new ShellTool(fs, cwd, git),
|
||||
read_console_messages: new ReadConsoleMessagesTool(() => consoleMessagesRef.current),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
@@ -174,7 +153,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId]);
|
||||
}, [fs, git, cwd, user, projectId, consoleMessagesRef]);
|
||||
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
@@ -204,6 +183,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,8 +203,14 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
tools,
|
||||
customTools,
|
||||
onUpdateMetadata,
|
||||
onAIError,
|
||||
});
|
||||
|
||||
// Handle console error help requests
|
||||
const handleConsoleErrorHelp = useCallback(() => {
|
||||
sendMessage('Read the console messages and fix any errors present.', providerModel);
|
||||
}, [sendMessage, providerModel]);
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading;
|
||||
|
||||
@@ -267,19 +257,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 +406,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 +450,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 +521,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 +613,17 @@ 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}
|
||||
onRequestConsoleErrorHelp={handleConsoleErrorHelp}
|
||||
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>
|
||||
|
||||
|
||||
@@ -3,12 +3,12 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages';
|
||||
import { useConsole, type ConsoleMessage } from '@/contexts/ConsoleContext';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
@@ -18,7 +18,12 @@ import {
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
@@ -66,7 +71,6 @@ interface JSONRPCResponse {
|
||||
id: number;
|
||||
}
|
||||
|
||||
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
@@ -78,12 +82,13 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
|
||||
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { messages: consoleMessages } = useConsoleMessages();
|
||||
const { addMessage: addConsoleMessage, messages: consoleMessages } = useConsole();
|
||||
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
@@ -166,67 +171,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);
|
||||
}
|
||||
@@ -255,19 +216,98 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
normalizedLevel = params.level as ConsoleMessage['level'];
|
||||
}
|
||||
|
||||
// Add to global console messages
|
||||
// Add to console messages
|
||||
addConsoleMessage(normalizedLevel, params.message);
|
||||
|
||||
// Log to parent console for debugging with appropriate level
|
||||
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
|
||||
}, []);
|
||||
}, [addConsoleMessage]);
|
||||
|
||||
const handleUpdateNavigationState = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
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
|
||||
const url = new URL(fetchRequest.url);
|
||||
@@ -290,6 +330,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 +353,27 @@ 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;
|
||||
}
|
||||
}
|
||||
|
||||
// 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,8 +393,6 @@ 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',
|
||||
result: {
|
||||
@@ -379,12 +436,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 +451,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 +474,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);
|
||||
@@ -437,98 +501,101 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
};
|
||||
|
||||
const ConsoleDropdown = () => {
|
||||
const getLevelColor = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return 'text-red-500';
|
||||
case 'warn': return 'text-yellow-500';
|
||||
case 'info': return 'text-blue-500';
|
||||
case 'debug': return 'text-gray-500';
|
||||
default: return 'text-gray-400';
|
||||
}
|
||||
};
|
||||
const [isOpen, setIsOpen] = useState(false);
|
||||
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
|
||||
|
||||
const getLevelIcon = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return '!';
|
||||
case 'warn': return '⚠';
|
||||
case 'info': return 'ℹ';
|
||||
case 'debug': return '🔍';
|
||||
default: return '•';
|
||||
}
|
||||
};
|
||||
|
||||
const clearConsole = () => {
|
||||
clearConsoleMessages();
|
||||
};
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
|
||||
try {
|
||||
// Create a formatted string with all message details
|
||||
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
|
||||
|
||||
await navigator.clipboard.writeText(formattedMessage);
|
||||
setCopiedMessageId(msg.id);
|
||||
|
||||
// Reset the copied state after 2 seconds
|
||||
setTimeout(() => {
|
||||
setCopiedMessageId(null);
|
||||
}, 2000);
|
||||
await navigator.clipboard.writeText(msg.message);
|
||||
setCopiedMessageIndex(index);
|
||||
setTimeout(() => setCopiedMessageIndex(null), 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
// consoleMessages is now available from the hook
|
||||
const messageCount = consoleMessages.length;
|
||||
const hasErrors = consoleMessages.some(msg => msg.level === 'error');
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
|
||||
<Popover open={isOpen} onOpenChange={setIsOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 relative hover:bg-accent hover:text-accent-foreground transition-colors"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{consoleMessages.some(msg => msg.level === 'error') && (
|
||||
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
|
||||
{hasErrors && (
|
||||
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
|
||||
<div className="flex items-center justify-between p-2 border-b">
|
||||
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
|
||||
<Button variant="ghost" size="sm" onClick={clearConsole}>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
|
||||
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
|
||||
{consoleMessages.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground text-sm py-4">
|
||||
No console messages
|
||||
</PopoverTrigger>
|
||||
<PopoverContent
|
||||
align="end"
|
||||
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
|
||||
sideOffset={4}
|
||||
>
|
||||
|
||||
{/* Messages */}
|
||||
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
|
||||
<div className="py-2 px-1 space-y-0">
|
||||
{messageCount === 0 ? (
|
||||
<div className="flex flex-col items-center justify-center py-12 text-center">
|
||||
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
|
||||
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
|
||||
</div>
|
||||
) : (
|
||||
consoleMessages.map((msg) => (
|
||||
consoleMessages.map((msg, index) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
|
||||
key={index}
|
||||
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
>
|
||||
<div className="flex items-start justify-between w-full">
|
||||
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copyMessageToClipboard(msg)}
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
|
||||
>
|
||||
{copiedMessageId === msg.id ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
<div className={cn(
|
||||
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
|
||||
msg.level === 'error' ? "text-destructive" :
|
||||
msg.level === 'warn' ? "text-warning" :
|
||||
msg.level === 'info' ? "text-primary" :
|
||||
"text-muted-foreground"
|
||||
)}>
|
||||
{msg.message}
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={(e) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
copyMessageToClipboard(msg, index);
|
||||
}}
|
||||
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
|
||||
>
|
||||
{copiedMessageIndex === index ? (
|
||||
<Check className="h-2 w-2 text-success" />
|
||||
) : (
|
||||
<Copy className="h-2 w-2" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
</div>
|
||||
|
||||
{/* Close button */}
|
||||
<button
|
||||
onClick={() => setIsOpen(false)}
|
||||
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
|
||||
>
|
||||
<X className="h-5 w-5 text-muted-foreground" />
|
||||
</button>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
);
|
||||
};
|
||||
|
||||
@@ -547,7 +614,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuContent align="end" className="w-48 sm:w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
@@ -583,10 +650,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 +680,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"
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,169 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { renderHook, act } from '@testing-library/react';
|
||||
import { ConsoleProvider, useConsole } from './ConsoleContext';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
|
||||
|
||||
// Test wrapper component
|
||||
function TestWrapper({ children }: { children: React.ReactNode }) {
|
||||
return <ConsoleProvider>{children}</ConsoleProvider>;
|
||||
}
|
||||
|
||||
describe('ConsoleContext', () => {
|
||||
it('should provide console functionality', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
expect(result.current.messages).toEqual([]);
|
||||
expect(result.current.messagesRef.current).toEqual([]);
|
||||
expect(typeof result.current.addMessage).toBe('function');
|
||||
expect(typeof result.current.clearMessages).toBe('function');
|
||||
expect(typeof result.current.addErrorListener).toBe('function');
|
||||
expect(typeof result.current.removeErrorListener).toBe('function');
|
||||
});
|
||||
|
||||
it('should add and retrieve messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test log message');
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(2);
|
||||
expect(result.current.messagesRef.current).toHaveLength(2);
|
||||
expect(result.current.messages[0]).toEqual({
|
||||
level: 'log',
|
||||
message: 'Test log message',
|
||||
});
|
||||
expect(result.current.messagesRef.current[0]).toEqual({
|
||||
level: 'log',
|
||||
message: 'Test log message',
|
||||
});
|
||||
expect(result.current.messages[1]).toEqual({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
});
|
||||
expect(result.current.messagesRef.current[1]).toEqual({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
});
|
||||
});
|
||||
|
||||
it('should clear messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test message');
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(1);
|
||||
expect(result.current.messagesRef.current).toHaveLength(1);
|
||||
|
||||
act(() => {
|
||||
result.current.clearMessages();
|
||||
});
|
||||
|
||||
expect(result.current.messages).toHaveLength(0);
|
||||
expect(result.current.messagesRef.current).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('should trigger error listener when error message is added', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(errorListener).toHaveBeenCalledTimes(1);
|
||||
expect(errorListener).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
message: 'Console error detected: Test error message',
|
||||
logs: expect.arrayContaining([
|
||||
expect.objectContaining({
|
||||
level: 'error',
|
||||
message: 'Test error message',
|
||||
}),
|
||||
]),
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('should not trigger error listener for non-error messages', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('log', 'Test log message');
|
||||
result.current.addMessage('warn', 'Test warning message');
|
||||
result.current.addMessage('info', 'Test info message');
|
||||
});
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should remove error listener correctly', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const errorListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(errorListener);
|
||||
result.current.removeErrorListener(errorListener);
|
||||
});
|
||||
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
|
||||
expect(errorListener).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should handle listener errors gracefully', () => {
|
||||
const { result } = renderHook(() => useConsole(), { wrapper: TestWrapper });
|
||||
const faultyListener = vi.fn(() => {
|
||||
throw new Error('Listener error');
|
||||
});
|
||||
const workingListener = vi.fn();
|
||||
|
||||
act(() => {
|
||||
result.current.addErrorListener(faultyListener);
|
||||
result.current.addErrorListener(workingListener);
|
||||
});
|
||||
|
||||
// Should not throw despite faulty listener
|
||||
expect(() => {
|
||||
act(() => {
|
||||
result.current.addMessage('error', 'Test error message');
|
||||
});
|
||||
}).not.toThrow();
|
||||
|
||||
expect(faultyListener).toHaveBeenCalled();
|
||||
expect(workingListener).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('should throw error when used outside provider', () => {
|
||||
expect(() => {
|
||||
renderHook(() => useConsole());
|
||||
}).toThrow('useConsole must be used within a ConsoleProvider');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProjectPreviewConsoleError', () => {
|
||||
it('should create error with console logs', () => {
|
||||
const logs = [{ level: 'error' as const, message: 'Test error' }];
|
||||
const error = new ProjectPreviewConsoleError('Test message', logs);
|
||||
|
||||
expect(error.message).toBe('Test message');
|
||||
expect(error.name).toBe('ProjectPreviewConsoleError');
|
||||
expect(error.logs).toEqual(logs);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,95 @@
|
||||
import React, { createContext, useContext, useState, useCallback, useRef, ReactNode } from 'react';
|
||||
|
||||
import { ProjectPreviewConsoleError } from '@/lib/errors/ProjectPreviewConsoleError';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export { ProjectPreviewConsoleError };
|
||||
|
||||
interface ConsoleContextType {
|
||||
messages: ConsoleMessage[];
|
||||
messagesRef: React.MutableRefObject<ConsoleMessage[]>;
|
||||
addMessage: (level: ConsoleMessage['level'], message: string) => void;
|
||||
clearMessages: () => void;
|
||||
addErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
|
||||
removeErrorListener: (listener: (error: ProjectPreviewConsoleError) => void) => void;
|
||||
}
|
||||
|
||||
const ConsoleContext = createContext<ConsoleContextType | undefined>(undefined);
|
||||
|
||||
export function useConsole(): ConsoleContextType {
|
||||
const context = useContext(ConsoleContext);
|
||||
if (context === undefined) {
|
||||
throw new Error('useConsole must be used within a ConsoleProvider');
|
||||
}
|
||||
return context;
|
||||
}
|
||||
|
||||
interface ConsoleProviderProps {
|
||||
children: ReactNode;
|
||||
}
|
||||
|
||||
export function ConsoleProvider({ children }: ConsoleProviderProps) {
|
||||
const [messages, setMessages] = useState<ConsoleMessage[]>([]);
|
||||
const messagesRef = useRef<ConsoleMessage[]>([]);
|
||||
const [errorListeners, setErrorListeners] = useState<Array<(error: ProjectPreviewConsoleError) => void>>([]);
|
||||
|
||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
||||
const consoleMessage: ConsoleMessage = {
|
||||
level,
|
||||
message,
|
||||
};
|
||||
|
||||
// Update both state and ref
|
||||
const newMessages = [...messagesRef.current, consoleMessage];
|
||||
messagesRef.current = newMessages;
|
||||
setMessages(newMessages);
|
||||
|
||||
// If this is an error, notify listeners
|
||||
if (level === 'error') {
|
||||
const error = new ProjectPreviewConsoleError(
|
||||
`Console error detected: ${message}`,
|
||||
newMessages.filter(msg => msg.level === 'error')
|
||||
);
|
||||
|
||||
errorListeners.forEach(listener => {
|
||||
try {
|
||||
listener(error);
|
||||
} catch (err) {
|
||||
console.warn('Error listener failed:', err);
|
||||
}
|
||||
});
|
||||
}
|
||||
}, [errorListeners]);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
setMessages([]);
|
||||
messagesRef.current = [];
|
||||
}, []);
|
||||
|
||||
const addErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
setErrorListeners(prev => [...prev, listener]);
|
||||
}, []);
|
||||
|
||||
const removeErrorListener = useCallback((listener: (error: ProjectPreviewConsoleError) => void) => {
|
||||
setErrorListeners(prev => prev.filter(l => l !== listener));
|
||||
}, []);
|
||||
|
||||
const value: ConsoleContextType = {
|
||||
messages,
|
||||
messagesRef,
|
||||
addMessage,
|
||||
clearMessages,
|
||||
addErrorListener,
|
||||
removeErrorListener,
|
||||
};
|
||||
|
||||
return (
|
||||
<ConsoleContext.Provider value={value}>
|
||||
{children}
|
||||
</ConsoleContext.Provider>
|
||||
);
|
||||
}
|
||||
+25
-7
@@ -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);
|
||||
|
||||
@@ -1,79 +0,0 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
id: number;
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
// Global state for console messages
|
||||
let globalConsoleMessages: ConsoleMessage[] = [];
|
||||
const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set();
|
||||
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach(listener => listener([...globalConsoleMessages]));
|
||||
};
|
||||
|
||||
export const useConsoleMessages = () => {
|
||||
const [messages, setMessages] = useState<ConsoleMessage[]>(globalConsoleMessages);
|
||||
|
||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(), // Ensure uniqueness
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const getErrorsSince = useCallback((timestamp: number) => {
|
||||
return globalConsoleMessages.filter(
|
||||
msg => msg.level === 'error' && msg.timestamp > timestamp
|
||||
);
|
||||
}, []);
|
||||
|
||||
// Subscribe to global state changes
|
||||
useEffect(() => {
|
||||
const listener = (newMessages: ConsoleMessage[]) => {
|
||||
setMessages(newMessages);
|
||||
};
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
addMessage,
|
||||
clearMessages,
|
||||
getErrorsSince,
|
||||
};
|
||||
};
|
||||
|
||||
// Export functions for external use (like PreviewPane)
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(),
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
};
|
||||
@@ -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
|
||||
};
|
||||
};
|
||||
@@ -2,6 +2,7 @@ import { Buffer } from 'buffer';
|
||||
import JSZip from 'jszip';
|
||||
import { Git } from '@/lib/git';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { ensurePersistentStorage } from '@/lib/persistentStorage';
|
||||
|
||||
// Polyfill Buffer for browser
|
||||
if (typeof window !== 'undefined') {
|
||||
@@ -93,6 +94,14 @@ export class ProjectsManager {
|
||||
},
|
||||
});
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
@@ -306,6 +315,14 @@ export class ProjectsManager {
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Automatically request persistent storage after project cloning
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project cloning if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project cloning:', error);
|
||||
}
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
|
||||
@@ -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');
|
||||
});
|
||||
});
|
||||
@@ -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;
|
||||
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { ConsoleMessage } from '@/contexts/ConsoleContext';
|
||||
|
||||
/**
|
||||
* Custom error class for project preview console errors
|
||||
*/
|
||||
export class ProjectPreviewConsoleError extends Error {
|
||||
public readonly logs: ConsoleMessage[];
|
||||
|
||||
constructor(message: string, logs: ConsoleMessage[]) {
|
||||
super(message);
|
||||
this.name = 'ProjectPreviewConsoleError';
|
||||
this.logs = logs;
|
||||
}
|
||||
}
|
||||
@@ -242,6 +242,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Data cleared successfully',
|
||||
dataClearedDescription: 'All local data has been removed. Redirecting to homepage...',
|
||||
failedToClearData: 'Failed to clear data',
|
||||
persistData: 'Persist Data',
|
||||
persistDataDescription: 'Request persistent storage to prevent data loss when browser storage is low. This helps protect your projects and settings.',
|
||||
persistentStorageGranted: 'Persistent storage granted',
|
||||
persistentStorageGrantedDescription: 'Your browser will now protect your data from automatic cleanup.',
|
||||
persistentStorageAlreadyGranted: 'Persistent storage already granted',
|
||||
persistentStorageAlreadyGrantedDescription: 'Your data is already protected from automatic cleanup.',
|
||||
persistentStorageDenied: 'Persistent storage request denied',
|
||||
persistentStorageDeniedDescription: 'Your browser declined the request. Data may still be cleared automatically when storage is low.',
|
||||
persistentStorageNotSupported: 'Persistent storage not supported',
|
||||
persistentStorageNotSupportedDescription: 'Your browser does not support persistent storage requests.',
|
||||
failedToRequestPersistentStorage: 'Failed to request persistent storage',
|
||||
|
||||
// 404 Page
|
||||
pageNotFound: 'Oops! Page not found',
|
||||
@@ -534,6 +545,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Dados limpos com sucesso',
|
||||
dataClearedDescription: 'Todos os dados locais foram removidos. Redirecionando para a página inicial...',
|
||||
failedToClearData: 'Falha ao limpar dados',
|
||||
persistData: 'Persistir Dados',
|
||||
persistDataDescription: 'Solicitar armazenamento persistente para evitar perda de dados quando o armazenamento do navegador estiver baixo. Isso ajuda a proteger seus projetos e configurações.',
|
||||
persistentStorageGranted: 'Armazenamento persistente concedido',
|
||||
persistentStorageGrantedDescription: 'Seu navegador agora protegerá seus dados da limpeza automática.',
|
||||
persistentStorageAlreadyGranted: 'Armazenamento persistente já concedido',
|
||||
persistentStorageAlreadyGrantedDescription: 'Seus dados já estão protegidos da limpeza automática.',
|
||||
persistentStorageDenied: 'Solicitação de armazenamento persistente negada',
|
||||
persistentStorageDeniedDescription: 'Seu navegador recusou a solicitação. Os dados ainda podem ser limpos automaticamente quando o armazenamento estiver baixo.',
|
||||
persistentStorageNotSupported: 'Armazenamento persistente não suportado',
|
||||
persistentStorageNotSupportedDescription: 'Seu navegador não suporta solicitações de armazenamento persistente.',
|
||||
failedToRequestPersistentStorage: 'Falha ao solicitar armazenamento persistente',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Sobre o Shakespeare',
|
||||
@@ -836,6 +858,17 @@ const resources = {
|
||||
dataClearedSuccessfully: '数据清除成功',
|
||||
dataClearedDescription: '所有本地数据已删除。正在重定向到主页...',
|
||||
failedToClearData: '清除数据失败',
|
||||
persistData: '持久化数据',
|
||||
persistDataDescription: '请求持久存储以防止浏览器存储不足时数据丢失。这有助于保护您的项目和设置。',
|
||||
persistentStorageGranted: '已授予持久存储',
|
||||
persistentStorageGrantedDescription: '您的浏览器现在将保护您的数据免受自动清理。',
|
||||
persistentStorageAlreadyGranted: '已授予持久存储',
|
||||
persistentStorageAlreadyGrantedDescription: '您的数据已受到保护,不会被自动清理。',
|
||||
persistentStorageDenied: '持久存储请求被拒绝',
|
||||
persistentStorageDeniedDescription: '您的浏览器拒绝了请求。当存储不足时,数据仍可能被自动清理。',
|
||||
persistentStorageNotSupported: '不支持持久存储',
|
||||
persistentStorageNotSupportedDescription: '您的浏览器不支持持久存储请求。',
|
||||
failedToRequestPersistentStorage: '请求持久存储失败',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: '关于Shakespeare',
|
||||
@@ -1138,6 +1171,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'An share bayanai cikin nasara',
|
||||
dataClearedDescription: 'An cire duk bayanan gida. Ana turawa zuwa shafin gida...',
|
||||
failedToClearData: 'Ya gaza share bayanai',
|
||||
persistData: 'Kiyaye Bayanai',
|
||||
persistDataDescription: 'Nemi ajiyar bayanai ta dindindin don hana asarar bayanai lokacin da ajiyar burauzar ta ragu. Wannan yana taimakawa wajen kare ayyukan ku da saitunan.',
|
||||
persistentStorageGranted: 'An ba da ajiyar ta dindindin',
|
||||
persistentStorageGrantedDescription: 'Burauzar ku yanzu za ta kare bayananku daga share mai sarrafa kansa.',
|
||||
persistentStorageAlreadyGranted: 'An riga an ba da ajiyar ta dindindin',
|
||||
persistentStorageAlreadyGrantedDescription: 'An riga an kare bayananku daga share mai sarrafa kansa.',
|
||||
persistentStorageDenied: 'An ki neman ajiyar ta dindindin',
|
||||
persistentStorageDeniedDescription: 'Burauzar ku ta ki bukatar. Ana iya share bayanai ta atomatik lokacin da ajiya ta ragu.',
|
||||
persistentStorageNotSupported: 'Ba a goyan bayan ajiyar ta dindindin ba',
|
||||
persistentStorageNotSupportedDescription: 'Burauzar ku ba ta goyan bayan bukatun ajiyar ta dindindin ba.',
|
||||
failedToRequestPersistentStorage: 'Ya gaza neman ajiyar ta dindindin',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Game da Shakespeare',
|
||||
@@ -1440,6 +1484,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Data ti nu ni aṣeyọri',
|
||||
dataClearedDescription: 'Gbogbo data agbegbe ti yọ kuro. N ṣe atunṣe si oju-iwe ile...',
|
||||
failedToClearData: 'O kuna lati nu data',
|
||||
persistData: 'Fi Data Pamọ',
|
||||
persistDataDescription: 'Beere ibi ipamọ ti o wa nigbagbogbo lati yago fun isonu data nigbati ibi ipamọ aṣawakiri ba kere. Eyi ṣe iranlọwọ lati daabobo awọn iṣẹ akanṣe ati awọn eto rẹ.',
|
||||
persistentStorageGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni',
|
||||
persistentStorageGrantedDescription: 'Aṣawakiri rẹ yoo daabobo data rẹ lati imukuro adaṣe.',
|
||||
persistentStorageAlreadyGranted: 'Ibi ipamọ ti o wa nigbagbogbo ti funni tẹlẹ',
|
||||
persistentStorageAlreadyGrantedDescription: 'Data rẹ ti wa ni aabo lati imukuro adaṣe.',
|
||||
persistentStorageDenied: 'Ibeere ibi ipamọ ti o wa nigbagbogbo ti kọ',
|
||||
persistentStorageDeniedDescription: 'Aṣawakiri rẹ ti kọ ibeere naa. Data le tun jẹ imukuro adaṣe nigbati ibi ipamọ ba kere.',
|
||||
persistentStorageNotSupported: 'Ibi ipamọ ti o wa nigbagbogbo ko ni atilẹyin',
|
||||
persistentStorageNotSupportedDescription: 'Aṣawakiri rẹ ko ni atilẹyin awọn ibeere ibi ipamọ ti o wa nigbagbogbo.',
|
||||
failedToRequestPersistentStorage: 'O kuna lati beere ibi ipamọ ti o wa nigbagbogbo',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Nipa Shakespeare',
|
||||
@@ -1737,6 +1792,17 @@ const resources = {
|
||||
dataClearedSuccessfully: 'Ehichapụrụ data nke ọma',
|
||||
dataClearedDescription: 'Ewepụrụ data mpaghara niile. Na-atụgharị gaa na ibe ụlọ...',
|
||||
failedToClearData: 'O dara ihichapụ data',
|
||||
persistData: 'Chekwaa Data Ogologo Oge',
|
||||
persistDataDescription: 'Rịọ nchekwa na-adịgide adịgide iji gbochie mfu data mgbe nchekwa browser dị ala. Nke a na-enyere aka ichebe ọrụ gị na ntọala.',
|
||||
persistentStorageGranted: 'Enyere nchekwa na-adịgide adịgide',
|
||||
persistentStorageGrantedDescription: 'Browser gị ga-echebe data gị ugbu a site na nhicha akpaaka.',
|
||||
persistentStorageAlreadyGranted: 'Enyerela nchekwa na-adịgide adịgide',
|
||||
persistentStorageAlreadyGrantedDescription: 'Echebeela data gị site na nhicha akpaaka.',
|
||||
persistentStorageDenied: 'Ajụrụ arịrịọ nchekwa na-adịgide adịgide',
|
||||
persistentStorageDeniedDescription: 'Browser gị jụrụ arịrịọ ahụ. Enwere ike ihichapụ data akpaaka mgbe nchekwa dị ala.',
|
||||
persistentStorageNotSupported: 'Akwadoghị nchekwa na-adịgide adịgide',
|
||||
persistentStorageNotSupportedDescription: 'Browser gị akwadoghị arịrịọ nchekwa na-adịgide adịgide.',
|
||||
failedToRequestPersistentStorage: 'O dara ịrịọ nchekwa na-adịgide adịgide',
|
||||
|
||||
// About Settings
|
||||
aboutShakespeare: 'Gbasara Shakespeare',
|
||||
|
||||
@@ -0,0 +1,111 @@
|
||||
/**
|
||||
* Utility functions for managing persistent storage in the browser
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks if persistent storage is supported by the browser
|
||||
*/
|
||||
export function isPersistentStorageSupported(): boolean {
|
||||
return 'storage' in navigator && 'persist' in navigator.storage;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if persistent storage is already granted
|
||||
*/
|
||||
export async function isPersistentStorageGranted(): Promise<boolean> {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
return await navigator.storage.persisted();
|
||||
} catch (error) {
|
||||
console.warn('Failed to check persistent storage status:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Requests persistent storage from the browser
|
||||
* Returns true if granted, false if denied or not supported
|
||||
*/
|
||||
export async function requestPersistentStorage(): Promise<boolean> {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
console.warn('Persistent storage is not supported in this browser');
|
||||
return false;
|
||||
}
|
||||
|
||||
try {
|
||||
// Check if already granted
|
||||
const alreadyGranted = await isPersistentStorageGranted();
|
||||
if (alreadyGranted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Request persistent storage
|
||||
const granted = await navigator.storage.persist();
|
||||
return granted;
|
||||
} catch (error) {
|
||||
console.warn('Failed to request persistent storage:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Automatically requests persistent storage if not already granted
|
||||
* This is intended to be called silently after project creation/cloning
|
||||
* Returns true if persistent storage is available (either already granted or newly granted)
|
||||
*/
|
||||
export async function ensurePersistentStorage(): Promise<boolean> {
|
||||
try {
|
||||
// Check if already granted
|
||||
const alreadyGranted = await isPersistentStorageGranted();
|
||||
if (alreadyGranted) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// Only request if supported
|
||||
if (!isPersistentStorageSupported()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Silently request persistent storage
|
||||
const granted = await requestPersistentStorage();
|
||||
|
||||
if (granted) {
|
||||
console.log('Persistent storage granted automatically');
|
||||
} else {
|
||||
console.log('Persistent storage request denied or failed');
|
||||
}
|
||||
|
||||
return granted;
|
||||
} catch (error) {
|
||||
console.warn('Failed to ensure persistent storage:', error);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets current storage usage information
|
||||
*/
|
||||
export async function getStorageInfo(): Promise<{
|
||||
quota: number;
|
||||
usage: number;
|
||||
usageDetails?: Record<string, number>;
|
||||
} | null> {
|
||||
if (!('storage' in navigator)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
try {
|
||||
const estimate = await navigator.storage.estimate();
|
||||
return {
|
||||
quota: estimate.quota || 0,
|
||||
usage: estimate.usage || 0,
|
||||
usageDetails: (estimate as StorageEstimate & { usageDetails?: Record<string, number> }).usageDetails,
|
||||
};
|
||||
} catch (error) {
|
||||
console.warn('Failed to get storage information:', error);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { ReadConsoleMessagesTool } from './ReadConsoleMessagesTool';
|
||||
import { ConsoleMessage, ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
|
||||
|
||||
describe('ReadConsoleMessagesTool', () => {
|
||||
let mockMessages: ConsoleMessage[];
|
||||
let getMessages: () => ConsoleMessage[];
|
||||
|
||||
beforeEach(() => {
|
||||
// Set up test messages
|
||||
mockMessages = [
|
||||
{ level: 'log', message: 'App started' },
|
||||
{ level: 'warn', message: 'Deprecated API used' },
|
||||
{ level: 'error', message: 'Network request failed' },
|
||||
{ level: 'info', message: 'User logged in' },
|
||||
];
|
||||
getMessages = () => mockMessages;
|
||||
});
|
||||
|
||||
it('should return all messages by default', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toContain('Found 4 console messages');
|
||||
expect(result).toContain('[LOG] App started');
|
||||
expect(result).toContain('[WARN] Deprecated API used');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
});
|
||||
|
||||
it('should filter messages by level', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ filter: 'error' });
|
||||
|
||||
expect(result).toContain('Found 1 console message (level: error)');
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should limit number of messages', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ limit: 2 });
|
||||
|
||||
expect(result).toContain('Found 2 console messages');
|
||||
// Should get the last 2 messages
|
||||
expect(result).toContain('[ERROR] Network request failed');
|
||||
expect(result).toContain('[INFO] User logged in');
|
||||
expect(result).not.toContain('[LOG] App started');
|
||||
});
|
||||
|
||||
it('should handle no messages found', async () => {
|
||||
const emptyGetMessages = () => [];
|
||||
const tool = new ReadConsoleMessagesTool(emptyGetMessages);
|
||||
const result = await tool.execute({});
|
||||
|
||||
expect(result).toBe('No console messages found.');
|
||||
});
|
||||
|
||||
it('should handle no messages found with filter', async () => {
|
||||
const tool = new ReadConsoleMessagesTool(getMessages);
|
||||
const result = await tool.execute({ filter: 'debug' });
|
||||
|
||||
expect(result).toBe('No console messages found for level: debug.');
|
||||
});
|
||||
});
|
||||
|
||||
describe('ProjectPreviewConsoleError', () => {
|
||||
it('should create error with console logs', () => {
|
||||
const logs = [
|
||||
{ level: 'error' as const, message: 'Test error' }
|
||||
];
|
||||
const error = new ProjectPreviewConsoleError('Test message', logs);
|
||||
|
||||
expect(error.message).toBe('Test message');
|
||||
expect(error.name).toBe('ProjectPreviewConsoleError');
|
||||
expect(error.logs).toEqual(logs);
|
||||
expect(error instanceof Error).toBe(true);
|
||||
expect(error instanceof ProjectPreviewConsoleError).toBe(true);
|
||||
});
|
||||
});
|
||||
|
||||
// Console error listener tests are now handled by the ConsoleContext
|
||||
// These tests should be moved to a separate ConsoleContext test file
|
||||
@@ -0,0 +1,34 @@
|
||||
import { Tool } from './Tool';
|
||||
|
||||
export interface ReadConsoleMessagesParams {
|
||||
filter?: 'error' | 'warn' | 'info' | 'debug' | 'log' | 'all';
|
||||
limit?: number;
|
||||
}
|
||||
|
||||
export class ReadConsoleMessagesTool implements Tool<ReadConsoleMessagesParams> {
|
||||
constructor(private getMessages: () => import('@/contexts/ConsoleContext').ConsoleMessage[]) {}
|
||||
|
||||
async execute(params: ReadConsoleMessagesParams): Promise<string> {
|
||||
const { filter = 'all', limit } = params;
|
||||
|
||||
// Filter and limit messages in one chain
|
||||
const filteredMessages = this.getMessages()
|
||||
.filter(msg => filter === 'all' || msg.level === filter)
|
||||
.slice(limit && limit > 0 ? -limit : 0);
|
||||
|
||||
if (filteredMessages.length === 0) {
|
||||
return `No console messages found${filter !== 'all' ? ` for level: ${filter}` : ''}.`;
|
||||
}
|
||||
|
||||
const formattedMessages = filteredMessages
|
||||
.map(msg => `[${msg.level.toUpperCase()}] ${msg.message}`)
|
||||
.join('\n');
|
||||
|
||||
const plural = filteredMessages.length !== 1 ? 's' : '';
|
||||
const levelInfo = filter !== 'all' ? ` (level: ${filter})` : '';
|
||||
|
||||
return `Found ${filteredMessages.length} console message${plural}${levelInfo}:\n\n${formattedMessages}`;
|
||||
}
|
||||
|
||||
description = 'Read console messages from the project preview. Can filter by level and limit results.';
|
||||
}
|
||||
@@ -17,6 +17,9 @@ describe('DataSettings', () => {
|
||||
// Check for description
|
||||
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
|
||||
|
||||
// Check for Persist Data section
|
||||
expect(screen.getByText('Persist Data')).toBeInTheDocument();
|
||||
|
||||
// Check for Export Files section
|
||||
expect(screen.getByText('Export Files')).toBeInTheDocument();
|
||||
expect(screen.getByText('Export All Files')).toBeInTheDocument();
|
||||
@@ -26,13 +29,17 @@ describe('DataSettings', () => {
|
||||
expect(screen.getByRole('button', { name: /clear all data/i })).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows export and clear buttons', () => {
|
||||
it('shows persist data toggle, export and clear buttons', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<DataSettings />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Persist storage toggle should be visible
|
||||
const persistToggle = screen.getByRole('switch');
|
||||
expect(persistToggle).toBeInTheDocument();
|
||||
|
||||
// Export button should be visible
|
||||
const exportButton = screen.getByRole('button', { name: /export all files/i });
|
||||
expect(exportButton).toBeInTheDocument();
|
||||
|
||||
+103
-12
@@ -1,14 +1,21 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } from 'lucide-react';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
requestPersistentStorage,
|
||||
getStorageInfo
|
||||
} from '@/lib/persistentStorage';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface StorageUsageDetails {
|
||||
@@ -28,8 +35,10 @@ export function DataSettings() {
|
||||
const { t } = useTranslation();
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [isClearing, setIsClearing] = useState(false);
|
||||
const [isRequestingPersistent, setIsRequestingPersistent] = useState(false);
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
@@ -44,27 +53,29 @@ export function DataSettings() {
|
||||
return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
|
||||
};
|
||||
|
||||
// Load storage information
|
||||
// Load storage information and persistent status
|
||||
useEffect(() => {
|
||||
const loadStorageInfo = async () => {
|
||||
try {
|
||||
// Check if StorageManager API is available
|
||||
if (!('storage' in navigator)) {
|
||||
if (!isPersistentStorageSupported()) {
|
||||
setStorageError('StorageManager API is not available in this browser');
|
||||
return;
|
||||
}
|
||||
|
||||
// Get storage estimate
|
||||
const estimate = await navigator.storage.estimate();
|
||||
const info = await getStorageInfo();
|
||||
if (info) {
|
||||
setStorageInfo({
|
||||
quota: info.quota,
|
||||
usage: info.usage,
|
||||
usageDetails: info.usageDetails as StorageUsageDetails,
|
||||
});
|
||||
}
|
||||
|
||||
// Extract usage details safely
|
||||
const usageDetails: StorageUsageDetails | undefined = (estimate as StorageEstimate & { usageDetails?: StorageUsageDetails }).usageDetails;
|
||||
|
||||
setStorageInfo({
|
||||
quota: estimate.quota || 0,
|
||||
usage: estimate.usage || 0,
|
||||
usageDetails,
|
||||
});
|
||||
// Check if storage is persistent
|
||||
const persistent = await isPersistentStorageGranted();
|
||||
setIsPersistent(persistent);
|
||||
} catch (error) {
|
||||
console.error('Failed to get storage information:', error);
|
||||
setStorageError(error instanceof Error ? error.message : 'Failed to get storage information');
|
||||
@@ -149,6 +160,63 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handlePersistentStorageToggle = async (checked: boolean) => {
|
||||
// If trying to turn off, we can't actually do that - just ignore
|
||||
if (!checked) {
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRequestingPersistent(true);
|
||||
try {
|
||||
// Check if persist method is available
|
||||
if (!isPersistentStorageSupported()) {
|
||||
toast({
|
||||
title: t('persistentStorageNotSupported'),
|
||||
description: t('persistentStorageNotSupportedDescription'),
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if already persistent
|
||||
const alreadyPersistent = await isPersistentStorageGranted();
|
||||
if (alreadyPersistent) {
|
||||
setIsPersistent(true);
|
||||
toast({
|
||||
title: t('persistentStorageAlreadyGranted'),
|
||||
description: t('persistentStorageAlreadyGrantedDescription'),
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Request persistent storage
|
||||
const granted = await requestPersistentStorage();
|
||||
|
||||
if (granted) {
|
||||
setIsPersistent(true);
|
||||
toast({
|
||||
title: t('persistentStorageGranted'),
|
||||
description: t('persistentStorageGrantedDescription'),
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: t('persistentStorageDenied'),
|
||||
description: t('persistentStorageDeniedDescription'),
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to request persistent storage:', error);
|
||||
toast({
|
||||
title: t('failedToRequestPersistentStorage'),
|
||||
description: error instanceof Error ? error.message : t('error'),
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsRequestingPersistent(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearAllData = async () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -268,6 +336,29 @@ export function DataSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Persist Data */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Shield className="h-5 w-5" />
|
||||
{t('persistData')}
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
{t('persistDataDescription')}
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<div className="flex items-center justify-start">
|
||||
<Switch
|
||||
id="persistent-storage"
|
||||
checked={isPersistent === true}
|
||||
onCheckedChange={handlePersistentStorageToggle}
|
||||
disabled={isRequestingPersistent || isPersistent === null}
|
||||
/>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Export Files */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
|
||||
@@ -14,12 +14,11 @@ 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';
|
||||
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { useConsole } from '@/contexts/ConsoleContext';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -30,42 +29,32 @@ export function ProjectView() {
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
|
||||
const projectsManager = useProjectsManager();
|
||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const { clearMessages: clearConsoleMessages } = useConsole();
|
||||
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
|
||||
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;
|
||||
|
||||
try {
|
||||
const projectData = await projectsManager.getProject(projectId);
|
||||
setProject(projectData);
|
||||
// Clear console messages when switching projects
|
||||
clearConsoleMessages();
|
||||
} catch (error) {
|
||||
console.error('Failed to load project:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
}, [projectId, projectsManager]);
|
||||
}, [projectId, projectsManager, clearConsoleMessages]);
|
||||
|
||||
useEffect(() => {
|
||||
loadProject();
|
||||
@@ -91,20 +80,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 +209,6 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
@@ -414,7 +388,6 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
|
||||
+16
-13
@@ -7,6 +7,7 @@ import NostrProvider from '@/components/NostrProvider';
|
||||
import { AppProvider } from '@/components/AppProvider';
|
||||
import { AppConfig } from '@/contexts/AppContext';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { ConsoleProvider } from '@/contexts/ConsoleContext';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { AISettingsProvider } from '@/components/AISettingsProvider';
|
||||
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
@@ -43,19 +44,21 @@ export function TestApp({ children }: TestAppProps) {
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey='test-app-config' defaultConfig={defaultConfig}>
|
||||
<FSProvider fs={fs}>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
<NostrProvider>
|
||||
<SessionManagerProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
</SessionManagerProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
<ConsoleProvider>
|
||||
<AISettingsProvider>
|
||||
<GitSettingsProvider>
|
||||
<NostrLoginProvider storageKey='test-login'>
|
||||
<NostrProvider>
|
||||
<SessionManagerProvider>
|
||||
<BrowserRouter>
|
||||
{children}
|
||||
</BrowserRouter>
|
||||
</SessionManagerProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</GitSettingsProvider>
|
||||
</AISettingsProvider>
|
||||
</ConsoleProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
|
||||
Reference in new issue
Block a user