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