mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
100
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e5ca49962e | ||
|
|
f5c5684ac8 | ||
|
|
6a72711aa0 | ||
|
|
1ed4a5abd4 | ||
|
|
db57619bca | ||
|
|
0f4075ce38 | ||
|
|
ec5d84d3f7 | ||
|
|
0b949d55b9 | ||
|
|
25f14ee2b3 | ||
|
|
7057c34f01 | ||
|
|
d932f05d04 | ||
|
|
e9f8e99ac5 | ||
|
|
0bdc9fa6a3 | ||
|
|
688b35fa41 | ||
|
|
2e38591943 | ||
|
|
568ea5dc04 | ||
|
|
9bd7e36597 | ||
|
|
77d8cdddad | ||
|
|
ecb74cd31e | ||
|
|
f40ef03b58 | ||
|
|
3751cb23fc | ||
|
|
399e9a0262 | ||
|
|
d6124119f7 | ||
|
|
e93a60be2c | ||
|
|
71f4397880 | ||
|
|
a1328cb321 | ||
|
|
f8b8f8e61b | ||
|
|
6facf72998 | ||
|
|
77508ea2fc | ||
|
|
0df1ef1e9d | ||
|
|
289caff882 | ||
|
|
bdb3b58cce | ||
|
|
0c379c5495 | ||
|
|
fcf6369356 | ||
|
|
fc36073654 | ||
|
|
131566750d | ||
|
|
540e017074 | ||
|
|
4881480679 | ||
|
|
be13d563c4 | ||
|
|
a5befda7dc | ||
|
|
fe82f36533 | ||
|
|
22de6889d9 | ||
|
|
d0a520ce17 | ||
|
|
aa35b13ad3 | ||
|
|
738b883f3b | ||
|
|
9ea9a4ac4b | ||
|
|
db697d0a85 | ||
|
|
3c75849434 | ||
|
|
8932413c2d | ||
|
|
9de4b167e7 | ||
|
|
c9073bb4bd | ||
|
|
f9f72e6a50 | ||
|
|
feb0bd7d3c | ||
|
|
0eac4c66ee | ||
|
|
aea8c1390b | ||
|
|
893d2e66ab | ||
|
|
e88a11ce21 | ||
|
|
3a8e040212 | ||
|
|
37e15ac786 | ||
|
|
c3fc719e82 | ||
|
|
02750c9b5c | ||
|
|
0e80915d58 | ||
|
|
89f8701855 | ||
|
|
ff95c13f84 | ||
|
|
c38113c9b8 | ||
|
|
c97117db5d | ||
|
|
999c250216 | ||
|
|
6d6f18a877 | ||
|
|
8e8976b9bc | ||
|
|
f4190d22fb | ||
|
|
92376d58b8 | ||
|
|
fb192b8657 | ||
|
|
3e9b15eed3 | ||
|
|
561e5614c5 | ||
|
|
04d812382b | ||
|
|
49d4c5120e | ||
|
|
8aaaea0b8f | ||
|
|
3c46c72bba | ||
|
|
d52d7b57a6 | ||
|
|
cadebaaa0e | ||
|
|
79be6c8252 | ||
|
|
35ac22c74f | ||
|
|
3ec89713bc | ||
|
|
7cbaaec734 | ||
|
|
46a5ca2a1e | ||
|
|
668a6c79d9 | ||
|
|
3692863830 | ||
|
|
6478ed21bb | ||
|
|
25f11dbe1d | ||
|
|
16ee1235d3 | ||
|
|
fed44cef5e | ||
|
|
4ce35b8ff0 | ||
|
|
f6dc218ae7 | ||
|
|
41d7d7834d | ||
|
|
785f75a39a | ||
|
|
8e3cc67ce2 | ||
|
|
fae90cc85e | ||
|
|
2ed44e43f7 | ||
|
|
53cf844fd6 | ||
|
|
6aa36b6738 |
No files matched your search
@@ -11,6 +11,8 @@ stages:
|
||||
test:
|
||||
stage: test
|
||||
script:
|
||||
- npm run typecheck
|
||||
- npm run build
|
||||
- npm run test
|
||||
|
||||
pages:
|
||||
|
||||
@@ -1,128 +0,0 @@
|
||||
# OPFS Compatibility Fix for isomorphic-git Clone Operations
|
||||
|
||||
## Issue Description
|
||||
|
||||
The error `TypeError: Cannot read properties of undefined (reading 'error')` occurs when using OPFS (Origin Private File System) with isomorphic-git during Git clone operations. This happens specifically in the `readObjectPacked` function within isomorphic-git when it tries to read Git pack files.
|
||||
|
||||
### Root Cause
|
||||
|
||||
The issue stems from subtle differences between how OPFS handles binary data compared to LightningFS/IndexedDB:
|
||||
|
||||
1. **Binary Data Handling**: isomorphic-git expects very specific behavior from Uint8Array objects, particularly when reading Git pack files
|
||||
2. **Error Object Structure**: isomorphic-git expects error objects in a specific Node.js-style format
|
||||
3. **Filesystem API Differences**: OPFS uses different APIs that don't always match the expected Node.js filesystem behavior
|
||||
|
||||
## Solution Implemented
|
||||
|
||||
### 1. Enhanced OPFS Adapter (`OPFSAdapterSimple.ts`)
|
||||
|
||||
**Improved Binary Data Handling:**
|
||||
- Added special handling for Git files to ensure Uint8Array compatibility
|
||||
- Created fresh Uint8Array instances to avoid browser-specific quirks
|
||||
- Added validation for array methods that isomorphic-git expects
|
||||
- Enhanced error handling with proper Node.js-style error codes
|
||||
|
||||
**Debug Mode:**
|
||||
- Added optional debug logging to track filesystem operations
|
||||
- Helps identify specific issues during Git operations
|
||||
|
||||
### 2. Better Error Handling (`ProjectsManager.ts`)
|
||||
|
||||
**Enhanced Clone Operation:**
|
||||
- Added timeout mechanism (60 seconds) to prevent hanging
|
||||
- Improved error detection for OPFS compatibility issues
|
||||
- Better cleanup of failed project directories
|
||||
- More descriptive error messages for users
|
||||
|
||||
**OPFS Issue Detection:**
|
||||
- Automatically detects filesystem compatibility issues
|
||||
- Provides clear recommendations to switch to LightningFS
|
||||
- User-friendly error messages explaining the problem
|
||||
|
||||
### 3. Filesystem Selection UI (`DataSettings.tsx`)
|
||||
|
||||
**User Interface Improvements:**
|
||||
- Clear warnings about OPFS Git compatibility issues
|
||||
- Information about when to use each filesystem type
|
||||
- Automatic fallback mechanism when OPFS initialization fails
|
||||
|
||||
### 4. Automatic Fallback (`App.tsx`)
|
||||
|
||||
**Robust Initialization:**
|
||||
- Tests OPFS functionality before using it
|
||||
- Automatically falls back to LightningFS if OPFS fails
|
||||
- Better error reporting and user feedback
|
||||
|
||||
## Usage Recommendations
|
||||
|
||||
### When to Use LightningFS (Recommended)
|
||||
- **Git Operations**: Better compatibility with isomorphic-git
|
||||
- **Stability**: Proven track record with Shakespeare
|
||||
- **Cross-browser**: Works in all modern browsers
|
||||
- **Default Choice**: Recommended for most users
|
||||
|
||||
### When to Use OPFS (Experimental)
|
||||
- **Large Storage**: When you need larger storage quotas
|
||||
- **Performance**: Potentially better performance for file operations
|
||||
- **Modern Browsers**: Only in Chrome, Edge, Firefox 111+
|
||||
- **Non-Git Workflows**: For projects that don't require Git operations
|
||||
|
||||
## Technical Details
|
||||
|
||||
### Error Patterns Detected
|
||||
The fix detects these specific error patterns that indicate OPFS compatibility issues:
|
||||
- `Cannot read properties of undefined`
|
||||
- `readObjectPacked` errors
|
||||
- `reading 'error'` errors
|
||||
- TypeError in isomorphic-git stack traces
|
||||
|
||||
### Binary Data Compatibility
|
||||
```typescript
|
||||
// Enhanced Uint8Array creation for Git compatibility
|
||||
const gitCompatibleArray = new Uint8Array(uint8Array.length);
|
||||
gitCompatibleArray.set(uint8Array);
|
||||
|
||||
// Validation of required methods
|
||||
if (!gitCompatibleArray.slice || typeof gitCompatibleArray.slice !== 'function') {
|
||||
throw new Error('Uint8Array missing required methods');
|
||||
}
|
||||
```
|
||||
|
||||
### Error Handling
|
||||
```typescript
|
||||
// Node.js-style error objects
|
||||
const nodeError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
nodeError.code = 'ENOENT';
|
||||
nodeError.errno = -2;
|
||||
nodeError.syscall = 'open';
|
||||
nodeError.path = path;
|
||||
```
|
||||
|
||||
## Testing
|
||||
|
||||
The fix includes:
|
||||
- ✅ All existing tests pass
|
||||
- ✅ Enhanced error handling
|
||||
- ✅ Automatic fallback mechanisms
|
||||
- ✅ User interface improvements
|
||||
- ✅ Debug logging capabilities
|
||||
|
||||
## Migration Path
|
||||
|
||||
For users experiencing OPFS issues:
|
||||
|
||||
1. **Immediate Fix**: Switch to LightningFS in Data Settings
|
||||
2. **Export Data**: Use the export feature before switching filesystems
|
||||
3. **Refresh**: Page will automatically refresh to apply new filesystem
|
||||
4. **Import**: Recreate projects as needed
|
||||
|
||||
## Future Improvements
|
||||
|
||||
1. **Better OPFS Support**: Continue improving OPFS compatibility
|
||||
2. **Hybrid Approach**: Use OPFS for regular files, LightningFS for Git
|
||||
3. **Performance Monitoring**: Track filesystem performance differences
|
||||
4. **User Analytics**: Monitor which filesystem users prefer
|
||||
|
||||
## Conclusion
|
||||
|
||||
This fix provides a robust solution for the OPFS/isomorphic-git compatibility issue while maintaining backward compatibility and providing clear user guidance. Users can continue using OPFS for non-Git operations while having LightningFS as a reliable fallback for Git-heavy workflows.
|
||||
@@ -1,44 +0,0 @@
|
||||
# OPFS Debugging Instructions
|
||||
|
||||
## Current Issue
|
||||
Project creation fails with OPFS due to isomorphic-git compatibility issues.
|
||||
|
||||
## Debug Steps
|
||||
|
||||
1. **Enable OPFS in browser**:
|
||||
- Go to Shakespeare app
|
||||
- Settings → Data Settings → Filesystem Type → OPFS
|
||||
- Save and refresh
|
||||
|
||||
2. **Try to create a project**:
|
||||
- Enter a description like "test project"
|
||||
- Select a model
|
||||
- Click "Create Project"
|
||||
|
||||
3. **Check browser console**:
|
||||
- Open DevTools (F12)
|
||||
- Look for debug logs starting with `OPFSAdapter.readFile called with path:`
|
||||
- Look for `OPFSAdapter.mkdir called with path:`
|
||||
- Look for `OPFSAdapter.stat called with path:`
|
||||
|
||||
## Expected Debug Output
|
||||
|
||||
If our fixes work, you should see logs like:
|
||||
```
|
||||
OPFSAdapter.readFile called with path: /projects/test-project/.git/config encoding: utf8
|
||||
OPFSAdapter.stat called with path: /projects/test-project
|
||||
OPFSAdapter.mkdir called with path: /projects/test-project options: { recursive: true }
|
||||
```
|
||||
|
||||
## Current Problems
|
||||
|
||||
1. **Undefined paths**: isomorphic-git calls our adapter with `undefined` paths
|
||||
2. **Git config parsing**: "text.split is not a function" error suggests Git is trying to parse error messages as config files
|
||||
3. **Directory creation**: Git directory structure creation fails
|
||||
|
||||
## Next Steps
|
||||
|
||||
Based on what we see in debug logs, we can:
|
||||
1. Identify exactly which paths are being called as undefined
|
||||
2. Fix the specific filesystem contract issues
|
||||
3. Ensure proper error handling that doesn't break Git operations
|
||||
-265
@@ -1,265 +0,0 @@
|
||||
# OPFS Fixes for Shakespeare
|
||||
|
||||
This document summarizes the fixes implemented to resolve OPFS (Origin Private File System) issues in Shakespeare.
|
||||
|
||||
## Problem Description
|
||||
|
||||
Users experienced complete failures when attempting to create projects using OPFS. The errors included:
|
||||
|
||||
1. **Undefined Path Error**: `Cannot read properties of undefined (reading 'includes')`
|
||||
2. **Directory Creation Failures**: `ENOENT: no such file or directory, scandir '/projects/squirrel-junction/.git'`
|
||||
3. **Git Operation Failures**: `text.split is not a function` from Git config parsing
|
||||
4. **Filesystem Incompatibility**: OPFS adapter wasn't fully compatible with isomorphic-git expectations
|
||||
|
||||
## Root Cause Analysis
|
||||
|
||||
The issues stemmed from several problems in the OPFS adapter implementation:
|
||||
|
||||
### 1. Insufficient Path Validation
|
||||
The `readFile` method didn't validate input paths, leading to attempts to call `.includes()` on undefined values.
|
||||
|
||||
### 2. Inconsistent Error Handling
|
||||
OPFS throws DOMException errors, but isomorphic-git expects Node.js-style errors with specific error codes (ENOENT, EACCES, etc.).
|
||||
|
||||
### 3. Recursive Directory Creation Issues
|
||||
The recursive directory creation logic didn't handle partial path failures properly, especially for Git directory structures.
|
||||
|
||||
### 4. Git Compatibility Problems
|
||||
The adapter didn't fully support the filesystem operations that isomorphic-git requires for repository operations.
|
||||
|
||||
## Fixes Implemented
|
||||
|
||||
### 1. Enhanced Path Validation
|
||||
|
||||
**File**: `src/lib/OPFSAdapter.ts`
|
||||
|
||||
**Changes**:
|
||||
```typescript
|
||||
// Added null/undefined path validation
|
||||
if (!path || typeof path !== 'string') {
|
||||
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'open';
|
||||
error.path = path || 'undefined';
|
||||
throw error;
|
||||
}
|
||||
```
|
||||
|
||||
**Impact**: Prevents the "Cannot read properties of undefined" error.
|
||||
|
||||
### 2. Improved Error Handling
|
||||
|
||||
**File**: `src/lib/OPFSAdapter.ts`
|
||||
|
||||
**Changes**:
|
||||
```typescript
|
||||
// Convert DOMException to Node.js style errors
|
||||
if (error instanceof Error && error.message.includes('NotFound')) {
|
||||
const nodeError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
nodeError.code = 'ENOENT';
|
||||
nodeError.errno = -2;
|
||||
nodeError.syscall = 'open';
|
||||
nodeError.path = path;
|
||||
throw nodeError;
|
||||
}
|
||||
```
|
||||
|
||||
**Impact**: Makes OPFS errors compatible with isomorphic-git.
|
||||
|
||||
### 3. Better Recursive Directory Creation
|
||||
|
||||
**File**: `src/lib/OPFSAdapter.ts`
|
||||
|
||||
**Changes**:
|
||||
```typescript
|
||||
private async createDirectoriesRecursive(path: string): Promise<void> {
|
||||
try {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
let currentHandle = await this.root;
|
||||
|
||||
for (const part of parts) {
|
||||
try {
|
||||
currentHandle = await currentHandle.getDirectoryHandle(part, { create: true });
|
||||
} catch (error) {
|
||||
console.error(`Failed to create directory part '${part}' in path '${path}':`, error);
|
||||
throw new Error(`Failed to create directory ${path}: ${error}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`OPFSAdapter.createDirectoriesRecursive failed for path: ${path}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Impact**: Ensures Git directory structures can be created reliably.
|
||||
|
||||
### 4. Enhanced Git Operation Support
|
||||
|
||||
**File**: `src/lib/OPFSAdapter.ts`
|
||||
|
||||
**Changes**:
|
||||
```typescript
|
||||
private async readFileForGit(path: string): Promise<Uint8Array> {
|
||||
try {
|
||||
// Guard against undefined path
|
||||
if (!path || typeof path !== 'string') {
|
||||
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'open';
|
||||
error.path = path || 'undefined';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const fileHandle = await this.getFileHandle(path);
|
||||
const file = await fileHandle.getFile();
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
return new Uint8Array(arrayBuffer);
|
||||
} catch (error) {
|
||||
// Enhanced error handling for Git operations
|
||||
console.error(`Git read operation failed for path: ${path}`, error);
|
||||
|
||||
// Create a more detailed error that isomorphic-git can handle
|
||||
const gitError = new Error(`Failed to read Git object: ${path}`) as NodeJS.ErrnoException;
|
||||
gitError.code = 'ENOENT';
|
||||
gitError.errno = -2;
|
||||
gitError.syscall = 'read';
|
||||
gitError.path = path;
|
||||
|
||||
// Preserve original error information by adding it to the message
|
||||
if (error instanceof Error) {
|
||||
gitError.message = `${gitError.message}: ${error.message}`;
|
||||
}
|
||||
|
||||
throw gitError;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Impact**: Makes Git operations (clone, commit, etc.) work reliably with OPFS.
|
||||
|
||||
### 5. Improved ProjectsManager Logging
|
||||
|
||||
**File**: `src/lib/ProjectsManager.ts`
|
||||
|
||||
**Changes**:
|
||||
```typescript
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
console.log(`Creating project: ${name}, customId: ${customId}`);
|
||||
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||
console.log(`Project cloned at path: ${project.path}`);
|
||||
|
||||
try {
|
||||
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
|
||||
console.log(`Created .ai/history directory for project ${project.id}`);
|
||||
} catch (error) {
|
||||
console.log(`Directory .ai/history might already exist for project ${project.id}:`, error);
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// ... rest of the method with enhanced logging
|
||||
}
|
||||
```
|
||||
|
||||
**Impact**: Provides better debugging information when issues occur.
|
||||
|
||||
### 6. Better Filesystem Initialization
|
||||
|
||||
**File**: `src/App.tsx`
|
||||
|
||||
**Changes**:
|
||||
```typescript
|
||||
constructor() {
|
||||
// Check if OPFS is available
|
||||
if (!('storage' in navigator) ||
|
||||
typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
|
||||
throw new Error('OPFS is not supported in this browser or environment');
|
||||
}
|
||||
|
||||
// Get the root directory handle for OPFS
|
||||
this.root = (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory();
|
||||
}
|
||||
```
|
||||
|
||||
**Impact**: Fails fast if OPFS is not available.
|
||||
|
||||
## Testing
|
||||
|
||||
All existing tests pass:
|
||||
```bash
|
||||
✓ Test Files 83 passed (83)
|
||||
Tests 564 passed | 6 skipped (570)
|
||||
```
|
||||
|
||||
Type checking and build also pass successfully.
|
||||
|
||||
## Browser Compatibility
|
||||
|
||||
OPFS is supported in:
|
||||
- Chrome 86+
|
||||
- Edge 86+
|
||||
- Firefox 111+ (limited support)
|
||||
- Safari 16.4+
|
||||
|
||||
For browsers that don't support OPFS, the system automatically falls back to LightningFS.
|
||||
|
||||
## Usage Instructions
|
||||
|
||||
To use OPFS in Shakespeare:
|
||||
|
||||
1. **Enable OPFS in Settings**:
|
||||
- Go to Settings → Data Settings
|
||||
- Change "Filesystem Type" to "OPFS"
|
||||
- Save changes
|
||||
|
||||
2. **Restart Application**:
|
||||
- Refresh the page to apply the new filesystem type
|
||||
|
||||
3. **Verify OPFS is Working**:
|
||||
- Try creating a new project
|
||||
- Check browser console for successful filesystem operations
|
||||
- Verify that project creation completes without errors
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
If OPFS still fails:
|
||||
|
||||
1. **Check Browser Support**:
|
||||
- Ensure you're using a supported browser version
|
||||
- Check browser console for OPFS availability errors
|
||||
|
||||
2. **Clear Browser Data**:
|
||||
- Clear site data and try again
|
||||
- This can resolve corrupted OPFS storage issues
|
||||
|
||||
3. **Fallback to LightningFS**:
|
||||
- If OPFS consistently fails, use LightningFS instead
|
||||
- The system will automatically fall back if OPFS initialization fails
|
||||
|
||||
## Performance Considerations
|
||||
|
||||
OPFS provides better performance than LightningFS for:
|
||||
- Large file operations
|
||||
- Concurrent file access
|
||||
- Storage persistence
|
||||
|
||||
However, OPFS has some limitations:
|
||||
- No symbolic links
|
||||
- Different permission model
|
||||
- Browser-specific implementation details
|
||||
|
||||
## Future Improvements
|
||||
|
||||
Potential enhancements for OPFS support:
|
||||
|
||||
1. **Atomic Operations**: Implement atomic file writes using OPFS transactions
|
||||
2. **File Locking**: Add file locking mechanisms for concurrent access
|
||||
3. **Storage Quotas**: Better handling of storage quota limits
|
||||
4. **Migration Tools**: Tools to migrate existing LightningFS data to OPFS
|
||||
|
||||
## Conclusion
|
||||
|
||||
The fixes implemented resolve the major OPFS compatibility issues and provide a robust filesystem backend for Shakespeare. The enhanced error handling, improved logging, and better Git compatibility ensure that project creation and management work reliably with OPFS.
|
||||
@@ -1,83 +0,0 @@
|
||||
# OPFS Git Clone Fix Summary
|
||||
|
||||
## Issues Identified and Fixed
|
||||
|
||||
### Issue 1: Binary Pack Files Returned as Text
|
||||
**Problem**: Git pack index files (`.idx`) were being returned as text instead of binary data because isomorphic-git was passing options objects as the encoding parameter.
|
||||
|
||||
**Log Evidence**:
|
||||
```
|
||||
[OPFSAdapter] readFile called: path="/projects/untitled-1/.git/objects/pack/pack-be5dbf750d545d214e0191ae909d83915c6beb6a.idx", encoding="[object Object]"
|
||||
[OPFSAdapter] Returning text content for encoding "[object Object]", length=5138
|
||||
```
|
||||
|
||||
**Fix**: Modified encoding detection logic to always return binary data for Git pack files regardless of encoding parameter.
|
||||
|
||||
### Issue 2: Git Config Files Returned as Binary
|
||||
**Problem**: Git configuration files (`.git/config`) were being returned as binary data when they should be text files.
|
||||
|
||||
**Log Evidence**:
|
||||
```
|
||||
[OPFSAdapter] readFile called: path="/projects/nut-cache/.git/config", encoding="[object Object]"
|
||||
[OPFSAdapter] Returning binary content: 130 bytes, constructor: Uint8Array, isGitFile: true
|
||||
TypeError: text.split is not a function
|
||||
```
|
||||
|
||||
**Fix**: Added proper distinction between Git text files and Git binary files.
|
||||
|
||||
### Issue 3: Filesystem Capability Testing
|
||||
**Problem**: isomorphic-git calls `readFile` with undefined paths to test filesystem capabilities, causing unnecessary error logs.
|
||||
|
||||
**Fix**: Added proper handling and logging for filesystem capability tests.
|
||||
|
||||
## Solution Implementation
|
||||
|
||||
### Enhanced File Type Detection
|
||||
|
||||
```typescript
|
||||
// Git binary files that should ALWAYS be returned as Uint8Array
|
||||
const isGitBinaryFile = path.includes('.git/objects/pack/') ||
|
||||
(path.includes('.git/objects/') && !path.includes('.git/objects/info/')) ||
|
||||
path.endsWith('.pack') ||
|
||||
path.endsWith('.idx') ||
|
||||
path.includes('.git/index');
|
||||
|
||||
// Git text files that should be returned as text
|
||||
const isGitTextFile = path.includes('.git/config') ||
|
||||
path.includes('.git/HEAD') ||
|
||||
path.includes('.git/refs/') ||
|
||||
path.includes('.git/logs/') ||
|
||||
path.includes('.git/info/') ||
|
||||
path.includes('.git/hooks/') ||
|
||||
path.includes('.git/description');
|
||||
|
||||
// Smart encoding detection
|
||||
const shouldReturnText = (encoding === 'utf8' && typeof encoding === 'string') ||
|
||||
(!isGitBinaryFile && (isGitTextFile || !path.includes('.git/'))) ||
|
||||
(isGitTextFile && typeof encoding !== 'string');
|
||||
```
|
||||
|
||||
### Key Insights
|
||||
|
||||
1. **isomorphic-git Behavior**: isomorphic-git passes options objects as encoding parameters, not just strings
|
||||
2. **File Type Distinction**: Git repositories contain both text files (config, refs) and binary files (pack, index, objects)
|
||||
3. **Capability Testing**: isomorphic-git tests filesystem capabilities by calling methods with invalid parameters
|
||||
|
||||
### Testing Status
|
||||
|
||||
- ✅ Fixed binary pack file handling
|
||||
- ✅ Fixed Git config file handling
|
||||
- ✅ Added proper capability test handling
|
||||
- ✅ Enhanced debug logging
|
||||
- ✅ All existing tests pass
|
||||
- 🔄 Ready for real-world Git clone testing
|
||||
|
||||
## Next Steps
|
||||
|
||||
The OPFS adapter should now correctly handle Git clone operations by:
|
||||
1. Returning binary data for Git pack files and objects
|
||||
2. Returning text data for Git configuration and reference files
|
||||
3. Properly handling isomorphic-git's filesystem capability tests
|
||||
4. Providing detailed debug logging for troubleshooting
|
||||
|
||||
This should resolve the `TypeError: Cannot read properties of undefined (reading 'error')` and `TypeError: text.split is not a function` errors during Git clone operations with OPFS.
|
||||
@@ -1,159 +0,0 @@
|
||||
# OPFS Implementation for Shakespeare
|
||||
|
||||
This document describes the implementation of OPFS (Origin Private File System) support as an alternative to LightningFS in the Shakespeare project.
|
||||
|
||||
## Overview
|
||||
|
||||
The project now supports two filesystem backends:
|
||||
1. **LightningFS** (IndexedDB) - The original filesystem implementation
|
||||
2. **OPFS** (Origin Private File System) - A modern browser API for better performance
|
||||
|
||||
## Implementation Details
|
||||
|
||||
### 1. OPFS Adapter (`src/lib/OPFSAdapter.ts`)
|
||||
|
||||
Created a new `OPFSAdapter` class that implements the `JSRuntimeFS` interface, making it compatible with the existing filesystem abstraction. The adapter provides:
|
||||
|
||||
- **File Operations**: `readFile`, `writeFile`, `stat`, `unlink`
|
||||
- **Directory Operations**: `readdir`, `mkdir`, `rmdir`
|
||||
- **Utility Operations**: `rename`, `copy`, `recursive operations`
|
||||
- **Error Handling**: Proper error handling with fallback to LightningFS
|
||||
|
||||
### 2. Configuration Updates
|
||||
|
||||
#### AppContext (`src/contexts/AppContext.ts`)
|
||||
- Added `FilesystemType` type: `"lightningfs" | "opfs"`
|
||||
- Extended `AppConfig` interface to include `filesystemType` field
|
||||
- Updated Zod schema for validation
|
||||
|
||||
#### AppProvider (`src/components/AppProvider.tsx`)
|
||||
- Updated AppConfigSchema to include filesystemType validation
|
||||
|
||||
### 3. Dynamic Filesystem Initialization (`src/App.tsx`)
|
||||
|
||||
Created a new `FilesystemProvider` component that:
|
||||
- Detects OPFS availability in the browser
|
||||
- Dynamically selects the appropriate filesystem backend
|
||||
- Provides automatic fallback to LightningFS if OPFS fails
|
||||
- Shows loading states and error messages
|
||||
|
||||
### 4. User Interface Updates
|
||||
|
||||
#### AppSettingsDialog (`src/components/AppSettingsDialog.tsx`)
|
||||
- Added filesystem selection UI with RadioGroup component
|
||||
- Shows OPFS availability detection
|
||||
- Displays warnings when OPFS is not available
|
||||
- Includes educational information about each filesystem type
|
||||
- Automatically refreshes the page when filesystem type changes
|
||||
|
||||
### 5. Type Definitions
|
||||
|
||||
#### Nostr Types (`src/types/nostr.d.ts`)
|
||||
- Added proper TypeScript definitions for `window.nostr` object
|
||||
- Fixed existing TypeScript errors related to Nostr extension access
|
||||
|
||||
## Features
|
||||
|
||||
### OPFS Advantages
|
||||
- **Better Performance**: Direct filesystem access without IndexedDB overhead
|
||||
- **Larger Storage Limits**: Typically higher storage quotas than IndexedDB
|
||||
- **Modern API**: Uses native browser filesystem APIs
|
||||
- **Atomic Operations**: Better support for atomic file operations
|
||||
|
||||
### LightningFS Advantages
|
||||
- **Universal Support**: Works in all modern browsers
|
||||
- **Mature Implementation**: Well-tested and stable
|
||||
- **Symbolic Links**: Supports symbolic links (OPFS does not)
|
||||
- **Proven Reliability**: Used in production for years
|
||||
|
||||
### User Experience
|
||||
- **Automatic Detection**: UI automatically shows available options
|
||||
- **Clear Warnings**: Users are informed when OPFS is not available
|
||||
- **Safe Switching**: Page refresh ensures clean filesystem transition
|
||||
- **Fallback Protection**: Automatic fallback prevents data loss
|
||||
|
||||
## Browser Compatibility
|
||||
|
||||
### OPFS Support
|
||||
- ✅ Chrome 87+
|
||||
- ✅ Edge 87+
|
||||
- ✅ Firefox 111+
|
||||
- ❌ Safari (limited support)
|
||||
- ❌ Mobile browsers (varies)
|
||||
|
||||
### LightningFS Support
|
||||
- ✅ All modern browsers
|
||||
- ✅ Mobile browsers
|
||||
- ✅ Older browsers (with polyfills)
|
||||
|
||||
## Usage
|
||||
|
||||
### For Users
|
||||
1. Go to Settings → App Settings
|
||||
2. Select preferred filesystem type in the Filesystem section
|
||||
3. Save changes (page will refresh automatically)
|
||||
4. The app will use the selected filesystem
|
||||
|
||||
### For Developers
|
||||
- The filesystem is abstracted through the `JSRuntimeFS` interface
|
||||
- All existing code continues to work without changes
|
||||
- New filesystem types can be added by implementing the interface
|
||||
- Use `useFS()` hook to access the filesystem
|
||||
|
||||
## Migration
|
||||
|
||||
### From LightningFS to OPFS
|
||||
1. Export current projects using Data Settings → Export Files
|
||||
2. Change filesystem type in settings
|
||||
3. Import projects if needed
|
||||
4. Verify all data is intact
|
||||
|
||||
### From OPFS to LightningFS
|
||||
1. Export current projects using Data Settings → Export Files
|
||||
2. Change filesystem type in settings
|
||||
3. Import projects if needed
|
||||
4. Verify all data is intact
|
||||
|
||||
## Error Handling
|
||||
|
||||
### OPFS Not Available
|
||||
- UI shows warning message
|
||||
- Option is disabled in settings
|
||||
- Automatic fallback to LightningFS
|
||||
|
||||
### Initialization Failures
|
||||
- Shows error message with details
|
||||
- Provides browser compatibility information
|
||||
- Suggests using LightningFS instead
|
||||
|
||||
### Runtime Errors
|
||||
- Graceful error handling in adapter
|
||||
- Proper error propagation to UI
|
||||
- Fallback mechanisms where possible
|
||||
|
||||
## Testing
|
||||
|
||||
- All existing tests continue to pass
|
||||
- TypeScript compilation successful
|
||||
- Build process works correctly
|
||||
- UI components properly render filesystem options
|
||||
- Error states are handled appropriately
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Potential Improvements
|
||||
1. **Data Migration Tools**: Automatic migration between filesystem types
|
||||
2. **Performance Metrics**: Show performance differences between backends
|
||||
3. **Storage Analytics**: Display usage statistics for each filesystem
|
||||
4. **Hybrid Approach**: Use different filesystems for different data types
|
||||
5. **Compression**: Add compression support for better storage efficiency
|
||||
|
||||
### Considerations
|
||||
- OPFS is still evolving; browser support may change
|
||||
- LightningFS remains the safer choice for maximum compatibility
|
||||
- Data portability is important for user freedom
|
||||
- Performance benefits may vary by use case and browser
|
||||
|
||||
## Conclusion
|
||||
|
||||
The OPFS implementation provides users with a choice between filesystem backends, balancing modern performance advantages with broad compatibility. The implementation maintains backward compatibility while providing a path forward for users on modern browsers.
|
||||
@@ -1,68 +0,0 @@
|
||||
# OPFS Git Compatibility Test
|
||||
|
||||
## Issue Fixed
|
||||
|
||||
The main issue was that isomorphic-git was calling `fs.readFile()` on Git pack index files (`.idx`) with an options object as the encoding parameter, but the OPFS adapter was incorrectly interpreting this as a string encoding and returning text data instead of binary data.
|
||||
|
||||
## Debug Output Analysis
|
||||
|
||||
```
|
||||
[OPFSAdapter] readFile called: path="/projects/untitled-1/.git/objects/pack/pack-be5dbf750d545d214e0191ae909d83915c6beb6a.idx", encoding="[object Object]"
|
||||
[OPFSAdapter] File found: size=5328, type="", lastModified=1758521210388
|
||||
[OPFSAdapter] Returning text content for encoding "[object Object]", length=5138
|
||||
```
|
||||
|
||||
**Problem**: The `.idx` file is a binary Git pack index file, but it was being returned as text because `encoding="[object Object]"` was being treated as a truthy string value.
|
||||
|
||||
**Solution**: Modified the encoding detection logic to:
|
||||
1. Always return binary data for Git pack files and object files
|
||||
2. Only return text for explicit `encoding === 'utf8'` on non-Git binary files
|
||||
3. Handle cases where isomorphic-git passes options objects as encoding
|
||||
|
||||
## Code Changes
|
||||
|
||||
### Before (Broken)
|
||||
```typescript
|
||||
if (encoding === 'utf8') {
|
||||
return await file.text();
|
||||
} else if (encoding) {
|
||||
// BUG: This treated "[object Object]" as truthy and returned text
|
||||
return await file.text();
|
||||
} else {
|
||||
// Binary data
|
||||
return new Uint8Array(arrayBuffer);
|
||||
}
|
||||
```
|
||||
|
||||
### After (Fixed)
|
||||
```typescript
|
||||
// Git pack files (.pack, .idx) and object files should always be binary
|
||||
const isGitBinaryFile = path.includes('.git/objects/pack/') ||
|
||||
(path.includes('.git/objects/') && !path.includes('.git/objects/info/')) ||
|
||||
path.endsWith('.pack') ||
|
||||
path.endsWith('.idx') ||
|
||||
path.includes('.git/index');
|
||||
|
||||
// Only return text for explicit 'utf8' encoding on non-Git binary files
|
||||
const shouldReturnText = !isGitBinaryFile &&
|
||||
encoding === 'utf8' &&
|
||||
typeof encoding === 'string';
|
||||
|
||||
if (shouldReturnText) {
|
||||
return await file.text();
|
||||
} else {
|
||||
// Return binary data (Uint8Array)
|
||||
return new Uint8Array(arrayBuffer);
|
||||
}
|
||||
```
|
||||
|
||||
## Expected Result
|
||||
|
||||
With this fix, Git pack index files will be correctly returned as `Uint8Array` binary data, which should resolve the `Cannot read properties of undefined (reading 'error')` error in isomorphic-git's `readObjectPacked` function.
|
||||
|
||||
## Testing
|
||||
|
||||
To test this fix:
|
||||
1. Try creating a new project with OPFS enabled
|
||||
2. The Git clone operation should now succeed
|
||||
3. Debug logs should show: `Returning binary content: X bytes` for `.idx` files instead of `Returning text content`
|
||||
@@ -1,138 +0,0 @@
|
||||
# OPFS UI Improvements
|
||||
|
||||
## Problem Addressed
|
||||
|
||||
The original implementation had a usability issue where the App Settings dialog (containing filesystem selection) was only accessible through a dropdown menu in the ActionsMenu component, making it very difficult for users to discover and access filesystem settings.
|
||||
|
||||
## Solution Implemented
|
||||
|
||||
### 1. **Added App Settings to Main Settings Page** (`src/pages/Settings.tsx`)
|
||||
|
||||
- Added "App Settings" option to the main settings menu
|
||||
- Positioned logically between data-related settings and about section
|
||||
- Uses `Settings` icon for clear visual identification
|
||||
|
||||
### 2. **Created Dedicated App Settings Page** (`src/pages/AppSettings.tsx`)
|
||||
|
||||
- Full-page settings interface for app configuration
|
||||
- Organized into clear sections:
|
||||
- **Filesystem Settings**: OPFS vs LightningFS selection
|
||||
- **Deployment Settings**: Deploy server configuration
|
||||
- Responsive design with mobile-friendly layout
|
||||
- Clear back navigation on mobile devices
|
||||
|
||||
### 3. **Updated Routing** (`src/AppRouter.tsx`)
|
||||
|
||||
- Added `/settings/app` route for App Settings page
|
||||
- Integrated with existing SettingsLayout for consistent navigation
|
||||
- Proper route ordering in settings hierarchy
|
||||
|
||||
### 4. **Removed Hidden Access** (`src/components/ActionsMenu.tsx`)
|
||||
|
||||
- Removed AppSettingsDialog from ActionsMenu dropdown
|
||||
- Cleaned up unused imports
|
||||
- Settings no longer buried in project-specific actions menu
|
||||
|
||||
### 5. **Complete Translation Support** (`src/lib/i18n.ts`)
|
||||
|
||||
Added comprehensive translations for all new UI elements:
|
||||
|
||||
#### English
|
||||
- `appSettings`: "App Settings"
|
||||
- `appSettingsDescription`: "Configure filesystem and deployment settings"
|
||||
- `filesystem`: "Filesystem"
|
||||
- `filesystemType`: "Filesystem Type"
|
||||
- `deployment`: "Deployment"
|
||||
- `deployServer`: "Deploy Server"
|
||||
- `deployServerDescription`: "Your projects will be deployed to subdomains of this server..."
|
||||
- `saveSettings`: "Save Settings"
|
||||
|
||||
#### Portuguese
|
||||
- `appSettings`: "Configurações do App"
|
||||
- `appSettingsDescription`: "Configure sistema de arquivos e configurações de implantação"
|
||||
- `filesystem`: "Sistema de Arquivos"
|
||||
- `filesystemType`: "Tipo de Sistema de Arquivos"
|
||||
- `deployment`: "Implantação"
|
||||
- `deployServer`: "Servidor de Implantação"
|
||||
- `deployServerDescription`: "Seus projetos serão implantados em subdomínios deste servidor..."
|
||||
- `saveSettings`: "Salvar Configurações"
|
||||
|
||||
#### Chinese
|
||||
- `appSettings`: "应用设置"
|
||||
- `appSettingsDescription`: "配置文件系统和部署设置"
|
||||
- `filesystem`: "文件系统"
|
||||
- `filesystemType`: "文件系统类型"
|
||||
- `deployment`: "部署"
|
||||
- `deployServer`: "部署服务器"
|
||||
- `deployServerDescription`: "您的项目将部署到此服务器的子域..."
|
||||
- `saveSettings`: "保存设置"
|
||||
|
||||
## Key UI Improvements
|
||||
|
||||
### **Discoverability**
|
||||
- ✅ Settings now easily accessible from main Settings page
|
||||
- ✅ Clear, descriptive menu item with appropriate icon
|
||||
- ✅ Logical grouping with related settings
|
||||
|
||||
### **User Experience**
|
||||
- ✅ Full-page interface with adequate space for explanations
|
||||
- ✅ Mobile-responsive design with proper navigation
|
||||
- ✅ Clear visual hierarchy with cards and sections
|
||||
- ✅ Informative descriptions for each filesystem type
|
||||
|
||||
### **Accessibility**
|
||||
- ✅ Proper semantic HTML structure
|
||||
- ✅ Clear form labels and associations
|
||||
- ✅ Keyboard navigation support
|
||||
- ✅ Screen reader friendly with proper ARIA labels
|
||||
|
||||
### **Error Handling**
|
||||
- ✅ Clear warnings when OPFS is not available
|
||||
- ✅ Visual indicators for disabled options
|
||||
- ✅ Helpful error messages and browser compatibility info
|
||||
- ✅ Automatic fallback to LightningFS when needed
|
||||
|
||||
### **Internationalization**
|
||||
- ✅ Complete translation support for all languages
|
||||
- ✅ Consistent terminology across languages
|
||||
- ✅ Culturally appropriate descriptions
|
||||
|
||||
## User Flow
|
||||
|
||||
### **Before (Poor UX)**
|
||||
1. User opens project
|
||||
2. Clicks tiny "more options" button (⋮)
|
||||
3. Finds "Settings" in dropdown menu
|
||||
4. Opens dialog to change filesystem settings
|
||||
5. Hidden and non-intuitive discovery
|
||||
|
||||
### **After (Good UX)**
|
||||
1. User navigates to Settings (accessible from main navigation)
|
||||
2. Sees "App Settings" option clearly listed
|
||||
3. Clicks to access full settings page
|
||||
4. Finds filesystem settings logically grouped with deployment settings
|
||||
5. Clear, discoverable, and intuitive
|
||||
|
||||
## Technical Benefits
|
||||
|
||||
### **Maintainability**
|
||||
- ✅ Dedicated page component for easier maintenance
|
||||
- ✅ Separation of concerns between settings types
|
||||
- ✅ Consistent patterns with other settings pages
|
||||
|
||||
### **Extensibility**
|
||||
- ✅ Easy to add new app-level settings
|
||||
- ✅ Scalable layout for additional configuration options
|
||||
- ✅ Consistent with existing settings architecture
|
||||
|
||||
### **Testing**
|
||||
- ✅ All existing tests continue to pass
|
||||
- ✅ TypeScript compilation successful
|
||||
- ✅ Build process works correctly
|
||||
- ✅ No breaking changes to existing functionality
|
||||
|
||||
## Conclusion
|
||||
|
||||
The UI improvements make filesystem settings significantly more discoverable and accessible to users. The implementation follows established patterns in the codebase, maintains complete internationalization support, and provides a much better user experience overall.
|
||||
|
||||
Users can now easily find and configure filesystem settings through the main Settings page, rather than having to discover them through a hidden dropdown menu in project-specific actions.
|
||||
@@ -148,6 +148,36 @@ consistent handling of both text and binary data across the messaging protocol.
|
||||
|
||||
**Result:** None (notification only, no response expected)
|
||||
|
||||
### Navigation Methods
|
||||
|
||||
#### `navigate`
|
||||
**Purpose:** Navigate iframe to a new URL within the same origin
|
||||
**Parameters:** `url` (string) - Target URL (must be same origin)
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `refresh`
|
||||
**Purpose:** Refresh/reload the current page in the iframe
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `goBack`
|
||||
**Purpose:** Navigate back in the iframe's history
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `goForward`
|
||||
**Purpose:** Navigate forward in the iframe's history
|
||||
**Parameters:** None
|
||||
**Result:** None (notification only)
|
||||
|
||||
#### `updateNavigationState`
|
||||
**Purpose:** Update parent about iframe's current navigation state
|
||||
**Parameters:**
|
||||
- `currentUrl` (string) - Current URL of the iframe
|
||||
- `canGoBack` (boolean) - Whether iframe can go back in history
|
||||
- `canGoForward` (boolean) - Whether iframe can go forward in history
|
||||
**Result:** None (notification only)
|
||||
|
||||
## Implementation
|
||||
|
||||
### Parent Page
|
||||
|
||||
@@ -136,7 +136,27 @@ The system now uses a simplified JSON-RPC 2.0 protocol with two methods:
|
||||
- Parent responds with serialized HTTP responses
|
||||
- ServiceWorker creates Response objects and returns them to the client app
|
||||
|
||||
3. **Content Replacement:**
|
||||
3. **SPA Routing Support:**
|
||||
- ServiceWorker detects navigation requests (HTML page requests with `mode: "navigate"`)
|
||||
- For SPA routes like `/about`, `/contact`, etc., the ServiceWorker serves the site's `index.html`
|
||||
- This allows the SPA's client-side router to handle the route properly
|
||||
- All other requests (assets, API calls, etc.) are handled normally via JSON-RPC
|
||||
|
||||
4. **Semantic Path Navigation:**
|
||||
- **Key Concept**: iframe stays on base URL (`/`) while communicating semantic paths to parent
|
||||
- When user navigates to `/about` in address bar, iframe doesn't actually change URL
|
||||
- Instead, NavigationHandler tracks semantic path (`/about`) and communicates it to parent
|
||||
- Parent displays semantic path while iframe remains on base URL
|
||||
- SPA's client-side router handles navigation internally without page reloads
|
||||
- This prevents 404 errors from literal path navigation
|
||||
|
||||
5. **SPA Navigation Tracking:**
|
||||
- NavigationHandler overrides `history.pushState()` and `history.replaceState()` to detect SPA navigation
|
||||
- When SPAs change URLs via history methods, NavigationHandler detects the change and sends navigation state to parent
|
||||
- Navigation state includes semantic path, back/forward capability, and history tracking
|
||||
- Parent can display current semantic path and enable proper back/forward navigation controls
|
||||
|
||||
6. **Content Replacement:**
|
||||
- Main thread requests `/` from parent via JSON-RPC fetch
|
||||
- Replaces its own content with the site index
|
||||
- Site runs normally, with all requests handled by SW via JSON-RPC
|
||||
@@ -322,6 +342,14 @@ function handleRequest(fetchRequest) {
|
||||
- Check that JSON-RPC messages are properly formatted
|
||||
- Ensure iframe has appropriate sandbox permissions
|
||||
|
||||
### SPA routes don't work
|
||||
|
||||
- Ensure the parent page serves the correct `index.html` for the root path `/`
|
||||
- Check that the SPA's client-side router is properly configured
|
||||
- Verify that navigation requests are being detected correctly by the ServiceWorker
|
||||
- Make sure the parent page returns the same `index.html` content for SPA routes as it does for the root path
|
||||
- **Important**: iframe should stay on base URL (`/`) while semantic paths are communicated to parent. If you see literal path navigation (iframe URL changing to `/about`), this indicates a configuration issue.
|
||||
|
||||
## Development
|
||||
|
||||
To modify the system:
|
||||
|
||||
@@ -13,6 +13,11 @@ class JSONRPCClient {
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
// Check if this is a response to our own request or a ServiceWorker request
|
||||
if (message.jsonrpc === "2.0" && message.id !== undefined) {
|
||||
@@ -148,19 +153,202 @@ class ConsoleInterceptor {
|
||||
}
|
||||
}
|
||||
|
||||
// Navigation Handler - manages iframe navigation and history
|
||||
class NavigationHandler {
|
||||
constructor() {
|
||||
// Get initial path from window property or default to root
|
||||
this.currentSemanticPath = window.__IFRAME_INITIAL_PATH__ || '/';
|
||||
|
||||
this.setupMessageListener();
|
||||
this.setupHistoryListeners();
|
||||
this.overrideHistoryMethods();
|
||||
this.updateNavigationState();
|
||||
}
|
||||
|
||||
// Extract semantic path from URL or string
|
||||
extractSemanticPath(urlOrString) {
|
||||
try {
|
||||
const url = typeof urlOrString === 'string'
|
||||
? new URL(urlOrString, window.location.origin)
|
||||
: urlOrString;
|
||||
return url.pathname + url.search + url.hash;
|
||||
} catch {
|
||||
return window.location.pathname + window.location.search + window.location.hash;
|
||||
}
|
||||
}
|
||||
|
||||
setupMessageListener() {
|
||||
window.addEventListener("message", (event) => {
|
||||
// Only accept messages from parent window for security
|
||||
if (event.source !== window.parent) {
|
||||
return;
|
||||
}
|
||||
|
||||
const message = event.data;
|
||||
if (message.jsonrpc === "2.0") {
|
||||
switch (message.method) {
|
||||
case "navigate":
|
||||
this.handleNavigate(message.params.url);
|
||||
break;
|
||||
case "refresh":
|
||||
this.handleRefresh();
|
||||
break;
|
||||
case "goBack":
|
||||
this.handleGoBack();
|
||||
break;
|
||||
case "goForward":
|
||||
this.handleGoForward();
|
||||
break;
|
||||
}
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
setupHistoryListeners() {
|
||||
// Listen for popstate events (back/forward navigation)
|
||||
window.addEventListener('popstate', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
|
||||
// Listen for hash changes
|
||||
window.addEventListener('hashchange', () => {
|
||||
this.currentSemanticPath = this.extractSemanticPath(window.location);
|
||||
this.updateNavigationState();
|
||||
});
|
||||
}
|
||||
|
||||
overrideHistoryMethods() {
|
||||
// Override history.pushState and history.replaceState to detect SPA navigation
|
||||
this.originalPushState = window.history.pushState;
|
||||
this.originalReplaceState = window.history.replaceState;
|
||||
|
||||
window.history.pushState = (...args) => {
|
||||
const result = this.originalPushState.apply(window.history, args);
|
||||
|
||||
// Extract semantic path from URL argument or use current location
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
|
||||
window.history.replaceState = (...args) => {
|
||||
const result = this.originalReplaceState.apply(window.history, args);
|
||||
|
||||
const semanticPath = args[2]
|
||||
? this.extractSemanticPath(args[2])
|
||||
: this.extractSemanticPath(window.location);
|
||||
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
return result;
|
||||
};
|
||||
}
|
||||
|
||||
handleNavigate(url) {
|
||||
try {
|
||||
// Validate URL - must be same origin
|
||||
const targetUrl = new URL(url, window.location.origin);
|
||||
if (targetUrl.origin !== window.location.origin) {
|
||||
console.error('Navigation to different origin not allowed:', url);
|
||||
return;
|
||||
}
|
||||
|
||||
const semanticPath = this.extractSemanticPath(targetUrl);
|
||||
this.currentSemanticPath = semanticPath;
|
||||
this.updateNavigationState();
|
||||
|
||||
// Trigger SPA navigation
|
||||
window.history.pushState({}, '', semanticPath);
|
||||
window.dispatchEvent(new PopStateEvent('popstate', { state: {} }));
|
||||
|
||||
} catch (error) {
|
||||
console.error('Invalid navigation URL:', url, error);
|
||||
}
|
||||
}
|
||||
|
||||
handleRefresh() {
|
||||
// Store current semantic path for reload
|
||||
const currentPath = this.currentSemanticPath || '/';
|
||||
|
||||
// Save the current path to sessionStorage so it persists across reload
|
||||
try {
|
||||
sessionStorage.setItem('iframe_initial_path', currentPath);
|
||||
} catch (error) {
|
||||
console.warn('Failed to store initial path in sessionStorage:', error);
|
||||
}
|
||||
|
||||
// Actually reload the iframe to get a fresh SPA instance
|
||||
window.location.reload();
|
||||
}
|
||||
|
||||
handleGoBack() {
|
||||
window.history.back();
|
||||
}
|
||||
|
||||
handleGoForward() {
|
||||
window.history.forward();
|
||||
}
|
||||
|
||||
updateNavigationState() {
|
||||
// Use tracked semantic path, fallback to current location if needed
|
||||
const semanticPath = this.currentSemanticPath || this.extractSemanticPath(window.location);
|
||||
|
||||
const state = {
|
||||
currentUrl: semanticPath,
|
||||
canGoBack: false, // Let parent handle history tracking
|
||||
canGoForward: false // Let parent handle history tracking
|
||||
};
|
||||
|
||||
// Send navigation state to parent
|
||||
try {
|
||||
window.parent.postMessage({
|
||||
jsonrpc: "2.0",
|
||||
method: "updateNavigationState",
|
||||
params: state
|
||||
}, "*");
|
||||
} catch (error) {
|
||||
console.error('Failed to send navigation state:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main Fetch Client
|
||||
class FetchClient {
|
||||
constructor() {
|
||||
this.rpcClient = new JSONRPCClient();
|
||||
this.consoleInterceptor = new ConsoleInterceptor();
|
||||
this.navigationHandler = new NavigationHandler();
|
||||
this.init();
|
||||
}
|
||||
|
||||
// Ensure SPA navigates to initial path after document is loaded
|
||||
ensureInitialNavigation() {
|
||||
// Wait for the SPA to initialize, then navigate to the initial path
|
||||
setTimeout(() => {
|
||||
const initialPath = window.__IFRAME_INITIAL_PATH__;
|
||||
|
||||
if (initialPath && initialPath !== '/') {
|
||||
const currentPath = window.location.pathname + window.location.search + window.location.hash;
|
||||
|
||||
// If we're not already at the initial path, navigate there
|
||||
if (currentPath !== initialPath) {
|
||||
this.navigationHandler.handleNavigate(initialPath);
|
||||
}
|
||||
}
|
||||
}, 150); // Give SPA more time to initialize
|
||||
}
|
||||
|
||||
async init() {
|
||||
try {
|
||||
await this.setupServiceWorker();
|
||||
await this.loadSiteIndex();
|
||||
} catch (error) {
|
||||
console.error("FetchClient: Initialization failed:", error);
|
||||
this.showError("Failed to initialize fetch client", error);
|
||||
}
|
||||
}
|
||||
@@ -212,6 +400,20 @@ class FetchClient {
|
||||
}
|
||||
|
||||
async loadSiteIndex() {
|
||||
// Check if we have a stored initial path from a refresh
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('iframe_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
// Clear the stored path after using it
|
||||
sessionStorage.removeItem('iframe_initial_path');
|
||||
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('loadSiteIndex: Failed to read initial path from sessionStorage:', error);
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: `${location.origin}/`,
|
||||
method: "GET",
|
||||
@@ -232,10 +434,33 @@ class FetchClient {
|
||||
const bytes = new Uint8Array(atob(response.body).split('').map(c => c.charCodeAt(0)));
|
||||
const text = new TextDecoder().decode(bytes);
|
||||
|
||||
// Set the initial path on window before replacing the document
|
||||
// This will be available to the NavigationHandler when it initializes
|
||||
if (initialPath && initialPath !== '/') {
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
|
||||
this.replaceDocument(text);
|
||||
}
|
||||
|
||||
replaceDocument(htmlContent) {
|
||||
console.log("replaceDocument: Starting...");
|
||||
|
||||
// Restore the initial path from sessionStorage before replacing document
|
||||
let initialPath = '/';
|
||||
try {
|
||||
const storedPath = sessionStorage.getItem('spa_initial_path');
|
||||
if (storedPath) {
|
||||
initialPath = storedPath;
|
||||
sessionStorage.removeItem('spa_initial_path');
|
||||
console.log('replaceDocument: Restored initial path:', initialPath);
|
||||
// Set it on window for the new document
|
||||
window.__IFRAME_INITIAL_PATH__ = initialPath;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('replaceDocument: Failed to restore initial path:', error);
|
||||
}
|
||||
|
||||
// Create a new document from the HTML content
|
||||
const parser = new DOMParser();
|
||||
const newDoc = parser.parseFromString(htmlContent, "text/html");
|
||||
@@ -266,7 +491,8 @@ class FetchClient {
|
||||
document.body.appendChild(newScript);
|
||||
});
|
||||
|
||||
console.log("Document replaced with site content");
|
||||
// Ensure initial navigation after document is loaded
|
||||
this.ensureInitialNavigation();
|
||||
}
|
||||
|
||||
showError(message, error) {
|
||||
|
||||
+60
-14
@@ -68,23 +68,37 @@ async function requestViaJSONRPC(request) {
|
||||
return new Promise(async (resolve, reject) => {
|
||||
const id = ++requestIdCounter;
|
||||
|
||||
// Serialize the fetch request
|
||||
let body = null;
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
// Check if request is a plain object or Request object
|
||||
let url, method, headers, body;
|
||||
|
||||
if (request instanceof Request) {
|
||||
// Handle Request object
|
||||
url = request.url;
|
||||
method = request.method;
|
||||
headers = Object.fromEntries(request.headers.entries());
|
||||
|
||||
if (request.body) {
|
||||
try {
|
||||
// Convert body to Uint8Array then base64 encode
|
||||
const bytes = await request.bytes();
|
||||
body = btoa(String.fromCharCode(...bytes));
|
||||
} catch (error) {
|
||||
reject(new Error(`Failed to serialize request body: ${error.message}`));
|
||||
return;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Handle plain request object
|
||||
url = request.url;
|
||||
method = request.method || 'GET';
|
||||
headers = request.headers || {};
|
||||
body = request.body || null;
|
||||
}
|
||||
|
||||
const serializedRequest = {
|
||||
url: request.url,
|
||||
method: request.method,
|
||||
headers: Object.fromEntries(request.headers.entries()),
|
||||
url: url,
|
||||
method: method,
|
||||
headers: headers,
|
||||
body: body,
|
||||
};
|
||||
|
||||
@@ -109,7 +123,7 @@ async function requestViaJSONRPC(request) {
|
||||
setTimeout(() => {
|
||||
if (pendingRequests.has(id)) {
|
||||
pendingRequests.delete(id);
|
||||
reject(new Error(`Timeout requesting: ${request.url}`));
|
||||
reject(new Error(`Timeout requesting: ${url}`));
|
||||
}
|
||||
}, 10000);
|
||||
});
|
||||
@@ -134,6 +148,38 @@ self.addEventListener("fetch", (event) => {
|
||||
return;
|
||||
}
|
||||
|
||||
// Let iframe client assets be handled normally (anything in _iframe-client directory and common assets)
|
||||
if (url.pathname.startsWith("/_iframe-client/") ||
|
||||
url.pathname === "/favicon.ico" ||
|
||||
url.pathname === "/manifest.webmanifest") {
|
||||
return;
|
||||
}
|
||||
|
||||
// For SPA routes, check if this is a navigation request (HTML page request)
|
||||
// But first check if we need to load the iframe client (this happens during refresh)
|
||||
if (event.request.mode === "navigate" &&
|
||||
(event.request.headers.get("accept") || "").includes("text/html")) {
|
||||
|
||||
// Check if this is a request for the iframe client itself
|
||||
// We need to serve the iframe client HTML first, which will then load the SPA
|
||||
if (url.pathname !== "/") {
|
||||
// Redirect to root to load the iframe client, which will then navigate to the target path
|
||||
const response = Response.redirect(new URL("/", event.request.url).href, 302);
|
||||
event.respondWith(response);
|
||||
return;
|
||||
}
|
||||
|
||||
// This is a request for the root path, serve the site's index.html via JSON-RPC
|
||||
const rootRequest = {
|
||||
url: new URL("/", event.request.url).href,
|
||||
method: event.request.method,
|
||||
headers: Object.fromEntries(event.request.headers.entries()),
|
||||
body: event.request.body
|
||||
};
|
||||
event.respondWith(handleRequest(rootRequest));
|
||||
return;
|
||||
}
|
||||
|
||||
// Handle all other requests through JSON-RPC communication
|
||||
event.respondWith(handleRequest(event.request));
|
||||
});
|
||||
|
||||
Generated
+15
@@ -80,6 +80,7 @@
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"turndown": "^7.2.1",
|
||||
"uri-templates": "^0.2.0",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
@@ -100,6 +101,7 @@
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@types/uri-templates": "^0.1.34",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.9.0",
|
||||
@@ -3849,6 +3851,13 @@
|
||||
"integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@types/uri-templates": {
|
||||
"version": "0.1.34",
|
||||
"resolved": "https://registry.npmjs.org/@types/uri-templates/-/uri-templates-0.1.34.tgz",
|
||||
"integrity": "sha512-13v4r/Op3iEO1y6FvEHQjrUNnrNyO67SigdFC9n80sVfsrM2AWJRNYbE1pBs4/p87I7z1J979JGeLAo3rM1L/Q==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/@typescript-eslint/eslint-plugin": {
|
||||
"version": "8.31.1",
|
||||
"resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.31.1.tgz",
|
||||
@@ -10627,6 +10636,12 @@
|
||||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/uri-templates": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/uri-templates/-/uri-templates-0.2.0.tgz",
|
||||
"integrity": "sha512-EWkjYEN0L6KOfEoOH6Wj4ghQqU7eBZMJqRHQnxQAq+dSEzRPClkWjf8557HkWQXF6BrAUoLSAyy9i3RVTliaNg==",
|
||||
"license": "http://geraintluff.github.io/tv4/LICENSE.txt"
|
||||
},
|
||||
"node_modules/use-callback-ref": {
|
||||
"version": "1.3.3",
|
||||
"resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz",
|
||||
|
||||
@@ -83,6 +83,7 @@
|
||||
"tailwind-merge": "^2.5.2",
|
||||
"tailwindcss-animate": "^1.0.7",
|
||||
"turndown": "^7.2.1",
|
||||
"uri-templates": "^0.2.0",
|
||||
"use-stick-to-bottom": "^1.1.1",
|
||||
"vaul": "^0.9.3",
|
||||
"webln": "^0.3.2",
|
||||
@@ -103,6 +104,7 @@
|
||||
"@types/react": "^18.3.1",
|
||||
"@types/react-dom": "^18.3.1",
|
||||
"@types/turndown": "^5.0.5",
|
||||
"@types/uri-templates": "^0.1.34",
|
||||
"@vitejs/plugin-react-swc": "^3.5.0",
|
||||
"autoprefixer": "^10.4.20",
|
||||
"eslint": "^9.9.0",
|
||||
|
||||
@@ -0,0 +1,40 @@
|
||||
export default {
|
||||
async fetch(request: Request): Promise<Response> {
|
||||
const url = new URL(request.url);
|
||||
const target = url.searchParams.get("url");
|
||||
|
||||
if (!target) {
|
||||
return new Response("Include a `url` query parameter", { status: 400 });
|
||||
}
|
||||
|
||||
// Handle CORS preflight requests
|
||||
if (request.method === "OPTIONS") {
|
||||
return new Response(null, {
|
||||
status: 200,
|
||||
headers: {
|
||||
"Access-Control-Allow-Origin": "*",
|
||||
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
|
||||
"Access-Control-Allow-Headers": "*", // Or specify specific headers
|
||||
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const headers = new Headers(request.headers);
|
||||
headers.set('User-Agent', 'Shakespeare Proxy <https://proxy.shakespeare.diy/>');
|
||||
|
||||
const targetResponse = await fetch(target, {
|
||||
method: request.method,
|
||||
headers: headers,
|
||||
body: request.body,
|
||||
});
|
||||
|
||||
const response = new Response(targetResponse.body, targetResponse);
|
||||
|
||||
response.headers.set("Access-Control-Allow-Origin", "*");
|
||||
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
|
||||
response.headers.set("Access-Control-Allow-Headers", "*");
|
||||
|
||||
return response;
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" width="166" height="20" role="img" aria-label="🎭 Edit with: Shakespeare">
|
||||
<title>🎭 Edit with: Shakespeare</title>
|
||||
<defs>
|
||||
<mask id="round">
|
||||
<rect width="166" height="20" rx="3" fill="#fff"/>
|
||||
</mask>
|
||||
<linearGradient id="shine" x2="0" y2="100%">
|
||||
<stop offset="0" stop-color="#fff" stop-opacity=".2"/>
|
||||
<stop offset="0.1" stop-color="#fff" stop-opacity=".05"/>
|
||||
<stop offset="1" stop-color="#fff" stop-opacity="0"/>
|
||||
</linearGradient>
|
||||
</defs>
|
||||
|
||||
<g mask="url(#round)">
|
||||
<!-- Left label background -->
|
||||
<rect width="78" height="20" fill="#555"/>
|
||||
<!-- Right label background -->
|
||||
<rect x="78" width="88" height="20" fill="#6f42c1"/>
|
||||
<rect width="166" height="20" fill="url(#shine)"/>
|
||||
</g>
|
||||
|
||||
<!-- Text -->
|
||||
<g fill="#fff" text-anchor="middle" font-family="-apple-system,BlinkMacSystemFont,Segoe UI,Helvetica,Arial,Ubuntu,Cantarell,Noto Sans,sans-serif" font-size="11">
|
||||
<text x="39" y="14">🎭 Edit with</text>
|
||||
<text x="122" y="14" font-weight="600">Shakespeare</text>
|
||||
</g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 1.1 KiB |
+10
-115
@@ -4,7 +4,7 @@
|
||||
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||
import { createHead, UnheadProvider } from '@unhead/react/client';
|
||||
import { InferSeoMetaPlugin } from '@unhead/addons';
|
||||
import { Suspense, useEffect, useState } from 'react';
|
||||
import { Suspense, useEffect } from 'react';
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import NostrProvider from '@/components/NostrProvider';
|
||||
import { Toaster } from "@/components/ui/toaster";
|
||||
@@ -17,11 +17,7 @@ import { GitSettingsProvider } from '@/components/GitSettingsProvider';
|
||||
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
|
||||
import { FSProvider } from '@/components/FSProvider';
|
||||
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
|
||||
import { OPFSAdapterSimple } from '@/lib/OPFSAdapterSimple';
|
||||
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
|
||||
import AppRouter from './AppRouter';
|
||||
|
||||
@@ -45,7 +41,6 @@ const defaultConfig: AppConfig = {
|
||||
theme: "light",
|
||||
relayUrl: "wss://relay.primal.net",
|
||||
deployServer: "shakespeare.wtf",
|
||||
filesystemType: "lightningfs",
|
||||
};
|
||||
|
||||
const presetRelays = [
|
||||
@@ -55,118 +50,18 @@ const presetRelays = [
|
||||
{ url: 'wss://relay.primal.net', name: 'Primal' },
|
||||
];
|
||||
|
||||
// Component to handle filesystem initialization and cleanup
|
||||
function FilesystemProvider({ children }: { children: React.ReactNode }) {
|
||||
const { config } = useAppContext();
|
||||
const [fs, setFS] = useState<JSRuntimeFS | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
const initializeFilesystem = async () => {
|
||||
try {
|
||||
let filesystem: JSRuntimeFS;
|
||||
|
||||
if (config.filesystemType === 'opfs') {
|
||||
// Check if OPFS is available
|
||||
if (!('storage' in navigator) || typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
|
||||
throw new Error('OPFS is not supported in this browser');
|
||||
}
|
||||
|
||||
console.log('Initializing OPFS filesystem...');
|
||||
filesystem = new OPFSAdapterSimple({ debug: true });
|
||||
|
||||
// Test basic filesystem operations to ensure OPFS works correctly
|
||||
try {
|
||||
await filesystem.mkdir('/test-opfs', { recursive: true });
|
||||
await filesystem.writeFile('/test-opfs/test.txt', 'test');
|
||||
const testContent = await filesystem.readFile('/test-opfs/test.txt', 'utf8');
|
||||
if (testContent !== 'test') {
|
||||
throw new Error('OPFS test failed: content mismatch');
|
||||
}
|
||||
await filesystem.unlink('/test-opfs/test.txt');
|
||||
await filesystem.rmdir('/test-opfs');
|
||||
console.log('OPFS filesystem test passed');
|
||||
} catch (testError) {
|
||||
console.warn('OPFS filesystem test failed:', testError);
|
||||
throw new Error(`OPFS filesystem test failed: ${testError}`);
|
||||
}
|
||||
} else {
|
||||
// Default to LightningFS
|
||||
console.log('Initializing LightningFS filesystem...');
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
filesystem = new LightningFSAdapter(lightningFS.promises);
|
||||
}
|
||||
|
||||
setFS(filesystem);
|
||||
setError(null);
|
||||
console.log(`Successfully initialized ${config.filesystemType === 'opfs' ? 'OPFS' : 'LightningFS'} filesystem`);
|
||||
} catch (err) {
|
||||
console.error('Failed to initialize filesystem:', err);
|
||||
const errorMessage = err instanceof Error ? err.message : 'Failed to initialize filesystem';
|
||||
|
||||
// Fallback to LightningFS if OPFS fails
|
||||
if (config.filesystemType === 'opfs') {
|
||||
console.warn('OPFS initialization failed, falling back to LightningFS...');
|
||||
try {
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
const fallbackFs = new LightningFSAdapter(lightningFS.promises);
|
||||
setFS(fallbackFs);
|
||||
setError(null);
|
||||
console.log('Successfully fell back to LightningFS');
|
||||
} catch (fallbackErr) {
|
||||
console.error('LightningFS fallback also failed:', fallbackErr);
|
||||
setError(`Failed to initialize both OPFS and LightningFS: ${errorMessage}; Fallback error: ${fallbackErr}`);
|
||||
}
|
||||
} else {
|
||||
setError(errorMessage);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
initializeFilesystem();
|
||||
}, [config.filesystemType]);
|
||||
|
||||
if (error) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center space-y-4">
|
||||
<h1 className="text-2xl font-bold text-red-600">Filesystem Error</h1>
|
||||
<p className="text-muted-foreground">{error}</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
Please try refreshing the page or using a different browser.
|
||||
If the problem persists, you may need to clear browser data and try again.
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (!fs) {
|
||||
return (
|
||||
<div className="flex items-center justify-center min-h-screen">
|
||||
<div className="text-center space-y-4">
|
||||
<div className="animate-spin rounded-full h-8 w-8 border-b-2 border-primary mx-auto"></div>
|
||||
<p className="text-muted-foreground">Initializing filesystem...</p>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return <FSProvider fs={fs}>{children}</FSProvider>;
|
||||
}
|
||||
// Initialize LightningFS
|
||||
const lightningFS = new LightningFS('shakespeare-fs');
|
||||
const fs = new LightningFSAdapter(lightningFS.promises);
|
||||
|
||||
// Component to handle filesystem cleanup on startup
|
||||
// Automatically removes files older than 1 hour from /tmp directory
|
||||
function FSCleanupHandler() {
|
||||
const { fs } = useFS();
|
||||
|
||||
useEffect(() => {
|
||||
if (fs) {
|
||||
// Run cleanup on application startup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
cleanupTmpDirectory(fs).catch(console.error);
|
||||
}
|
||||
}, [fs]);
|
||||
// Run cleanup on application startup to remove stale temporary files
|
||||
// This helps prevent the VFS from accumulating old files over time
|
||||
cleanupTmpDirectory(fs).catch(console.error);
|
||||
}, []);
|
||||
|
||||
return null;
|
||||
}
|
||||
@@ -176,7 +71,7 @@ export function App() {
|
||||
<UnheadProvider head={head}>
|
||||
<QueryClientProvider client={queryClient}>
|
||||
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
|
||||
<FilesystemProvider>
|
||||
<FSProvider fs={fs}>
|
||||
<FSCleanupHandler />
|
||||
<NostrLoginProvider storageKey='nostr:login'>
|
||||
<NostrProvider>
|
||||
@@ -194,7 +89,7 @@ export function App() {
|
||||
</AISettingsProvider>
|
||||
</NostrProvider>
|
||||
</NostrLoginProvider>
|
||||
</FilesystemProvider>
|
||||
</FSProvider>
|
||||
</AppProvider>
|
||||
</QueryClientProvider>
|
||||
</UnheadProvider>
|
||||
|
||||
@@ -11,6 +11,7 @@ import AISettings from "./pages/AISettings";
|
||||
import GitSettings from "./pages/GitSettings";
|
||||
import DataSettings from "./pages/DataSettings";
|
||||
import AboutSettings from "./pages/AboutSettings";
|
||||
import EmailSettings from "./pages/EmailSettings";
|
||||
import GitHubOAuth from "./pages/GitHubOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
@@ -33,6 +34,7 @@ export function AppRouter() {
|
||||
<Route path="ai" element={<AISettings />} />
|
||||
<Route path="git" element={<GitSettings />} />
|
||||
<Route path="data" element={<DataSettings />} />
|
||||
<Route path="email" element={<EmailSettings />} />
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
|
||||
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" width="500px" height="500px" style="shape-rendering:geometricPrecision; text-rendering:geometricPrecision; image-rendering:optimizeQuality; fill-rule:evenodd; clip-rule:evenodd" xmlns:xlink="http://www.w3.org/1999/xlink">
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 1.5,10.5 C 2.83333,11.1667 2.83333,11.1667 1.5,10.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 287.5,14.5 C 288.833,15.1667 288.833,15.1667 287.5,14.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 393.5,19.5 C 394.833,20.1667 394.833,20.1667 393.5,19.5 Z"/></g>
|
||||
<g><path style="opacity:0.067" fill="#d8d5d1" d="M 257.5,33.5 C 252.167,33.5 246.833,33.5 241.5,33.5C 246.567,32.8118 251.733,32.1451 257,31.5C 257.464,32.0944 257.631,32.7611 257.5,33.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 304.5,37.5 C 305.833,38.1667 305.833,38.1667 304.5,37.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 199.5,52.5 C 198.833,51.1667 198.833,51.1667 199.5,52.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#272422" d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z"/></g>
|
||||
<g><path style="opacity:0.435" fill="#9b9895" d="M 195.5,57.5 C 195.573,59.0269 194.906,60.0269 193.5,60.5C 193.427,58.9731 194.094,57.9731 195.5,57.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 404.5,60.5 C 405.833,61.1667 405.833,61.1667 404.5,60.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 92.5,61.5 C 93.8333,62.1667 93.8333,62.1667 92.5,61.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#1c1a18" d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 448.5,63.5 C 449.833,64.1667 449.833,64.1667 448.5,63.5 Z"/></g>
|
||||
<g><path style="opacity:0.141" fill="#b0abaa" d="M 291.5,64.5 C 293.104,65.287 293.771,66.6203 293.5,68.5C 292.326,67.4863 291.66,66.153 291.5,64.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 426.5,69.5 C 427.833,70.1667 427.833,70.1667 426.5,69.5 Z"/></g>
|
||||
<g><path style="opacity:0.09" fill="#c3bbb9" d="M 187.5,70.5 C 187.573,72.0269 186.906,73.0269 185.5,73.5C 185.427,71.9731 186.094,70.9731 187.5,70.5 Z"/></g>
|
||||
<g><path style="opacity:0.824" fill="#726e69" d="M 312.5,71.5 C 314.729,74.3538 316.062,77.6871 316.5,81.5C 315.043,79.7582 313.876,77.7582 313,75.5C 312.51,74.2068 312.343,72.8734 312.5,71.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 487.5,76.5 C 488.833,77.1667 488.833,77.1667 487.5,76.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 387.5,78.5 C 388.833,79.1667 388.833,79.1667 387.5,78.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#1e1d1b" d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 20.5,86.5 C 21.8333,87.1667 21.8333,87.1667 20.5,86.5 Z"/></g>
|
||||
<g><path style="opacity:0.792" fill="#97938f" d="M 272.5,96.5 C 275.189,97.1894 276.856,98.856 277.5,101.5C 275.451,100.118 273.785,98.4516 272.5,96.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#23201e" d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#d7d2ce" d="M 269.5,104.5 C 270.5,104.833 271.167,105.5 271.5,106.5C 270.167,106.5 269.5,105.833 269.5,104.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#242220" d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#272422" d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z"/></g>
|
||||
<g><path style="opacity:0.137" fill="#a59b96" d="M 163.5,112.5 C 163.573,114.027 162.906,115.027 161.5,115.5C 161.427,113.973 162.094,112.973 163.5,112.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 89.5,117.5 C 90.8333,118.167 90.8333,118.167 89.5,117.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,118.5 C 438.833,119.167 438.833,119.167 437.5,118.5 Z"/></g>
|
||||
<g><path style="opacity:0.992" fill="#72716a" d="M 216.5,118.5 C 216.167,120.833 214.833,122.167 212.5,122.5C 213.09,121.234 213.59,119.901 214,118.5C 214.77,119.598 215.603,119.598 216.5,118.5 Z"/></g>
|
||||
<g><path style="opacity:0.098" fill="#bfb8b7" d="M 339.5,117.5 C 340.906,117.973 341.573,118.973 341.5,120.5C 340.094,120.027 339.427,119.027 339.5,117.5 Z"/></g>
|
||||
<g><path style="opacity:0.508" fill="#7f7a74" d="M 203.5,121.5 C 206.43,122.299 209.43,122.632 212.5,122.5C 210.034,123.634 207.367,123.801 204.5,123C 203.944,122.617 203.611,122.117 203.5,121.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 408.5,124.5 C 409.833,125.167 409.833,125.167 408.5,124.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 424.5,133.5 C 425.833,134.167 425.833,134.167 424.5,133.5 Z"/></g>
|
||||
<g><path style="opacity:0.333" fill="#9e9894" d="M 344.5,127.5 C 345.954,130.718 346.621,134.218 346.5,138C 346.496,140.361 346.163,142.527 345.5,144.5C 345.553,138.804 345.22,133.138 344.5,127.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 140.5,135.5 C 141.833,136.167 141.833,136.167 140.5,135.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 53.5,137.5 C 54.8333,138.167 54.8333,138.167 53.5,137.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 353.5,140.5 C 354.833,141.167 354.833,141.167 353.5,140.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 493.5,141.5 C 494.833,142.167 494.833,142.167 493.5,141.5 Z"/></g>
|
||||
<g><path style="opacity:0.455" fill="#918f8b" d="M 243.5,143.5 C 242.135,145.794 240.135,147.461 237.5,148.5C 239.385,146.947 240.385,144.947 240.5,142.5C 241.791,142.263 242.791,142.596 243.5,143.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 437.5,153.5 C 438.833,154.167 438.833,154.167 437.5,153.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 438.5,183.5 C 439.833,184.167 439.833,184.167 438.5,183.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 446.5,183.5 C 447.833,184.167 447.833,184.167 446.5,183.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 123.5,185.5 C 124.833,186.167 124.833,186.167 123.5,185.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,186.5 C 130.833,187.167 130.833,187.167 129.5,186.5 Z"/></g>
|
||||
<g><path style="opacity:0.839" fill="#756a67" d="M 333.5,187.5 C 333.346,189.97 332.346,191.97 330.5,193.5C 330.455,190.923 331.455,188.923 333.5,187.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#262321" d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 26.5,198.5 C 27.8333,199.167 27.8333,199.167 26.5,198.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 413.5,204.5 C 414.833,205.167 414.833,205.167 413.5,204.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 74.5,209.5 C 75.8333,210.167 75.8333,210.167 74.5,209.5 Z"/></g>
|
||||
<g><path style="opacity:0.965" fill="#272422" d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z"/></g>
|
||||
<g><path style="opacity:0.129" fill="#b5b4af" d="M 206.5,184.5 C 207.906,184.973 208.573,185.973 208.5,187.5C 207.094,187.027 206.427,186.027 206.5,184.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#35312f" d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#171513" d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#413d38" d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z"/></g>
|
||||
<g><path style="opacity:0.098" fill="#cecbc4" d="M 177.5,212.5 C 181.151,211.835 184.985,211.501 189,211.5C 195.725,211.4 202.225,212.066 208.5,213.5C 198.183,212.774 187.85,212.44 177.5,212.5 Z"/></g>
|
||||
<g><path style="opacity:0.149" fill="#adaaa7" d="M 150.5,210.5 C 150.573,212.027 149.906,213.027 148.5,213.5C 148.427,211.973 149.094,210.973 150.5,210.5 Z"/></g>
|
||||
<g><path style="opacity:0.122" fill="#c4b9b8" d="M 217.5,211.5 C 217.5,212.167 217.5,212.833 217.5,213.5C 215.833,214.833 214.167,214.833 212.5,213.5C 214.554,213.635 216.221,212.968 217.5,211.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#181614" d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z"/></g>
|
||||
<g><path style="opacity:0.047" fill="#e0dfd7" d="M 198.5,219.5 C 198.5,219.833 198.5,220.167 198.5,220.5C 195.287,220.19 192.287,220.523 189.5,221.5C 188.957,221.44 188.624,221.107 188.5,220.5C 191.768,219.513 195.102,219.18 198.5,219.5 Z"/></g>
|
||||
<g><path style="opacity:0.592" fill="#7d7976" d="M 299.5,222.5 C 298.833,224.167 298.167,225.833 297.5,227.5C 296.833,227.5 296.167,227.5 295.5,227.5C 296.124,225.246 297.457,223.579 299.5,222.5 Z"/></g>
|
||||
<g><path style="opacity:0.592" fill="#94908e" d="M 189.5,221.5 C 190.377,223.728 191.71,225.728 193.5,227.5C 190.224,226.878 188.891,224.878 189.5,221.5 Z"/></g>
|
||||
<g><path style="opacity:0.247" fill="#837f7a" d="M 201.5,225.5 C 201.423,226.75 200.756,227.583 199.5,228C 197.288,228.789 195.288,228.622 193.5,227.5C 196.421,227.717 199.087,227.051 201.5,225.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,229.5 C 33.8333,230.167 33.8333,230.167 32.5,229.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#252421" d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 490.5,245.5 C 491.833,246.167 491.833,246.167 490.5,245.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 230.5,246.5 C 231.833,247.167 231.833,247.167 230.5,246.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 223.5,250.5 C 224.833,251.167 224.833,251.167 223.5,250.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,254.5 C 486.833,255.167 486.833,255.167 485.5,254.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 411.5,255.5 C 412.833,256.167 412.833,256.167 411.5,255.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 144.5,270.5 C 145.833,271.167 145.833,271.167 144.5,270.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#22201e" d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z"/></g>
|
||||
<g><path style="opacity:0.184" fill="#a6a29e" d="M 278.5,242.5 C 280.027,242.427 281.027,243.094 281.5,244.5C 279.973,244.573 278.973,243.906 278.5,242.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 257.5,237.5 C 258.833,238.167 258.833,238.167 257.5,237.5 Z"/></g>
|
||||
<g><path style="opacity:0.247" fill="#aca7a5" d="M 295.5,227.5 C 295.573,229.027 294.906,230.027 293.5,230.5C 293.427,228.973 294.094,227.973 295.5,227.5 Z"/></g>
|
||||
<g><path style="opacity:0.306" fill="#7f7772" d="M 244.5,228.5 C 246.167,228.5 247.833,228.5 249.5,228.5C 249.598,230.553 248.931,232.22 247.5,233.5C 247.33,232.178 247.663,231.011 248.5,230C 246.942,229.79 245.609,229.29 244.5,228.5 Z"/></g>
|
||||
<g><path style="opacity:0.114" fill="#bcb6b2" d="M 213.5,222.5 C 212.523,225.287 212.19,228.287 212.5,231.5C 211.833,231.5 211.5,231.167 211.5,230.5C 211.183,227.428 211.516,224.428 212.5,221.5C 213.107,221.624 213.44,221.957 213.5,222.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 202.5,272.5 C 203.833,273.167 203.833,273.167 202.5,272.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 32.5,280.5 C 33.8333,281.167 33.8333,281.167 32.5,280.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 255.5,283.5 C 256.833,284.167 256.833,284.167 255.5,283.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 239.5,290.5 C 240.833,291.167 240.833,291.167 239.5,290.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 110.5,295.5 C 111.833,296.167 111.833,296.167 110.5,295.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 405.5,295.5 C 406.833,296.167 406.833,296.167 405.5,295.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 330.5,302.5 C 331.833,303.167 331.833,303.167 330.5,302.5 Z"/></g>
|
||||
<g><path style="opacity:0.342" fill="#837e7a" d="M 172.5,220.5 C 172.5,220.167 172.5,219.833 172.5,219.5C 175.167,219.5 177.833,219.5 180.5,219.5C 180.5,273.833 180.5,328.167 180.5,382.5C 179.501,328.669 179.168,274.669 179.5,220.5C 177.167,220.5 174.833,220.5 172.5,220.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 394.5,307.5 C 395.833,308.167 395.833,308.167 394.5,307.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 406.5,308.5 C 407.833,309.167 407.833,309.167 406.5,308.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 63.5,320.5 C 64.8333,321.167 64.8333,321.167 63.5,320.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 105.5,321.5 C 106.833,322.167 106.833,322.167 105.5,321.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 400.5,323.5 C 401.833,324.167 401.833,324.167 400.5,323.5 Z"/></g>
|
||||
<g><path style="opacity:0.224" fill="#6b6662" d="M 200.5,235.5 C 198.735,236.461 196.735,236.795 194.5,236.5C 194.185,286.857 194.518,337.19 195.5,387.5C 194.732,386.737 194.232,385.737 194,384.5C 193.5,334.834 193.333,285.168 193.5,235.5C 195.833,235.5 198.167,235.5 200.5,235.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 492.5,372.5 C 493.833,373.167 493.833,373.167 492.5,372.5 Z"/></g>
|
||||
<g><path style="opacity:1" fill="#706d68" d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z"/></g>
|
||||
<g><path style="opacity:0.471" fill="#89837d" d="M 262.5,374.5 C 260.321,375.926 257.821,376.592 255,376.5C 253.293,376.492 251.793,376.158 250.5,375.5C 254.534,375.495 258.534,375.162 262.5,374.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 308.5,385.5 C 309.833,386.167 309.833,386.167 308.5,385.5 Z"/></g>
|
||||
<g><path style="opacity:0.039" fill="#cdc9c7" d="M 308.5,397.5 C 308.573,399.027 307.906,400.027 306.5,400.5C 306.427,398.973 307.094,397.973 308.5,397.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 384.5,401.5 C 385.833,402.167 385.833,402.167 384.5,401.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 130.5,431.5 C 131.833,432.167 131.833,432.167 130.5,431.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 129.5,437.5 C 130.833,438.167 130.833,438.167 129.5,437.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 172.5,437.5 C 173.833,438.167 173.833,438.167 172.5,437.5 Z"/></g>
|
||||
<g><path style="opacity:0.998" fill="#1f1d1b" d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z"/></g>
|
||||
<g><path style="opacity:0.755" fill="#706a67" d="M 266.5,434.5 C 266.082,435.222 265.416,435.722 264.5,436C 258.984,436.817 253.65,436.651 248.5,435.5C 254.545,435.697 260.545,435.363 266.5,434.5 Z"/></g>
|
||||
<g><path style="opacity:0.165" fill="#a6a19f" d="M 276.5,445.5 C 275.22,446.931 273.553,447.598 271.5,447.5C 272.78,446.069 274.447,445.402 276.5,445.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 496.5,448.5 C 497.833,449.167 497.833,449.167 496.5,448.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 485.5,449.5 C 486.833,450.167 486.833,450.167 485.5,449.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 295.5,468.5 C 296.833,469.167 296.833,469.167 295.5,468.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 31.5,477.5 C 32.8333,478.167 32.8333,478.167 31.5,477.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 78.5,478.5 C 79.8333,479.167 79.8333,479.167 78.5,478.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 135.5,485.5 C 136.833,486.167 136.833,486.167 135.5,485.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 67.5,492.5 C 68.8333,493.167 68.8333,493.167 67.5,492.5 Z"/></g>
|
||||
<g><path style="opacity:0.004" fill="#fefffe" d="M 11.5,495.5 C 12.8333,496.167 12.8333,496.167 11.5,495.5 Z"/></g>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 29 KiB |
@@ -16,14 +16,12 @@ interface AIMessageItemProps {
|
||||
message: AIMessage;
|
||||
isCurrentlyLoading?: boolean;
|
||||
toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message
|
||||
reasoningContent?: string; // Reasoning content for streaming messages
|
||||
}
|
||||
|
||||
export const AIMessageItem = memo(({
|
||||
message,
|
||||
isCurrentlyLoading = false,
|
||||
toolCall,
|
||||
reasoningContent
|
||||
}: AIMessageItemProps) => {
|
||||
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
||||
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
||||
@@ -186,6 +184,75 @@ export const AIMessageItem = memo(({
|
||||
const toolInfo = getToolInfo();
|
||||
const IconComponent = toolInfo.icon;
|
||||
|
||||
// Get tool call arguments for special rendering
|
||||
let toolArgs: Record<string, unknown> = {};
|
||||
let toolName = '';
|
||||
if (toolCall?.type === 'function') {
|
||||
toolName = toolCall.function.name;
|
||||
try {
|
||||
toolArgs = JSON.parse(toolCall.function.arguments);
|
||||
} catch {
|
||||
toolArgs = {};
|
||||
}
|
||||
}
|
||||
|
||||
// Special rendering for tools
|
||||
const renderSpecialContent = () => {
|
||||
if (toolName === 'text_editor_write' && toolArgs.file_text) {
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{toolArgs.file_text as string}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) {
|
||||
const oldLines = (toolArgs.old_str as string).split('\n');
|
||||
const newLines = (toolArgs.new_str as string).split('\n');
|
||||
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs font-mono">
|
||||
<div className="space-y-1">
|
||||
{/* Old content (removed) */}
|
||||
<div className="space-y-0">
|
||||
{oldLines.map((line, index) => (
|
||||
<div key={`old-${index}`} className="flex">
|
||||
<span className="text-red-500 select-none mr-2">-</span>
|
||||
<span className="bg-red-50 dark:bg-red-950/30 text-red-700 dark:text-red-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
|
||||
{/* New content (added) */}
|
||||
<div className="space-y-0">
|
||||
{newLines.map((line, index) => (
|
||||
<div key={`new-${index}`} className="flex">
|
||||
<span className="text-green-500 select-none mr-2">+</span>
|
||||
<span className="bg-green-50 dark:bg-green-950/30 text-green-700 dark:text-green-300 flex-1 whitespace-pre-wrap break-words">
|
||||
{line}
|
||||
</span>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
// Default rendering for other tools
|
||||
return (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
};
|
||||
|
||||
// Regular tool message rendering
|
||||
return (
|
||||
<div className="-mt-2"> {/* -mt-2 to make it snug with the previous assistant message */}
|
||||
@@ -202,13 +269,7 @@ export const AIMessageItem = memo(({
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isToolExpanded && (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words font-mono">
|
||||
{content}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{isToolExpanded && renderSpecialContent()}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -233,16 +294,19 @@ export const AIMessageItem = memo(({
|
||||
);
|
||||
}
|
||||
|
||||
// If there's no reasoning content and the main content is empty, render nothing
|
||||
if (!hasReasoningContent(message) && !getContent().trim()) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Assistant messages: left-aligned without avatar/name
|
||||
return (
|
||||
<div className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm">
|
||||
<div className="text-sm space-y-3">
|
||||
{/* Reasoning content display */}
|
||||
{((reasoningContent && reasoningContent.trim()) ||
|
||||
(hasReasoningContent(message) && message.reasoning_content.trim()) ||
|
||||
(reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading)) && (
|
||||
<div className="mb-3">
|
||||
{hasReasoningContent(message) && message.reasoning_content.trim() && (
|
||||
<div>
|
||||
<button
|
||||
onClick={() => setIsReasoningExpanded(!isReasoningExpanded)}
|
||||
className={cn(
|
||||
@@ -250,7 +314,7 @@ export const AIMessageItem = memo(({
|
||||
"hover:bg-muted/30 rounded transition-colors duration-200"
|
||||
)}
|
||||
>
|
||||
{reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading ? (
|
||||
{!getContent().trim() && isCurrentlyLoading ? (
|
||||
<Loader2 className="h-3 w-3 text-muted-foreground flex-shrink-0 animate-spin" />
|
||||
) : (
|
||||
<Lightbulb className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||
@@ -260,7 +324,7 @@ export const AIMessageItem = memo(({
|
||||
</span>
|
||||
</button>
|
||||
|
||||
{isReasoningExpanded && (reasoningContent?.trim() || (hasReasoningContent(message) && message.reasoning_content.trim())) && (
|
||||
{isReasoningExpanded && (
|
||||
<div className="mt-1 p-3 bg-muted/30 rounded border text-xs">
|
||||
<div className="whitespace-pre-wrap break-words">
|
||||
<Streamdown
|
||||
@@ -268,7 +332,7 @@ export const AIMessageItem = memo(({
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
|
||||
>
|
||||
{reasoningContent || (hasReasoningContent(message) ? message.reasoning_content : '') || ''}
|
||||
{message.reasoning_content}
|
||||
</Streamdown>
|
||||
</div>
|
||||
</div>
|
||||
@@ -276,15 +340,18 @@ export const AIMessageItem = memo(({
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
|
||||
>
|
||||
{getContent()}
|
||||
</Streamdown>
|
||||
</div>
|
||||
{/* Main content display */}
|
||||
{getContent().trim() && (
|
||||
<div className="break-words">
|
||||
<Streamdown
|
||||
className='size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0'
|
||||
parseIncompleteMarkdown={isCurrentlyLoading}
|
||||
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
|
||||
>
|
||||
{getContent()}
|
||||
</Streamdown>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Tool calls are now hidden from assistant messages */}
|
||||
</div>
|
||||
|
||||
+23
-243
@@ -4,192 +4,45 @@ import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuSeparator,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import {
|
||||
GitBranch,
|
||||
MoreHorizontal,
|
||||
MessageSquarePlus,
|
||||
Play,
|
||||
CloudUpload,
|
||||
Loader2,
|
||||
GitBranch,
|
||||
Download,
|
||||
Trash2,
|
||||
GitMerge,
|
||||
History,
|
||||
Folder,
|
||||
} from 'lucide-react';
|
||||
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ActionsMenuProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
onNewChat: () => void;
|
||||
onBuild: () => void;
|
||||
onDeploy: () => void;
|
||||
onProjectDetails?: () => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
isDeployLoading?: boolean;
|
||||
disabled?: boolean;
|
||||
onFirstInteraction?: () => void;
|
||||
onProjectDeleted?: () => void;
|
||||
}
|
||||
|
||||
export function ActionsMenu({
|
||||
projectId,
|
||||
projectName,
|
||||
projectName: _projectName,
|
||||
onNewChat,
|
||||
onBuild,
|
||||
onDeploy,
|
||||
onProjectDetails,
|
||||
isLoading = false,
|
||||
isBuildLoading = false,
|
||||
isDeployLoading = false,
|
||||
disabled = false,
|
||||
onFirstInteraction,
|
||||
onProjectDeleted
|
||||
onFirstInteraction: _onFirstInteraction,
|
||||
}: ActionsMenuProps) {
|
||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||
const [gitDialogOpen, setGitDialogOpen] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
|
||||
const navigate = useNavigate();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const isAnyLoading = isLoading || isBuildLoading;
|
||||
|
||||
const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting;
|
||||
|
||||
const handleDeleteProject = async () => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await projectsManager.deleteProject(projectId);
|
||||
|
||||
toast({
|
||||
title: "Project deleted",
|
||||
description: `"${projectName}" has been permanently deleted.`,
|
||||
});
|
||||
|
||||
// Navigate back to home and notify parent
|
||||
navigate('/');
|
||||
if (onProjectDeleted) {
|
||||
onProjectDeleted();
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to delete project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportProject = async () => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const zip = new JSZip();
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Recursive function to add files and directories to zip from a specific project
|
||||
const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => {
|
||||
try {
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zipFolder.folder(entry.name);
|
||||
if (folder) {
|
||||
await addProjectToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await fs.readFile(fullPath);
|
||||
zipFolder.file(entry.name, fileContent);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read file ${fullPath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read directory ${dirPath}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Start from the project directory
|
||||
await addProjectToZip(projectPath, zip);
|
||||
|
||||
// Generate zip file
|
||||
const content = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create download link
|
||||
const url = URL.createObjectURL(content);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
|
||||
// Generate filename with commit hash
|
||||
let filename = `${projectName}.zip`;
|
||||
try {
|
||||
// Get the current commit hash
|
||||
const commits = await git.log({
|
||||
dir: projectPath,
|
||||
depth: 1,
|
||||
});
|
||||
|
||||
if (commits.length > 0) {
|
||||
const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters
|
||||
filename = `${projectName}-${commitHash}.zip`;
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to get commit hash, using project name only:', error);
|
||||
}
|
||||
|
||||
link.download = filename;
|
||||
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
toast({
|
||||
title: "Project exported successfully",
|
||||
description: `"${projectName}" has been downloaded as a zip file.`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to export project:', error);
|
||||
toast({
|
||||
title: "Failed to export project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -215,109 +68,34 @@ export function ActionsMenu({
|
||||
New Chat
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitMerge className="h-4 w-4" />
|
||||
Git Status
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitHistoryOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<History className="h-4 w-4" />
|
||||
Rollback
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => setGitDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Git History
|
||||
</DropdownMenuItem>
|
||||
|
||||
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={handleExportProject}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isExporting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4" />
|
||||
)}
|
||||
{isExporting ? 'Exporting...' : 'Export Project'}
|
||||
Repository
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (onFirstInteraction) onFirstInteraction();
|
||||
onBuild();
|
||||
}}
|
||||
onClick={onProjectDetails}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Play className="h-4 w-4" />
|
||||
)}
|
||||
{isBuildLoading ? 'Building...' : 'Build'}
|
||||
<Folder className="h-4 w-4" />
|
||||
Project Details
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuItem
|
||||
onClick={() => {
|
||||
if (onFirstInteraction) onFirstInteraction();
|
||||
onDeploy();
|
||||
}}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isDeployLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<CloudUpload className="h-4 w-4" />
|
||||
)}
|
||||
{isDeployLoading ? 'Deploying...' : 'Deploy'}
|
||||
</DropdownMenuItem>
|
||||
|
||||
<DropdownMenuSeparator />
|
||||
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<DropdownMenuItem
|
||||
className="text-destructive focus:text-destructive cursor-pointer gap-2"
|
||||
onSelect={(e) => e.preventDefault()}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete Project
|
||||
</DropdownMenuItem>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Project</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete "{projectName}"? This action cannot be undone and will permanently delete all project data including files.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteProject}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Deleting...
|
||||
</>
|
||||
) : (
|
||||
'Delete Project'
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
|
||||
@@ -333,6 +111,8 @@ export function ActionsMenu({
|
||||
open={gitHistoryOpen}
|
||||
onOpenChange={setGitHistoryOpen}
|
||||
/>
|
||||
|
||||
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -20,7 +20,6 @@ const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
|
||||
relayUrl: z.string().url(),
|
||||
deployServer: z.string().min(1),
|
||||
language: z.string().optional(),
|
||||
filesystemType: z.enum(['lightningfs', 'opfs']),
|
||||
});
|
||||
|
||||
export function AppProvider(props: AppProviderProps) {
|
||||
|
||||
@@ -1,207 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Settings, Save, Database, AlertTriangle } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
|
||||
interface AppSettingsDialogProps {
|
||||
children?: React.ReactNode;
|
||||
}
|
||||
|
||||
export function AppSettingsDialog({ children }: AppSettingsDialogProps) {
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [deployServer, setDeployServer] = useState(config.deployServer);
|
||||
const [filesystemType, setFilesystemType] = useState(config.filesystemType);
|
||||
const [opfsAvailable, setOpfsAvailable] = useState(false);
|
||||
|
||||
// Check OPFS availability on mount
|
||||
useEffect(() => {
|
||||
const checkOPFSAvailability = () => {
|
||||
const available = 'storage' in navigator && !!((navigator.storage as unknown as { getDirectory: () => FileSystemDirectoryHandle }).getDirectory);
|
||||
setOpfsAvailable(available);
|
||||
};
|
||||
|
||||
checkOPFSAvailability();
|
||||
}, []);
|
||||
|
||||
const handleSave = () => {
|
||||
// Validate deploy server
|
||||
if (!deployServer.trim()) {
|
||||
toast({
|
||||
title: "Invalid deploy server",
|
||||
description: "Deploy server cannot be empty.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate filesystem type
|
||||
if (filesystemType === 'opfs' && !opfsAvailable) {
|
||||
toast({
|
||||
title: "OPFS not available",
|
||||
description: "OPFS is not supported in your browser. Please use LightningFS instead.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove protocol if present
|
||||
const cleanDeployServer = deployServer.replace(/^https?:\/\//, '');
|
||||
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
deployServer: cleanDeployServer,
|
||||
filesystemType,
|
||||
}));
|
||||
|
||||
toast({
|
||||
title: "Settings saved",
|
||||
description: "Your settings have been updated. The page will refresh to apply the new filesystem.",
|
||||
});
|
||||
|
||||
// Refresh the page to apply filesystem changes
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
const handleCancel = () => {
|
||||
// Reset to current config
|
||||
setDeployServer(config.deployServer);
|
||||
setFilesystemType(config.filesystemType);
|
||||
setOpen(false);
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
{children || (
|
||||
<Button variant="outline" size="sm">
|
||||
<Settings className="h-4 w-4 mr-2" />
|
||||
Settings
|
||||
</Button>
|
||||
)}
|
||||
</DialogTrigger>
|
||||
<DialogContent className="sm:max-w-[500px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>App Settings</DialogTitle>
|
||||
<DialogDescription>
|
||||
Configure your application preferences and deployment settings.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-6">
|
||||
{/* Filesystem Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg flex items-center gap-2">
|
||||
<Database className="h-5 w-5" />
|
||||
Filesystem
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>Filesystem Type</Label>
|
||||
<RadioGroup
|
||||
value={filesystemType}
|
||||
onValueChange={(value) => setFilesystemType(value as 'lightningfs' | 'opfs')}
|
||||
className="grid grid-cols-1 gap-3"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="lightningfs" id="lightningfs" />
|
||||
<Label htmlFor="lightningfs" className="cursor-pointer">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">LightningFS (IndexedDB)</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Uses IndexedDB for storage. Works in all modern browsers.
|
||||
</span>
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="opfs"
|
||||
id="opfs"
|
||||
disabled={!opfsAvailable}
|
||||
/>
|
||||
<Label htmlFor="opfs" className={`cursor-pointer ${!opfsAvailable ? 'opacity-50' : ''}`}>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium flex items-center gap-2">
|
||||
OPFS (Origin Private File System)
|
||||
{!opfsAvailable && (
|
||||
<AlertTriangle className="h-4 w-4 text-orange-500" />
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{opfsAvailable
|
||||
? "Modern browser API with better performance and larger storage limits."
|
||||
: "Not available in this browser. Use Chrome, Edge, or Firefox 111+."
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{!opfsAvailable && filesystemType === 'opfs' && (
|
||||
<div className="flex items-center gap-2 p-3 bg-orange-50 dark:bg-orange-950/20 rounded-md border border-orange-200 dark:border-orange-800">
|
||||
<AlertTriangle className="h-4 w-4 text-orange-600 dark:text-orange-400" />
|
||||
<span className="text-sm text-orange-800 dark:text-orange-200">
|
||||
OPFS is not available in your browser. Please use LightningFS or upgrade to a modern browser.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p><strong>Note:</strong> Changing the filesystem type will refresh the page and may cause data loss if not properly exported first.</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">Deployment</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deployServer">Deploy Server</Label>
|
||||
<Input
|
||||
id="deployServer"
|
||||
value={deployServer}
|
||||
onChange={(e) => setDeployServer(e.target.value)}
|
||||
placeholder="shakespeare.wtf"
|
||||
className="font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your projects will be deployed to subdomains of this server.
|
||||
Example: yourproject.{deployServer || 'shakespeare.wtf'}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end space-x-2">
|
||||
<Button variant="outline" onClick={handleCancel}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button onClick={handleSave}>
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
Save Settings
|
||||
</Button>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -3,7 +3,6 @@ import { render, screen, fireEvent } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { CreditsBadge } from './CreditsBadge';
|
||||
|
||||
|
||||
// Mock the useAICredits hook
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
useAICredits: () => ({
|
||||
@@ -16,7 +15,8 @@ vi.mock('@/hooks/useAICredits', () => ({
|
||||
// Mock the fetch function
|
||||
global.fetch = vi.fn();
|
||||
|
||||
const mockConnection = {
|
||||
const mockProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
};
|
||||
@@ -25,10 +25,7 @@ describe('CreditsBadge', () => {
|
||||
it('renders the credits amount', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
/>
|
||||
<CreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
@@ -41,8 +38,7 @@ describe('CreditsBadge', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
onOpenDialog={mockCallback}
|
||||
/>
|
||||
</TestApp>
|
||||
@@ -57,10 +53,7 @@ describe('CreditsBadge', () => {
|
||||
it('has proper styling for clickable badge', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
/>
|
||||
<CreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
@@ -72,10 +65,7 @@ describe('CreditsBadge', () => {
|
||||
it('does not render dialog directly', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<CreditsBadge
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
/>
|
||||
<CreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
|
||||
@@ -1,13 +1,9 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
|
||||
interface CreditsBadgeProps {
|
||||
providerId: string;
|
||||
connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
};
|
||||
provider: AIProvider;
|
||||
className?: string;
|
||||
onOpenDialog?: () => void;
|
||||
}
|
||||
@@ -15,8 +11,8 @@ interface CreditsBadgeProps {
|
||||
/**
|
||||
* Displays a clickable credits badge showing the remaining credits for an AI provider
|
||||
*/
|
||||
export function CreditsBadge({ providerId, connection, className, onOpenDialog }: CreditsBadgeProps) {
|
||||
const { data: credits, isLoading, error } = useAICredits(providerId, connection);
|
||||
export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadgeProps) {
|
||||
const { data: credits, isLoading, error } = useAICredits(provider);
|
||||
|
||||
// Don't render anything if there's an error (provider doesn't support credits endpoint)
|
||||
if (error || isLoading) {
|
||||
|
||||
@@ -2,14 +2,16 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { CreditsDialog } from './CreditsDialog';
|
||||
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock the fetch function
|
||||
global.fetch = vi.fn();
|
||||
|
||||
const mockConnection = {
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
nostr: false,
|
||||
};
|
||||
|
||||
describe('CreditsDialog', () => {
|
||||
@@ -19,8 +21,7 @@ describe('CreditsDialog', () => {
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -36,8 +37,7 @@ describe('CreditsDialog', () => {
|
||||
<CreditsDialog
|
||||
open={false}
|
||||
onOpenChange={() => {}}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -51,8 +51,7 @@ describe('CreditsDialog', () => {
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -67,8 +66,7 @@ describe('CreditsDialog', () => {
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -89,8 +87,7 @@ describe('CreditsDialog', () => {
|
||||
<CreditsDialog
|
||||
open={false}
|
||||
onOpenChange={mockCallback}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -101,8 +98,7 @@ describe('CreditsDialog', () => {
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={mockCallback}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
@@ -13,15 +13,12 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
interface CreditsDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
providerId: string;
|
||||
connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
};
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
interface Payment {
|
||||
@@ -184,7 +181,7 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
|
||||
);
|
||||
}
|
||||
|
||||
export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) {
|
||||
export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
@@ -196,9 +193,9 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
|
||||
|
||||
// Query for payment history
|
||||
const { data: payments, isLoading: isLoadingPayments } = useQuery({
|
||||
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
|
||||
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
queryFn: async (): Promise<Payment[]> => {
|
||||
const ai = createAIClient(connection, user);
|
||||
const ai = createAIClient(provider, user);
|
||||
const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse;
|
||||
return data.data;
|
||||
},
|
||||
@@ -210,7 +207,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
|
||||
// Mutation for adding credits
|
||||
const addCreditsMutation = useMutation({
|
||||
mutationFn: async (request: AddCreditsRequest): Promise<Payment> => {
|
||||
const ai = createAIClient(connection, user);
|
||||
const ai = createAIClient(provider, user);
|
||||
return await ai.post('/credits/add', {
|
||||
body: request,
|
||||
}) as Payment;
|
||||
@@ -230,12 +227,12 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
|
||||
|
||||
// Refresh payments list
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
|
||||
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
|
||||
// Refresh credits balance
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
|
||||
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
},
|
||||
onError: (error: Error) => {
|
||||
@@ -251,7 +248,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
|
||||
// Mutation for checking payment status
|
||||
const checkPaymentMutation = useMutation({
|
||||
mutationFn: async (paymentId: string): Promise<Payment> => {
|
||||
const ai = createAIClient(connection, user);
|
||||
const ai = createAIClient(provider, user);
|
||||
return await ai.get(`/credits/payments/${paymentId}`) as Payment;
|
||||
},
|
||||
onMutate: async (paymentId: string) => {
|
||||
@@ -268,7 +265,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
|
||||
|
||||
// Update the specific payment in the cache instead of refetching
|
||||
queryClient.setQueryData<Payment[]>(
|
||||
['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId],
|
||||
['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
(oldPayments) => {
|
||||
if (!oldPayments) return oldPayments;
|
||||
return oldPayments.map(payment =>
|
||||
@@ -280,7 +277,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr
|
||||
// If payment completed, refresh credits balance
|
||||
if (updatedPayment.status === 'completed') {
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
|
||||
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
});
|
||||
toast({
|
||||
title: 'Payment completed!',
|
||||
|
||||
@@ -0,0 +1,182 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useMutation } from '@tanstack/react-query';
|
||||
import { deployProject } from '@/lib/deploy';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import {
|
||||
CloudUpload,
|
||||
Loader2,
|
||||
} from 'lucide-react';
|
||||
|
||||
interface DeployDialogProps {
|
||||
projectId: string;
|
||||
projectName: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onFirstInteraction?: () => void;
|
||||
}
|
||||
|
||||
export function DeployDialog({
|
||||
projectId,
|
||||
projectName,
|
||||
open,
|
||||
onOpenChange,
|
||||
onFirstInteraction
|
||||
}: DeployDialogProps) {
|
||||
const { config } = useAppContext();
|
||||
const { user } = useCurrentUser();
|
||||
const { fs } = useFS();
|
||||
const { toast } = useToast();
|
||||
|
||||
// State for the deploy URL input
|
||||
const [deployUrl, setDeployUrl] = useState('');
|
||||
|
||||
// Initialize deploy URL when dialog opens
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setDeployUrl(`${projectId}.${config.deployServer}`);
|
||||
}
|
||||
}, [open, projectId, config.deployServer]);
|
||||
|
||||
const deployMutation = useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!user) {
|
||||
throw new Error("You must be logged into Nostr to deploy a project");
|
||||
}
|
||||
|
||||
// Parse the deploy URL to extract hostname and server
|
||||
const hostname = deployUrl.trim();
|
||||
const parts = hostname.split('.');
|
||||
|
||||
if (parts.length < 2) {
|
||||
throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com");
|
||||
}
|
||||
|
||||
// Extract the deploy server (everything after the first dot)
|
||||
const deployServer = parts.slice(1).join('.');
|
||||
|
||||
return await deployProject({
|
||||
fs,
|
||||
projectId, // Keep the original projectId for file path
|
||||
deployServer,
|
||||
projectPath: `/projects/${projectId}`,
|
||||
signer: user.signer,
|
||||
customHostname: hostname, // Pass the custom hostname
|
||||
});
|
||||
},
|
||||
onSuccess: (result) => {
|
||||
toast({
|
||||
title: "Deployment successful!",
|
||||
description: `Your project is now live at ${result.hostname}`,
|
||||
});
|
||||
|
||||
// Open the deployed site in a new tab
|
||||
window.open(result.url, '_blank');
|
||||
|
||||
// Close the dialog
|
||||
onOpenChange(false);
|
||||
},
|
||||
onError: (error) => {
|
||||
toast({
|
||||
title: "Deployment failed",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
const handleDeploy = () => {
|
||||
if (onFirstInteraction) {
|
||||
onFirstInteraction();
|
||||
}
|
||||
deployMutation.mutate();
|
||||
};
|
||||
|
||||
const handleUrlChange = (value: string) => {
|
||||
// Remove protocol if user enters it
|
||||
const cleanValue = value.replace(/^https?:\/\//, '');
|
||||
setDeployUrl(cleanValue);
|
||||
};
|
||||
|
||||
const isValidUrl = () => {
|
||||
const trimmed = deployUrl.trim();
|
||||
return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.');
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<CloudUpload className="h-5 w-5" />
|
||||
Deploy "{projectName}"
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deploy-url">Deploy URL</Label>
|
||||
<div className="relative">
|
||||
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
|
||||
https://
|
||||
</span>
|
||||
<Input
|
||||
id="deploy-url"
|
||||
value={deployUrl}
|
||||
onChange={(e) => handleUrlChange(e.target.value)}
|
||||
placeholder={`${projectId}.${config.deployServer}`}
|
||||
className="pl-16"
|
||||
disabled={deployMutation.isPending}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Your project will be deployed to this URL. You can customize the subdomain.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!user && (
|
||||
<div className="p-3 bg-muted rounded-lg">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
You must be logged into Nostr to deploy projects.
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
<DialogFooter>
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={() => onOpenChange(false)}
|
||||
disabled={deployMutation.isPending}
|
||||
>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleDeploy}
|
||||
disabled={!user || !isValidUrl() || deployMutation.isPending}
|
||||
className="gap-2"
|
||||
>
|
||||
{deployMutation.isPending ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<CloudUpload className="h-4 w-4" />
|
||||
)}
|
||||
{deployMutation.isPending ? 'Deploying...' : 'Deploy'}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -43,17 +43,10 @@ vi.mock('@/hooks/useToast', () => ({
|
||||
})),
|
||||
}));
|
||||
|
||||
const mockUseGitSettings = vi.fn();
|
||||
|
||||
vi.mock('@/hooks/useGitSettings', () => ({
|
||||
useGitSettings: vi.fn(() => ({
|
||||
settings: {
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
},
|
||||
},
|
||||
})),
|
||||
useGitSettings: () => mockUseGitSettings(),
|
||||
}));
|
||||
|
||||
describe('GitDialog', () => {
|
||||
@@ -62,9 +55,20 @@ describe('GitDialog', () => {
|
||||
data: baseGitStatus,
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {
|
||||
'https://github.com': {
|
||||
username: 'git',
|
||||
password: 'github-token',
|
||||
},
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('renders git repository information', () => {
|
||||
it('renders git dialog without repository information section', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -73,11 +77,9 @@ describe('GitDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Git Repository Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Repository Information')).toBeInTheDocument();
|
||||
expect(screen.getByText('main')).toBeInTheDocument();
|
||||
expect(screen.getByText('5')).toBeInTheDocument();
|
||||
expect(screen.getAllByText('origin')).toHaveLength(2); // Appears in remotes and credentials sections
|
||||
expect(screen.getByText('Repository')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Repository Information')).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows sync status', () => {
|
||||
@@ -145,7 +147,7 @@ describe('GitDialog', () => {
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('shows configured credentials status', () => {
|
||||
it('does not show credentials warning when credentials are configured', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -154,8 +156,38 @@ describe('GitDialog', () => {
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Authentication')).toBeInTheDocument();
|
||||
expect(screen.getByText('github.com')).toBeInTheDocument();
|
||||
expect(screen.getByText('Configured')).toBeInTheDocument();
|
||||
// Should not show warning when credentials are configured
|
||||
expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows credentials warning when no credentials are configured', () => {
|
||||
// Mock git settings with no credentials and mock git status with an https remote
|
||||
mockUseGitSettings.mockReturnValue({
|
||||
settings: {
|
||||
credentials: {},
|
||||
},
|
||||
});
|
||||
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }],
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Should show warning when credentials are missing
|
||||
expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument();
|
||||
expect(screen.getByText('log in')).toBeInTheDocument();
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
});
|
||||
+192
-180
@@ -1,10 +1,9 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogTrigger,
|
||||
@@ -19,6 +18,8 @@ import {
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import {
|
||||
GitBranch,
|
||||
Upload,
|
||||
@@ -31,10 +32,9 @@ import {
|
||||
Plus,
|
||||
Minus,
|
||||
Edit,
|
||||
RefreshCw,
|
||||
Settings,
|
||||
AlertTriangle,
|
||||
Zap,
|
||||
Save,
|
||||
} from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
@@ -44,7 +44,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"];
|
||||
@@ -60,8 +60,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isPushing, setIsPushing] = useState(false);
|
||||
const [isPulling, setIsPulling] = useState(false);
|
||||
const [isPushingToNostr, setIsPushingToNostr] = useState(false);
|
||||
const [pushResult, setPushResult] = useState<string | null>(null);
|
||||
const [pullResult, setPullResult] = useState<string | null>(null);
|
||||
const [originUrl, setOriginUrl] = useState('');
|
||||
const [isSavingOrigin, setIsSavingOrigin] = useState(false);
|
||||
const navigate = useNavigate();
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
@@ -74,6 +74,70 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Initialize origin URL from git status
|
||||
useEffect(() => {
|
||||
if (gitStatus?.remotes) {
|
||||
const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin');
|
||||
setOriginUrl(originRemote?.url || '');
|
||||
}
|
||||
}, [gitStatus?.remotes]);
|
||||
|
||||
const handleSaveOrigin = async () => {
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
toast({
|
||||
title: "Cannot configure origin",
|
||||
description: "Not a git repository",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSavingOrigin(true);
|
||||
|
||||
try {
|
||||
// Remove existing origin if it exists
|
||||
try {
|
||||
await git.deleteRemote({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
});
|
||||
} catch {
|
||||
// Ignore if origin doesn't exist
|
||||
}
|
||||
|
||||
// Add new origin if URL is provided
|
||||
if (originUrl.trim()) {
|
||||
await git.addRemote({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
url: originUrl.trim(),
|
||||
});
|
||||
|
||||
toast({
|
||||
title: "Origin configured",
|
||||
description: `Origin remote set to ${originUrl.trim()}`,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Origin removed",
|
||||
description: "Origin remote has been removed",
|
||||
});
|
||||
}
|
||||
|
||||
// Refresh git status after changing origin
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: "Failed to configure origin",
|
||||
description: errorMessage,
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSavingOrigin(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handlePushToNostr = async () => {
|
||||
if (!user) {
|
||||
toast({
|
||||
@@ -94,7 +158,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
|
||||
setIsPushingToNostr(true);
|
||||
setPushResult(null);
|
||||
|
||||
try {
|
||||
// Check if repo announcement already exists
|
||||
@@ -265,10 +328,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
description: "Waiting for GRASP servers to update...",
|
||||
});
|
||||
|
||||
setPushResult(`✅ Successfully published repository to Nostr`);
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
setPushResult(`❌ Push to Nostr failed: ${errorMessage}`);
|
||||
toast({
|
||||
title: "Push to Nostr failed",
|
||||
description: errorMessage,
|
||||
@@ -308,7 +369,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
|
||||
setIsPushing(true);
|
||||
setPushResult(null);
|
||||
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
@@ -321,7 +381,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
signer: user?.signer, // For signing if pushing to Nostr
|
||||
});
|
||||
|
||||
setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`);
|
||||
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
@@ -331,7 +391,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
setPushResult(`❌ Push failed: ${errorMessage}`);
|
||||
toast({
|
||||
title: "Push failed",
|
||||
description: errorMessage,
|
||||
@@ -362,7 +421,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
|
||||
setIsPulling(true);
|
||||
setPullResult(null);
|
||||
|
||||
try {
|
||||
const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin')
|
||||
@@ -378,7 +436,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
onAuth: (url) => findCredentialsForRepo(url, settings.credentials),
|
||||
});
|
||||
|
||||
setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`);
|
||||
|
||||
toast({
|
||||
title: "Pull successful",
|
||||
description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`,
|
||||
@@ -388,7 +446,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
setPullResult(`❌ Pull failed: ${errorMessage}`);
|
||||
toast({
|
||||
title: "Pull failed",
|
||||
description: errorMessage,
|
||||
@@ -399,11 +456,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
};
|
||||
|
||||
const handleRefresh = async () => {
|
||||
await refetchGitStatus();
|
||||
setPushResult(null);
|
||||
setPullResult(null);
|
||||
};
|
||||
|
||||
|
||||
const getFileStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
@@ -473,158 +526,131 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
{children && <DialogTrigger asChild>{children}</DialogTrigger>}
|
||||
<DialogContent className="max-w-2xl max-h-[80vh]">
|
||||
<DialogContent className="max-w-2xl max-h-[80vh]" onOpenAutoFocus={(e) => e.preventDefault()}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitBranch className="h-5 w-5" />
|
||||
Git Repository Status
|
||||
Repository
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
View repository status and sync with remote repositories
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{/* URL Configuration */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm">Git URL</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
<div className="flex gap-2">
|
||||
<div className="flex-1">
|
||||
<Label htmlFor="origin-url" className="sr-only">
|
||||
URL
|
||||
</Label>
|
||||
<Input
|
||||
id="origin-url"
|
||||
placeholder="https://github.com/username/repository.git"
|
||||
value={originUrl}
|
||||
onChange={(e) => setOriginUrl(e.target.value)}
|
||||
disabled={isSavingOrigin}
|
||||
/>
|
||||
</div>
|
||||
<Button
|
||||
onClick={handleSaveOrigin}
|
||||
disabled={isSavingOrigin}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-10 shrink-0"
|
||||
>
|
||||
{isSavingOrigin ? (
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isSavingOrigin ? 'Saving...' : 'Save'}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Credentials Warning */}
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
(() => {
|
||||
const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials));
|
||||
if (!remoteWithoutCredentials) return null;
|
||||
|
||||
let protocol = '';
|
||||
let hostname = 'the remote host';
|
||||
try {
|
||||
const url = new URL(remoteWithoutCredentials.url);
|
||||
protocol = url.protocol;
|
||||
hostname = url.hostname;
|
||||
} catch {
|
||||
// Invalid URL
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
Invalid URL format. Enter an https URL.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// Check for unsupported protocols
|
||||
if (protocol !== 'https:' && protocol !== 'nostr:') {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
The {protocol.replace(':', '')} URL type is not supported. Enter an https URL.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// For nostr protocol, only show warning if user is not logged in
|
||||
if (protocol === 'nostr:' && !user) {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
You are not logged into Nostr. Push & pull might not work unless you{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/nostr')}
|
||||
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
log in
|
||||
</button>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
// For https protocol, show warning if no credentials
|
||||
if (protocol === 'https:') {
|
||||
return (
|
||||
<Alert className="border-amber-200 bg-amber-50 dark:border-amber-800 dark:bg-amber-950/50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
You are not logged into {hostname}. Push & pull might not work unless you{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="underline hover:no-underline font-medium text-amber-700 dark:text-amber-300"
|
||||
>
|
||||
log in
|
||||
</button>.
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
);
|
||||
}
|
||||
|
||||
return null;
|
||||
})()
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-4">
|
||||
{/* Repository Info */}
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm flex items-center justify-between">
|
||||
Repository Information
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleRefresh}
|
||||
className="h-7 w-7 p-0"
|
||||
>
|
||||
<RefreshCw className="h-3 w-3" />
|
||||
</Button>
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{gitStatus?.isGitRepo ? (
|
||||
<>
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Current Branch:</span>
|
||||
<Badge variant="outline" className="font-mono">
|
||||
{gitStatus.currentBranch || 'unknown'}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center justify-between">
|
||||
<span className="text-sm text-muted-foreground">Total Commits:</span>
|
||||
<Badge variant="secondary">{gitStatus.totalCommits}</Badge>
|
||||
</div>
|
||||
|
||||
{gitStatus.latestCommit && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-sm text-muted-foreground">Latest Commit:</span>
|
||||
<div className="bg-muted/50 rounded-md p-2 space-y-1">
|
||||
<div className="font-mono text-xs text-muted-foreground">
|
||||
{gitStatus.latestCommit.oid.substring(0, 7)}
|
||||
</div>
|
||||
<div className="text-sm">{gitStatus.latestCommit.message}</div>
|
||||
<div className="text-xs text-muted-foreground flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(gitStatus.latestCommit.author.timestamp * 1000).toLocaleString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<span className="text-sm text-muted-foreground">Remotes:</span>
|
||||
{gitStatus.remotes.map((remote) => (
|
||||
<div key={remote.name} className="bg-muted/50 rounded-md p-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<Badge variant="outline">{remote.name}</Badge>
|
||||
<span className="font-mono text-xs text-muted-foreground truncate ml-2">
|
||||
{remote.url}
|
||||
</span>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
<div className="text-center py-4 text-muted-foreground">
|
||||
<AlertCircle className="h-8 w-8 mx-auto mb-2" />
|
||||
<p>Not a Git repository</p>
|
||||
</div>
|
||||
)}
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Credentials Status */}
|
||||
{gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && (
|
||||
<Card>
|
||||
<CardHeader className="pb-3">
|
||||
<CardTitle className="text-sm flex items-center justify-between">
|
||||
Authentication
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="h-7 gap-1 text-xs"
|
||||
>
|
||||
<Settings className="h-3 w-3" />
|
||||
Settings
|
||||
</Button>
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Credentials for push/pull operations
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-3">
|
||||
{gitStatus.remotes.map((remote) => {
|
||||
const credentials = findCredentialsForRepo(remote.url, settings.credentials);
|
||||
const originDisplayName = getOriginDisplayName(remote.url);
|
||||
|
||||
return (
|
||||
<div key={remote.name} className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex items-center gap-2">
|
||||
<Badge variant="outline">{remote.name}</Badge>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{originDisplayName}
|
||||
</span>
|
||||
</div>
|
||||
{credentials ? (
|
||||
<div className="flex items-center gap-1 text-green-600">
|
||||
<CheckCircle className="h-3 w-3" />
|
||||
<span className="text-xs">Configured</span>
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex items-center gap-1 text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs">No credentials</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{!credentials && (
|
||||
<Alert className="border-amber-200 bg-amber-50">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
<AlertDescription className="text-sm">
|
||||
No credentials configured for {originDisplayName}.
|
||||
Push/pull operations may fail for private repositories.{' '}
|
||||
<button
|
||||
onClick={() => navigate('/settings/git')}
|
||||
className="underline hover:no-underline font-medium"
|
||||
>
|
||||
Configure credentials
|
||||
</button>
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
{/* Sync Status */}
|
||||
{gitStatus?.isGitRepo && (
|
||||
@@ -694,21 +720,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Operation Results */}
|
||||
{(pushResult || pullResult) && (
|
||||
<div className="mt-3 space-y-2">
|
||||
{pushResult && (
|
||||
<div className="text-xs font-mono bg-muted/50 rounded p-2">
|
||||
{pushResult}
|
||||
</div>
|
||||
)}
|
||||
{pullResult && (
|
||||
<div className="text-xs font-mono bg-muted/50 rounded p-2">
|
||||
{pullResult}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
</CardContent>
|
||||
</Card>
|
||||
)}
|
||||
|
||||
@@ -179,7 +179,7 @@ describe('GitSettingsProvider', () => {
|
||||
password: 'test-token',
|
||||
}
|
||||
},
|
||||
corsProxy: 'https://cors.isomorphic-git.org'
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}'
|
||||
})
|
||||
);
|
||||
});
|
||||
@@ -220,7 +220,7 @@ describe('GitSettingsProvider', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
|
||||
});
|
||||
});
|
||||
|
||||
@@ -232,7 +232,7 @@ describe('GitSettingsProvider', () => {
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org');
|
||||
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
|
||||
});
|
||||
|
||||
fireEvent.click(screen.getByText('Update CORS Proxy'));
|
||||
|
||||
@@ -9,7 +9,7 @@ interface GitSettingsProviderProps {
|
||||
|
||||
const DEFAULT_SETTINGS: GitSettings = {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
@@ -22,6 +22,10 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
|
||||
const initializeSettings = async () => {
|
||||
try {
|
||||
const settings = await readGitSettings(fs);
|
||||
// Migrate old CORS proxy format
|
||||
if (settings.corsProxy === 'https://cors.isomorphic-git.org') {
|
||||
settings.corsProxy = DEFAULT_SETTINGS.corsProxy;
|
||||
}
|
||||
setSettings(settings);
|
||||
} catch (error) {
|
||||
console.error('Failed to initialize Git settings:', error);
|
||||
|
||||
@@ -47,6 +47,24 @@ export function LanguagePicker({ className }: LanguagePickerProps) {
|
||||
{t('chinese')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="ha">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇳🇬</span>
|
||||
{t('hausa')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="yo">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇳🇬</span>
|
||||
{t('yoruba')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
<SelectItem value="ig">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-lg">🇳🇬</span>
|
||||
{t('igbo')}
|
||||
</div>
|
||||
</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Mock QRCode
|
||||
vi.mock('qrcode', () => ({
|
||||
@@ -18,9 +19,11 @@ const mockWebLN = {
|
||||
// We need to import the component after mocking
|
||||
const { CreditsDialog } = await import('./CreditsDialog');
|
||||
|
||||
const mockConnection = {
|
||||
const mockProvider: AIProvider = {
|
||||
id: 'test-provider',
|
||||
baseURL: 'https://api.test.com/v1',
|
||||
apiKey: 'test-key',
|
||||
nostr: false,
|
||||
};
|
||||
|
||||
describe('Lightning Payment', () => {
|
||||
@@ -39,8 +42,7 @@ describe('Lightning Payment', () => {
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -61,8 +63,7 @@ describe('Lightning Payment', () => {
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
@@ -77,8 +78,7 @@ describe('Lightning Payment', () => {
|
||||
<CreditsDialog
|
||||
open={true}
|
||||
onOpenChange={() => {}}
|
||||
providerId="test-provider"
|
||||
connection={mockConnection}
|
||||
provider={mockProvider}
|
||||
/>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
@@ -17,6 +17,8 @@ interface ModelSelectorProps {
|
||||
className?: string;
|
||||
disabled?: boolean;
|
||||
placeholder?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ModelSelector({
|
||||
@@ -25,9 +27,16 @@ export function ModelSelector({
|
||||
className,
|
||||
disabled = false,
|
||||
placeholder,
|
||||
open: controlledOpen,
|
||||
onOpenChange: setControlledOpen,
|
||||
}: ModelSelectorProps) {
|
||||
const { t } = useTranslation();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
|
||||
|
||||
// Use controlled state if provided, otherwise use local state
|
||||
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
|
||||
const setOpen = setControlledOpen || setUncontrolledOpen;
|
||||
|
||||
const [isCustomInput, setIsCustomInput] = useState(false);
|
||||
const [customValue, setCustomValue] = useState('');
|
||||
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
|
||||
@@ -140,23 +149,23 @@ export function ModelSelector({
|
||||
|
||||
return (
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
|
||||
className
|
||||
)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<span className="w-full truncate">
|
||||
{value || placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
role="combobox"
|
||||
aria-expanded={open}
|
||||
className={cn(
|
||||
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
|
||||
className
|
||||
)}
|
||||
disabled={disabled}
|
||||
>
|
||||
<span className="w-full truncate">
|
||||
{value || placeholder || defaultPlaceholder}
|
||||
</span>
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-96 p-0" align="end">
|
||||
<Command>
|
||||
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
|
||||
|
||||
@@ -243,9 +243,16 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{model.name ?? model.id}
|
||||
</CardTitle>
|
||||
<div className="flex-1">
|
||||
<CardTitle className="text-base font-semibold">
|
||||
{model.description || model.name || model.id}
|
||||
</CardTitle>
|
||||
{model.description && (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{model.name || model.id}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
{isFree && (
|
||||
<Badge variant="secondary" className="text-xs">
|
||||
@@ -261,11 +268,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</CardHeader>
|
||||
<CardContent className="pt-0">
|
||||
{model.description && (
|
||||
<p className="text-sm text-muted-foreground mb-3">
|
||||
{model.description}
|
||||
</p>
|
||||
)}
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<>
|
||||
@@ -332,8 +334,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
handleCreditsDialogClose();
|
||||
}
|
||||
}}
|
||||
providerId="shakespeare"
|
||||
connection={SHAKESPEARE_PROVIDER}
|
||||
provider={SHAKESPEARE_PROVIDER}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,320 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import {
|
||||
AlertDialog,
|
||||
AlertDialogAction,
|
||||
AlertDialogCancel,
|
||||
AlertDialogContent,
|
||||
AlertDialogDescription,
|
||||
AlertDialogFooter,
|
||||
AlertDialogHeader,
|
||||
AlertDialogTitle,
|
||||
AlertDialogTrigger,
|
||||
} from '@/components/ui/alert-dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import {
|
||||
Calendar,
|
||||
Folder,
|
||||
Download,
|
||||
Loader2,
|
||||
Trash2,
|
||||
Save,
|
||||
} from 'lucide-react';
|
||||
import JSZip from 'jszip';
|
||||
import { Separator } from './ui/separator';
|
||||
|
||||
interface ProjectDetailsDialogProps {
|
||||
project: Project;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onProjectDeleted?: () => void;
|
||||
}
|
||||
|
||||
export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectDetailsDialogProps) {
|
||||
const [isExporting, setIsExporting] = useState(false);
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
const [newProjectName, setNewProjectName] = useState(project.id);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const navigate = useNavigate();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Reset state when project changes
|
||||
useEffect(() => {
|
||||
setNewProjectName(project.id);
|
||||
setIsRenaming(false);
|
||||
}, [project.id]);
|
||||
|
||||
const formatDistanceToNow = (date: Date) => {
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
|
||||
if (diffInSeconds < 60) return 'just now';
|
||||
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`;
|
||||
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
|
||||
if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`;
|
||||
if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} months ago`;
|
||||
return `${Math.floor(diffInSeconds / 31536000)} years ago`;
|
||||
};
|
||||
|
||||
const handleSaveProject = async () => {
|
||||
if (!newProjectName.trim() || newProjectName === project.id) {
|
||||
setNewProjectName(project.id);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsRenaming(true);
|
||||
try {
|
||||
await projectsManager.renameProject(project.id, newProjectName);
|
||||
|
||||
// Invalidate the projects query to update the sidebar
|
||||
await queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
toast({
|
||||
title: "Project renamed",
|
||||
description: `Project renamed from "${project.id}" to "${newProjectName}".`,
|
||||
});
|
||||
|
||||
// Close the dialog first
|
||||
onOpenChange(false);
|
||||
|
||||
// Navigate to the new URL
|
||||
navigate(`/project/${newProjectName}`);
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to rename project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
setNewProjectName(project.id); // Reset to original name
|
||||
} finally {
|
||||
setIsRenaming(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleDeleteProject = async () => {
|
||||
setIsDeleting(true);
|
||||
try {
|
||||
await projectsManager.deleteProject(project.id);
|
||||
|
||||
// Invalidate the projects query to update the sidebar
|
||||
await queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
toast({
|
||||
title: "Project deleted",
|
||||
description: `"${project.name}" has been permanently deleted.`,
|
||||
});
|
||||
|
||||
// Close the dialog first
|
||||
onOpenChange(false);
|
||||
|
||||
// Navigate back to home and notify parent
|
||||
navigate('/');
|
||||
if (onProjectDeleted) {
|
||||
onProjectDeleted();
|
||||
}
|
||||
} catch (error) {
|
||||
toast({
|
||||
title: "Failed to delete project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeleting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleExportProject = async () => {
|
||||
setIsExporting(true);
|
||||
try {
|
||||
const zip = new JSZip();
|
||||
const projectPath = `/projects/${project.id}`;
|
||||
|
||||
// Recursive function to add files and directories to zip from a specific project
|
||||
const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => {
|
||||
try {
|
||||
const entries = await fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
const fullPath = `${dirPath}/${entry.name}`;
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
// Create folder in zip and recursively add its contents
|
||||
const folder = zipFolder.folder(entry.name);
|
||||
if (folder) {
|
||||
await addFolderToZip(fullPath, folder);
|
||||
}
|
||||
} else if (entry.isFile()) {
|
||||
// Add file to zip
|
||||
try {
|
||||
const fileContent = await fs.readFile(fullPath);
|
||||
zipFolder.file(entry.name, fileContent);
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read file ${fullPath}:`, error);
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to read directory ${dirPath}:`, error);
|
||||
}
|
||||
};
|
||||
|
||||
// Start from the project directory
|
||||
await addFolderToZip(projectPath, zip);
|
||||
|
||||
// Generate zip file
|
||||
const content = await zip.generateAsync({ type: 'blob' });
|
||||
|
||||
// Create download link
|
||||
const url = URL.createObjectURL(content);
|
||||
const link = document.createElement('a');
|
||||
link.href = url;
|
||||
link.download = `${project.id}.zip`;
|
||||
document.body.appendChild(link);
|
||||
link.click();
|
||||
document.body.removeChild(link);
|
||||
URL.revokeObjectURL(url);
|
||||
|
||||
toast({
|
||||
title: "Project exported successfully",
|
||||
description: `"${project.name}" has been downloaded as a zip file.`,
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Failed to export project:', error);
|
||||
toast({
|
||||
title: "Failed to export project",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsExporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-md">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Folder className="h-5 w-5" />
|
||||
{project.name}
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{/* Last Modified */}
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Last Modified:</span>
|
||||
<span>{formatDistanceToNow(project.lastModified)}</span>
|
||||
</div>
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="project-name">Project Name</Label>
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
id="project-name"
|
||||
value={newProjectName}
|
||||
onChange={(e) => setNewProjectName(e.target.value)}
|
||||
disabled={isRenaming}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter') {
|
||||
handleSaveProject();
|
||||
} else if (e.key === 'Escape') {
|
||||
setNewProjectName(project.id);
|
||||
}
|
||||
}}
|
||||
className="flex-1"
|
||||
placeholder="Enter project name"
|
||||
/>
|
||||
<Button
|
||||
size="sm"
|
||||
onClick={handleSaveProject}
|
||||
disabled={isRenaming || !newProjectName.trim() || newProjectName === project.id}
|
||||
className="h-10"
|
||||
>
|
||||
{isRenaming ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Save className="h-4 w-4" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<Separator />
|
||||
|
||||
{/* Export Project Button */}
|
||||
<Button
|
||||
onClick={handleExportProject}
|
||||
disabled={isExporting || isDeleting || isRenaming}
|
||||
className="w-full gap-2"
|
||||
variant="outline"
|
||||
>
|
||||
{isExporting ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Download className="h-4 w-4" />
|
||||
)}
|
||||
{isExporting ? 'Exporting...' : 'Export Project'}
|
||||
</Button>
|
||||
|
||||
{/* Delete Project Button */}
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
variant="destructive"
|
||||
className="w-full gap-2"
|
||||
disabled={isExporting || isDeleting || isRenaming}
|
||||
>
|
||||
<Trash2 className="h-4 w-4" />
|
||||
Delete Project
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle>Delete Project</AlertDialogTitle>
|
||||
<AlertDialogDescription>
|
||||
Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files.
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={handleDeleteProject}
|
||||
disabled={isDeleting}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
>
|
||||
{isDeleting ? (
|
||||
<>
|
||||
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
|
||||
Deleting...
|
||||
</>
|
||||
) : (
|
||||
'Delete Project'
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -1,359 +0,0 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { type Project } from '@/lib/ProjectsManager';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import {
|
||||
Calendar,
|
||||
Folder,
|
||||
GitBranch,
|
||||
Package,
|
||||
FileText,
|
||||
GitCommit,
|
||||
GitMerge,
|
||||
Globe,
|
||||
Clock,
|
||||
User,
|
||||
Hash,
|
||||
AlertCircle,
|
||||
CheckCircle,
|
||||
Plus,
|
||||
Minus,
|
||||
Edit,
|
||||
Eye
|
||||
} from 'lucide-react';
|
||||
|
||||
interface ProjectInfoDialogProps {
|
||||
project: Project;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
interface ProjectMetadata {
|
||||
description?: string;
|
||||
version?: string;
|
||||
nostrRepoAddress?: string;
|
||||
fileCount?: number;
|
||||
}
|
||||
|
||||
export function ProjectInfoDialog({ project, open, onOpenChange }: ProjectInfoDialogProps) {
|
||||
const [metadata, setMetadata] = useState<ProjectMetadata>({});
|
||||
const [isLoading, setIsLoading] = useState(false);
|
||||
const projectsManager = useProjectsManager();
|
||||
const gitStatus = useGitStatus(project.id);
|
||||
|
||||
useEffect(() => {
|
||||
if (!open) return;
|
||||
|
||||
const loadProjectMetadata = async () => {
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const meta: ProjectMetadata = {};
|
||||
|
||||
// Try to read package.json
|
||||
try {
|
||||
const packageJsonContent = await projectsManager.readFile(project.id, 'package.json');
|
||||
const packageJson = JSON.parse(packageJsonContent);
|
||||
meta.description = packageJson.description;
|
||||
meta.version = packageJson.version;
|
||||
} catch {
|
||||
// package.json doesn't exist or is invalid
|
||||
}
|
||||
|
||||
// Get Nostr repo address
|
||||
try {
|
||||
const repoAddress = await projectsManager.getNostrRepoAddress(project.id);
|
||||
if (repoAddress) {
|
||||
meta.nostrRepoAddress = repoAddress;
|
||||
}
|
||||
} catch {
|
||||
// No Nostr repo configured
|
||||
}
|
||||
|
||||
// Calculate file count and size (simplified)
|
||||
try {
|
||||
const files = await projectsManager.listFiles(project.id);
|
||||
meta.fileCount = files.length;
|
||||
} catch {
|
||||
// Can't read directory
|
||||
}
|
||||
|
||||
setMetadata(meta);
|
||||
} catch (error) {
|
||||
console.error('Failed to load project metadata:', error);
|
||||
} finally {
|
||||
setIsLoading(false);
|
||||
}
|
||||
};
|
||||
|
||||
loadProjectMetadata();
|
||||
}, [open, project.id, projectsManager]);
|
||||
|
||||
const formatDate = (date: Date) => {
|
||||
return new Intl.DateTimeFormat('en-US', {
|
||||
year: 'numeric',
|
||||
month: 'long',
|
||||
day: 'numeric',
|
||||
hour: '2-digit',
|
||||
minute: '2-digit',
|
||||
}).format(date);
|
||||
};
|
||||
|
||||
const formatDistanceToNow = (date: Date) => {
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
|
||||
if (diffInSeconds < 60) return 'just now';
|
||||
if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`;
|
||||
if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`;
|
||||
if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`;
|
||||
if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} months ago`;
|
||||
return `${Math.floor(diffInSeconds / 31536000)} years ago`;
|
||||
};
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl max-h-[80vh] overflow-y-auto">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Folder className="h-5 w-5" />
|
||||
{project.name}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Project information and metadata
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
{isLoading ? (
|
||||
<div className="space-y-4">
|
||||
<div className="animate-pulse">
|
||||
<div className="h-4 bg-muted rounded w-3/4 mb-2"></div>
|
||||
<div className="h-4 bg-muted rounded w-1/2"></div>
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-6">
|
||||
{/* Basic Information */}
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Basic Information
|
||||
</h3>
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
<div className="flex items-center gap-2">
|
||||
<Folder className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Project ID:</span>
|
||||
<code className="bg-muted px-1.5 py-0.5 rounded text-xs">{project.id}</code>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<Calendar className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Last Modified:</span>
|
||||
<span>{formatDistanceToNow(project.lastModified)}</span>
|
||||
</div>
|
||||
{metadata.version && (
|
||||
<div className="flex items-center gap-2">
|
||||
<Package className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Version:</span>
|
||||
<Badge variant="secondary">{metadata.version}</Badge>
|
||||
</div>
|
||||
)}
|
||||
{metadata.fileCount !== undefined && (
|
||||
<div className="flex items-center gap-2">
|
||||
<FileText className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Files:</span>
|
||||
<span>{metadata.fileCount}</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Created:</span>
|
||||
<span className="ml-2">{formatDate(project.lastModified)}</span>
|
||||
</div>
|
||||
{metadata.description && (
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Description:</span>
|
||||
<p className="mt-1 text-foreground">{metadata.description}</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Nostr Information */}
|
||||
{metadata.nostrRepoAddress && (
|
||||
<>
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4" />
|
||||
Nostr Repository
|
||||
</h3>
|
||||
<div className="text-sm">
|
||||
<span className="text-muted-foreground">Repository Address:</span>
|
||||
<code className="ml-2 bg-muted px-1.5 py-0.5 rounded text-xs break-all">
|
||||
{metadata.nostrRepoAddress}
|
||||
</code>
|
||||
</div>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Git Status Information */}
|
||||
<Separator />
|
||||
<div className="space-y-3">
|
||||
<h3 className="text-sm font-semibold text-muted-foreground uppercase tracking-wide flex items-center gap-2">
|
||||
<GitCommit className="h-4 w-4" />
|
||||
Git Repository
|
||||
</h3>
|
||||
|
||||
{gitStatus.isLoading ? (
|
||||
<div className="space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
<Skeleton className="h-4 w-1/2" />
|
||||
<Skeleton className="h-4 w-2/3" />
|
||||
</div>
|
||||
) : !gitStatus.data?.isGitRepo ? (
|
||||
<div className="text-sm text-muted-foreground flex items-center gap-2">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
This project is not a Git repository
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-4">
|
||||
{/* Repository Status */}
|
||||
<div className="grid grid-cols-2 gap-4 text-sm">
|
||||
{/* Current Branch */}
|
||||
<div className="flex items-center gap-2">
|
||||
<GitBranch className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Branch:</span>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{gitStatus.data?.currentBranch || 'unknown'}
|
||||
</Badge>
|
||||
</div>
|
||||
|
||||
{/* Uncommitted Changes */}
|
||||
<div className="flex items-center gap-2">
|
||||
{gitStatus.data?.hasUncommittedChanges ? (
|
||||
<>
|
||||
<AlertCircle className="h-4 w-4 text-orange-500" />
|
||||
<span className="text-muted-foreground">Status:</span>
|
||||
<Badge variant="destructive" className="text-xs">
|
||||
{gitStatus.data.changedFiles.length} uncommitted changes
|
||||
</Badge>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<CheckCircle className="h-4 w-4 text-green-500" />
|
||||
<span className="text-muted-foreground">Status:</span>
|
||||
<Badge variant="secondary" className="text-xs bg-green-100 text-green-800 dark:bg-green-900/20 dark:text-green-400">
|
||||
Clean working tree
|
||||
</Badge>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{/* Total Commits */}
|
||||
<div className="flex items-center gap-2">
|
||||
<Hash className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Commits:</span>
|
||||
<span>{gitStatus.data?.totalCommits || 0}</span>
|
||||
</div>
|
||||
|
||||
{/* All Branches */}
|
||||
<div className="flex items-center gap-2">
|
||||
<GitMerge className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Branches:</span>
|
||||
<span>{gitStatus.data?.branches.length || 0}</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Latest Commit */}
|
||||
{gitStatus.data?.latestCommit && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Latest Commit
|
||||
</h4>
|
||||
<div className="bg-muted/30 rounded-md p-3 space-y-2">
|
||||
<div className="flex items-start gap-2">
|
||||
<GitCommit className="h-4 w-4 text-muted-foreground mt-0.5" />
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm font-medium break-words">
|
||||
{gitStatus.data.latestCommit.message.split('\n')[0]}
|
||||
</div>
|
||||
<div className="text-xs text-muted-foreground font-mono">
|
||||
{gitStatus.data.latestCommit.oid.substring(0, 7)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div className="flex items-center gap-4 text-xs text-muted-foreground">
|
||||
<div className="flex items-center gap-1">
|
||||
<User className="h-3 w-3" />
|
||||
{gitStatus.data.latestCommit.author.name}
|
||||
</div>
|
||||
<div className="flex items-center gap-1">
|
||||
<Clock className="h-3 w-3" />
|
||||
{new Date(gitStatus.data.latestCommit.author.timestamp * 1000).toLocaleDateString()}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Changed Files */}
|
||||
{gitStatus.data?.hasUncommittedChanges && gitStatus.data.changedFiles.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Uncommitted Changes
|
||||
</h4>
|
||||
<div className="space-y-1 max-h-32 overflow-y-auto">
|
||||
{gitStatus.data.changedFiles.map((file, index) => (
|
||||
<div key={index} className="flex items-center gap-2 text-sm">
|
||||
{file.status === 'added' && <Plus className="h-3 w-3 text-green-500" />}
|
||||
{file.status === 'modified' && <Edit className="h-3 w-3 text-blue-500" />}
|
||||
{file.status === 'deleted' && <Minus className="h-3 w-3 text-red-500" />}
|
||||
{file.status === 'untracked' && <Eye className="h-3 w-3 text-orange-500" />}
|
||||
{file.status === 'staged' && <CheckCircle className="h-3 w-3 text-purple-500" />}
|
||||
<span className="text-muted-foreground capitalize">{file.status}:</span>
|
||||
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono">
|
||||
{file.filepath}
|
||||
</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Remotes */}
|
||||
{gitStatus.data?.remotes && gitStatus.data.remotes.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
<h4 className="text-xs font-semibold text-muted-foreground uppercase tracking-wide">
|
||||
Remote Repositories
|
||||
</h4>
|
||||
<div className="space-y-1">
|
||||
{gitStatus.data.remotes.map((remote, index) => (
|
||||
<div key={index} className="flex items-center gap-2 text-sm">
|
||||
<Globe className="h-3 w-3 text-muted-foreground" />
|
||||
<span className="text-muted-foreground font-medium">{remote.name}:</span>
|
||||
<code className="text-xs bg-muted px-1 py-0.5 rounded font-mono break-all">
|
||||
{remote.url}
|
||||
</code>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
</div>
|
||||
)}
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
);
|
||||
}
|
||||
@@ -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>
|
||||
);
|
||||
}
|
||||
@@ -17,13 +17,13 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps
|
||||
const { fs } = useFS();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user } = useCurrentUser();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => user;
|
||||
const getCurrentUser = () => ({ user, metadata });
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser);
|
||||
}, [fs, settings, models, user]);
|
||||
}, [fs, settings, models, user, metadata]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
|
||||
@@ -3,7 +3,7 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
@@ -56,6 +56,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
@@ -7,6 +7,7 @@ import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { CircularProgress } from '@/components/ui/circular-progress';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
@@ -36,21 +37,19 @@ import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { makeSystemPrompt } from '@/lib/system';
|
||||
import { assistantContentEmpty } from '@/lib/ai-messages';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
interface ChatPaneProps {
|
||||
projectId: string;
|
||||
onNewChat?: () => void;
|
||||
onBuild?: () => void;
|
||||
onDeploy?: () => void;
|
||||
onNewChat: () => void;
|
||||
onFirstInteraction?: () => void;
|
||||
onLoadingChange?: (isLoading: boolean) => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
isDeployLoading?: boolean;
|
||||
}
|
||||
|
||||
export interface ChatPaneRef {
|
||||
@@ -59,32 +58,33 @@ export interface ChatPaneRef {
|
||||
|
||||
export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
projectId,
|
||||
onNewChat: _onNewChat,
|
||||
onBuild: _onBuild,
|
||||
onDeploy: _onDeploy,
|
||||
onNewChat,
|
||||
onFirstInteraction,
|
||||
onLoadingChange,
|
||||
isLoading: externalIsLoading,
|
||||
isBuildLoading: externalIsBuildLoading,
|
||||
isDeployLoading: externalIsDeployLoading
|
||||
}, ref) => {
|
||||
const { t } = useTranslation();
|
||||
const [input, setInput] = useState('');
|
||||
const [systemPrompt, setSystemPrompt] = useState('');
|
||||
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
|
||||
const [attachedFiles, setAttachedFiles] = useState<File[]>([]);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [scrolledProjects] = useState(() => new Set<string>());
|
||||
const [showOnboarding, setShowOnboarding] = useState(false);
|
||||
const [isStuck, setIsStuck] = useState(false);
|
||||
const [aiError, setAIError] = useState<Error | null>(null);
|
||||
|
||||
// Use external state if provided, otherwise default to false
|
||||
const isBuildLoading = externalIsBuildLoading || false;
|
||||
const isDeployLoading = externalIsDeployLoading || false;
|
||||
const scrollAreaRef = useRef<HTMLDivElement>(null);
|
||||
const { isConfigured, settings, addRecentlyUsedModel } = useAISettings();
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
});
|
||||
// State to control model selector dropdown
|
||||
const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false);
|
||||
const autostartedRef = useRef(false);
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
@@ -92,10 +92,15 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [providerModel, settings.recentlyUsedModels]);
|
||||
|
||||
// Reset error state when navigating between projects and switching models
|
||||
useEffect(() => {
|
||||
setAIError(null);
|
||||
}, [projectId, providerModel]);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
const { user } = useCurrentUser();
|
||||
const { models } = useProviderModels();
|
||||
|
||||
// Initialize AI chat with tools
|
||||
@@ -142,7 +147,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
enabled: externalIsLoading || isBuildLoading || isDeployLoading,
|
||||
enabled: externalIsLoading || isBuildLoading,
|
||||
title: 'Shakespeare',
|
||||
artist: `Working on ${projectId}...`,
|
||||
artwork: [
|
||||
@@ -159,18 +164,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
updateMetadata(title, description);
|
||||
}, [updateMetadata]);
|
||||
|
||||
useEffect(() => {
|
||||
makeSystemPrompt({
|
||||
cwd,
|
||||
fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(tools),
|
||||
user,
|
||||
metadata,
|
||||
}).then(setSystemPrompt)
|
||||
}, [fs, cwd, tools, user, metadata]);
|
||||
// Handle AI errors from the SessionManager
|
||||
const onAIError = useCallback((error: Error) => {
|
||||
setAIError(error);
|
||||
}, []);
|
||||
|
||||
const {
|
||||
messages,
|
||||
@@ -186,8 +183,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
projectId,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
onUpdateMetadata,
|
||||
onAIError,
|
||||
});
|
||||
|
||||
// Use external loading state if provided, otherwise use internal state
|
||||
@@ -211,8 +208,40 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}, [internalIsLoading, onLoadingChange]);
|
||||
|
||||
// Timer to detect when AI appears stuck during tool generation
|
||||
useEffect(() => {
|
||||
// Start a 2-second timer
|
||||
const timer = streamingMessage
|
||||
? setTimeout(() => setIsStuck(true), 2000)
|
||||
: undefined;
|
||||
|
||||
return () => {
|
||||
setIsStuck(false);
|
||||
clearTimeout(timer);
|
||||
};
|
||||
}, [streamingMessage]);
|
||||
|
||||
// Function to scroll to bottom
|
||||
const scrollToBottom = useCallback(() => {
|
||||
if (scrollAreaRef.current) {
|
||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||
}
|
||||
}, []);
|
||||
|
||||
// Function to open model selector dropdown
|
||||
const openModelSelector = useCallback(() => {
|
||||
setIsModelSelectorOpen(true);
|
||||
}, []);
|
||||
|
||||
// Scroll to bottom when AI error occurs
|
||||
useEffect(() => {
|
||||
scrollToBottom();
|
||||
}, [aiError, scrollToBottom]);
|
||||
|
||||
// Check for autostart parameter and trigger AI generation
|
||||
useEffect(() => {
|
||||
if (autostartedRef.current) return;
|
||||
|
||||
const autostart = searchParams.get('autostart');
|
||||
const urlModel = searchParams.get('model');
|
||||
|
||||
@@ -235,18 +264,11 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Start AI generation
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
startGeneration(modelToUse);
|
||||
autostartedRef.current = true;
|
||||
}
|
||||
}
|
||||
}, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]);
|
||||
|
||||
|
||||
// Function to scroll to bottom
|
||||
const scrollToBottom = () => {
|
||||
if (scrollAreaRef.current) {
|
||||
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
|
||||
}
|
||||
};
|
||||
|
||||
// Simple scroll event listener
|
||||
useEffect(() => {
|
||||
const container = scrollAreaRef.current;
|
||||
@@ -281,7 +303,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
if (isNearBottom) {
|
||||
container.scrollTop = container.scrollHeight;
|
||||
}
|
||||
|
||||
}
|
||||
}, [messages, streamingMessage, isLoading]);
|
||||
|
||||
@@ -296,7 +317,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
return () => clearTimeout(timer);
|
||||
}
|
||||
}, [projectId, scrolledProjects]);
|
||||
}, [projectId, scrolledProjects, scrollToBottom]);
|
||||
|
||||
const handleFileSelect = (file: File) => {
|
||||
setAttachedFiles(prev => [...prev, file]);
|
||||
@@ -349,8 +370,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
setAttachedFiles(prev => [...prev, ...files]);
|
||||
};
|
||||
|
||||
const handleSend = async () => {
|
||||
if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return;
|
||||
const send = useCallback(async (input: string, attachedFiles: File[]) => {
|
||||
if ((!input.trim() && attachedFiles.length === 0) || isLoading) return;
|
||||
|
||||
// If AI is not configured, show onboarding dialog
|
||||
if (!isConfigured) {
|
||||
setShowOnboarding(true);
|
||||
return;
|
||||
}
|
||||
|
||||
// If configured but no model selected, don't proceed
|
||||
if (!providerModel.trim()) return;
|
||||
|
||||
setAIError(null);
|
||||
|
||||
const modelToUse = providerModel.trim();
|
||||
|
||||
@@ -394,15 +426,14 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
try {
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
} catch (error) {
|
||||
console.error('AI chat error:', error);
|
||||
// Error handling is done in the useAIChat hook
|
||||
}
|
||||
};
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]);
|
||||
|
||||
const handleSend = useCallback(async () => {
|
||||
await send(input, attachedFiles);
|
||||
}, [input, attachedFiles, send]);
|
||||
|
||||
const handleKeyDown = (e: React.KeyboardEvent) => {
|
||||
if (e.key === 'Enter' && !e.shiftKey) {
|
||||
@@ -440,6 +471,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
};
|
||||
|
||||
// Handle textarea focus - show onboarding if not configured
|
||||
const handleTextareaFocus = () => {
|
||||
if (!isConfigured) {
|
||||
setShowOnboarding(true);
|
||||
}
|
||||
if (onFirstInteraction) {
|
||||
onFirstInteraction();
|
||||
}
|
||||
};
|
||||
|
||||
// Handle first user interaction to enable audio context
|
||||
const handleFirstInteraction = () => {
|
||||
// This will be handled automatically by the useKeepAlive hook
|
||||
@@ -456,29 +497,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
}), [internalStartNewSession]);
|
||||
|
||||
if (!isConfigured) {
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
<div className="flex-1 flex items-center justify-center bg-gradient-to-br from-primary/5 to-accent/5">
|
||||
<div className="text-center space-y-4 max-w-md mx-auto p-6">
|
||||
<div className="text-4xl mb-4">🤖</div>
|
||||
<div>
|
||||
<h3 className="text-lg font-semibold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('aiNotConfigured')}</h3>
|
||||
<p className="text-sm text-muted-foreground mb-4">
|
||||
{t('configureAI')}
|
||||
</p>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('useMenuForAI')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col relative">
|
||||
|
||||
@@ -508,11 +526,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
)}
|
||||
|
||||
{messages.map((message, index) => {
|
||||
// Skip assistant messages with no content
|
||||
if (message.role === 'assistant' && assistantContentEmpty(message.content)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Find the corresponding tool call for tool messages
|
||||
let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined;
|
||||
if (message.role === 'tool') {
|
||||
@@ -536,12 +549,23 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
})}
|
||||
{streamingMessage && (
|
||||
streamingMessage.content || streamingMessage.reasoning_content ? (
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
reasoningContent={streamingMessage.reasoning_content}
|
||||
/>
|
||||
<>
|
||||
<AIMessageItem
|
||||
key="streaming-message"
|
||||
message={streamingMessage}
|
||||
isCurrentlyLoading={isLoading}
|
||||
/>
|
||||
{/* Show loading skeleton if AI appears stuck generating tools */}
|
||||
{isStuck && (
|
||||
<div key="stuck-loading-skeleton" className="flex">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="text-sm space-y-2">
|
||||
<Skeleton className="h-4 w-3/4" />
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
) : (
|
||||
!(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
|
||||
<div key="streaming-loading" className="flex">
|
||||
@@ -564,6 +588,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* AI Error Alert */}
|
||||
{aiError && (
|
||||
<Quilly
|
||||
error={aiError}
|
||||
onDismiss={() => setAIError(null)}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={openModelSelector}
|
||||
providerModel={providerModel}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -584,9 +619,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
<div className="border-t p-4">
|
||||
{/* Chat Input Container */}
|
||||
<div
|
||||
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
|
||||
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
}`}
|
||||
className={`flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
}`}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
@@ -597,10 +631,16 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onChange={(e) => setInput(e.target.value)}
|
||||
onKeyDown={handleKeyDown}
|
||||
onPaste={handlePaste}
|
||||
onFocus={handleFirstInteraction}
|
||||
placeholder={providerModel.trim() ? t('askToAddFeatures') : t('selectModelFirst')}
|
||||
onFocus={handleTextareaFocus}
|
||||
placeholder={
|
||||
!isConfigured
|
||||
? t('askToAddFeatures')
|
||||
: providerModel.trim()
|
||||
? t('askToAddFeatures')
|
||||
: t('selectModelFirst')
|
||||
}
|
||||
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
|
||||
disabled={isLoading || !providerModel.trim()}
|
||||
disabled={isLoading || (isConfigured && !providerModel.trim())}
|
||||
rows={1}
|
||||
aria-label="Chat message input"
|
||||
style={{
|
||||
@@ -673,6 +713,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
className="w-full"
|
||||
disabled={isLoading}
|
||||
placeholder={t('chooseModel')}
|
||||
open={isModelSelectorOpen}
|
||||
onOpenChange={setIsModelSelectorOpen}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -691,7 +733,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
<Button
|
||||
onClick={handleSend}
|
||||
onMouseDown={handleFirstInteraction}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || !providerModel.trim()}
|
||||
disabled={(!input.trim() && attachedFiles.length === 0) || (isConfigured && !providerModel.trim())}
|
||||
size="sm"
|
||||
className="size-8 [&_svg]:size-5 rounded-full p-0"
|
||||
>
|
||||
@@ -702,6 +744,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Onboarding Dialog */}
|
||||
<OnboardingDialog
|
||||
open={showOnboarding}
|
||||
onOpenChange={setShowOnboarding}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
});
|
||||
@@ -3,21 +3,26 @@ import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { Tabs, TabsContent } from '@/components/ui/tabs';
|
||||
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check } from 'lucide-react';
|
||||
import { FolderOpen, ArrowLeft, X, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
|
||||
import {
|
||||
DropdownMenu,
|
||||
DropdownMenuContent,
|
||||
DropdownMenuItem,
|
||||
DropdownMenuTrigger,
|
||||
} from '@/components/ui/dropdown-menu';
|
||||
|
||||
import { FileTree } from './FileTree';
|
||||
import { FileEditor } from './FileEditor';
|
||||
import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
|
||||
// Get iframe domain from environment variable
|
||||
const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev';
|
||||
@@ -25,6 +30,10 @@ const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.d
|
||||
interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
activeTab: 'preview' | 'code';
|
||||
onToggleView?: () => void;
|
||||
projectName?: string;
|
||||
onFirstInteraction?: () => void;
|
||||
isPreviewable?: boolean;
|
||||
}
|
||||
|
||||
interface JSONRPCRequest {
|
||||
@@ -57,13 +66,8 @@ interface JSONRPCResponse {
|
||||
id: number;
|
||||
}
|
||||
|
||||
interface ConsoleMessage {
|
||||
id: number;
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
}
|
||||
|
||||
export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) {
|
||||
const { t } = useTranslation();
|
||||
const [selectedFile, setSelectedFile] = useState<string | null>(null);
|
||||
const [fileContent, setFileContent] = useState<string>('');
|
||||
@@ -74,11 +78,44 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
const [currentPath, setCurrentPath] = useState('/');
|
||||
const [navigationHistory, setNavigationHistory] = useState<string[]>(['/']);
|
||||
const [historyIndex, setHistoryIndex] = useState(0);
|
||||
const [consoleMessages, setConsoleMessages] = useState<ConsoleMessage[]>([]);
|
||||
const [copiedMessageId, setCopiedMessageId] = useState<number | null>(null);
|
||||
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null);
|
||||
const { fs } = useFS();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { messages: consoleMessages } = useConsoleMessages();
|
||||
const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId);
|
||||
|
||||
const [searchParams, setSearchParams] = useSearchParams();
|
||||
const [shouldBuild, setShouldBuild] = useState(false);
|
||||
|
||||
const handleBuildProject = useCallback(() => {
|
||||
buildProject(undefined, {
|
||||
onError: (error) => {
|
||||
console.error('Build failed:', error);
|
||||
}
|
||||
});
|
||||
}, [buildProject]);
|
||||
|
||||
// Handle "build" URL parameter on initial load
|
||||
useEffect(() => {
|
||||
if (searchParams.has('build')) {
|
||||
setShouldBuild(true);
|
||||
|
||||
// Remove the build parameter from URL
|
||||
const newSearchParams = new URLSearchParams(searchParams);
|
||||
newSearchParams.delete('build');
|
||||
setSearchParams(newSearchParams, { replace: true });
|
||||
}
|
||||
}, [searchParams, setSearchParams]);
|
||||
|
||||
// Build automatically if "build" parameter was present
|
||||
useEffect(() => {
|
||||
if (shouldBuild && isPreviewable && !isBuildLoading) {
|
||||
setShouldBuild(false);
|
||||
handleBuildProject();
|
||||
}
|
||||
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
|
||||
|
||||
const loadFileContent = useCallback(async (filePath: string) => {
|
||||
setIsLoading(true);
|
||||
@@ -129,68 +166,23 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
}
|
||||
}, [projectId, projectsManager]);
|
||||
|
||||
const refreshIframe = useCallback(() => {
|
||||
// Legacy refresh function for build completion events
|
||||
const refreshIframeLegacy = useCallback(() => {
|
||||
if (iframeRef.current) {
|
||||
// Force reload the iframe by updating its src
|
||||
const currentSrc = iframeRef.current.src;
|
||||
iframeRef.current.src = '';
|
||||
iframeRef.current.src = '/';
|
||||
// Use a small timeout to ensure the src is cleared before setting it back
|
||||
setTimeout(() => {
|
||||
if (iframeRef.current) {
|
||||
iframeRef.current.src = currentSrc;
|
||||
iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}/`;
|
||||
}
|
||||
}, 10);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const navigateToPath = useCallback((path: string) => {
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
setCurrentPath(path);
|
||||
|
||||
// Update navigation history
|
||||
const newHistory = navigationHistory.slice(0, historyIndex + 1);
|
||||
newHistory.push(path);
|
||||
setNavigationHistory(newHistory);
|
||||
setHistoryIndex(newHistory.length - 1);
|
||||
}
|
||||
}, [projectId, navigationHistory, historyIndex]);
|
||||
|
||||
const goBack = useCallback(() => {
|
||||
if (historyIndex > 0) {
|
||||
const newIndex = historyIndex - 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
|
||||
const goForward = useCallback(() => {
|
||||
if (historyIndex < navigationHistory.length - 1) {
|
||||
const newIndex = historyIndex + 1;
|
||||
const path = navigationHistory[newIndex];
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(path);
|
||||
|
||||
if (iframeRef.current) {
|
||||
const baseUrl = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
const newUrl = `${baseUrl}${path}`;
|
||||
iframeRef.current.src = newUrl;
|
||||
}
|
||||
}
|
||||
}, [historyIndex, navigationHistory, projectId]);
|
||||
}, [projectId]);
|
||||
|
||||
const sendResponse = useCallback((message: JSONRPCResponse) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
console.log(`Sending response to iframe:`, message);
|
||||
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
@@ -219,23 +211,99 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
normalizedLevel = params.level as ConsoleMessage['level'];
|
||||
}
|
||||
|
||||
const newConsoleMessage: ConsoleMessage = {
|
||||
id: Date.now(),
|
||||
level: normalizedLevel,
|
||||
message: params.message,
|
||||
};
|
||||
|
||||
setConsoleMessages(prev => [...prev, newConsoleMessage]);
|
||||
// Add to global console messages
|
||||
addConsoleMessage(normalizedLevel, params.message);
|
||||
|
||||
// Log to parent console for debugging with appropriate level
|
||||
console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`);
|
||||
}, []);
|
||||
|
||||
const handleUpdateNavigationState = useCallback((message: {
|
||||
jsonrpc: '2.0';
|
||||
method: 'updateNavigationState';
|
||||
params: {
|
||||
currentUrl: string;
|
||||
canGoBack: boolean;
|
||||
canGoForward: boolean;
|
||||
};
|
||||
}) => {
|
||||
const { params } = message;
|
||||
|
||||
try {
|
||||
// params.currentUrl is now just a semantic path (e.g., "/about", "/contact?param=value#section")
|
||||
const path = params.currentUrl;
|
||||
|
||||
setCurrentPath(path);
|
||||
|
||||
// Update navigation history if this is a new navigation
|
||||
// But only if it's different from current path (avoid duplicates)
|
||||
if (path !== navigationHistory[historyIndex]) {
|
||||
const newHistory = navigationHistory.slice(0, historyIndex + 1);
|
||||
newHistory.push(path);
|
||||
setNavigationHistory(newHistory);
|
||||
setHistoryIndex(newHistory.length - 1);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to handle navigation state:', params.currentUrl, error);
|
||||
}
|
||||
}, [historyIndex, navigationHistory]);
|
||||
|
||||
const sendNavigationCommand = useCallback((method: string, params?: Record<string, unknown>) => {
|
||||
if (iframeRef.current?.contentWindow) {
|
||||
const message = {
|
||||
jsonrpc: '2.0',
|
||||
method,
|
||||
params: params || {},
|
||||
id: Date.now()
|
||||
};
|
||||
const targetOrigin = `https://${projectId}.${IFRAME_DOMAIN}`;
|
||||
iframeRef.current.contentWindow.postMessage(message, targetOrigin);
|
||||
}
|
||||
}, [projectId]);
|
||||
|
||||
const navigateIframe = useCallback((url: string) => {
|
||||
// Send semantic path directly (e.g., "/about", "/contact")
|
||||
// The iframe's NavigationHandler will handle this as semantic navigation
|
||||
sendNavigationCommand('navigate', { url });
|
||||
}, [sendNavigationCommand]);
|
||||
|
||||
const refreshIframe = useCallback(() => {
|
||||
sendNavigationCommand('refresh');
|
||||
}, [sendNavigationCommand]);
|
||||
|
||||
const goBackIframe = useCallback(() => {
|
||||
if (historyIndex > 0) {
|
||||
// Move back in history
|
||||
const newIndex = historyIndex - 1;
|
||||
const targetPath = navigationHistory[newIndex];
|
||||
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(targetPath);
|
||||
|
||||
// Tell iframe to navigate to this path
|
||||
sendNavigationCommand('navigate', { url: targetPath });
|
||||
}
|
||||
}, [historyIndex, navigationHistory, sendNavigationCommand]);
|
||||
|
||||
const goForwardIframe = useCallback(() => {
|
||||
if (historyIndex < navigationHistory.length - 1) {
|
||||
// Move forward in history
|
||||
const newIndex = historyIndex + 1;
|
||||
const targetPath = navigationHistory[newIndex];
|
||||
|
||||
setHistoryIndex(newIndex);
|
||||
setCurrentPath(targetPath);
|
||||
|
||||
// Tell iframe to navigate to this path
|
||||
sendNavigationCommand('navigate', { url: targetPath });
|
||||
}
|
||||
}, [historyIndex, navigationHistory, sendNavigationCommand]);
|
||||
|
||||
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
|
||||
const { params, id } = request;
|
||||
const { request: fetchRequest } = params;
|
||||
|
||||
console.log(`Preview iframe requesting: ${fetchRequest.url}`);
|
||||
|
||||
|
||||
try {
|
||||
// Parse the URL and validate origin
|
||||
@@ -259,6 +327,9 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
const path = url.pathname;
|
||||
const filePath = path;
|
||||
|
||||
// Skip SPA fallback for static assets (files with extensions)
|
||||
const isStaticAsset = /\.[a-zA-Z0-9]+$/.test(path);
|
||||
|
||||
// SPA routing: try to serve the exact file first
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist' + filePath);
|
||||
@@ -279,11 +350,30 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
});
|
||||
return;
|
||||
} catch {
|
||||
// File not found, try SPA fallback to index.html
|
||||
console.log(`File not found: ${filePath}, trying index.html fallback`);
|
||||
|
||||
// For static assets, return 404 immediately
|
||||
if (isStaticAsset) {
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
result: {
|
||||
status: 404,
|
||||
statusText: 'Not Found',
|
||||
headers: {
|
||||
'Content-Type': 'text/plain',
|
||||
},
|
||||
body: encodeBase64(`Static asset not found: ${path}`),
|
||||
},
|
||||
id
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// For non-static assets, try SPA fallback to index.html
|
||||
|
||||
}
|
||||
|
||||
// SPA fallback: serve index.html for non-file requests
|
||||
// SPA fallback: serve index.html for non-file requests (SPA routing)
|
||||
try {
|
||||
const bytes = await projectsManager.readFileBytes(projectId, 'dist/index.html');
|
||||
console.log(`Serving index.html fallback for: ${path}`);
|
||||
@@ -303,7 +393,7 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
});
|
||||
} catch {
|
||||
// Even index.html doesn't exist
|
||||
console.log(`No files found, returning 404 for: ${path}`);
|
||||
|
||||
|
||||
sendResponse({
|
||||
jsonrpc: '2.0',
|
||||
@@ -348,12 +438,14 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
handleFetch(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
|
||||
handleConsoleMessage(message);
|
||||
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
|
||||
handleUpdateNavigationState(message);
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('message', handleMessage);
|
||||
return () => window.removeEventListener('message', handleMessage);
|
||||
}, [handleFetch, handleConsoleMessage, projectId]);
|
||||
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
if (selectedFile) {
|
||||
@@ -361,6 +453,18 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
}
|
||||
}, [selectedFile, loadFileContent]);
|
||||
|
||||
// Reset selected file and navigation history when projectId changes
|
||||
useEffect(() => {
|
||||
setSelectedFile(null);
|
||||
setFileContent('');
|
||||
setMobileCodeView('explorer');
|
||||
|
||||
// Reset navigation history and state
|
||||
setCurrentPath('/');
|
||||
setNavigationHistory(['/']);
|
||||
setHistoryIndex(0);
|
||||
}, [projectId]);
|
||||
|
||||
useEffect(() => {
|
||||
checkForBuiltProject();
|
||||
}, [checkForBuiltProject]);
|
||||
@@ -372,13 +476,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
console.log('Build completed for project, refreshing preview');
|
||||
// Check for built project and refresh iframe
|
||||
checkForBuiltProject();
|
||||
refreshIframe();
|
||||
refreshIframeLegacy();
|
||||
}
|
||||
};
|
||||
|
||||
window.addEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
return () => window.removeEventListener('buildComplete', handleBuildComplete as EventListener);
|
||||
}, [projectId, checkForBuiltProject, refreshIframe]);
|
||||
}, [projectId, checkForBuiltProject, refreshIframeLegacy]);
|
||||
|
||||
const handleFileSelect = (filePath: string) => {
|
||||
setSelectedFile(filePath);
|
||||
@@ -399,161 +503,244 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
};
|
||||
|
||||
const ConsoleDropdown = () => {
|
||||
const getLevelColor = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return 'text-red-500';
|
||||
case 'warn': return 'text-yellow-500';
|
||||
case 'info': return 'text-blue-500';
|
||||
case 'debug': return 'text-gray-500';
|
||||
default: return 'text-gray-400';
|
||||
}
|
||||
};
|
||||
const getLevelColor = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return 'text-red-500';
|
||||
case 'warn': return 'text-yellow-500';
|
||||
case 'info': return 'text-blue-500';
|
||||
case 'debug': return 'text-gray-500';
|
||||
default: return 'text-gray-400';
|
||||
}
|
||||
};
|
||||
|
||||
const getLevelIcon = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return '!';
|
||||
case 'warn': return '⚠';
|
||||
case 'info': return 'ℹ';
|
||||
case 'debug': return '🔍';
|
||||
default: return '•';
|
||||
}
|
||||
};
|
||||
const getLevelIcon = (level: ConsoleMessage['level']) => {
|
||||
switch (level) {
|
||||
case 'error': return '!';
|
||||
case 'warn': return '⚠';
|
||||
case 'info': return 'ℹ';
|
||||
case 'debug': return '🔍';
|
||||
default: return '•';
|
||||
}
|
||||
};
|
||||
|
||||
const clearConsole = () => {
|
||||
setConsoleMessages([]);
|
||||
};
|
||||
const clearConsole = () => {
|
||||
clearConsoleMessages();
|
||||
};
|
||||
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
|
||||
try {
|
||||
// Create a formatted string with all message details
|
||||
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
|
||||
const copyMessageToClipboard = async (msg: ConsoleMessage) => {
|
||||
try {
|
||||
// Create a formatted string with all message details
|
||||
const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`;
|
||||
|
||||
await navigator.clipboard.writeText(formattedMessage);
|
||||
setCopiedMessageId(msg.id);
|
||||
await navigator.clipboard.writeText(formattedMessage);
|
||||
setCopiedMessageId(msg.id);
|
||||
|
||||
// Reset the copied state after 2 seconds
|
||||
setTimeout(() => {
|
||||
setCopiedMessageId(null);
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
// Reset the copied state after 2 seconds
|
||||
setTimeout(() => {
|
||||
setCopiedMessageId(null);
|
||||
}, 2000);
|
||||
} catch (error) {
|
||||
console.error('Failed to copy message to clipboard:', error);
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
|
||||
<Bug className="h-4 w-4" />
|
||||
{consoleMessages.some(msg => msg.level === 'error') && (
|
||||
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
|
||||
<div className="flex items-center justify-between p-2 border-b">
|
||||
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
|
||||
<Button variant="ghost" size="sm" onClick={clearConsole}>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
|
||||
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
|
||||
{consoleMessages.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground text-sm py-4">
|
||||
No console messages
|
||||
</div>
|
||||
) : (
|
||||
consoleMessages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
|
||||
>
|
||||
<div className="flex items-start justify-between w-full">
|
||||
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copyMessageToClipboard(msg)}
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
|
||||
>
|
||||
{copiedMessageId === msg.id ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="ghost" size="sm" className="h-8 w-8 p-0 relative">
|
||||
<Bug className="h-4 w-4" />
|
||||
{consoleMessages.some(msg => msg.level === 'error') && (
|
||||
<span className="absolute bottom-0 left-0 h-2 w-2 bg-red-500 rounded-full"></span>
|
||||
)}
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-96 max-w-96 max-h-96 overflow-x-hidden">
|
||||
<div className="flex items-center justify-between p-2 border-b">
|
||||
<span className="font-medium text-sm">Console Output ({consoleMessages.length})</span>
|
||||
<Button variant="ghost" size="sm" onClick={clearConsole}>
|
||||
<X className="h-3 w-3" />
|
||||
</Button>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
};
|
||||
<ScrollArea className="h-80 w-full max-w-full overflow-x-hidden">
|
||||
<div className="space-y-1 p-2 w-full max-w-full overflow-x-hidden">
|
||||
{consoleMessages.length === 0 ? (
|
||||
<div className="text-center text-muted-foreground text-sm py-4">
|
||||
No console messages
|
||||
</div>
|
||||
) : (
|
||||
consoleMessages.map((msg) => (
|
||||
<div
|
||||
key={msg.id}
|
||||
className={`text-xs font-mono p-2 rounded ${getLevelColor(msg.level)} bg-muted/50 group relative w-full overflow-hidden`}
|
||||
>
|
||||
<div className="flex items-start justify-between w-full">
|
||||
<div className="whitespace-pre-wrap break-all flex-1 pr-2 overflow-x-hidden">{getLevelIcon(msg.level)} {msg.message}</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => copyMessageToClipboard(msg)}
|
||||
className="h-6 w-6 p-0 opacity-0 group-hover:opacity-100 transition-opacity duration-200 flex-shrink-0"
|
||||
>
|
||||
{copiedMessageId === msg.id ? (
|
||||
<Check className="h-3 w-3 text-green-500" />
|
||||
) : (
|
||||
<Copy className="h-3 w-3" />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
))
|
||||
)}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
};
|
||||
|
||||
const Menu = () => {
|
||||
const isAnyLoading = isBuildLoading;
|
||||
|
||||
return (
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0"
|
||||
>
|
||||
<MenuIcon className="h-4 w-4" />
|
||||
<span className="sr-only">Open menu</span>
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end" className="w-48">
|
||||
<DropdownMenuItem
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<Loader2 className="h-4 w-4 animate-spin" />
|
||||
) : (
|
||||
<Play className="h-4 w-4" />
|
||||
)}
|
||||
{isBuildLoading ? 'Building...' : 'Build'}
|
||||
</DropdownMenuItem>
|
||||
<DropdownMenuItem
|
||||
onClick={() => setDeployDialogOpen(true)}
|
||||
disabled={isAnyLoading}
|
||||
className="gap-2"
|
||||
>
|
||||
<CloudUpload className="h-4 w-4" />
|
||||
Deploy
|
||||
</DropdownMenuItem>
|
||||
</DropdownMenuContent>
|
||||
</DropdownMenu>
|
||||
);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="h-full">
|
||||
<Tabs value={activeTab} className="h-full">
|
||||
<TabsContent value="preview" className="h-full mt-0">
|
||||
{hasBuiltProject ? (
|
||||
<div className="h-full w-full flex flex-col">
|
||||
<div className="flex items-center border-b w-full">
|
||||
<BrowserAddressBar
|
||||
currentPath={currentPath}
|
||||
onNavigate={navigateToPath}
|
||||
onRefresh={refreshIframe}
|
||||
onBack={goBack}
|
||||
onForward={goForward}
|
||||
canGoBack={historyIndex > 0}
|
||||
canGoForward={historyIndex < navigationHistory.length - 1}
|
||||
extraContent={<ConsoleDropdown />}
|
||||
/>
|
||||
</div>
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${IFRAME_DOMAIN}${currentPath}`}
|
||||
className="w-full flex-1 border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
{isPreviewable && (
|
||||
<TabsContent value="preview" className="h-full mt-0">
|
||||
<div className="h-full w-full flex flex-col relative">
|
||||
{/* Always show browser address bar */}
|
||||
<div className="h-12 flex items-center w-full">
|
||||
<BrowserAddressBar
|
||||
currentPath={currentPath}
|
||||
onNavigate={hasBuiltProject ? navigateIframe : undefined}
|
||||
onRefresh={hasBuiltProject ? refreshIframe : undefined}
|
||||
onBack={hasBuiltProject ? goBackIframe : undefined}
|
||||
onForward={hasBuiltProject ? goForwardIframe : undefined}
|
||||
canGoBack={hasBuiltProject && historyIndex > 0}
|
||||
canGoForward={hasBuiltProject && historyIndex < navigationHistory.length - 1}
|
||||
extraContent={(
|
||||
<div className="flex items-center">
|
||||
{(!isMobile && onToggleView && isPreviewable) && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onToggleView}
|
||||
className="h-8 gap-2"
|
||||
>
|
||||
<Code className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<ConsoleDropdown />
|
||||
<Menu />
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center bg-muted">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{t('buildProjectToSeePreview')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Content area */}
|
||||
<div className="flex-1">
|
||||
{hasBuiltProject ? (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={`https://${projectId}.${IFRAME_DOMAIN}/`}
|
||||
className="w-full h-full border-0"
|
||||
title="Project Preview"
|
||||
sandbox="allow-scripts allow-same-origin"
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center bg-muted">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
|
||||
<p className="text-muted-foreground mb-4">
|
||||
{t('buildProjectToSeePreview')}
|
||||
</p>
|
||||
<Button
|
||||
onClick={handleBuildProject}
|
||||
disabled={isBuildLoading}
|
||||
variant="outline"
|
||||
className="gap-2"
|
||||
>
|
||||
{isBuildLoading ? (
|
||||
<>
|
||||
<Loader2 className="h-5 w-5 animate-spin" />
|
||||
Building...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Play className="h-5 w-5" />
|
||||
Build Project
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Build loading overlay */}
|
||||
{isBuildLoading && (
|
||||
<div className="absolute inset-0 bg-background/50 backdrop-blur-sm flex items-center justify-center z-10">
|
||||
<div className="bg-background/90 border rounded-lg p-4 shadow-lg flex items-center gap-3">
|
||||
<Loader2 className="h-5 w-5 animate-spin text-primary" />
|
||||
<span className="text-sm font-medium">Building project...</span>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</TabsContent>
|
||||
)}
|
||||
|
||||
<TabsContent value="code" className="h-full mt-0">
|
||||
{isMobile ? (
|
||||
<div className="h-full flex flex-col">
|
||||
{mobileCodeView === 'explorer' ? (
|
||||
<>
|
||||
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</>
|
||||
</ScrollArea>
|
||||
) : (
|
||||
<>
|
||||
<div className="p-3 border-b bg-gradient-to-r from-primary/5 to-accent/5 flex items-center gap-2">
|
||||
@@ -602,49 +789,80 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) {
|
||||
)}
|
||||
</div>
|
||||
) : (
|
||||
<div className="h-full flex">
|
||||
<div className="w-1/3 border-r">
|
||||
<div className="p-4 border-b bg-gradient-to-r from-primary/5 to-accent/5">
|
||||
<div className="flex items-center justify-between">
|
||||
<h3 className="font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">{t('fileExplorer')}</h3>
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Code view header with back button */}
|
||||
{!isMobile && onToggleView && isPreviewable && (
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onToggleView}
|
||||
className="gap-2 text-muted-foreground hover:text-foreground"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
{t('backToPreview')}
|
||||
</Button>
|
||||
<div className="flex-1" />
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
<ScrollArea className="h-[calc(100%-60px)]">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)}
|
||||
{/* Code view header without back button for non-previewable projects */}
|
||||
{!isMobile && !isPreviewable && (
|
||||
<div className="h-12 px-4 border-b flex items-center bg-gradient-to-r from-muted/20 to-background">
|
||||
<div className="flex-1" />
|
||||
<GitStatusIndicator projectId={projectId} />
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
<div className="flex-1 flex min-h-0">
|
||||
<div className="w-1/3 border-r flex flex-col">
|
||||
<ScrollArea className="flex-1">
|
||||
<ScrollBar orientation="horizontal" />
|
||||
<div className="min-w-max">
|
||||
<FileTree
|
||||
projectId={projectId}
|
||||
onFileSelect={handleFileSelect}
|
||||
selectedFile={selectedFile}
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</div>
|
||||
|
||||
<div className="flex-1">
|
||||
{selectedFile ? (
|
||||
<FileEditor
|
||||
filePath={selectedFile}
|
||||
content={fileContent}
|
||||
onSave={handleFileSave}
|
||||
isLoading={isLoading}
|
||||
projectId={projectId}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full flex items-center justify-center">
|
||||
<div className="text-center">
|
||||
<p className="text-muted-foreground">
|
||||
{t('selectFileFromExplorer')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</TabsContent>
|
||||
</Tabs>
|
||||
|
||||
{/* Deploy Dialog */}
|
||||
{projectName && (
|
||||
<DeployDialog
|
||||
projectId={projectId}
|
||||
projectName={projectName}
|
||||
open={deployDialogOpen}
|
||||
onOpenChange={setDeployDialogOpen}
|
||||
onFirstInteraction={onFirstInteraction}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -1,13 +1,14 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
@@ -46,6 +47,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { toast } = useToast();
|
||||
const navigate = useNavigate();
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
const loadGitHistory = useCallback(async () => {
|
||||
setIsLoading(true);
|
||||
@@ -214,8 +217,9 @@ ${commitsToRevert.map(c => {
|
||||
description: `Reverted ${commitsToRevert.length} commit(s) back to ${targetCommit.oid.substring(0, 7)}`,
|
||||
});
|
||||
|
||||
// Reload the git history to show the new commit
|
||||
await loadGitHistory();
|
||||
// Close the dialog and navigate to project page with build query parameter
|
||||
setIsOpen(false);
|
||||
navigate(`/project/${projectId}?build`);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Failed to rollback:', err);
|
||||
@@ -227,7 +231,106 @@ ${commitsToRevert.map(c => {
|
||||
} finally {
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [git, fs, projectId, toast, loadGitHistory]);
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen]);
|
||||
|
||||
const resetToHead = useCallback(async () => {
|
||||
if (!fs) return;
|
||||
|
||||
setIsRollingBack('HEAD');
|
||||
|
||||
try {
|
||||
const projectPath = `/projects/${projectId}`;
|
||||
|
||||
// Get the current HEAD commit
|
||||
const headCommit = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
// Get all files from HEAD
|
||||
const headFiles = await git.listFiles({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
|
||||
// Get current files in working directory
|
||||
const currentFiles = await git.listFiles({
|
||||
dir: projectPath,
|
||||
});
|
||||
|
||||
// Remove files that don't exist in HEAD (equivalent to git clean -fd for tracked files)
|
||||
for (const filepath of currentFiles) {
|
||||
if (!headFiles.includes(filepath)) {
|
||||
try {
|
||||
await fs.unlink(`${projectPath}/${filepath}`);
|
||||
} catch (err) {
|
||||
console.warn(`Could not remove ${filepath}:`, err);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Reset all files to HEAD state (equivalent to git reset --hard HEAD)
|
||||
for (const filepath of headFiles) {
|
||||
try {
|
||||
const { blob } = await git.readBlob({
|
||||
dir: projectPath,
|
||||
oid: headCommit,
|
||||
filepath,
|
||||
});
|
||||
|
||||
// Ensure directory exists
|
||||
const dirPath = filepath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await fs.mkdir(`${projectPath}/${dirPath}`, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file
|
||||
await fs.writeFile(`${projectPath}/${filepath}`, blob);
|
||||
} catch (err) {
|
||||
console.error(`Failed to reset ${filepath}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
// Remove untracked files and directories (equivalent to git clean -fd)
|
||||
// Get git status to find untracked files
|
||||
const status = await git.statusMatrix({
|
||||
dir: projectPath,
|
||||
});
|
||||
|
||||
const untrackedFiles = status
|
||||
.filter(([, headStatus, workdirStatus, stageStatus]) =>
|
||||
headStatus === 0 && workdirStatus === 1 && stageStatus === 0
|
||||
)
|
||||
.map(([filepath]) => filepath);
|
||||
|
||||
for (const filepath of untrackedFiles) {
|
||||
try {
|
||||
await fs.unlink(`${projectPath}/${filepath}`);
|
||||
} catch (err) {
|
||||
console.warn(`Could not remove untracked file ${filepath}:`, err);
|
||||
}
|
||||
}
|
||||
|
||||
toast({
|
||||
title: "Reset successful",
|
||||
description: "All changes have been discarded and working directory reset to HEAD",
|
||||
});
|
||||
|
||||
// Close the dialog and navigate to project page with build query parameter
|
||||
setIsOpen(false);
|
||||
navigate(`/project/${projectId}?build`);
|
||||
|
||||
} catch (err) {
|
||||
console.error('Failed to reset:', err);
|
||||
toast({
|
||||
title: "Reset failed",
|
||||
description: err instanceof Error ? err.message : 'Failed to reset to HEAD',
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsRollingBack(null);
|
||||
}
|
||||
}, [git, fs, projectId, toast, navigate, setIsOpen]);
|
||||
|
||||
useEffect(() => {
|
||||
if (isOpen) {
|
||||
@@ -289,18 +392,18 @@ ${commitsToRevert.map(c => {
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
<DialogContent className="max-w-4xl max-h-[80vh]">
|
||||
<DialogContent className="max-w-4xl max-h-[80vh] overflow-hidden">
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<GitCommit className="h-5 w-5" />
|
||||
Git History
|
||||
<History className="h-5 w-5" />
|
||||
Rollback
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
View the commit history for this project
|
||||
Revert to an older commit
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 min-h-0">
|
||||
<div className="flex-1 min-h-0 max-w-full overflow-hidden">
|
||||
{isLoading ? (
|
||||
<div className="flex items-center justify-center py-8">
|
||||
<div className="flex items-center gap-2 text-muted-foreground">
|
||||
@@ -329,7 +432,7 @@ ${commitsToRevert.map(c => {
|
||||
</div>
|
||||
</div>
|
||||
) : (
|
||||
<ScrollArea className="h-[60vh]">
|
||||
<div className="h-[60vh] overflow-y-scroll">
|
||||
<div className="space-y-1 pr-4">
|
||||
{commits.map((commit, index) => {
|
||||
const { firstLine, hasMoreLines, fullMessage } = getCommitMessageLines(commit.commit.message);
|
||||
@@ -340,7 +443,7 @@ ${commitsToRevert.map(c => {
|
||||
<div className="flex items-start justify-between gap-3">
|
||||
<div className="flex-1 min-w-0 space-y-1">
|
||||
<div className="flex items-center gap-2 mb-1">
|
||||
<h3 className="font-medium text-sm text-foreground break-words">
|
||||
<h3 className="font-medium text-sm text-foreground truncate">
|
||||
{firstLine}
|
||||
</h3>
|
||||
{hasMoreLines && (
|
||||
@@ -372,7 +475,76 @@ ${commitsToRevert.map(c => {
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-2 shrink-0">
|
||||
{index > 0 && ( // Don't show rollback for the most recent commit
|
||||
{index === 0 ? (
|
||||
// Show "Current" or "Rollback" for the most recent commit
|
||||
gitStatus?.hasUncommittedChanges ? (
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs gap-1 hover:bg-destructive/10 hover:border-destructive/20 hover:text-destructive"
|
||||
disabled={isRollingBack !== null}
|
||||
>
|
||||
<RotateCcw className="h-3 w-3" />
|
||||
Rollback
|
||||
</Button>
|
||||
</AlertDialogTrigger>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertTriangle className="h-5 w-5 text-destructive" />
|
||||
Discard All Changes
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-2">
|
||||
<p>
|
||||
This will discard all unstaged changes and reset your working directory to the current commit:
|
||||
</p>
|
||||
<div className="bg-muted p-3 rounded-md text-sm">
|
||||
<div className="font-medium break-words">{firstLine}</div>
|
||||
<div className="text-muted-foreground text-xs mt-1">
|
||||
{commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)}
|
||||
</div>
|
||||
</div>
|
||||
<p className="text-sm">
|
||||
This action cannot be undone.
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={resetToHead}
|
||||
className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
|
||||
disabled={isRollingBack !== null}
|
||||
>
|
||||
{isRollingBack === 'HEAD' ? (
|
||||
<>
|
||||
<div className="h-3 w-3 animate-spin rounded-full border border-current border-t-transparent mr-1" />
|
||||
Discarding...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<RotateCcw className="h-3 w-3 mr-1" />
|
||||
Discard Changes
|
||||
</>
|
||||
)}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
) : (
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="h-7 px-2 text-xs gap-1 cursor-default"
|
||||
disabled
|
||||
>
|
||||
Current
|
||||
</Button>
|
||||
)
|
||||
) : (
|
||||
// Show rollback button for older commits
|
||||
<AlertDialog>
|
||||
<AlertDialogTrigger asChild>
|
||||
<Button
|
||||
@@ -430,17 +602,13 @@ ${commitsToRevert.map(c => {
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
)}
|
||||
|
||||
<Badge variant="secondary" className="text-xs font-mono">
|
||||
{commit.oid.substring(0, 7)}
|
||||
</Badge>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
import React from 'react';
|
||||
|
||||
interface QuillySVGProps extends React.SVGProps<SVGSVGElement> {
|
||||
className?: string;
|
||||
fillColor?: string;
|
||||
}
|
||||
|
||||
export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) {
|
||||
return (
|
||||
<svg
|
||||
className={className}
|
||||
viewBox="140 30 220 420"
|
||||
xmlns="http://www.w3.org/2000/svg"
|
||||
{...props}
|
||||
>
|
||||
{/* Main quill head/top part */}
|
||||
<path fill={fillColor} d="M 241.5,33.5 C 246.833,33.5 252.167,33.5 257.5,33.5C 269.508,34.507 280.508,38.3403 290.5,45C 294,47.3342 297,50.1675 299.5,53.5C 298.21,54.0577 297.377,55.0577 297,56.5C 294.888,52.8729 293.221,52.8729 292,56.5C 291.086,55.3463 290.253,55.513 289.5,57C 292.321,58.6213 292.987,60.788 291.5,63.5C 281.078,49.3135 266.911,42.3135 249,42.5C 229.512,42.5414 213.845,50.2081 202,65.5C 196.198,75.0401 193.698,85.3734 194.5,96.5C 193.546,91.1876 192.546,85.1876 191.5,78.5C 189.508,78.6715 187.842,78.0049 186.5,76.5C 183.867,77.7822 183.867,79.1156 186.5,80.5C 185.234,81.3624 183.901,82.0291 182.5,82.5C 183.047,79.2976 184.047,76.2976 185.5,73.5C 186.906,73.0269 187.573,72.0269 187.5,70.5C 188.498,66.4945 190.498,63.1612 193.5,60.5C 194.906,60.0269 195.573,59.0269 195.5,57.5C 196.833,55.8333 198.167,54.1667 199.5,52.5C 211.392,41.6322 225.392,35.2989 241.5,33.5 Z" />
|
||||
|
||||
{/* Main quill feather/plume part */}
|
||||
<path fill={fillColor} d="M 299.5,53.5 C 305.302,58.4362 309.635,64.4362 312.5,71.5C 312.343,72.8734 312.51,74.2068 313,75.5C 313.876,77.7582 315.043,79.7582 316.5,81.5C 318.737,87.0285 320.903,92.6952 323,98.5C 328.732,104.725 334.232,111.058 339.5,117.5C 339.427,119.027 340.094,120.027 341.5,120.5C 343.293,122.426 344.293,124.759 344.5,127.5C 345.22,133.138 345.553,138.804 345.5,144.5C 344.999,150.505 342.499,155.505 338,159.5C 338.33,165.569 338.164,171.569 337.5,177.5C 336.732,178.263 336.232,179.263 336,180.5C 335.261,178.779 334.427,177.113 333.5,175.5C 333.034,177.705 333.034,179.705 333.5,181.5C 332.23,180.438 331.063,179.438 330,178.5C 329.667,178.833 329.333,179.167 329,179.5C 328.333,178.5 328.333,177.5 329,176.5C 329.718,177.451 330.551,177.617 331.5,177C 330.418,175.67 329.751,174.17 329.5,172.5C 329.799,170.396 329.466,168.396 328.5,166.5C 317.499,170.764 306.666,170.431 296,165.5C 295.617,166.056 295.117,166.389 294.5,166.5C 293.533,167.806 292.199,168.473 290.5,168.5C 290.688,170.103 290.188,171.437 289,172.5C 287.477,170.431 286.643,168.097 286.5,165.5C 287.351,161.435 288.517,157.435 290,153.5C 293.306,151.968 296.806,150.801 300.5,150C 303.708,147.229 305.708,143.729 306.5,139.5C 305.527,137.36 304.027,135.693 302,134.5C 299.684,135.367 297.684,134.701 296,132.5C 293.685,129.223 292.351,125.556 292,121.5C 292.692,108.983 293.858,96.4825 295.5,84C 295.554,78.7227 294.887,73.556 293.5,68.5C 293.771,66.6203 293.104,65.287 291.5,64.5C 291.5,64.1667 291.5,63.8333 291.5,63.5C 292.987,60.788 292.321,58.6213 289.5,57C 290.253,55.513 291.086,55.3463 292,56.5C 293.221,52.8729 294.888,52.8729 297,56.5C 297.377,55.0577 298.21,54.0577 299.5,53.5 Z" />
|
||||
|
||||
{/* Body/torso part */}
|
||||
<path fill={fillColor} d="M 194.5,96.5 C 205.307,90.5958 215.64,91.2624 225.5,98.5C 227.97,102.11 229.304,106.11 229.5,110.5C 227.359,120.522 224.859,130.522 222,140.5C 221.176,143.882 221.343,147.216 222.5,150.5C 223.607,151.022 224.774,151.355 226,151.5C 229.926,150.727 233.759,149.727 237.5,148.5C 240.135,147.461 242.135,145.794 243.5,143.5C 247.778,147.659 247.111,151.159 241.5,154C 245.303,156.071 248.97,158.404 252.5,161C 255.77,162.66 259.103,162.994 262.5,162C 263.935,164.267 263.602,166.267 261.5,168C 258.448,169.211 255.281,170.045 252,170.5C 244.065,169.521 236.398,167.521 229,164.5C 222.843,167.108 216.51,169.108 210,170.5C 207.815,170.079 205.649,169.579 203.5,169C 202.424,167.274 202.257,165.441 203,163.5C 207.408,161.43 211.575,158.93 215.5,156C 213.504,151.729 213.004,147.229 214,142.5C 216.819,132.558 219.319,122.558 221.5,112.5C 221.81,108.306 220.143,105.139 216.5,103C 208.667,100.569 201.501,101.736 195,106.5C 191.661,123.896 191.827,141.229 195.5,158.5C 194.895,160.026 193.729,161.026 192,161.5C 191.14,156.863 188.307,154.697 183.5,155C 184.833,154.333 184.833,153.667 183.5,153C 181.934,152.7 180.601,153.2 179.5,154.5C 166.076,151.07 158.742,142.403 157.5,128.5C 158.051,123.851 159.385,119.518 161.5,115.5C 162.906,115.027 163.573,114.027 163.5,112.5C 167.455,107.373 171.622,102.373 176,97.5C 178.486,92.5113 180.652,87.5113 182.5,82.5C 183.901,82.0291 185.234,81.3624 186.5,80.5C 183.867,79.1156 183.867,77.7822 186.5,76.5C 187.842,78.0049 189.508,78.6715 191.5,78.5C 192.546,85.1876 193.546,91.1876 194.5,96.5 Z" />
|
||||
|
||||
{/* Additional body details */}
|
||||
<path fill={fillColor} d="M 272.5,96.5 C 273.785,98.4516 275.451,100.118 277.5,101.5C 279.574,103.715 279.907,106.215 278.5,109C 275.758,109.295 273.425,108.462 271.5,106.5C 271.167,105.5 270.5,104.833 269.5,104.5C 265.505,102.79 261.339,101.456 257,100.5C 252.701,101.544 248.535,102.878 244.5,104.5C 237.97,101.229 237.97,97.7288 244.5,94C 251.789,91.6687 259.122,91.3353 266.5,93C 268.727,93.941 270.727,95.1077 272.5,96.5 Z" />
|
||||
|
||||
{/* Eyes */}
|
||||
<path fill={fillColor} d="M 216.5,118.5 C 215.603,119.598 214.77,119.598 214,118.5C 213.59,119.901 213.09,121.234 212.5,122.5C 209.43,122.632 206.43,122.299 203.5,121.5C 200.197,118.335 199.697,114.668 202,110.5C 209.746,105.174 214.913,107.008 217.5,116C 217.257,116.902 216.923,117.735 216.5,118.5 Z" />
|
||||
<path fill={fillColor} d="M 254.5,107.5 C 262.982,107.765 266.149,112.099 264,120.5C 258.514,126.08 253.514,125.747 249,119.5C 247.486,113.877 249.319,109.877 254.5,107.5 Z" />
|
||||
|
||||
{/* Extended body details */}
|
||||
<path fill={fillColor} d="M 329.5,172.5 C 329.751,174.17 330.418,175.67 331.5,177C 330.551,177.617 329.718,177.451 329,176.5C 328.333,177.5 328.333,178.5 329,179.5C 329.333,179.167 329.667,178.833 330,178.5C 331.063,179.438 332.23,180.438 333.5,181.5C 333.034,179.705 333.034,177.705 333.5,175.5C 334.427,177.113 335.261,178.779 336,180.5C 336.232,179.263 336.732,178.263 337.5,177.5C 337.657,178.873 337.49,180.207 337,181.5C 336.124,183.758 334.957,185.758 333.5,187.5C 331.455,188.923 330.455,190.923 330.5,193.5C 321.603,207.727 311.937,221.394 301.5,234.5C 301.785,232.712 301.452,231.045 300.5,229.5C 297.606,230.909 296.606,230.242 297.5,227.5C 298.167,225.833 298.833,224.167 299.5,222.5C 306.66,212.186 313.827,201.853 321,191.5C 324.438,185.303 327.271,178.969 329.5,172.5 Z" />
|
||||
|
||||
{/* Main body section */}
|
||||
<path fill={fillColor} d="M 195.5,158.5 C 199.127,167.099 202.794,175.765 206.5,184.5C 206.427,186.027 207.094,187.027 208.5,187.5C 213.391,196.567 220.558,202.9 230,206.5C 254.97,200.996 273.803,187.329 286.5,165.5C 286.643,168.097 287.477,170.431 289,172.5C 290.188,171.437 290.688,170.103 290.5,168.5C 292.199,168.473 293.533,167.806 294.5,166.5C 290.454,177.733 283.787,187.233 274.5,195C 259.369,206.946 243.036,214.112 225.5,216.5C 222.868,215.466 220.201,214.466 217.5,213.5C 217.5,212.833 217.5,212.167 217.5,211.5C 211.822,206.986 206.989,201.653 203,195.5C 198.434,187.483 194.434,179.15 191,170.5C 175.85,181.982 164.684,196.482 157.5,214C 164.095,213.183 170.762,212.683 177.5,212.5C 174.695,213.319 171.695,213.819 168.5,214C 170.167,214.333 171.833,214.667 173.5,215C 171.136,216.012 169.802,217.345 169.5,219C 170.448,219.483 171.448,219.649 172.5,219.5C 172.5,219.833 172.5,220.167 172.5,220.5C 164.95,221.221 157.617,222.888 150.5,225.5C 148.06,224.726 146.727,223.06 146.5,220.5C 146.886,218.068 147.553,215.734 148.5,213.5C 149.906,213.027 150.573,212.027 150.5,210.5C 153.084,202.664 156.751,195.331 161.5,188.5C 169.649,178.517 178.649,169.351 188.5,161C 187.62,159.644 187.286,158.144 187.5,156.5C 184.505,156.706 181.838,156.04 179.5,154.5C 180.601,153.2 181.934,152.7 183.5,153C 184.833,153.667 184.833,154.333 183.5,155C 188.307,154.697 191.14,156.863 192,161.5C 193.729,161.026 194.895,160.026 195.5,158.5 Z M 217.5,211.5 C 216.221,212.968 214.554,213.635 212.5,213.5C 211.167,213.5 209.833,213.5 208.5,213.5C 202.225,212.066 195.725,211.4 189,211.5C 184.985,211.501 181.151,211.835 177.5,212.5C 170.762,212.683 164.095,213.183 157.5,214C 164.684,196.482 175.85,181.982 191,170.5C 194.434,179.15 198.434,187.483 203,195.5C 206.989,201.653 211.822,206.986 217.5,211.5 Z" />
|
||||
|
||||
{/* Additional body details */}
|
||||
<path fill={fillColor} d="M 221.5,184.5 C 224.113,183.565 226.779,183.398 229.5,184C 227.709,184.415 226.376,185.415 225.5,187C 228.167,187.667 230.833,187.667 233.5,187C 230.983,183.799 231.483,180.966 235,178.5C 235.667,177.167 235.667,175.833 235,174.5C 232.323,172.959 229.49,171.959 226.5,171.5C 232.176,171.072 237.843,170.905 243.5,171C 245.283,172.067 245.783,173.567 245,175.5C 243.247,176.627 241.413,177.627 239.5,178.5C 238.303,181.934 236.636,185.1 234.5,188C 231.167,188.667 227.833,188.667 224.5,188C 223.29,186.961 222.29,185.794 221.5,184.5 Z" />
|
||||
|
||||
{/* Body shading */}
|
||||
<path fill={fillColor} d="M 226.5,171.5 C 229.49,171.959 232.323,172.959 235,174.5C 235.667,175.833 235.667,177.167 235,178.5C 231.483,180.966 230.983,183.799 233.5,187C 230.833,187.667 228.167,187.667 225.5,187C 226.376,185.415 227.709,184.415 229.5,184C 226.779,183.398 224.113,183.565 221.5,184.5C 221.5,183.833 221.5,183.167 221.5,182.5C 221.656,179.934 221.322,177.434 220.5,175C 220.905,174.055 221.572,173.388 222.5,173C 221.5,172.667 220.5,172.333 219.5,172C 221.81,171.503 224.143,171.337 226.5,171.5 Z" />
|
||||
|
||||
{/* More body shading */}
|
||||
<path fill={fillColor} d="M 226.5,171.5 C 224.143,171.337 221.81,171.503 219.5,172C 220.5,172.333 221.5,172.667 222.5,173C 221.572,173.388 220.905,174.055 220.5,175C 221.322,177.434 221.656,179.934 221.5,182.5C 220.916,180.257 219.75,178.257 218,176.5C 217.333,174.833 217.333,173.167 218,171.5C 220.937,170.183 223.77,170.183 226.5,171.5 Z" />
|
||||
|
||||
{/* Lower body/legs area */}
|
||||
<path fill={fillColor} d="M 177.5,212.5 C 187.85,212.44 198.183,212.774 208.5,213.5C 209.833,213.5 211.167,213.5 212.5,213.5C 214.167,214.833 215.833,214.833 217.5,213.5C 220.201,214.466 222.868,215.466 225.5,216.5C 225.034,218.201 225.034,219.701 225.5,221C 224.429,221.852 223.429,222.685 222.5,223.5C 219.43,223.632 216.43,223.299 213.5,222.5C 213.44,221.957 213.107,221.624 212.5,221.5C 211.516,224.428 211.183,227.428 211.5,230.5C 209.859,228.797 208.859,226.63 208.5,224C 207.258,223.689 206.258,224.189 205.5,225.5C 204.692,225.192 204.025,224.692 203.5,224C 204.833,222.667 204.833,221.333 203.5,220C 201.866,219.506 200.199,219.34 198.5,219.5C 195.102,219.18 191.768,219.513 188.5,220.5C 188.624,221.107 188.957,221.44 189.5,221.5C 188.891,224.878 190.224,226.878 193.5,227.5C 195.288,228.622 197.288,228.789 199.5,228C 200.756,227.583 201.423,226.75 201.5,225.5C 202.995,225.415 203.995,226.081 204.5,227.5C 203.092,228.243 201.759,229.077 200.5,230C 202.249,232.213 204.249,233.213 206.5,233C 204.881,233.236 203.881,234.069 203.5,235.5C 202.5,235.5 201.5,235.5 200.5,235.5C 198.167,235.5 195.833,235.5 193.5,235.5C 193.333,285.168 193.5,334.834 194,384.5C 194.232,385.737 194.732,386.737 195.5,387.5C 197.821,396.471 201.488,404.805 206.5,412.5C 207.956,415.431 207.123,416.098 204,414.5C 203.333,416.167 203.333,417.833 204,419.5C 204.333,418.833 204.667,418.167 205,417.5C 206.109,420.947 205.109,423.614 202,425.5C 200.086,424.324 200.252,423.324 202.5,422.5C 202.167,422.167 201.833,421.833 201.5,421.5C 199.557,421.535 197.557,421.202 195.5,420.5C 186.876,409.404 181.876,396.738 180.5,382.5C 180.5,328.167 180.5,273.833 180.5,219.5C 177.833,219.5 175.167,219.5 172.5,219.5C 171.448,219.649 170.448,219.483 169.5,219C 169.802,217.345 171.136,216.012 173.5,215C 171.833,214.667 170.167,214.333 168.5,214C 171.695,213.819 174.695,213.319 177.5,212.5 Z M 189.5,221.5 C 192.287,220.523 195.287,220.19 198.5,220.5C 203.5,220.134 204.5,221.8 201.5,225.5C 199.087,227.051 196.421,227.717 193.5,227.5C 191.71,225.728 190.377,223.728 189.5,221.5 Z" />
|
||||
|
||||
{/* Extended body section */}
|
||||
<path fill={fillColor} d="M 225.5,216.5 C 247.583,219.231 268.249,225.898 287.5,236.5C 289.507,234.467 291.507,232.467 293.5,230.5C 294.906,230.027 295.573,229.027 295.5,227.5C 296.167,227.5 296.833,227.5 297.5,227.5C 296.606,230.242 297.606,230.909 300.5,229.5C 301.452,231.045 301.785,232.712 301.5,234.5C 300.585,236.754 299.252,238.754 297.5,240.5C 296.667,276.829 296.167,313.162 296,349.5C 295.065,357.682 292.231,365.016 287.5,371.5C 286.118,372.801 284.452,373.634 282.5,374C 283.252,374.671 283.586,375.504 283.5,376.5C 272.573,387.751 259.239,391.917 243.5,389C 219.325,381.522 207.825,365.022 209,339.5C 208.333,313.833 208.333,288.167 209,262.5C 209.391,257.944 211.891,255.61 216.5,255.5C 219.037,255.435 221.037,256.435 222.5,258.5C 223.333,289.495 223.833,320.495 224,351.5C 227.652,365.323 236.485,373.323 250.5,375.5C 251.793,376.158 253.293,376.492 255,376.5C 257.821,376.592 260.321,375.926 262.5,374.5C 272.878,370.283 279.044,362.616 281,351.5C 281.5,315.835 281.667,280.168 281.5,244.5C 281.027,243.094 280.027,242.427 278.5,242.5C 272.117,238.977 265.451,235.977 258.5,233.5C 257.558,233.608 256.725,233.941 256,234.5C 251.175,245.334 243.342,248.501 232.5,244C 230.622,242.457 229.122,240.624 228,238.5C 226.992,240.259 225.492,241.426 223.5,242C 220.167,242.667 216.833,242.667 213.5,242C 209.903,240.048 206.569,237.881 203.5,235.5C 203.881,234.069 204.881,233.236 206.5,233C 204.249,233.213 202.249,232.213 200.5,230C 201.759,229.077 203.092,228.243 204.5,227.5C 203.995,226.081 202.995,225.415 201.5,225.5C 204.5,221.8 203.5,220.134 198.5,220.5C 198.5,220.167 198.5,219.833 198.5,219.5C 200.199,219.34 201.866,219.506 203.5,220C 204.833,221.333 204.833,222.667 203.5,224C 204.025,224.692 204.692,225.192 205.5,225.5C 206.258,224.189 207.258,223.689 208.5,224C 208.859,226.63 209.859,228.797 211.5,230.5C 211.5,231.167 211.833,231.5 212.5,231.5C 215.518,234.97 218.852,235.304 222.5,232.5C 223.965,230.401 225.299,228.234 226.5,226C 225.644,224.405 224.311,223.572 222.5,223.5C 223.429,222.685 224.429,221.852 225.5,221C 225.034,219.701 225.034,218.201 225.5,216.5 Z M 244.5,228.5 C 245.609,229.29 246.942,229.79 248.5,230C 247.663,231.011 247.33,232.178 247.5,233.5C 238.193,240.515 234.36,238.181 236,226.5C 238.778,227.325 241.611,227.992 244.5,228.5 Z M 213.5,222.5 C 216.43,223.299 219.43,223.632 222.5,223.5C 224.311,223.572 225.644,224.405 226.5,226C 225.299,228.234 223.965,230.401 222.5,232.5C 218.852,235.304 215.518,234.97 212.5,231.5C 212.19,228.287 212.523,225.287 213.5,222.5 Z" />
|
||||
|
||||
{/* Additional details */}
|
||||
<path fill={fillColor} d="M 325.5,381.5 C 324.176,384.148 322.843,386.814 321.5,389.5C 318.621,387.559 315.788,388.226 313,391.5C 311.798,389.323 311.298,386.989 311.5,384.5C 311.333,336.832 311.5,289.166 312,241.5C 313.399,235.938 316.899,234.105 322.5,236C 324.049,237.214 325.215,238.714 326,240.5C 326.832,287.668 326.665,334.668 325.5,381.5 Z" />
|
||||
|
||||
{/* Final details */}
|
||||
<path fill={fillColor} d="M 287.5,371.5 C 286.92,373.749 285.587,375.415 283.5,376.5C 283.586,375.504 283.252,374.671 282.5,374C 284.452,373.634 286.118,372.801 287.5,371.5 Z" />
|
||||
|
||||
{/* Bottom section */}
|
||||
<path fill={fillColor} d="M 325.5,381.5 C 322.774,410.382 308.44,431.215 282.5,444C 280.564,444.813 278.564,445.313 276.5,445.5C 274.447,445.402 272.78,446.069 271.5,447.5C 243.945,453.656 220.111,446.99 200,427.5C 198.25,425.266 196.75,422.932 195.5,420.5C 197.557,421.202 199.557,421.535 201.5,421.5C 201.833,421.833 202.167,422.167 202.5,422.5C 200.252,423.324 200.086,424.324 202,425.5C 205.109,423.614 206.109,420.947 205,417.5C 204.667,418.167 204.333,418.833 204,419.5C 203.333,417.833 203.333,416.167 204,414.5C 207.123,416.098 207.956,415.431 206.5,412.5C 217.31,425.907 231.31,433.573 248.5,435.5C 253.65,436.651 258.984,436.817 264.5,436C 265.416,435.722 266.082,435.222 266.5,434.5C 284.985,429.357 298.318,418.024 306.5,400.5C 307.906,400.027 308.573,399.027 308.5,397.5C 309.598,393.089 310.598,388.755 311.5,384.5C 311.298,386.989 311.798,389.323 313,391.5C 315.788,388.226 318.621,387.559 321.5,389.5C 322.843,386.814 324.176,384.148 325.5,381.5 Z" />
|
||||
</svg>
|
||||
);
|
||||
}
|
||||
@@ -5,7 +5,7 @@ import { BrowserAddressBar } from './browser-address-bar';
|
||||
describe('BrowserAddressBar', () => {
|
||||
it('renders navigation buttons and address input', () => {
|
||||
render(<BrowserAddressBar />);
|
||||
|
||||
|
||||
expect(screen.getByTitle('Go back')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Go forward')).toBeInTheDocument();
|
||||
expect(screen.getByTitle('Refresh')).toBeInTheDocument();
|
||||
@@ -15,33 +15,56 @@ describe('BrowserAddressBar', () => {
|
||||
it('calls onNavigate with proper path when form is submitted', () => {
|
||||
const onNavigate = vi.fn();
|
||||
render(<BrowserAddressBar onNavigate={onNavigate} />);
|
||||
|
||||
|
||||
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
|
||||
fireEvent.change(input, { target: { value: 'about' } });
|
||||
fireEvent.submit(input.closest('form')!);
|
||||
|
||||
|
||||
expect(onNavigate).toHaveBeenCalledWith('/about');
|
||||
});
|
||||
|
||||
it('disables back/forward buttons based on canGoBack/canGoForward props', () => {
|
||||
it('disables back/forward buttons based on canGoBack/canGoForward props and handlers', () => {
|
||||
// Test with handlers provided
|
||||
const onBack = vi.fn();
|
||||
const onForward = vi.fn();
|
||||
|
||||
render(
|
||||
<BrowserAddressBar
|
||||
canGoBack={false}
|
||||
<BrowserAddressBar
|
||||
onBack={onBack}
|
||||
onForward={onForward}
|
||||
canGoBack={false}
|
||||
canGoForward={true}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
expect(screen.getByTitle('Go back')).toBeDisabled(); // disabled because canGoBack=false
|
||||
expect(screen.getByTitle('Go forward')).not.toBeDisabled(); // enabled because canGoForward=true and handler provided
|
||||
});
|
||||
|
||||
it('disables buttons when no handlers are provided', () => {
|
||||
render(
|
||||
<BrowserAddressBar
|
||||
canGoBack={true}
|
||||
canGoForward={true}
|
||||
/>
|
||||
);
|
||||
|
||||
// All buttons should be disabled when no handlers are provided
|
||||
expect(screen.getByTitle('Go back')).toBeDisabled();
|
||||
expect(screen.getByTitle('Go forward')).not.toBeDisabled();
|
||||
expect(screen.getByTitle('Go forward')).toBeDisabled();
|
||||
expect(screen.getByTitle('Refresh')).toBeDisabled();
|
||||
|
||||
// Input should also be disabled when no onNavigate handler is provided
|
||||
expect(screen.getByPlaceholderText('Enter path (e.g., /, /about)')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('calls navigation handlers when buttons are clicked', () => {
|
||||
const onBack = vi.fn();
|
||||
const onForward = vi.fn();
|
||||
const onRefresh = vi.fn();
|
||||
|
||||
|
||||
render(
|
||||
<BrowserAddressBar
|
||||
<BrowserAddressBar
|
||||
onBack={onBack}
|
||||
onForward={onForward}
|
||||
onRefresh={onRefresh}
|
||||
@@ -49,13 +72,30 @@ describe('BrowserAddressBar', () => {
|
||||
canGoForward={true}
|
||||
/>
|
||||
);
|
||||
|
||||
|
||||
fireEvent.click(screen.getByTitle('Go back'));
|
||||
fireEvent.click(screen.getByTitle('Go forward'));
|
||||
fireEvent.click(screen.getByTitle('Refresh'));
|
||||
|
||||
|
||||
expect(onBack).toHaveBeenCalled();
|
||||
expect(onForward).toHaveBeenCalled();
|
||||
expect(onRefresh).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('updates input value when currentPath prop changes', () => {
|
||||
const { rerender } = render(<BrowserAddressBar currentPath="/" />);
|
||||
|
||||
const input = screen.getByPlaceholderText('Enter path (e.g., /, /about)');
|
||||
expect(input).toHaveValue('/');
|
||||
|
||||
// Re-render with new currentPath
|
||||
rerender(<BrowserAddressBar currentPath="/about" />);
|
||||
|
||||
expect(input).toHaveValue('/about');
|
||||
|
||||
// Re-render with another path
|
||||
rerender(<BrowserAddressBar currentPath="/contact" />);
|
||||
|
||||
expect(input).toHaveValue('/contact');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useState } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { ChevronLeft, ChevronRight, RefreshCw } from 'lucide-react';
|
||||
@@ -30,8 +30,15 @@ export function BrowserAddressBar({
|
||||
}: BrowserAddressBarProps) {
|
||||
const [inputValue, setInputValue] = useState(currentPath);
|
||||
|
||||
// Update input value when currentPath changes (e.g., when iframe navigates)
|
||||
useEffect(() => {
|
||||
setInputValue(currentPath);
|
||||
}, [currentPath]);
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
if (!onNavigate) return;
|
||||
|
||||
let path = inputValue.trim();
|
||||
|
||||
// Ensure path starts with /
|
||||
@@ -39,7 +46,7 @@ export function BrowserAddressBar({
|
||||
path = '/' + path;
|
||||
}
|
||||
|
||||
onNavigate?.(path);
|
||||
onNavigate(path);
|
||||
};
|
||||
|
||||
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
|
||||
@@ -57,7 +64,7 @@ export function BrowserAddressBar({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onBack}
|
||||
disabled={!canGoBack}
|
||||
disabled={!canGoBack || !onBack}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Go back"
|
||||
>
|
||||
@@ -67,7 +74,7 @@ export function BrowserAddressBar({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onForward}
|
||||
disabled={!canGoForward}
|
||||
disabled={!canGoForward || !onForward}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Go forward"
|
||||
>
|
||||
@@ -77,6 +84,7 @@ export function BrowserAddressBar({
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={onRefresh}
|
||||
disabled={!onRefresh}
|
||||
className="h-8 w-8 p-0"
|
||||
title="Refresh"
|
||||
>
|
||||
@@ -85,13 +93,14 @@ export function BrowserAddressBar({
|
||||
</div>
|
||||
|
||||
{/* Address bar */}
|
||||
<form onSubmit={handleSubmit} className="flex-1 mx-2">
|
||||
<form onSubmit={handleSubmit} className="flex-1 mx-auto px-4 max-w-2xl">
|
||||
<Input
|
||||
type="text"
|
||||
value={inputValue}
|
||||
onChange={handleInputChange}
|
||||
placeholder="Enter path (e.g., /, /about)"
|
||||
className="h-8 bg-muted/50 border-muted-foreground/20 focus:bg-background"
|
||||
disabled={!onNavigate}
|
||||
/>
|
||||
</form>
|
||||
|
||||
|
||||
@@ -29,7 +29,7 @@ const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttribut
|
||||
<button
|
||||
type="button"
|
||||
onClick={() => setShowPassword(!showPassword)}
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 rounded-sm disabled:cursor-not-allowed disabled:opacity-50"
|
||||
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
|
||||
disabled={props.disabled}
|
||||
aria-label={showPassword ? "Hide password" : "Show password"}
|
||||
>
|
||||
|
||||
@@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef<
|
||||
<ToastPrimitives.Viewport
|
||||
ref={ref}
|
||||
className={cn(
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]",
|
||||
"fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[480px]",
|
||||
className
|
||||
)}
|
||||
{...props}
|
||||
@@ -41,7 +41,7 @@ const toastVariants = cva(
|
||||
const Toast = React.forwardRef<
|
||||
React.ElementRef<typeof ToastPrimitives.Root>,
|
||||
React.ComponentPropsWithoutRef<typeof ToastPrimitives.Root> &
|
||||
VariantProps<typeof toastVariants>
|
||||
VariantProps<typeof toastVariants>
|
||||
>(({ className, variant, ...props }, ref) => {
|
||||
return (
|
||||
<ToastPrimitives.Root
|
||||
|
||||
@@ -1,7 +1,6 @@
|
||||
import { createContext } from "react";
|
||||
|
||||
export type Theme = "dark" | "light" | "system";
|
||||
export type FilesystemType = "lightningfs" | "opfs";
|
||||
|
||||
export interface AppConfig {
|
||||
/** Current theme */
|
||||
@@ -12,8 +11,6 @@ export interface AppConfig {
|
||||
deployServer: string;
|
||||
/** Selected language */
|
||||
language?: string;
|
||||
/** Filesystem type to use */
|
||||
filesystemType: FilesystemType;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
|
||||
+27
-11
@@ -10,9 +10,9 @@ interface UseAIChatSessionOptions {
|
||||
projectId: string;
|
||||
tools?: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools?: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
maxSteps?: number;
|
||||
onUpdateMetadata?: (title: string, description: string) => void;
|
||||
onAIError?: (error: Error) => void;
|
||||
}
|
||||
|
||||
interface StreamingMessage {
|
||||
@@ -30,9 +30,9 @@ export function useAIChat({
|
||||
projectId,
|
||||
tools = {},
|
||||
customTools = {},
|
||||
systemPrompt,
|
||||
maxSteps = 50,
|
||||
onUpdateMetadata
|
||||
onUpdateMetadata,
|
||||
onAIError
|
||||
}: UseAIChatSessionOptions) {
|
||||
const sessionManager = useSessionManager();
|
||||
const { isConfigured } = useAISettings();
|
||||
@@ -46,14 +46,14 @@ export function useAIChat({
|
||||
|
||||
const initSession = useCallback(async () => {
|
||||
// Load or update session
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps);
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps);
|
||||
// Initialize individual state variables from existing session
|
||||
setMessages([...session.messages]);
|
||||
setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined);
|
||||
setIsLoading(session.isLoading);
|
||||
setTotalCost(session.totalCost || 0);
|
||||
setLastInputTokens(session.lastInputTokens || 0);
|
||||
}, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]);
|
||||
}, [sessionManager, projectId, tools, customTools, maxSteps]);
|
||||
|
||||
// Initialize session
|
||||
useEffect(() => {
|
||||
@@ -115,14 +115,30 @@ export function useAIChat({
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
try {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
onAIError(error);
|
||||
} else {
|
||||
console.error('AI chat error:', error);
|
||||
}
|
||||
}
|
||||
}, [projectId, sessionManager, initSession, onAIError]);
|
||||
|
||||
const startGeneration = useCallback(async (providerModel: string) => {
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
}, [projectId, sessionManager, initSession]);
|
||||
try {
|
||||
await initSession();
|
||||
await sessionManager.startGeneration(projectId, providerModel);
|
||||
} catch (error) {
|
||||
if (onAIError && error instanceof Error) {
|
||||
onAIError(error);
|
||||
} else {
|
||||
console.error('AI chat error:', error);
|
||||
}
|
||||
}
|
||||
}, [projectId, sessionManager, initSession, onAIError]);
|
||||
|
||||
const stopGeneration = useCallback(() => {
|
||||
sessionManager.stopGeneration(projectId);
|
||||
|
||||
@@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query';
|
||||
import { z } from 'zod';
|
||||
import { createAIClient } from '@/lib/ai-client';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
// Zod schemas for the two possible response formats
|
||||
const creditsResponseV1Schema = z.object({
|
||||
@@ -31,18 +32,14 @@ export interface CreditsResponse {
|
||||
* @param connection - The AI connection configuration
|
||||
* @returns Query result with credits information
|
||||
*/
|
||||
export function useAICredits(providerId: string, connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
}) {
|
||||
export function useAICredits(provider: AIProvider) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId],
|
||||
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
|
||||
queryFn: async (): Promise<CreditsResponse> => {
|
||||
try {
|
||||
const ai = createAIClient(connection, user);
|
||||
const ai = createAIClient(provider, user);
|
||||
const data = await ai.get('/credits');
|
||||
|
||||
// Validate and normalize the response
|
||||
@@ -68,5 +65,6 @@ export function useAICredits(providerId: string, connection: {
|
||||
retry: false, // Don't retry as not all providers support this endpoint
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled: provider.id === 'shakespeare' && !!user,
|
||||
});
|
||||
}
|
||||
@@ -42,9 +42,8 @@ describe('useAIProjectId', () => {
|
||||
|
||||
// Mock parseProviderModel
|
||||
mockParseProviderModel.mockReturnValue({
|
||||
provider: 'openai',
|
||||
provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
model: 'gpt-4',
|
||||
connection: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
});
|
||||
|
||||
// Mock createAIClient
|
||||
@@ -86,7 +85,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -110,7 +109,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -134,7 +133,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -157,7 +156,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -170,7 +169,7 @@ describe('useAIProjectId', () => {
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
|
||||
]);
|
||||
expect(mockCreateAIClient).toHaveBeenCalledWith(
|
||||
{ apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
|
||||
undefined
|
||||
);
|
||||
});
|
||||
@@ -188,7 +187,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -241,7 +240,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -296,7 +295,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -346,7 +345,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -396,7 +395,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -453,7 +452,7 @@ describe('useAIProjectId', () => {
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
});
|
||||
|
||||
|
||||
@@ -28,8 +28,8 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
|
||||
|
||||
try {
|
||||
// Initialize OpenAI client
|
||||
const { model, connection } = parseProviderModel(providerModel, settings.providers);
|
||||
const openai = createAIClient(connection, user);
|
||||
const { model, provider } = parseProviderModel(providerModel, settings.providers);
|
||||
const openai = createAIClient(provider, user);
|
||||
|
||||
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { buildProject } from "@/lib/build";
|
||||
import { useFS } from "./useFS";
|
||||
|
||||
export function useBuildProject(projectId: string) {
|
||||
const { fs } = useFS();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
return await buildProject({
|
||||
fs,
|
||||
projectPath: `/projects/${projectId}`,
|
||||
domParser: new DOMParser(),
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
import { useState, useCallback, useEffect } from 'react';
|
||||
|
||||
export interface ConsoleMessage {
|
||||
id: number;
|
||||
level: 'log' | 'warn' | 'error' | 'info' | 'debug';
|
||||
message: string;
|
||||
timestamp: number;
|
||||
}
|
||||
|
||||
// Global state for console messages
|
||||
let globalConsoleMessages: ConsoleMessage[] = [];
|
||||
const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set();
|
||||
|
||||
const notifyListeners = () => {
|
||||
listeners.forEach(listener => listener([...globalConsoleMessages]));
|
||||
};
|
||||
|
||||
export const useConsoleMessages = () => {
|
||||
const [messages, setMessages] = useState<ConsoleMessage[]>(globalConsoleMessages);
|
||||
|
||||
const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(), // Ensure uniqueness
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const clearMessages = useCallback(() => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
}, []);
|
||||
|
||||
const getErrorsSince = useCallback((timestamp: number) => {
|
||||
return globalConsoleMessages.filter(
|
||||
msg => msg.level === 'error' && msg.timestamp > timestamp
|
||||
);
|
||||
}, []);
|
||||
|
||||
// Subscribe to global state changes
|
||||
useEffect(() => {
|
||||
const listener = (newMessages: ConsoleMessage[]) => {
|
||||
setMessages(newMessages);
|
||||
};
|
||||
listeners.add(listener);
|
||||
return () => {
|
||||
listeners.delete(listener);
|
||||
};
|
||||
}, []);
|
||||
|
||||
return {
|
||||
messages,
|
||||
addMessage,
|
||||
clearMessages,
|
||||
getErrorsSince,
|
||||
};
|
||||
};
|
||||
|
||||
// Export functions for external use (like PreviewPane)
|
||||
export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => {
|
||||
const newMessage: ConsoleMessage = {
|
||||
id: Date.now() + Math.random(),
|
||||
level,
|
||||
message,
|
||||
timestamp: Date.now(),
|
||||
};
|
||||
|
||||
globalConsoleMessages = [...globalConsoleMessages, newMessage];
|
||||
notifyListeners();
|
||||
};
|
||||
|
||||
export const clearConsoleMessages = () => {
|
||||
globalConsoleMessages = [];
|
||||
notifyListeners();
|
||||
};
|
||||
@@ -0,0 +1,26 @@
|
||||
import { useMutation } from "@tanstack/react-query";
|
||||
import { deployProject } from "@/lib/deploy";
|
||||
import { useFS } from "./useFS";
|
||||
import { useAppContext } from "./useAppContext";
|
||||
import { useCurrentUser } from "./useCurrentUser";
|
||||
|
||||
export function useDeployProject(projectId: string) {
|
||||
const { fs } = useFS();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async () => {
|
||||
if (!user) {
|
||||
throw new Error("You must be logged into Nostr to deploy a project");
|
||||
}
|
||||
return await deployProject({
|
||||
fs,
|
||||
projectId: projectId,
|
||||
deployServer: config.deployServer,
|
||||
projectPath: `/projects/${projectId}`,
|
||||
signer: user.signer,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -61,7 +61,7 @@ describe('useGitHubOAuth PKCE', () => {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
// Mock fetch for token exchange and user info (using corsproxy.io URLs)
|
||||
// Mock fetch for token exchange and user info (using proxy URLs)
|
||||
const mockFetch = vi.fn()
|
||||
.mockResolvedValueOnce({
|
||||
ok: true,
|
||||
@@ -147,7 +147,7 @@ describe('useGitHubOAuth PKCE', () => {
|
||||
|
||||
// Check that the token request includes the code verifier
|
||||
expect(mockFetch).toHaveBeenCalledWith(
|
||||
expect.stringContaining('corsproxy.io/?url=https://github.com/login/oauth/access_token'),
|
||||
'https://proxy.shakespeare.diy/?url=https%3A%2F%2Fgithub.com%2Flogin%2Foauth%2Faccess_token',
|
||||
expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: expect.stringContaining('"code_verifier":"test-verifier"'),
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useState, useCallback } from 'react';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { proxyUrl } from '@/lib/proxyUrl';
|
||||
|
||||
interface GitHubOAuthState {
|
||||
isLoading: boolean;
|
||||
@@ -17,7 +18,8 @@ export function useGitHubOAuth() {
|
||||
isLoading: false,
|
||||
error: null,
|
||||
});
|
||||
const { addCredential } = useGitSettings();
|
||||
const { settings, addCredential } = useGitSettings();
|
||||
const { corsProxy } = settings;
|
||||
|
||||
// Check if OAuth is configured
|
||||
const isOAuthConfigured = !!(
|
||||
@@ -70,7 +72,7 @@ export function useGitHubOAuth() {
|
||||
const params = new URLSearchParams({
|
||||
client_id: clientId,
|
||||
redirect_uri: window.location.origin + '/oauth/github',
|
||||
scope: 'repo',
|
||||
scope: 'repo workflow',
|
||||
state: state,
|
||||
code_challenge: codeChallenge,
|
||||
code_challenge_method: 'S256',
|
||||
@@ -122,7 +124,8 @@ export function useGitHubOAuth() {
|
||||
code_verifier: codeVerifier,
|
||||
};
|
||||
|
||||
const tokenResponse = await fetch('https://corsproxy.io/?url=https://github.com/login/oauth/access_token', {
|
||||
const tokenUrl = proxyUrl(corsProxy, 'https://github.com/login/oauth/access_token');
|
||||
const tokenResponse = await fetch(tokenUrl, {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Accept': 'application/json',
|
||||
@@ -142,7 +145,8 @@ export function useGitHubOAuth() {
|
||||
}
|
||||
|
||||
// Get user info to verify the token works
|
||||
const userResponse = await fetch('https://corsproxy.io/?url=https://api.github.com/user', {
|
||||
const userUrl = proxyUrl(corsProxy, 'https://api.github.com/user');
|
||||
const userResponse = await fetch(userUrl, {
|
||||
headers: {
|
||||
'Authorization': `Bearer ${tokenData.access_token}`,
|
||||
'Accept': 'application/vnd.github.v3+json',
|
||||
@@ -177,7 +181,7 @@ export function useGitHubOAuth() {
|
||||
}));
|
||||
return false;
|
||||
}
|
||||
}, [addCredential]);
|
||||
}, [addCredential, corsProxy]);
|
||||
|
||||
return {
|
||||
...state,
|
||||
|
||||
@@ -0,0 +1,117 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useIsProjectPreviewable } from './useIsProjectPreviewable';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the useProjectsManager hook
|
||||
const mockFileExists = vi.fn();
|
||||
vi.mock('./useProjectsManager', () => ({
|
||||
useProjectsManager: () => ({
|
||||
fileExists: mockFileExists,
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('useIsProjectPreviewable', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('returns true when all required files exist', async () => {
|
||||
mockFileExists.mockResolvedValue(true);
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(true);
|
||||
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'index.html');
|
||||
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package.json');
|
||||
expect(mockFileExists).toHaveBeenCalledWith('test-project', 'package-lock.json');
|
||||
});
|
||||
|
||||
it('returns false when index.html is missing', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'index.html') return Promise.resolve(false);
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when package.json is missing', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'package.json') return Promise.resolve(false);
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when package-lock.json is missing', async () => {
|
||||
mockFileExists.mockImplementation((projectId: string, filePath: string) => {
|
||||
if (filePath === 'package-lock.json') return Promise.resolve(false);
|
||||
return Promise.resolve(true);
|
||||
});
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(false);
|
||||
});
|
||||
|
||||
it('returns false when projectId is empty', async () => {
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable(''),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
// When projectId is empty, the query is disabled, so it should not be loading or successful
|
||||
expect(result.current.data).toBe(false);
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(mockFileExists).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('returns false when file check throws an error', async () => {
|
||||
mockFileExists.mockRejectedValue(new Error('File system error'));
|
||||
|
||||
const { result } = renderHook(
|
||||
() => useIsProjectPreviewable('test-project'),
|
||||
{ wrapper: TestApp }
|
||||
);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,38 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useProjectsManager } from './useProjectsManager';
|
||||
|
||||
/**
|
||||
* Hook to check if a project is previewable
|
||||
* A project is previewable if it has index.html, package.json, and package-lock.json
|
||||
*/
|
||||
export function useIsProjectPreviewable(projectId: string) {
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
const result = useQuery({
|
||||
queryKey: ['project-previewable', projectId],
|
||||
queryFn: async () => {
|
||||
try {
|
||||
// Check for required files
|
||||
const [hasIndexHtml, hasPackageJson, hasPackageLock] = await Promise.all([
|
||||
projectsManager.fileExists(projectId, 'index.html'),
|
||||
projectsManager.fileExists(projectId, 'package.json'),
|
||||
projectsManager.fileExists(projectId, 'package-lock.json'),
|
||||
]);
|
||||
|
||||
return hasIndexHtml && hasPackageJson && hasPackageLock;
|
||||
} catch (error) {
|
||||
console.error('Failed to check if project is previewable:', error);
|
||||
return false;
|
||||
}
|
||||
},
|
||||
enabled: !!projectId,
|
||||
staleTime: 5000, // Cache for 5 seconds
|
||||
refetchOnWindowFocus: false,
|
||||
});
|
||||
|
||||
// Return false when query is disabled (empty projectId) or when data is undefined
|
||||
return {
|
||||
...result,
|
||||
data: result.data ?? false,
|
||||
};
|
||||
}
|
||||
@@ -45,9 +45,8 @@ export function useProviderModels(): ModelFetchResult {
|
||||
|
||||
// Fetch models from each configured provider in parallel
|
||||
const providerPromises = settings.providers.map(async (provider) => {
|
||||
const { id: providerKey, ...connection } = provider;
|
||||
try {
|
||||
const openai = createAIClient(connection, user);
|
||||
const openai = createAIClient(provider, user);
|
||||
|
||||
// Fetch models with timeout
|
||||
try {
|
||||
@@ -59,8 +58,8 @@ export function useProviderModels(): ModelFetchResult {
|
||||
const providerModels = response.data.map((model) => {
|
||||
const providerModel: ProviderModel = {
|
||||
id: model.id,
|
||||
provider: providerKey,
|
||||
fullId: `${providerKey}/${model.id}`,
|
||||
provider: provider.id,
|
||||
fullId: `${provider.id}/${model.id}`,
|
||||
};
|
||||
|
||||
if ('name' in model && typeof model.name === 'string') {
|
||||
@@ -95,16 +94,16 @@ export function useProviderModels(): ModelFetchResult {
|
||||
return providerModels;
|
||||
} catch (fetchError) {
|
||||
if (fetchError instanceof Error && fetchError.name === 'AbortError') {
|
||||
errors.push(`${providerKey}: Request timeout`);
|
||||
errors.push(`${provider.id}: Request timeout`);
|
||||
} else {
|
||||
throw fetchError;
|
||||
}
|
||||
return [];
|
||||
}
|
||||
} catch (providerError) {
|
||||
console.warn(`Failed to fetch models from ${providerKey}:`, providerError);
|
||||
console.warn(`Failed to fetch models from ${provider.id}:`, providerError);
|
||||
errors.push(
|
||||
`${providerKey}: ${
|
||||
`${provider.id}: ${
|
||||
providerError instanceof Error ? providerError.message : 'Unknown error'
|
||||
}`
|
||||
);
|
||||
|
||||
@@ -20,14 +20,12 @@ export interface JSRuntimeFS {
|
||||
stat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isSymbolicLink?(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}>;
|
||||
lstat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
isSymbolicLink?(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}>;
|
||||
|
||||
@@ -1,441 +0,0 @@
|
||||
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
|
||||
/**
|
||||
* OPFS (Origin Private File System) adapter that implements JSRuntimeFS interface
|
||||
* This makes OPFS compatible with the unified filesystem interface
|
||||
*/
|
||||
export class OPFSAdapter implements JSRuntimeFS {
|
||||
private root: Promise<FileSystemDirectoryHandle>;
|
||||
|
||||
constructor() {
|
||||
// Check if OPFS is available
|
||||
if (!('storage' in navigator) ||
|
||||
typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
|
||||
throw new Error('OPFS is not supported in this browser or environment');
|
||||
}
|
||||
|
||||
// Get the root directory handle for OPFS
|
||||
this.root = (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory();
|
||||
}
|
||||
|
||||
/**
|
||||
* Special method to handle Git-specific read operations more robustly
|
||||
* This helps with isomorphic-git compatibility
|
||||
*/
|
||||
private async readFileForGit(path: string): Promise<Uint8Array> {
|
||||
try {
|
||||
// Guard against undefined path
|
||||
if (!path || typeof path !== 'string') {
|
||||
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'open';
|
||||
error.path = path || 'undefined';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const fileHandle = await this.getFileHandle(path);
|
||||
const file = await fileHandle.getFile();
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
return new Uint8Array(arrayBuffer);
|
||||
} catch (error) {
|
||||
// Enhanced error handling for Git operations
|
||||
console.error(`Git read operation failed for path: ${path}`, error);
|
||||
|
||||
// Create a more detailed error that isomorphic-git can handle
|
||||
const gitError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
gitError.code = 'ENOENT';
|
||||
gitError.errno = -2;
|
||||
gitError.syscall = 'open';
|
||||
gitError.path = path;
|
||||
|
||||
// Preserve original error information by adding it to the message
|
||||
if (error instanceof Error) {
|
||||
gitError.message = `${gitError.message}: ${error.message}`;
|
||||
}
|
||||
|
||||
throw gitError;
|
||||
}
|
||||
}
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array>;
|
||||
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||
async readFile(path: string, encoding: string): Promise<string>;
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||
try {
|
||||
// Debug logging to see what's being called
|
||||
console.log(`OPFSAdapter.readFile called with path:`, path, `encoding:`, encoding);
|
||||
|
||||
// Simple path validation like LightningFS
|
||||
if (!path || typeof path !== 'string') {
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}
|
||||
|
||||
// Use special Git handling for Git object files
|
||||
if (path.includes('.git/objects/') || path.includes('.git/')) {
|
||||
return await this.readFileForGit(path);
|
||||
}
|
||||
|
||||
const fileHandle = await this.getFileHandle(path);
|
||||
const file = await fileHandle.getFile();
|
||||
|
||||
if (encoding === 'utf8') {
|
||||
const text = await file.text();
|
||||
return text;
|
||||
} else if (encoding) {
|
||||
// For other encodings, we might need additional handling
|
||||
const text = await file.text();
|
||||
return text;
|
||||
} else {
|
||||
// Return as Uint8Array by default
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
return new Uint8Array(arrayBuffer);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`OPFSAdapter.readFile failed for path: ${path}`, error);
|
||||
|
||||
// Convert to Node.js style error for consistency
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
const nodeError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
nodeError.code = 'ENOENT';
|
||||
nodeError.errno = -2;
|
||||
nodeError.syscall = 'open';
|
||||
nodeError.path = path;
|
||||
throw nodeError;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
|
||||
const fileHandle = await this.getFileHandle(path, { create: true });
|
||||
const writable = await fileHandle.createWritable();
|
||||
|
||||
if (typeof data === 'string') {
|
||||
await writable.write(data);
|
||||
} else {
|
||||
await writable.write(data);
|
||||
}
|
||||
|
||||
await writable.close();
|
||||
}
|
||||
|
||||
async readdir(path: string): Promise<string[]>;
|
||||
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
|
||||
try {
|
||||
console.log(`OPFSAdapter.readdir called with path:`, path, `options:`, options);
|
||||
const dirHandle = await this.getDirectoryHandle(path);
|
||||
const entries: string[] = [];
|
||||
const directoryEntries: DirectoryEntry[] = [];
|
||||
|
||||
// Use asyncIterator to iterate through directory entries
|
||||
const dirIterator = (dirHandle as unknown as { values: () => AsyncIterableIterator<FileSystemHandle> }).values();
|
||||
let result = await dirIterator.next();
|
||||
|
||||
while (!result.done) {
|
||||
const entry = result.value;
|
||||
if (options?.withFileTypes) {
|
||||
directoryEntries.push({
|
||||
name: entry.name,
|
||||
isDirectory: () => entry.kind === 'directory',
|
||||
isFile: () => entry.kind === 'file',
|
||||
});
|
||||
} else {
|
||||
entries.push(entry.name);
|
||||
}
|
||||
result = await dirIterator.next();
|
||||
}
|
||||
|
||||
return options?.withFileTypes ? directoryEntries : entries;
|
||||
} catch (error) {
|
||||
console.error(`OPFSAdapter.readdir failed for path: ${path}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
try {
|
||||
console.log(`OPFSAdapter.mkdir called with path:`, path, `options:`, options);
|
||||
|
||||
// Guard against undefined path
|
||||
if (!path || typeof path !== 'string') {
|
||||
const error = new Error('ENOENT: no such file or directory, mkdir \'undefined\'') as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'mkdir';
|
||||
error.path = path || 'undefined';
|
||||
throw error;
|
||||
}
|
||||
|
||||
if (options?.recursive) {
|
||||
await this.createDirectoriesRecursive(path);
|
||||
} else {
|
||||
const parentPath = this.getParentPath(path);
|
||||
const dirName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.getDirectoryHandle(dirName, { create: true });
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`OPFSAdapter.mkdir failed for path: ${path}`, error);
|
||||
|
||||
// Convert to Node.js style error for consistency
|
||||
let mkdirError: NodeJS.ErrnoException;
|
||||
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
// Parent directory doesn't exist
|
||||
mkdirError = new Error(`ENOENT: no such file or directory, mkdir '${path}'`) as NodeJS.ErrnoException;
|
||||
mkdirError.code = 'ENOENT';
|
||||
mkdirError.errno = -2;
|
||||
} else {
|
||||
// Other errors
|
||||
mkdirError = new Error(`EACCES: permission denied, mkdir '${path}'`) as NodeJS.ErrnoException;
|
||||
mkdirError.code = 'EACCES';
|
||||
mkdirError.errno = -13;
|
||||
}
|
||||
|
||||
mkdirError.syscall = 'mkdir';
|
||||
mkdirError.path = path;
|
||||
|
||||
// Preserve original error information by adding it to the message
|
||||
if (error instanceof Error) {
|
||||
mkdirError.message = `${mkdirError.message}: ${error.message}`;
|
||||
}
|
||||
|
||||
throw mkdirError;
|
||||
}
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}> {
|
||||
try {
|
||||
console.log(`OPFSAdapter.stat called with path:`, path);
|
||||
const fileHandle = await this.getFileHandle(path);
|
||||
const file = await fileHandle.getFile();
|
||||
|
||||
return {
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: file.size,
|
||||
mtimeMs: file.lastModified,
|
||||
};
|
||||
} catch (fileError) {
|
||||
// If not a file, try as directory
|
||||
try {
|
||||
await this.getDirectoryHandle(path);
|
||||
return {
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
};
|
||||
} catch (dirError) {
|
||||
// Throw ENOENT error to match Node.js fs convention
|
||||
const error = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'stat';
|
||||
error.path = path;
|
||||
console.error(`OPFSAdapter.stat failed for path: ${path}`, { fileError, dirError });
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}> {
|
||||
// OPFS doesn't have symbolic links, so lstat is the same as stat
|
||||
return this.stat(path);
|
||||
}
|
||||
|
||||
async unlink(path: string): Promise<void> {
|
||||
const parentPath = this.getParentPath(path);
|
||||
const fileName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.removeEntry(fileName);
|
||||
}
|
||||
|
||||
async rmdir(path: string): Promise<void> {
|
||||
const parentPath = this.getParentPath(path);
|
||||
const dirName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.removeEntry(dirName, { recursive: true });
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
// OPFS doesn't have a native rename operation, so we need to copy and delete
|
||||
await this.copyRecursive(oldPath, newPath);
|
||||
await this.unlinkRecursive(oldPath);
|
||||
}
|
||||
|
||||
async readlink(_path: string): Promise<string> {
|
||||
// OPFS doesn't support symbolic links
|
||||
throw new Error('Symbolic links are not supported in OPFS');
|
||||
}
|
||||
|
||||
async symlink(_target: string, _path: string): Promise<void> {
|
||||
// OPFS doesn't support symbolic links
|
||||
throw new Error('Symbolic links are not supported in OPFS');
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
private async getDirectoryHandle(path: string, options?: { create?: boolean }): Promise<FileSystemDirectoryHandle> {
|
||||
if (path === '/' || path === '') {
|
||||
return this.root;
|
||||
}
|
||||
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
let currentHandle = await this.root;
|
||||
|
||||
for (const part of parts) {
|
||||
try {
|
||||
currentHandle = await currentHandle.getDirectoryHandle(part, options);
|
||||
} catch (error) {
|
||||
if (!options?.create) {
|
||||
// Convert OPFS error to ENOENT for consistency
|
||||
const errorWithCode = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
|
||||
errorWithCode.code = 'ENOENT';
|
||||
errorWithCode.errno = -2;
|
||||
errorWithCode.syscall = 'scandir';
|
||||
errorWithCode.path = path;
|
||||
throw errorWithCode;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
return currentHandle;
|
||||
}
|
||||
|
||||
private async getFileHandle(path: string, options?: { create?: boolean }): Promise<FileSystemFileHandle> {
|
||||
// Guard against undefined path
|
||||
if (!path || typeof path !== 'string') {
|
||||
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'open';
|
||||
error.path = path || 'undefined';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const parentPath = this.getParentPath(path);
|
||||
const fileName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
try {
|
||||
return parentHandle.getFileHandle(fileName, options);
|
||||
} catch (error) {
|
||||
if (!options?.create) {
|
||||
// Convert OPFS error to ENOENT for consistency
|
||||
const errorWithCode = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
errorWithCode.code = 'ENOENT';
|
||||
errorWithCode.errno = -2;
|
||||
errorWithCode.syscall = 'open';
|
||||
errorWithCode.path = path;
|
||||
throw errorWithCode;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private getParentPath(path: string): string {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
parts.pop(); // Remove the last part
|
||||
return parts.length > 0 ? `/${parts.join('/')}` : '/';
|
||||
}
|
||||
|
||||
private getBaseName(path: string): string {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
return parts[parts.length - 1] || '';
|
||||
}
|
||||
|
||||
private async createDirectoriesRecursive(path: string): Promise<void> {
|
||||
try {
|
||||
// Guard against undefined path
|
||||
if (!path || typeof path !== 'string') {
|
||||
const error = new Error('ENOENT: no such file or directory, mkdir \'undefined\'') as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'mkdir';
|
||||
error.path = path || 'undefined';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
let currentHandle = await this.root;
|
||||
|
||||
for (const part of parts) {
|
||||
try {
|
||||
currentHandle = await currentHandle.getDirectoryHandle(part, { create: true });
|
||||
} catch (error) {
|
||||
console.error(`Failed to create directory part '${part}' in path '${path}':`, error);
|
||||
// Convert to proper Node.js error
|
||||
const mkdirError = new Error(`ENOENT: no such file or directory, mkdir '${path}'`) as NodeJS.ErrnoException;
|
||||
mkdirError.code = 'ENOENT';
|
||||
mkdirError.errno = -2;
|
||||
mkdirError.syscall = 'mkdir';
|
||||
mkdirError.path = path;
|
||||
if (error instanceof Error) {
|
||||
mkdirError.message = `${mkdirError.message}: ${error.message}`;
|
||||
}
|
||||
throw mkdirError;
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`OPFSAdapter.createDirectoriesRecursive failed for path: ${path}`, error);
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
private async copyRecursive(source: string, destination: string): Promise<void> {
|
||||
const sourceStat = await this.stat(source);
|
||||
|
||||
if (sourceStat.isFile()) {
|
||||
// Copy file
|
||||
const sourceHandle = await this.getFileHandle(source);
|
||||
const file = await sourceHandle.getFile();
|
||||
const destHandle = await this.getFileHandle(destination, { create: true });
|
||||
const writable = await destHandle.createWritable();
|
||||
await writable.write(file);
|
||||
await writable.close();
|
||||
} else if (sourceStat.isDirectory()) {
|
||||
// Copy directory
|
||||
await this.mkdir(destination, { recursive: true });
|
||||
const entries = await this.readdir(source);
|
||||
|
||||
for (const entry of entries) {
|
||||
const sourceEntry = source === '/' ? `/${entry}` : `${source}/${entry}`;
|
||||
const destEntry = destination === '/' ? `/${entry}` : `${destination}/${entry}`;
|
||||
await this.copyRecursive(sourceEntry, destEntry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async unlinkRecursive(path: string): Promise<void> {
|
||||
const stat = await this.stat(path);
|
||||
|
||||
if (stat.isFile()) {
|
||||
await this.unlink(path);
|
||||
} else if (stat.isDirectory()) {
|
||||
const entries = await this.readdir(path);
|
||||
|
||||
for (const entry of entries) {
|
||||
const entryPath = path === '/' ? `/${entry}` : `${path}/${entry}`;
|
||||
await this.unlinkRecursive(entryPath);
|
||||
}
|
||||
|
||||
// Remove the directory itself
|
||||
const parentPath = this.getParentPath(path);
|
||||
const dirName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.removeEntry(dirName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,698 +0,0 @@
|
||||
import type { JSRuntimeFS, DirectoryEntry } from './JSRuntime';
|
||||
|
||||
/**
|
||||
* Simple OPFS (Origin Private File System) adapter that implements JSRuntimeFS interface
|
||||
* This version is designed to work with isomorphic-git with minimal interference
|
||||
*/
|
||||
export class OPFSAdapterSimple implements JSRuntimeFS {
|
||||
private root: Promise<FileSystemDirectoryHandle>;
|
||||
private debugMode: boolean = false;
|
||||
|
||||
constructor(options?: { debug?: boolean }) {
|
||||
this.debugMode = options?.debug || false;
|
||||
|
||||
// Check if OPFS is available
|
||||
if (!('storage' in navigator) ||
|
||||
typeof (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory !== 'function') {
|
||||
throw new Error('OPFS is not supported in this browser or environment');
|
||||
}
|
||||
|
||||
// Get the root directory handle for OPFS
|
||||
this.root = (navigator.storage as unknown as { getDirectory: () => Promise<FileSystemDirectoryHandle> }).getDirectory();
|
||||
|
||||
if (this.debugMode) {
|
||||
console.log('OPFSAdapterSimple initialized with debug mode enabled');
|
||||
}
|
||||
}
|
||||
|
||||
private log(...args: unknown[]) {
|
||||
if (this.debugMode) {
|
||||
console.log('[OPFSAdapter]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
private logError(...args: unknown[]) {
|
||||
if (this.debugMode) {
|
||||
console.error('[OPFSAdapter]', ...args);
|
||||
}
|
||||
}
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array>;
|
||||
async readFile(path: string, encoding: 'utf8'): Promise<string>;
|
||||
async readFile(path: string, encoding: string): Promise<string>;
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array>;
|
||||
async readFile(path: string, encoding?: string): Promise<string | Uint8Array> {
|
||||
this.log(`readFile called: path="${path}", encoding="${encoding}", type: ${typeof encoding}`);
|
||||
|
||||
try {
|
||||
// Basic path validation - handle isomorphic-git calling with undefined paths
|
||||
// Note: isomorphic-git sometimes calls readFile with undefined paths to test filesystem capabilities
|
||||
if (!path || typeof path !== 'string' || path === 'undefined') {
|
||||
this.log(`Filesystem capability test with invalid path: ${path} (type: ${typeof path}) - this is normal`);
|
||||
const error = new Error(`ENOENT: no such file or directory, open '${path || 'undefined'}'`) as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'open';
|
||||
error.path = path || 'undefined';
|
||||
throw error;
|
||||
}
|
||||
|
||||
const fileHandle = await this.getFileHandle(path);
|
||||
const file = await fileHandle.getFile();
|
||||
|
||||
this.log(`File found: size=${file.size}, type="${file.type}", lastModified=${file.lastModified}`);
|
||||
|
||||
// Additional validation for Git files
|
||||
if (path.includes('.git/') && file.size === 0) {
|
||||
this.logError(`Warning: Git file is empty: ${path}`);
|
||||
}
|
||||
|
||||
// Handle encoding parameter exactly like LightningFS
|
||||
// Key insight: isomorphic-git sometimes passes options objects as encoding parameter
|
||||
// We need to distinguish between text files (config, refs, etc.) and binary files (pack, index, objects)
|
||||
|
||||
// Git binary files that should ALWAYS be returned as Uint8Array
|
||||
const isGitBinaryFile = path.includes('.git/objects/pack/') ||
|
||||
(path.includes('.git/objects/') && !path.includes('.git/objects/info/')) ||
|
||||
path.endsWith('.pack') ||
|
||||
path.endsWith('.idx') ||
|
||||
path.includes('.git/index');
|
||||
|
||||
// Git text files that should be returned as text when no explicit binary encoding is requested
|
||||
const isGitTextFile = path.includes('.git/config') ||
|
||||
path.includes('.git/HEAD') ||
|
||||
path.includes('.git/refs/') ||
|
||||
path.includes('.git/logs/') ||
|
||||
path.includes('.git/info/') ||
|
||||
path.includes('.git/hooks/') ||
|
||||
path.includes('.git/description');
|
||||
|
||||
// Determine if we should return text:
|
||||
// 1. Explicit utf8 encoding request
|
||||
// 2. Git text files (unless explicit binary encoding)
|
||||
// 3. Non-Git files (unless explicit binary encoding)
|
||||
const shouldReturnText = (encoding === 'utf8' && typeof encoding === 'string') ||
|
||||
(!isGitBinaryFile && (isGitTextFile || !path.includes('.git/'))) ||
|
||||
(isGitTextFile && typeof encoding !== 'string');
|
||||
|
||||
this.log(`File type analysis: isGitBinaryFile=${isGitBinaryFile}, isGitTextFile=${isGitTextFile}, shouldReturnText=${shouldReturnText}, encoding type=${typeof encoding}`);
|
||||
|
||||
if (shouldReturnText) {
|
||||
const text = await file.text();
|
||||
this.log(`Returning text content for encoding "${encoding}", length=${text.length}`);
|
||||
return text;
|
||||
} else {
|
||||
// No encoding or undefined, return as Uint8Array (binary data)
|
||||
let arrayBuffer: ArrayBuffer;
|
||||
|
||||
try {
|
||||
arrayBuffer = await file.arrayBuffer();
|
||||
if (!arrayBuffer) {
|
||||
throw new Error('ArrayBuffer is null or undefined');
|
||||
}
|
||||
} catch (bufferError) {
|
||||
this.logError(`Failed to get ArrayBuffer for ${path}:`, bufferError);
|
||||
throw new Error(`Failed to read binary data from file: ${path}`);
|
||||
}
|
||||
|
||||
// Create a proper Uint8Array that behaves like Node.js Buffer/Uint8Array
|
||||
// This is critical for isomorphic-git compatibility
|
||||
let uint8Array: Uint8Array;
|
||||
|
||||
try {
|
||||
uint8Array = new Uint8Array(arrayBuffer);
|
||||
|
||||
// For Git pack files and other binary Git objects, we need to be extra careful
|
||||
// isomorphic-git expects very specific behavior from these arrays
|
||||
if (path.includes('.git/')) {
|
||||
// Create a fresh Uint8Array to avoid any browser-specific quirks
|
||||
const gitCompatibleArray = new Uint8Array(uint8Array.length);
|
||||
gitCompatibleArray.set(uint8Array);
|
||||
|
||||
// Ensure the array has proper prototype and methods
|
||||
// Some isomorphic-git operations check for specific array methods
|
||||
if (!gitCompatibleArray.slice || typeof gitCompatibleArray.slice !== 'function') {
|
||||
this.logError(`Uint8Array missing slice method for Git file: ${path}`);
|
||||
}
|
||||
if (!gitCompatibleArray.subarray || typeof gitCompatibleArray.subarray !== 'function') {
|
||||
this.logError(`Uint8Array missing subarray method for Git file: ${path}`);
|
||||
}
|
||||
|
||||
uint8Array = gitCompatibleArray;
|
||||
}
|
||||
|
||||
// Validate the array before returning
|
||||
if (!uint8Array || uint8Array.length === undefined) {
|
||||
throw new Error(`Invalid Uint8Array created for file: ${path}`);
|
||||
}
|
||||
|
||||
this.log(`Returning binary content: ${uint8Array.length} bytes, constructor: ${uint8Array.constructor.name}, isGitFile: ${path.includes('.git/')}`);
|
||||
return uint8Array;
|
||||
} catch (arrayError) {
|
||||
this.logError(`Failed to create Uint8Array for ${path}:`, arrayError);
|
||||
throw new Error(`Failed to create binary array from file: ${path}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
this.logError(`readFile failed for path="${path}":`, error);
|
||||
|
||||
// Enhanced error handling for isomorphic-git compatibility
|
||||
let finalError: Error & NodeJS.ErrnoException;
|
||||
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'open';
|
||||
finalError.path = path;
|
||||
} else if (error instanceof Error) {
|
||||
// Wrap any other error to ensure it has required properties
|
||||
finalError = error as NodeJS.ErrnoException;
|
||||
if (!finalError.code) finalError.code = 'EIO';
|
||||
if (!finalError.errno) finalError.errno = -5;
|
||||
if (!finalError.syscall) finalError.syscall = 'read';
|
||||
if (!finalError.path) finalError.path = path;
|
||||
} else {
|
||||
// Convert non-Error objects to proper Error
|
||||
finalError = new Error(String(error)) as NodeJS.ErrnoException;
|
||||
finalError.code = 'EIO';
|
||||
finalError.errno = -5;
|
||||
finalError.syscall = 'read';
|
||||
finalError.path = path;
|
||||
}
|
||||
|
||||
// Ensure the error has the original error information
|
||||
if (error instanceof Error && error !== finalError) {
|
||||
// finalError.cause = error; // Not available in older TypeScript
|
||||
finalError.stack = error.stack;
|
||||
}
|
||||
|
||||
throw finalError;
|
||||
}
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array, _encoding?: string): Promise<void> {
|
||||
try {
|
||||
const fileHandle = await this.getFileHandle(path, { create: true });
|
||||
const writable = await fileHandle.createWritable();
|
||||
|
||||
if (typeof data === 'string') {
|
||||
await writable.write(data);
|
||||
} else {
|
||||
// For binary data, ensure we write it correctly
|
||||
// Some browsers may have issues with Uint8Array variants
|
||||
if (data instanceof Uint8Array) {
|
||||
await writable.write(data);
|
||||
} else {
|
||||
// Convert ArrayBuffer or other array-like objects to Uint8Array
|
||||
const uint8Array = new Uint8Array(data);
|
||||
await writable.write(uint8Array);
|
||||
}
|
||||
}
|
||||
|
||||
await writable.close();
|
||||
} catch (error) {
|
||||
// Enhanced error handling for write operations
|
||||
let finalError: Error & NodeJS.ErrnoException;
|
||||
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'open';
|
||||
finalError.path = path;
|
||||
} else if (error instanceof Error) {
|
||||
finalError = error as NodeJS.ErrnoException;
|
||||
if (!finalError.code) finalError.code = 'EIO';
|
||||
if (!finalError.errno) finalError.errno = -5;
|
||||
if (!finalError.syscall) finalError.syscall = 'write';
|
||||
if (!finalError.path) finalError.path = path;
|
||||
} else {
|
||||
finalError = new Error(String(error)) as NodeJS.ErrnoException;
|
||||
finalError.code = 'EIO';
|
||||
finalError.errno = -5;
|
||||
finalError.syscall = 'write';
|
||||
finalError.path = path;
|
||||
}
|
||||
|
||||
if (error instanceof Error && error !== finalError) {
|
||||
finalError.stack = error.stack;
|
||||
}
|
||||
|
||||
throw finalError;
|
||||
}
|
||||
}
|
||||
|
||||
async readdir(path: string): Promise<string[]>;
|
||||
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
|
||||
try {
|
||||
const dirHandle = await this.getDirectoryHandle(path);
|
||||
const entries: string[] = [];
|
||||
const directoryEntries: DirectoryEntry[] = [];
|
||||
|
||||
// Use asyncIterator to iterate through directory entries
|
||||
const dirIterator = (dirHandle as unknown as { values: () => AsyncIterableIterator<FileSystemHandle> }).values();
|
||||
let result = await dirIterator.next();
|
||||
|
||||
while (!result.done) {
|
||||
const entry = result.value;
|
||||
if (options?.withFileTypes) {
|
||||
directoryEntries.push({
|
||||
name: entry.name,
|
||||
isDirectory: () => entry.kind === 'directory',
|
||||
isFile: () => entry.kind === 'file',
|
||||
});
|
||||
} else {
|
||||
entries.push(entry.name);
|
||||
}
|
||||
result = await dirIterator.next();
|
||||
}
|
||||
|
||||
return options?.withFileTypes ? directoryEntries : entries;
|
||||
} catch (error) {
|
||||
// Convert DOMException to Node.js style error for isomorphic-git compatibility
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
const nodeError = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException;
|
||||
nodeError.code = 'ENOENT';
|
||||
nodeError.errno = -2;
|
||||
nodeError.syscall = 'scandir';
|
||||
nodeError.path = path;
|
||||
throw nodeError;
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
try {
|
||||
if (options?.recursive) {
|
||||
await this.createDirectoriesRecursive(path);
|
||||
} else {
|
||||
const parentPath = this.getParentPath(path);
|
||||
const dirName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.getDirectoryHandle(dirName, { create: true });
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
isFile(): boolean;
|
||||
}> {
|
||||
// Basic path validation
|
||||
if (!path || typeof path !== 'string') {
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}
|
||||
|
||||
try {
|
||||
const fileHandle = await this.getFileHandle(path);
|
||||
const file = await fileHandle.getFile();
|
||||
|
||||
// Check if this is a Git symlink file
|
||||
// Git symlinks are small files that contain target paths
|
||||
// We'll consider files < 1024 bytes that don't contain null bytes as potential symlinks
|
||||
// const isSymlink = file.size < 1024 && file.size > 0;
|
||||
|
||||
return {
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
// isSymbolicLink: () => isSymlink,
|
||||
size: file.size,
|
||||
mtimeMs: file.lastModified,
|
||||
};
|
||||
} catch {
|
||||
// If not a file, try as directory
|
||||
try {
|
||||
await this.getDirectoryHandle(path);
|
||||
return {
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
// isSymbolicLink: () => false,
|
||||
};
|
||||
} catch (dirError) {
|
||||
// Enhanced error handling for isomorphic-git compatibility
|
||||
let finalError: Error & NodeJS.ErrnoException;
|
||||
|
||||
if (dirError instanceof Error && (dirError.message.includes('NotFound') || dirError.name === 'NotFoundError')) {
|
||||
finalError = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'stat';
|
||||
finalError.path = path;
|
||||
} else if (dirError instanceof Error) {
|
||||
// Wrap any other error to ensure it has required properties
|
||||
finalError = dirError as NodeJS.ErrnoException;
|
||||
if (!finalError.code) finalError.code = 'UNKNOWN';
|
||||
if (!finalError.errno) finalError.errno = -1;
|
||||
if (!finalError.syscall) finalError.syscall = 'stat';
|
||||
if (!finalError.path) finalError.path = path;
|
||||
} else {
|
||||
// Convert non-Error objects to proper Error
|
||||
finalError = new Error(String(dirError)) as NodeJS.ErrnoException;
|
||||
finalError.code = 'UNKNOWN';
|
||||
finalError.errno = -1;
|
||||
finalError.syscall = 'stat';
|
||||
finalError.path = path;
|
||||
}
|
||||
|
||||
// Ensure error has original error information
|
||||
if (dirError instanceof Error && dirError !== finalError) {
|
||||
finalError.stack = dirError.stack;
|
||||
}
|
||||
|
||||
throw finalError;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{
|
||||
isDirectory(): boolean;
|
||||
isFile(): boolean;
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}> {
|
||||
// OPFS doesn't have real symbolic links, but we emulate them for Git
|
||||
// lstat should behave the same as stat in our emulation
|
||||
return this.stat(path);
|
||||
}
|
||||
|
||||
async unlink(path: string): Promise<void> {
|
||||
const parentPath = this.getParentPath(path);
|
||||
const fileName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.removeEntry(fileName);
|
||||
}
|
||||
|
||||
async rmdir(path: string): Promise<void> {
|
||||
const parentPath = this.getParentPath(path);
|
||||
const dirName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.removeEntry(dirName, { recursive: true });
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
// OPFS doesn't have a native rename operation, so we need to copy and delete
|
||||
await this.copyRecursive(oldPath, newPath);
|
||||
await this.unlinkRecursive(oldPath);
|
||||
}
|
||||
|
||||
async readlink(path: string): Promise<string> {
|
||||
try {
|
||||
// Basic path validation
|
||||
if (!path || typeof path !== 'string') {
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}
|
||||
|
||||
// OPFS doesn't support real symlinks, but Git uses them for .git/HEAD and refs
|
||||
// We emulate symlinks by storing the target as file content
|
||||
const fileHandle = await this.getFileHandle(path);
|
||||
const file = await fileHandle.getFile();
|
||||
const content = await file.text();
|
||||
|
||||
// Git symlink files contain the target path
|
||||
// Remove any trailing newlines and return the target
|
||||
return content.trim();
|
||||
} catch (error) {
|
||||
// Enhanced error handling for isomorphic-git compatibility
|
||||
let finalError: Error & NodeJS.ErrnoException;
|
||||
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
finalError = new Error(`ENOENT: no such file or directory, readlink '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'readlink';
|
||||
finalError.path = path;
|
||||
} else if (error instanceof Error) {
|
||||
// Wrap any other error to ensure it has required properties
|
||||
finalError = error as NodeJS.ErrnoException;
|
||||
if (!finalError.code) finalError.code = 'UNKNOWN';
|
||||
if (!finalError.errno) finalError.errno = -1;
|
||||
if (!finalError.syscall) finalError.syscall = 'readlink';
|
||||
if (!finalError.path) finalError.path = path;
|
||||
} else {
|
||||
// Convert non-Error objects to proper Error
|
||||
finalError = new Error(String(error)) as NodeJS.ErrnoException;
|
||||
finalError.code = 'UNKNOWN';
|
||||
finalError.errno = -1;
|
||||
finalError.syscall = 'readlink';
|
||||
finalError.path = path;
|
||||
}
|
||||
|
||||
// Ensure error has original error information
|
||||
if (error instanceof Error && error !== finalError) {
|
||||
finalError.stack = error.stack;
|
||||
}
|
||||
|
||||
throw finalError;
|
||||
}
|
||||
}
|
||||
|
||||
async symlink(target: string, path: string): Promise<void> {
|
||||
try {
|
||||
// Basic path validation
|
||||
if (!path || typeof path !== 'string') {
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}
|
||||
|
||||
// OPFS doesn't support real symlinks, but we can emulate them
|
||||
// by writing the target as file content (this is how Git stores symlinks)
|
||||
const fileHandle = await this.getFileHandle(path, { create: true });
|
||||
const writable = await fileHandle.createWritable();
|
||||
await writable.write(target);
|
||||
await writable.close();
|
||||
} catch (error) {
|
||||
// Enhanced error handling for isomorphic-git compatibility
|
||||
let finalError: Error & NodeJS.ErrnoException;
|
||||
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
finalError = new Error(`ENOENT: no such file or directory, symlink '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'symlink';
|
||||
finalError.path = path;
|
||||
} else if (error instanceof Error) {
|
||||
// Wrap any other error to ensure it has required properties
|
||||
finalError = error as NodeJS.ErrnoException;
|
||||
if (!finalError.code) finalError.code = 'UNKNOWN';
|
||||
if (!finalError.errno) finalError.errno = -1;
|
||||
if (!finalError.syscall) finalError.syscall = 'symlink';
|
||||
if (!finalError.path) finalError.path = path;
|
||||
} else {
|
||||
// Convert non-Error objects to proper Error
|
||||
finalError = new Error(String(error)) as NodeJS.ErrnoException;
|
||||
finalError.code = 'UNKNOWN';
|
||||
finalError.errno = -1;
|
||||
finalError.syscall = 'symlink';
|
||||
finalError.path = path;
|
||||
}
|
||||
|
||||
// Ensure error has original error information
|
||||
if (error instanceof Error && error !== finalError) {
|
||||
finalError.stack = error.stack;
|
||||
}
|
||||
|
||||
throw finalError;
|
||||
}
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
private async getDirectoryHandle(path: string, options?: { create?: boolean }): Promise<FileSystemDirectoryHandle> {
|
||||
if (path === '/' || path === '') {
|
||||
return this.root;
|
||||
}
|
||||
|
||||
// Basic path validation
|
||||
if (!path || typeof path !== 'string') {
|
||||
throw new Error('ENOENT: no such file or directory');
|
||||
}
|
||||
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
let currentHandle = await this.root;
|
||||
|
||||
for (const part of parts) {
|
||||
try {
|
||||
currentHandle = await currentHandle.getDirectoryHandle(part, options);
|
||||
} catch (error) {
|
||||
// Enhanced error handling for isomorphic-git compatibility
|
||||
let finalError: Error & NodeJS.ErrnoException;
|
||||
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
if (options?.create) {
|
||||
// If we're supposed to create, this shouldn't happen, but re-throw with better error
|
||||
finalError = new Error(`Failed to create directory part '${part}' in path '${path}': ${error.message}`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'EIO';
|
||||
finalError.errno = -5;
|
||||
finalError.syscall = 'mkdir';
|
||||
finalError.path = path;
|
||||
} else {
|
||||
// Directory doesn't exist and we're not creating it
|
||||
finalError = new Error(`ENOENT: no such file or directory, stat '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'stat';
|
||||
finalError.path = path;
|
||||
}
|
||||
} else if (error instanceof Error) {
|
||||
// Wrap any other error to ensure it has required properties
|
||||
finalError = error as NodeJS.ErrnoException;
|
||||
if (!finalError.code) finalError.code = 'UNKNOWN';
|
||||
if (!finalError.errno) finalError.errno = -1;
|
||||
if (!finalError.syscall) finalError.syscall = 'stat';
|
||||
if (!finalError.path) finalError.path = path;
|
||||
} else {
|
||||
// Convert non-Error objects to proper Error
|
||||
finalError = new Error(String(error)) as NodeJS.ErrnoException;
|
||||
finalError.code = 'UNKNOWN';
|
||||
finalError.errno = -1;
|
||||
finalError.syscall = 'stat';
|
||||
finalError.path = path;
|
||||
}
|
||||
|
||||
// Ensure error has original error information
|
||||
if (error instanceof Error && error !== finalError) {
|
||||
finalError.stack = error.stack;
|
||||
}
|
||||
|
||||
throw finalError;
|
||||
}
|
||||
}
|
||||
|
||||
return currentHandle;
|
||||
}
|
||||
|
||||
private async getFileHandle(path: string, options?: { create?: boolean }): Promise<FileSystemFileHandle> {
|
||||
// Basic path validation
|
||||
if (!path || typeof path !== 'string') {
|
||||
const error = new Error('ENOENT: no such file or directory, open \'undefined\'') as NodeJS.ErrnoException;
|
||||
error.code = 'ENOENT';
|
||||
error.errno = -2;
|
||||
error.syscall = 'open';
|
||||
error.path = 'undefined';
|
||||
throw error;
|
||||
}
|
||||
|
||||
try {
|
||||
const parentPath = this.getParentPath(path);
|
||||
const fileName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
return parentHandle.getFileHandle(fileName, options);
|
||||
} catch (error) {
|
||||
// Enhanced error handling for isomorphic-git compatibility
|
||||
let finalError: Error & NodeJS.ErrnoException;
|
||||
|
||||
if (error instanceof Error && (error.message.includes('NotFound') || error.name === 'NotFoundError')) {
|
||||
if (options?.create) {
|
||||
// If we're supposed to create, this shouldn't happen
|
||||
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'open';
|
||||
finalError.path = path;
|
||||
} else {
|
||||
// File doesn't exist and we're not creating it
|
||||
finalError = new Error(`ENOENT: no such file or directory, open '${path}'`) as NodeJS.ErrnoException;
|
||||
finalError.code = 'ENOENT';
|
||||
finalError.errno = -2;
|
||||
finalError.syscall = 'open';
|
||||
finalError.path = path;
|
||||
}
|
||||
} else if (error instanceof Error) {
|
||||
// Wrap any other error to ensure it has required properties
|
||||
finalError = error as NodeJS.ErrnoException;
|
||||
if (!finalError.code) finalError.code = 'UNKNOWN';
|
||||
if (!finalError.errno) finalError.errno = -1;
|
||||
if (!finalError.syscall) finalError.syscall = 'open';
|
||||
if (!finalError.path) finalError.path = path;
|
||||
} else {
|
||||
// Convert non-Error objects to proper Error
|
||||
finalError = new Error(String(error)) as NodeJS.ErrnoException;
|
||||
finalError.code = 'UNKNOWN';
|
||||
finalError.errno = -1;
|
||||
finalError.syscall = 'open';
|
||||
finalError.path = path;
|
||||
}
|
||||
|
||||
// Ensure error has original error information
|
||||
if (error instanceof Error && error !== finalError) {
|
||||
finalError.stack = error.stack;
|
||||
}
|
||||
|
||||
throw finalError;
|
||||
}
|
||||
}
|
||||
|
||||
private getParentPath(path: string): string {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
parts.pop(); // Remove the last part
|
||||
return parts.length > 0 ? `/${parts.join('/')}` : '/';
|
||||
}
|
||||
|
||||
private getBaseName(path: string): string {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
return parts[parts.length - 1] || '';
|
||||
}
|
||||
|
||||
private async createDirectoriesRecursive(path: string): Promise<void> {
|
||||
const parts = path.split('/').filter(Boolean);
|
||||
let currentHandle = await this.root;
|
||||
|
||||
for (const part of parts) {
|
||||
currentHandle = await currentHandle.getDirectoryHandle(part, { create: true });
|
||||
}
|
||||
}
|
||||
|
||||
private async copyRecursive(source: string, destination: string): Promise<void> {
|
||||
const sourceStat = await this.stat(source);
|
||||
|
||||
if (sourceStat.isFile()) {
|
||||
// Copy file
|
||||
const sourceHandle = await this.getFileHandle(source);
|
||||
const file = await sourceHandle.getFile();
|
||||
const destHandle = await this.getFileHandle(destination, { create: true });
|
||||
const writable = await destHandle.createWritable();
|
||||
await writable.write(file);
|
||||
await writable.close();
|
||||
} else if (sourceStat.isDirectory()) {
|
||||
// Copy directory
|
||||
await this.mkdir(destination, { recursive: true });
|
||||
const entries = await this.readdir(source);
|
||||
|
||||
for (const entry of entries) {
|
||||
const sourceEntry = source === '/' ? `/${entry}` : `${source}/${entry}`;
|
||||
const destEntry = destination === '/' ? `/${entry}` : `${destination}/${entry}`;
|
||||
await this.copyRecursive(sourceEntry, destEntry);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
private async unlinkRecursive(path: string): Promise<void> {
|
||||
const stat = await this.stat(path);
|
||||
|
||||
if (stat.isFile()) {
|
||||
await this.unlink(path);
|
||||
} else if (stat.isDirectory()) {
|
||||
const entries = await this.readdir(path);
|
||||
|
||||
for (const entry of entries) {
|
||||
const entryPath = path === '/' ? `/${entry}` : `${path}/${entry}`;
|
||||
await this.unlinkRecursive(entryPath);
|
||||
}
|
||||
|
||||
// Remove the directory itself
|
||||
const parentPath = this.getParentPath(path);
|
||||
const dirName = this.getBaseName(path);
|
||||
const parentHandle = await this.getDirectoryHandle(parentPath);
|
||||
await parentHandle.removeEntry(dirName);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -59,7 +59,7 @@ class MockFS implements JSRuntimeFS {
|
||||
error.code = 'ENOENT';
|
||||
throw error;
|
||||
}
|
||||
|
||||
|
||||
const entries: string[] = [];
|
||||
|
||||
// Find subdirectories
|
||||
@@ -125,6 +125,63 @@ class MockFS implements JSRuntimeFS {
|
||||
async rmdir(path: string): Promise<void> {
|
||||
this.dirs.delete(path);
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
// Handle both files and directories
|
||||
if (this.files.has(oldPath)) {
|
||||
const content = this.files.get(oldPath);
|
||||
this.files.delete(oldPath);
|
||||
this.files.set(newPath, content!);
|
||||
}
|
||||
|
||||
if (this.dirs.has(oldPath)) {
|
||||
this.dirs.delete(oldPath);
|
||||
this.dirs.add(newPath);
|
||||
|
||||
// Also move all subdirectories and files
|
||||
const itemsToMove: Array<{ oldPath: string; newPath: string; isDir: boolean }> = [];
|
||||
|
||||
// Collect directories to move
|
||||
for (const dir of this.dirs) {
|
||||
if (dir.startsWith(oldPath + '/')) {
|
||||
const relativePath = dir.slice(oldPath.length);
|
||||
itemsToMove.push({
|
||||
oldPath: dir,
|
||||
newPath: newPath + relativePath,
|
||||
isDir: true
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Collect files to move
|
||||
for (const file of this.files.keys()) {
|
||||
if (file.startsWith(oldPath + '/')) {
|
||||
const relativePath = file.slice(oldPath.length);
|
||||
itemsToMove.push({
|
||||
oldPath: file,
|
||||
newPath: newPath + relativePath,
|
||||
isDir: false
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Move all items
|
||||
for (const item of itemsToMove) {
|
||||
if (item.isDir) {
|
||||
this.dirs.delete(item.oldPath);
|
||||
this.dirs.add(item.newPath);
|
||||
} else {
|
||||
const content = this.files.get(item.oldPath);
|
||||
this.files.delete(item.oldPath);
|
||||
this.files.set(item.newPath, content!);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; mtimeMs?: number }> {
|
||||
return this.stat(path);
|
||||
}
|
||||
}
|
||||
|
||||
describe('ProjectsManager', () => {
|
||||
@@ -211,4 +268,68 @@ describe('ProjectsManager', () => {
|
||||
expect(project).toBeNull();
|
||||
});
|
||||
});
|
||||
|
||||
describe('renameProject', () => {
|
||||
it('should rename a project directory', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create a project
|
||||
await fs.mkdir('/projects/old-name');
|
||||
await fs.writeFile('/projects/old-name/package.json', '{}');
|
||||
|
||||
// Verify the project exists
|
||||
const originalProject = await projectsManager.getProject('old-name');
|
||||
expect(originalProject).not.toBeNull();
|
||||
|
||||
// Rename the project
|
||||
const renamedProject = await projectsManager.renameProject('old-name', 'new-name');
|
||||
|
||||
// Verify the renamed project
|
||||
expect(renamedProject.id).toBe('new-name');
|
||||
expect(renamedProject.name).toBe('new-name');
|
||||
expect(renamedProject.path).toBe('/projects/new-name');
|
||||
|
||||
// Verify old project no longer exists
|
||||
const oldProject = await projectsManager.getProject('old-name');
|
||||
expect(oldProject).toBeNull();
|
||||
|
||||
// Verify new project exists
|
||||
const newProject = await projectsManager.getProject('new-name');
|
||||
expect(newProject).not.toBeNull();
|
||||
expect(newProject?.id).toBe('new-name');
|
||||
});
|
||||
|
||||
it('should throw error when old project does not exist', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
await expect(projectsManager.renameProject('non-existent', 'new-name'))
|
||||
.rejects.toThrow('Project with ID "non-existent" does not exist');
|
||||
});
|
||||
|
||||
it('should throw error when new project name already exists', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create two projects
|
||||
await fs.mkdir('/projects/project-1');
|
||||
await fs.mkdir('/projects/project-2');
|
||||
|
||||
await expect(projectsManager.renameProject('project-1', 'project-2'))
|
||||
.rejects.toThrow('Project with ID "project-2" already exists');
|
||||
});
|
||||
|
||||
it('should validate and normalize project names', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Create a project
|
||||
await fs.mkdir('/projects/old-name');
|
||||
|
||||
// Try to rename with invalid characters
|
||||
await expect(projectsManager.renameProject('old-name', 'New Name With Spaces'))
|
||||
.rejects.toThrow('Project name must contain only lowercase letters, numbers, and hyphens');
|
||||
|
||||
// Try to rename with empty name
|
||||
await expect(projectsManager.renameProject('old-name', ''))
|
||||
.rejects.toThrow('Project name cannot be empty');
|
||||
});
|
||||
});
|
||||
});
|
||||
+84
-150
@@ -42,94 +42,60 @@ export class ProjectsManager {
|
||||
}
|
||||
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
console.log(`Creating project: ${name}, customId: ${customId}`);
|
||||
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||
console.log(`Project cloned at path: ${project.path}`);
|
||||
|
||||
try {
|
||||
await this.fs.mkdir(this.dir + `/${project.id}/.ai/history`, { recursive: true });
|
||||
console.log(`Created .ai/history directory for project ${project.id}`);
|
||||
} catch (error) {
|
||||
console.log(`Directory .ai/history might already exist for project ${project.id}:`, error);
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// Delete README.md if it exists
|
||||
try {
|
||||
await this.fs.unlink(`${project.path}/README.md`);
|
||||
console.log(`Deleted README.md for project ${project.id}`);
|
||||
} catch (error) {
|
||||
console.log(`README.md might not exist for project ${project.id}:`, error);
|
||||
} catch {
|
||||
// README.md might not exist, ignore error
|
||||
}
|
||||
|
||||
// Delete .git directory and reinitialize
|
||||
try {
|
||||
await this.deleteDirectory(`${project.path}/.git`);
|
||||
console.log(`Deleted .git directory for project ${project.id}`);
|
||||
} catch (error) {
|
||||
console.log(`.git directory might not exist for project ${project.id}:`, error);
|
||||
} catch {
|
||||
// .git directory might not exist, ignore error
|
||||
}
|
||||
|
||||
// Initialize new git repository
|
||||
try {
|
||||
await this.git.init({
|
||||
dir: project.path,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
console.log(`Initialized git repository for project ${project.id}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to initialize git repository for project ${project.id}:`, error);
|
||||
throw new Error(`Failed to initialize git repository: ${error}`);
|
||||
}
|
||||
await this.git.init({
|
||||
dir: project.path,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
try {
|
||||
const files = await this.getAllFiles(project.path);
|
||||
console.log(`Found ${files.length} files to add to git for project ${project.id}`);
|
||||
|
||||
for (const file of files) {
|
||||
// Skip .git directory and other hidden files we don't want to track
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: project.path,
|
||||
filepath: file,
|
||||
});
|
||||
} catch (error) {
|
||||
console.warn(`Failed to add file ${file} to git:`, error);
|
||||
}
|
||||
}
|
||||
const files = await this.getAllFiles(project.path);
|
||||
for (const file of files) {
|
||||
// Skip .git directory and other hidden files we don't want to track
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
await this.git.add({
|
||||
dir: project.path,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to get files for project ${project.id}:`, error);
|
||||
// Continue with commit even if we can't get all files
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
try {
|
||||
await this.git.commit({
|
||||
dir: project.path,
|
||||
message: 'New project created with Shakespeare',
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
console.log(`Made initial commit for project ${project.id}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to make initial commit for project ${project.id}:`, error);
|
||||
throw new Error(`Failed to make initial commit: ${error}`);
|
||||
}
|
||||
await this.git.commit({
|
||||
dir: project.path,
|
||||
message: 'New project created with Shakespeare',
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: 'assistant@shakespeare.diy',
|
||||
},
|
||||
});
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||
console.log(`Cloning project: ${name}, repo: ${repoUrl}, customId: ${customId}`);
|
||||
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
// Check if project with this ID already exists when using custom ID
|
||||
@@ -138,103 +104,28 @@ export class ProjectsManager {
|
||||
}
|
||||
|
||||
const projectPath = `${this.dir}/${id}`;
|
||||
console.log(`Project will be created at: ${projectPath}`);
|
||||
|
||||
try {
|
||||
await this.fs.mkdir(projectPath);
|
||||
console.log(`Created project directory: ${projectPath}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to create project directory ${projectPath}:`, error);
|
||||
throw new Error(`Failed to create project directory: ${error}`);
|
||||
}
|
||||
await this.fs.mkdir(projectPath);
|
||||
|
||||
// Clone the repository (Git class now handles Nostr URIs automatically)
|
||||
try {
|
||||
console.log(`Starting clone operation: ${repoUrl} -> ${projectPath}`);
|
||||
console.log(`Clone options:`, { singleBranch: true, depth: options?.depth });
|
||||
|
||||
// Add a timeout to prevent hanging
|
||||
const cloneTimeout = 60000; // 60 seconds
|
||||
const clonePromise = this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
singleBranch: true,
|
||||
depth: options?.depth, // Use depth if provided, otherwise clone full history
|
||||
});
|
||||
|
||||
const timeoutPromise = new Promise<never>((_, reject) => {
|
||||
setTimeout(() => {
|
||||
reject(new Error(`Clone operation timed out after ${cloneTimeout}ms`));
|
||||
}, cloneTimeout);
|
||||
});
|
||||
|
||||
await Promise.race([clonePromise, timeoutPromise]);
|
||||
console.log(`Successfully cloned repository to: ${projectPath}`);
|
||||
} catch (error) {
|
||||
console.error(`Failed to clone repository ${repoUrl} to ${projectPath}:`, error);
|
||||
|
||||
// Log additional debugging information
|
||||
if (error instanceof Error) {
|
||||
console.error(`Error name: ${error.name}`);
|
||||
console.error(`Error message: ${error.message}`);
|
||||
console.error(`Error stack:`, error.stack);
|
||||
|
||||
// Check if it's a filesystem-related error that suggests OPFS incompatibility
|
||||
const isOPFSCompatibilityIssue =
|
||||
error.message.includes('Cannot read properties of undefined') ||
|
||||
error.message.includes('readObjectPacked') ||
|
||||
error.message.includes('reading \'error\'') ||
|
||||
error.message.includes('TypeError') && error.stack?.includes('isomorphic-git');
|
||||
|
||||
if (isOPFSCompatibilityIssue) {
|
||||
console.error('🚨 DETECTED: Filesystem compatibility issue with isomorphic-git and OPFS');
|
||||
console.error('📋 ISSUE: isomorphic-git expects Node.js-style filesystem behavior, but OPFS has subtle differences');
|
||||
console.error('💡 SOLUTION: This project works best with LightningFS for Git operations');
|
||||
console.error('⚙️ RECOMMENDATION: Change filesystem setting to "lightningfs" in preferences');
|
||||
|
||||
// Provide a more user-friendly error message
|
||||
throw new Error(
|
||||
'Git clone failed due to filesystem compatibility issues. ' +
|
||||
'OPFS (Origin Private File System) has some compatibility limitations with Git operations. ' +
|
||||
'Please switch to LightningFS in your preferences for better Git support.'
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Clean up the failed project directory
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
console.log(`Cleaned up failed project directory: ${projectPath}`);
|
||||
} catch (cleanupError) {
|
||||
console.warn(`Failed to clean up project directory after clone failure:`, cleanupError);
|
||||
}
|
||||
|
||||
throw new Error(`Failed to clone repository: ${error}`);
|
||||
}
|
||||
await this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
singleBranch: true,
|
||||
depth: options?.depth, // Use depth if provided, otherwise clone full history
|
||||
});
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
try {
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
console.log(`Project stats retrieved, timestamp: ${timestamp}`);
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error(`Failed to get stats for project path ${projectPath}:`, error);
|
||||
// Return project with current timestamp if stats fail
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id),
|
||||
path: projectPath,
|
||||
lastModified: new Date(),
|
||||
};
|
||||
}
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
async getProjects(): Promise<Project[]> {
|
||||
@@ -373,6 +264,50 @@ export class ProjectsManager {
|
||||
await this.deleteDirectory(projectPath);
|
||||
}
|
||||
|
||||
async renameProject(oldId: string, newId: string): Promise<Project> {
|
||||
// Validate that the old project exists
|
||||
const oldProject = await this.getProject(oldId);
|
||||
if (!oldProject) {
|
||||
throw new Error(`Project with ID "${oldId}" does not exist`);
|
||||
}
|
||||
|
||||
// Validate that the new ID doesn't already exist
|
||||
if (await this.projectExists(newId)) {
|
||||
throw new Error(`Project with ID "${newId}" already exists`);
|
||||
}
|
||||
|
||||
// Validate the new ID format (same rules as generateUniqueProjectId)
|
||||
const validatedNewId = newId
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
|
||||
if (validatedNewId !== newId) {
|
||||
throw new Error(`Project name must contain only lowercase letters, numbers, and hyphens`);
|
||||
}
|
||||
|
||||
if (!validatedNewId) {
|
||||
throw new Error(`Project name cannot be empty`);
|
||||
}
|
||||
|
||||
const oldPath = `${this.dir}/${oldId}`;
|
||||
const newPath = `${this.dir}/${newId}`;
|
||||
|
||||
// Rename the directory
|
||||
await this.fs.rename(oldPath, newPath);
|
||||
|
||||
// Return the updated project object
|
||||
const stats = await this.fs.stat(newPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
return {
|
||||
id: newId,
|
||||
name: this.formatProjectName(newId),
|
||||
path: newPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
private async deleteDirectory(dirPath: string): Promise<void> {
|
||||
const files = await this.fs.readdir(dirPath);
|
||||
|
||||
@@ -414,8 +349,7 @@ export class ProjectsManager {
|
||||
const projectPath = `${this.dir}/${id}`;
|
||||
await this.fs.stat(projectPath);
|
||||
return true;
|
||||
} catch (error) {
|
||||
console.log(`Project ${id} does not exist or stat failed:`, error);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -95,4 +95,26 @@ describe('SessionManager', () => {
|
||||
expect(messageWithReasoning.reasoning_content).toBe('Let me think about this step by step...');
|
||||
}
|
||||
});
|
||||
|
||||
it('should throw service errors instead of adding them to message history', async () => {
|
||||
const projectId = 'test-project';
|
||||
const tools = {};
|
||||
const customTools = {};
|
||||
|
||||
// Load a session
|
||||
await sessionManager.loadSession(projectId, tools, customTools);
|
||||
|
||||
// Add a user message to enable generation
|
||||
await sessionManager.addMessage(projectId, { role: 'user', content: 'test message' });
|
||||
|
||||
// Attempt to start generation with invalid provider - should throw error instead of adding to messages
|
||||
await expect(
|
||||
sessionManager.startGeneration(projectId, 'invalid-provider/invalid-model')
|
||||
).rejects.toThrow('Provider "invalid-provider" not found');
|
||||
|
||||
// Verify that no error message was added to the conversation
|
||||
const updatedSession = sessionManager.getSession(projectId);
|
||||
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
|
||||
expect(updatedSession?.messages[0].role).toBe('user');
|
||||
});
|
||||
});
|
||||
+65
-39
@@ -6,6 +6,8 @@ import { createAIClient } from './ai-client';
|
||||
import type { Tool } from './tools/Tool';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { makeSystemPrompt } from './system';
|
||||
import { NostrMetadata } from '@nostrify/nostrify';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
role: 'assistant';
|
||||
@@ -18,7 +20,6 @@ export interface SessionState {
|
||||
projectId: string;
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
customTools: Record<string, Tool<unknown>>;
|
||||
systemPrompt?: string;
|
||||
maxSteps?: number;
|
||||
messages: AIMessage[];
|
||||
streamingMessage?: {
|
||||
@@ -55,13 +56,13 @@ export class SessionManager {
|
||||
private fs: JSRuntimeFS;
|
||||
private aiSettings: { providers: AIProvider[] };
|
||||
private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>;
|
||||
private getCurrentUser?: () => NUser | undefined;
|
||||
private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata };
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
aiSettings: { providers: AIProvider[] },
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
getCurrentUser?: () => NUser | undefined
|
||||
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.aiSettings = aiSettings;
|
||||
@@ -76,7 +77,6 @@ export class SessionManager {
|
||||
projectId: string,
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>,
|
||||
customTools: Record<string, Tool<unknown>>,
|
||||
systemPrompt?: string,
|
||||
maxSteps?: number
|
||||
): Promise<SessionState> {
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [];
|
||||
@@ -98,7 +98,6 @@ export class SessionManager {
|
||||
projectId,
|
||||
tools,
|
||||
customTools,
|
||||
systemPrompt,
|
||||
maxSteps,
|
||||
isLoading: false,
|
||||
lastActivity: new Date(),
|
||||
@@ -114,7 +113,6 @@ export class SessionManager {
|
||||
session.tools = tools;
|
||||
|
||||
session.customTools = customTools;
|
||||
session.systemPrompt = systemPrompt;
|
||||
session.maxSteps = maxSteps;
|
||||
|
||||
this.sessions.set(projectId, session);
|
||||
@@ -180,6 +178,7 @@ export class SessionManager {
|
||||
* Start AI generation for a session
|
||||
*/
|
||||
async startGeneration(projectId: string, providerModel: string): Promise<void> {
|
||||
console.log('Starting AI generation for project:', projectId, 'with model:', providerModel);
|
||||
let session = this.sessions.get(projectId);
|
||||
|
||||
if (!session) {
|
||||
@@ -203,12 +202,12 @@ export class SessionManager {
|
||||
try {
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const connectionConfig = parsed.connection;
|
||||
const modelName = parsed.model;
|
||||
const provider = parsed.provider;
|
||||
const model = parsed.model;
|
||||
|
||||
// Initialize OpenAI client
|
||||
const currentUser = this.getCurrentUser?.();
|
||||
const openai = createAIClient(connectionConfig, currentUser);
|
||||
const { user, metadata } = this.getCurrentUser?.() ?? {};
|
||||
const openai = createAIClient(provider, user);
|
||||
|
||||
let stepCount = 0;
|
||||
const maxSteps = session.maxSteps || 50;
|
||||
@@ -230,14 +229,25 @@ export class SessionManager {
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
const systemPrompt = await makeSystemPrompt({
|
||||
cwd: `/projects/${projectId}`,
|
||||
fs: this.fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(session.tools),
|
||||
user,
|
||||
metadata,
|
||||
});
|
||||
|
||||
// Prepare messages for AI
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt
|
||||
? [{ role: 'system', content: session.systemPrompt }, ...session.messages]
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
|
||||
? [{ role: 'system', content: systemPrompt }, ...session.messages]
|
||||
: session.messages;
|
||||
|
||||
// Prepare completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
model: modelName,
|
||||
model,
|
||||
messages,
|
||||
tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined,
|
||||
tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined,
|
||||
@@ -258,12 +268,12 @@ export class SessionManager {
|
||||
let finishReason: string | null = null;
|
||||
|
||||
// Process the stream
|
||||
let usage: { prompt_tokens: number; completion_tokens: number } | undefined;
|
||||
let usage: { prompt_tokens: number; completion_tokens: number; cost?: number } | undefined;
|
||||
for await (const chunk of stream) {
|
||||
// Check if session was cancelled
|
||||
if (!session.isLoading) break;
|
||||
|
||||
const delta = chunk.choices[0]?.delta;
|
||||
const delta = chunk.choices[0]?.delta as OpenAI.Chat.Completions.ChatCompletionChunk.Choice.Delta | undefined;
|
||||
|
||||
if (delta?.content) {
|
||||
accumulatedContent += delta.content;
|
||||
@@ -274,11 +284,18 @@ export class SessionManager {
|
||||
}
|
||||
|
||||
// Handle reasoning content if present (some providers may include this)
|
||||
const deltaWithReasoning = delta as { reasoning_content?: string };
|
||||
if (deltaWithReasoning?.reasoning_content) {
|
||||
accumulatedReasoningContent += deltaWithReasoning.reasoning_content;
|
||||
let reasoningContent: string | undefined;
|
||||
// LiteLLM, Z.ai, etc. use 'reasoning_content'
|
||||
if (delta && 'reasoning_content' in delta && typeof delta.reasoning_content === 'string') {
|
||||
reasoningContent = delta.reasoning_content;
|
||||
// ollama uses 'reasoning'
|
||||
} else if (delta && 'reasoning' in delta && typeof delta.reasoning === 'string') {
|
||||
reasoningContent = delta.reasoning;
|
||||
}
|
||||
if (reasoningContent) {
|
||||
accumulatedReasoningContent += reasoningContent;
|
||||
if (session.streamingMessage) {
|
||||
session.streamingMessage.reasoning_content += deltaWithReasoning.reasoning_content;
|
||||
session.streamingMessage.reasoning_content += reasoningContent;
|
||||
this.emit('streamingUpdate', projectId, session.streamingMessage.content, session.streamingMessage.reasoning_content, session.streamingMessage.tool_calls);
|
||||
}
|
||||
}
|
||||
@@ -312,13 +329,25 @@ export class SessionManager {
|
||||
|
||||
// Capture usage data if available (some providers include it in the final chunk)
|
||||
if (chunk.usage) {
|
||||
const cost = 'cost' in chunk.usage && typeof chunk.usage.cost === 'number'
|
||||
? chunk.usage.cost
|
||||
: undefined;
|
||||
|
||||
usage = {
|
||||
prompt_tokens: chunk.usage.prompt_tokens || 0,
|
||||
completion_tokens: chunk.usage.completion_tokens || 0
|
||||
completion_tokens: chunk.usage.completion_tokens || 0,
|
||||
cost,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Fix tool calls with empty arguments
|
||||
for (const toolCall of accumulatedToolCalls) {
|
||||
if (toolCall.type === 'function') {
|
||||
toolCall.function.arguments = toolCall.function.arguments || '{}';
|
||||
}
|
||||
}
|
||||
|
||||
// Create final assistant message
|
||||
const assistantMessage: AIMessage = {
|
||||
role: 'assistant',
|
||||
@@ -375,23 +404,13 @@ export class SessionManager {
|
||||
} catch (error) {
|
||||
console.error('AI generation error:', error);
|
||||
|
||||
// Handle different error types
|
||||
if (error?.name === 'AbortError') return; // User cancelled
|
||||
|
||||
let errorMessage = 'Sorry, I encountered an unexpected error. Please try again.';
|
||||
const errorMsg = error?.message || '';
|
||||
|
||||
if (error?.name === 'TypeError' && errorMsg.includes('fetch')) {
|
||||
errorMessage = 'Network error: Unable to connect to AI service. Please check your internet connection and AI settings.';
|
||||
} else if (errorMsg.includes('API key')) {
|
||||
errorMessage = 'Authentication error: Please check your API key in AI settings.';
|
||||
} else if (errorMsg.includes('rate limit')) {
|
||||
errorMessage = 'Rate limit exceeded. Please wait a moment before trying again.';
|
||||
} else if (errorMsg) {
|
||||
errorMessage = `AI service error: ${errorMsg}`;
|
||||
// Handle user cancellation
|
||||
if (error instanceof OpenAI.APIUserAbortError || error?.name === 'AbortError') {
|
||||
return; // User cancelled
|
||||
}
|
||||
|
||||
await this.addMessage(projectId, { role: 'assistant', content: errorMessage });
|
||||
// Re-throw service errors to be handled at the UI level
|
||||
throw error;
|
||||
} finally {
|
||||
if (session) {
|
||||
session.isLoading = false;
|
||||
@@ -454,20 +473,28 @@ export class SessionManager {
|
||||
/**
|
||||
* Update session cost and context usage based on usage data
|
||||
*/
|
||||
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void {
|
||||
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
|
||||
if (!this.getProviderModels) return;
|
||||
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
// If provider gives direct cost, use it
|
||||
if (typeof usage.cost === 'number') {
|
||||
session.totalCost = (session.totalCost || 0) + usage.cost;
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, get the cost from the models endpoint
|
||||
try {
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const modelName = parsed.model;
|
||||
const providerName = parsed.provider;
|
||||
const provider = parsed.provider;
|
||||
|
||||
// Find the model in provider models to get pricing and context length
|
||||
const models = this.getProviderModels();
|
||||
const model = models.find(m => m.id === modelName && m.provider === providerName);
|
||||
const model = models.find(m => m.id === modelName && m.provider === provider.id);
|
||||
|
||||
// Update input tokens for context usage tracking
|
||||
session.lastInputTokens = usage.prompt_tokens;
|
||||
@@ -484,7 +511,6 @@ export class SessionManager {
|
||||
|
||||
// Update session total cost
|
||||
session.totalCost = (session.totalCost || 0) + requestCost;
|
||||
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
} catch (error) {
|
||||
console.warn('Failed to calculate session cost:', error);
|
||||
|
||||
+30
-11
@@ -1,33 +1,52 @@
|
||||
import OpenAI from 'openai';
|
||||
import { NIP98Client } from '@nostrify/nostrify';
|
||||
import type { NUser } from '@nostrify/react/login';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
/**
|
||||
* Create an OpenAI client instance with the appropriate configuration.
|
||||
* If the connection requires Nostr authentication (NIP-98), it will use
|
||||
* the NIP98Client for authenticated requests.
|
||||
*/
|
||||
export function createAIClient(connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
}, user?: NUser): OpenAI {
|
||||
export function createAIClient(provider: AIProvider, user?: NUser): OpenAI {
|
||||
const baseConfig: ConstructorParameters<typeof OpenAI>[0] = {
|
||||
baseURL: connection.baseURL,
|
||||
apiKey: connection.apiKey ?? '',
|
||||
baseURL: provider.baseURL,
|
||||
apiKey: provider.apiKey ?? '',
|
||||
dangerouslyAllowBrowser: true,
|
||||
defaultHeaders: {
|
||||
// https://openrouter.ai/docs/app-attribution
|
||||
'HTTP-Referer': 'https://shakespeare.diy',
|
||||
'X-Title': 'Shakespeare',
|
||||
},
|
||||
};
|
||||
|
||||
let openai: OpenAI;
|
||||
|
||||
// If Nostr authentication is required and we have a user, use NIP-98
|
||||
if (connection.nostr && user?.signer) {
|
||||
if (provider.nostr && user?.signer) {
|
||||
const nip98Client = new NIP98Client({ signer: user.signer });
|
||||
|
||||
return new OpenAI({
|
||||
openai = new OpenAI({
|
||||
...baseConfig,
|
||||
fetch: (input, init) => nip98Client.fetch(input, init),
|
||||
});
|
||||
} else {
|
||||
// Standard OpenAI client
|
||||
openai = new OpenAI(baseConfig);
|
||||
}
|
||||
|
||||
// Standard OpenAI client
|
||||
return new OpenAI(baseConfig);
|
||||
const createCompletion: typeof openai.chat.completions.create
|
||||
= openai.chat.completions.create.bind(openai.chat.completions);
|
||||
|
||||
openai.chat.completions.create = ((...[body, options]: Parameters<typeof createCompletion>) => {
|
||||
// OpenRouter usage accounting
|
||||
// https://openrouter.ai/docs/use-cases/usage-accounting
|
||||
if (provider.id === 'openrouter') {
|
||||
(body as { usage?: { include?: boolean } }).usage = { include: true };
|
||||
}
|
||||
|
||||
return createCompletion(body, options);
|
||||
}) as typeof createCompletion;
|
||||
|
||||
return openai;
|
||||
}
|
||||
@@ -1,21 +0,0 @@
|
||||
import OpenAI from "openai";
|
||||
|
||||
export function assistantContentEmpty(
|
||||
content: OpenAI.ChatCompletionAssistantMessageParam['content'],
|
||||
): boolean {
|
||||
if (!content) return true;
|
||||
const text: string[] = [];
|
||||
|
||||
if (typeof content === 'string') {
|
||||
text.push(content);
|
||||
} else if (Array.isArray(content)) {
|
||||
for (const part of content) {
|
||||
if (part.type === 'text') {
|
||||
text.push(part.text);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = text.join('\n\n');
|
||||
return !result.trim();
|
||||
}
|
||||
@@ -76,7 +76,7 @@ describe('CurlCommand', () => {
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('Hello World');
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
method: 'GET',
|
||||
headers: expect.objectContaining({
|
||||
'User-Agent': 'curl/8.0.0 (compatible; JavaScript fetch)'
|
||||
@@ -103,7 +103,7 @@ describe('CurlCommand', () => {
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('{"success": true}');
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2Fapi', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2Fapi', expect.objectContaining({
|
||||
method: 'POST',
|
||||
body: '{"name": "test"}',
|
||||
headers: expect.objectContaining({
|
||||
@@ -131,7 +131,7 @@ describe('CurlCommand', () => {
|
||||
], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
headers: expect.objectContaining({
|
||||
'Authorization': 'Bearer token123',
|
||||
'Content-Type': 'application/json',
|
||||
@@ -245,7 +245,7 @@ describe('CurlCommand', () => {
|
||||
], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://corsproxy.io/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
expect(mockFetch).toHaveBeenCalledWith('https://proxy.shakespeare.diy/?url=https%3A%2F%2Fexample.com%2F', expect.objectContaining({
|
||||
method: 'DELETE',
|
||||
headers: expect.objectContaining({
|
||||
'User-Agent': 'curl/8.0.0 (compatible; JavaScript fetch)'
|
||||
|
||||
@@ -62,7 +62,7 @@ export class CurlCommand implements ShellCommand {
|
||||
|
||||
// Proxy the URL through CorsProxy
|
||||
const originalUrl = url.toString();
|
||||
const proxiedUrl = `https://corsproxy.io/?url=${encodeURIComponent(originalUrl)}`;
|
||||
const proxiedUrl = `https://proxy.shakespeare.diy/?url=${encodeURIComponent(originalUrl)}`;
|
||||
|
||||
// Prepare request
|
||||
const requestInit: RequestInit = {
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import { HexdumpCommand } from './hexdump';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('HexdumpCommand', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let command: HexdumpCommand;
|
||||
const testCwd = '/test/dir';
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
command = new HexdumpCommand(mockFS);
|
||||
});
|
||||
|
||||
it('should have correct name and description', () => {
|
||||
expect(command.name).toBe('hexdump');
|
||||
expect(command.description).toBe('Display file contents in hexadecimal format');
|
||||
expect(command.usage).toBe('hexdump [-C] [-n length] [-s skip] [file...]');
|
||||
});
|
||||
|
||||
it('should show error when no file is specified', async () => {
|
||||
const result = await command.execute([], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing file operand');
|
||||
});
|
||||
|
||||
it('should show error for non-existent file', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await command.execute(['nonexistent.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should show error for directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await command.execute(['testdir'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Is a directory');
|
||||
});
|
||||
|
||||
it('should display hexdump in default format', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('0000000');
|
||||
expect(result.stdout).toContain('000000e'); // Final offset
|
||||
});
|
||||
|
||||
it('should display hexdump in canonical format with -C', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000000');
|
||||
expect(result.stdout).toContain('|Hello, World!');
|
||||
expect(result.stdout).toContain('|'); // Should have ASCII representation
|
||||
});
|
||||
|
||||
it('should handle -n length option', async () => {
|
||||
const content = 'Hello, World!\nThis is a longer line.';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', '-n', '5', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('|Hello|');
|
||||
expect(result.stdout).not.toContain('World');
|
||||
});
|
||||
|
||||
it('should handle -s skip option', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', '-s', '7', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000007');
|
||||
expect(result.stdout).toContain('|World!');
|
||||
expect(result.stdout).not.toContain('Hello');
|
||||
});
|
||||
|
||||
it('should handle -n and -s together', async () => {
|
||||
const content = 'Hello, World!\n';
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content));
|
||||
|
||||
const result = await command.execute(['-C', '-s', '7', '-n', '5', 'test.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000007');
|
||||
expect(result.stdout).toContain('|World|');
|
||||
expect(result.stdout).not.toContain('Hello');
|
||||
expect(result.stdout).not.toContain('!');
|
||||
});
|
||||
|
||||
it('should show error for invalid -n value', async () => {
|
||||
const result = await command.execute(['-n', 'invalid'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('invalid length');
|
||||
});
|
||||
|
||||
it('should show error for invalid -s value', async () => {
|
||||
const result = await command.execute(['-s', 'invalid'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('invalid skip offset');
|
||||
});
|
||||
|
||||
it('should show error for missing -n argument', async () => {
|
||||
const result = await command.execute(['-n'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('option requires an argument -- n');
|
||||
});
|
||||
|
||||
it('should show error for missing -s argument', async () => {
|
||||
const result = await command.execute(['-s'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('option requires an argument -- s');
|
||||
});
|
||||
|
||||
it('should show error for invalid option', async () => {
|
||||
const result = await command.execute(['-x'], testCwd);
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('invalid option -- x');
|
||||
});
|
||||
|
||||
it('should handle multiple files', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile)
|
||||
.mockResolvedValueOnce(Buffer.from('ABC'))
|
||||
.mockResolvedValueOnce(Buffer.from('XYZ'));
|
||||
|
||||
const result = await command.execute(['-C', 'file1.txt', 'file2.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('==> file1.txt <==');
|
||||
expect(result.stdout).toContain('==> file2.txt <==');
|
||||
expect(result.stdout).toContain('|ABC|');
|
||||
expect(result.stdout).toContain('|XYZ|');
|
||||
});
|
||||
|
||||
it('should handle piped input', async () => {
|
||||
const input = 'Hello, World!';
|
||||
const result = await command.execute(['-C'], testCwd, input);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000000');
|
||||
expect(result.stdout).toContain('|Hello, World!|');
|
||||
});
|
||||
|
||||
it('should handle binary data correctly', async () => {
|
||||
// Create binary data with non-printable characters
|
||||
const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x7F, 0x80, 0xFF, 0x41, 0x42, 0x43]);
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(binaryData);
|
||||
|
||||
const result = await command.execute(['-C', 'binary.dat'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('00000000');
|
||||
expect(result.stdout).toContain('00 01 02 7f 80 ff 41 42 43');
|
||||
expect(result.stdout).toContain('|......ABC|'); // Non-printable chars shown as dots
|
||||
});
|
||||
|
||||
it('should handle empty file', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(''));
|
||||
|
||||
const result = await command.execute(['-C', 'empty.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // No output for empty file
|
||||
});
|
||||
|
||||
it('should handle skip beyond file length', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('Hi'));
|
||||
|
||||
const result = await command.execute(['-C', '-s', '10', 'short.txt'], testCwd);
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // No output since skip is beyond file
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,272 @@
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'hexdump' command
|
||||
* Display file contents in hexadecimal format
|
||||
*/
|
||||
export class HexdumpCommand implements ShellCommand {
|
||||
name = 'hexdump';
|
||||
description = 'Display file contents in hexadecimal format';
|
||||
usage = 'hexdump [-C] [-n length] [-s skip] [file...]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
|
||||
// Parse command line options
|
||||
const options = this.parseOptions(args);
|
||||
|
||||
if (options.error) {
|
||||
return createErrorResult(options.error);
|
||||
}
|
||||
|
||||
// If input is provided (from pipe), process it
|
||||
if (input !== undefined) {
|
||||
const buffer = Buffer.from(input, 'utf8');
|
||||
const output = this.formatHexdump(buffer, options);
|
||||
return createSuccessResult(output);
|
||||
}
|
||||
|
||||
// If no files specified, show usage
|
||||
if (options.files.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const outputs: string[] = [];
|
||||
|
||||
for (const filePath of options.files) {
|
||||
try {
|
||||
// Handle both absolute and relative paths
|
||||
let absolutePath: string;
|
||||
|
||||
if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) {
|
||||
// It's an absolute path - use it directly
|
||||
absolutePath = filePath;
|
||||
} else {
|
||||
// It's a relative path - resolve it relative to the current working directory
|
||||
absolutePath = join(cwd, filePath);
|
||||
}
|
||||
|
||||
// Check if path exists and is a file
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Is a directory`);
|
||||
}
|
||||
|
||||
// Read file content as binary
|
||||
const content = await this.fs.readFile(absolutePath);
|
||||
const buffer = Buffer.from(content);
|
||||
|
||||
// Format the hexdump
|
||||
const hexOutput = this.formatHexdump(buffer, options);
|
||||
|
||||
// Add filename header if multiple files
|
||||
if (options.files.length > 1) {
|
||||
outputs.push(`==> ${filePath} <==`);
|
||||
outputs.push(hexOutput);
|
||||
} else {
|
||||
outputs.push(hexOutput);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
// Handle file not found or permission errors
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: No such file or directory`);
|
||||
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Permission denied`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${filePath}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const result = outputs.join('\n');
|
||||
return createSuccessResult(result);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse command line options
|
||||
*/
|
||||
private parseOptions(args: string[]): {
|
||||
canonical: boolean;
|
||||
length?: number;
|
||||
skip: number;
|
||||
files: string[];
|
||||
error?: string;
|
||||
} {
|
||||
const options = {
|
||||
canonical: false,
|
||||
length: undefined as number | undefined,
|
||||
skip: 0,
|
||||
files: [] as string[],
|
||||
};
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '-C') {
|
||||
options.canonical = true;
|
||||
} else if (arg === '-n') {
|
||||
// Next argument should be the length
|
||||
if (i + 1 >= args.length) {
|
||||
return { ...options, error: `${this.name}: option requires an argument -- n` };
|
||||
}
|
||||
const lengthStr = args[++i];
|
||||
const length = parseInt(lengthStr, 10);
|
||||
if (isNaN(length) || length < 0) {
|
||||
return { ...options, error: `${this.name}: invalid length: ${lengthStr}` };
|
||||
}
|
||||
options.length = length;
|
||||
} else if (arg === '-s') {
|
||||
// Next argument should be the skip offset
|
||||
if (i + 1 >= args.length) {
|
||||
return { ...options, error: `${this.name}: option requires an argument -- s` };
|
||||
}
|
||||
const skipStr = args[++i];
|
||||
const skip = parseInt(skipStr, 10);
|
||||
if (isNaN(skip) || skip < 0) {
|
||||
return { ...options, error: `${this.name}: invalid skip offset: ${skipStr}` };
|
||||
}
|
||||
options.skip = skip;
|
||||
} else if (arg.startsWith('-')) {
|
||||
return { ...options, error: `${this.name}: invalid option -- ${arg.slice(1)}` };
|
||||
} else {
|
||||
// It's a filename
|
||||
options.files.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
return options;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format buffer content as hexdump
|
||||
*/
|
||||
private formatHexdump(buffer: Buffer, options: {
|
||||
canonical: boolean;
|
||||
length?: number;
|
||||
skip: number;
|
||||
}): string {
|
||||
const lines: string[] = [];
|
||||
const bytesPerLine = 16;
|
||||
|
||||
// Apply skip offset
|
||||
const startOffset = options.skip;
|
||||
if (startOffset >= buffer.length) {
|
||||
return ''; // Nothing to display
|
||||
}
|
||||
|
||||
// Apply length limit
|
||||
let endOffset = buffer.length;
|
||||
if (options.length !== undefined) {
|
||||
endOffset = Math.min(startOffset + options.length, buffer.length);
|
||||
}
|
||||
|
||||
for (let offset = startOffset; offset < endOffset; offset += bytesPerLine) {
|
||||
const lineEnd = Math.min(offset + bytesPerLine, endOffset);
|
||||
const lineBytes = buffer.subarray(offset, lineEnd);
|
||||
|
||||
if (options.canonical) {
|
||||
// Canonical format (-C): address, hex bytes, ASCII
|
||||
lines.push(this.formatCanonicalLine(offset, lineBytes));
|
||||
} else {
|
||||
// Default format: address followed by 16-bit words in hex
|
||||
lines.push(this.formatDefaultLine(offset, lineBytes));
|
||||
}
|
||||
}
|
||||
|
||||
// Add final offset line if we have data
|
||||
if (endOffset > startOffset) {
|
||||
const finalOffset = endOffset;
|
||||
lines.push(this.formatOffsetLine(finalOffset));
|
||||
}
|
||||
|
||||
return lines.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a line in canonical format (-C option)
|
||||
*/
|
||||
private formatCanonicalLine(offset: number, bytes: Buffer): string {
|
||||
const addressStr = offset.toString(16).padStart(8, '0');
|
||||
|
||||
// Format hex bytes (2 groups of 8 bytes each)
|
||||
const group1: string[] = [];
|
||||
const group2: string[] = [];
|
||||
|
||||
for (let i = 0; i < 16; i++) {
|
||||
const hexByte = i < bytes.length
|
||||
? bytes[i].toString(16).padStart(2, '0')
|
||||
: ' ';
|
||||
|
||||
if (i < 8) {
|
||||
group1.push(hexByte);
|
||||
} else {
|
||||
group2.push(hexByte);
|
||||
}
|
||||
}
|
||||
|
||||
const hexStr = group1.join(' ') + ' ' + group2.join(' ');
|
||||
|
||||
// Format ASCII representation
|
||||
let asciiStr = '';
|
||||
for (let i = 0; i < bytes.length; i++) {
|
||||
const byte = bytes[i];
|
||||
if (byte >= 32 && byte <= 126) {
|
||||
// Printable ASCII character
|
||||
asciiStr += String.fromCharCode(byte);
|
||||
} else {
|
||||
// Non-printable character
|
||||
asciiStr += '.';
|
||||
}
|
||||
}
|
||||
|
||||
return `${addressStr} ${hexStr} |${asciiStr}|`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format a line in default format
|
||||
*/
|
||||
private formatDefaultLine(offset: number, bytes: Buffer): string {
|
||||
const addressStr = offset.toString(16).padStart(7, '0');
|
||||
|
||||
// Group bytes into 16-bit words (little-endian)
|
||||
const words: string[] = [];
|
||||
for (let i = 0; i < bytes.length; i += 2) {
|
||||
if (i + 1 < bytes.length) {
|
||||
// Full 16-bit word (little-endian)
|
||||
const word = (bytes[i + 1] << 8) | bytes[i];
|
||||
words.push(word.toString(16).padStart(4, '0'));
|
||||
} else {
|
||||
// Partial word (only one byte)
|
||||
const word = bytes[i];
|
||||
words.push(word.toString(16).padStart(2, '0') + ' ');
|
||||
}
|
||||
}
|
||||
|
||||
return `${addressStr} ${words.join(' ')}`;
|
||||
}
|
||||
|
||||
/**
|
||||
* Format the final offset line
|
||||
*/
|
||||
private formatOffsetLine(offset: number): string {
|
||||
return offset.toString(16).padStart(7, '0');
|
||||
}
|
||||
}
|
||||
@@ -13,6 +13,7 @@ export { FindCommand } from './find';
|
||||
export { GitCommand } from './git';
|
||||
export { GrepCommand } from './grep';
|
||||
export { HeadCommand } from './head';
|
||||
export { HexdumpCommand } from './hexdump';
|
||||
export { LsCommand } from './ls';
|
||||
export { MkdirCommand } from './mkdir';
|
||||
export { MvCommand } from './mv';
|
||||
@@ -25,4 +26,5 @@ export { TrCommand } from './tr';
|
||||
export { UniqCommand } from './uniq';
|
||||
export { WcCommand } from './wc';
|
||||
export { WhoamiCommand } from './whoami';
|
||||
export { WhichCommand } from './which';
|
||||
export { WhichCommand } from './which';
|
||||
export { UnzipCommand } from './unzip';
|
||||
@@ -0,0 +1,303 @@
|
||||
import { describe, it, expect, beforeEach, vi } from 'vitest';
|
||||
import JSZip from 'jszip';
|
||||
import { UnzipCommand } from './unzip';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const createMockFS = (): JSRuntimeFS => ({
|
||||
readFile: vi.fn(),
|
||||
writeFile: vi.fn(),
|
||||
readdir: vi.fn(),
|
||||
mkdir: vi.fn(),
|
||||
stat: vi.fn(),
|
||||
lstat: vi.fn(),
|
||||
unlink: vi.fn(),
|
||||
rmdir: vi.fn(),
|
||||
rename: vi.fn(),
|
||||
readlink: vi.fn(),
|
||||
symlink: vi.fn(),
|
||||
});
|
||||
|
||||
describe('UnzipCommand', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let command: UnzipCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = createMockFS();
|
||||
command = new UnzipCommand(mockFS);
|
||||
});
|
||||
|
||||
const createTestZip = async (files: Record<string, string | Uint8Array>): Promise<Uint8Array> => {
|
||||
const zip = new JSZip();
|
||||
|
||||
for (const [path, content] of Object.entries(files)) {
|
||||
if (path.endsWith('/')) {
|
||||
zip.folder(path.slice(0, -1));
|
||||
} else {
|
||||
zip.file(path, content);
|
||||
}
|
||||
}
|
||||
|
||||
return zip.generateAsync({ type: 'uint8array' });
|
||||
};
|
||||
|
||||
it('should show usage when no arguments provided', async () => {
|
||||
const result = await command.execute([], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing archive operand');
|
||||
expect(result.stderr).toContain('Usage:');
|
||||
});
|
||||
|
||||
it('should show error for invalid options', async () => {
|
||||
const result = await command.execute(['-x', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("invalid option '-x'");
|
||||
});
|
||||
|
||||
it('should show error for non-existent archive', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await command.execute(['nonexistent.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should show error when trying to unzip a directory', async () => {
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
});
|
||||
|
||||
const result = await command.execute(['testdir'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Is a directory');
|
||||
});
|
||||
|
||||
it('should list archive contents with -l option', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World',
|
||||
'dir1/': '',
|
||||
'dir1/file2.txt': 'Test content'
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
|
||||
const result = await command.execute(['-l', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Archive: test.zip');
|
||||
expect(result.stdout).toContain('file1.txt');
|
||||
expect(result.stdout).toContain('dir1/');
|
||||
expect(result.stdout).toContain('dir1/file2.txt');
|
||||
});
|
||||
|
||||
it('should extract files to current directory', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
// Mock file operations - keep it simple
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Archive: test.zip');
|
||||
expect(result.stdout).toContain('inflating: file1.txt');
|
||||
|
||||
// Verify writeFile was called for extracted files
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
|
||||
});
|
||||
|
||||
it('should handle command line options correctly', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
// Test -d option
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['-d', 'extract', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('inflating: file1.txt');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/extract/file1.txt', expect.any(Uint8Array));
|
||||
});
|
||||
|
||||
it('should handle overwrite option', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'New content'
|
||||
});
|
||||
|
||||
// Mock file exists scenario
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
// Without -o option, should fail
|
||||
const resultWithoutOverwrite = await command.execute(['test.zip'], '/home');
|
||||
expect(resultWithoutOverwrite.exitCode).toBe(1);
|
||||
expect(resultWithoutOverwrite.stderr).toContain('File exists (use -o to overwrite)');
|
||||
|
||||
// Reset mocks
|
||||
vi.clearAllMocks();
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
// With -o option, should succeed
|
||||
const resultWithOverwrite = await command.execute(['-o', 'test.zip'], '/home');
|
||||
expect(resultWithOverwrite.exitCode).toBe(0);
|
||||
expect(resultWithOverwrite.stdout).toContain('inflating: file1.txt');
|
||||
});
|
||||
|
||||
it('should prevent extraction outside allowed directories', async () => {
|
||||
// Since JSZip normalizes paths during creation, we'll test the security logic
|
||||
// by mocking the internal zip.files object to simulate a malicious ZIP
|
||||
const zipData = await createTestZip({
|
||||
'normal.txt': 'safe content'
|
||||
});
|
||||
|
||||
// Mock the zip loading to return a ZIP with malicious paths
|
||||
const originalLoadAsync = JSZip.loadAsync;
|
||||
vi.spyOn(JSZip, 'loadAsync').mockImplementation(async () => {
|
||||
const zip = new JSZip();
|
||||
// Simulate malicious ZIP file entries that would escape the directory
|
||||
(zip as unknown as { files: Record<string, { name: string; dir: boolean; async: () => Promise<Uint8Array> }> }).files = {
|
||||
'../../../etc/passwd': {
|
||||
name: '../../../etc/passwd',
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])),
|
||||
},
|
||||
'../../outside.txt': {
|
||||
name: '../../outside.txt',
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])),
|
||||
},
|
||||
'normal.txt': {
|
||||
name: 'normal.txt',
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])),
|
||||
}
|
||||
};
|
||||
return zip;
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['test.zip'], '/home/user');
|
||||
|
||||
// Should return error because some files were skipped
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Path is outside allowed directories');
|
||||
expect(result.stderr).toContain('../../../etc/passwd');
|
||||
expect(result.stderr).toContain('../../outside.txt');
|
||||
|
||||
// Should only extract the safe file
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/user/normal.txt', expect.any(Uint8Array));
|
||||
expect(mockFS.writeFile).toHaveBeenCalledTimes(1);
|
||||
|
||||
// Restore the original method
|
||||
JSZip.loadAsync = originalLoadAsync;
|
||||
});
|
||||
|
||||
it('should allow extraction to /tmp directory', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockRejectedValueOnce(new Error('ENOENT')) // extraction dir doesn't exist
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['-d', '/tmp', 'test.zip'], '/home/user');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('inflating: file1.txt');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/file1.txt', expect.any(Uint8Array));
|
||||
});
|
||||
|
||||
it('should reject extraction directory outside allowed paths', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World'
|
||||
});
|
||||
|
||||
// Mock that the archive exists and provide zip data
|
||||
vi.mocked(mockFS.stat).mockResolvedValue({
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
});
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
|
||||
const result = await command.execute(['-d', '/etc', 'test.zip'], '/home/user');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("extraction directory '/etc' is outside allowed paths");
|
||||
});
|
||||
|
||||
it('should support quiet mode with -q flag', async () => {
|
||||
const zipData = await createTestZip({
|
||||
'file1.txt': 'Hello World',
|
||||
'dir1/': '',
|
||||
'dir1/file2.txt': 'Test content'
|
||||
});
|
||||
|
||||
vi.mocked(mockFS.stat)
|
||||
.mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists
|
||||
.mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists
|
||||
.mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check)
|
||||
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(zipData);
|
||||
vi.mocked(mockFS.writeFile).mockResolvedValue(undefined);
|
||||
vi.mocked(mockFS.mkdir).mockResolvedValue(undefined);
|
||||
|
||||
const result = await command.execute(['-q', 'test.zip'], '/home');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
// In quiet mode, should not show archive header or extraction messages
|
||||
expect(result.stdout).toBe('');
|
||||
|
||||
// But files should still be extracted
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array));
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/home/dir1/file2.txt', expect.any(Uint8Array));
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,220 @@
|
||||
import { join, dirname, normalize } from "path-browserify";
|
||||
import JSZip from "jszip";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'unzip' command
|
||||
* Extract files from ZIP archives
|
||||
*/
|
||||
export class UnzipCommand implements ShellCommand {
|
||||
name = 'unzip';
|
||||
description = 'Extract files from ZIP archives';
|
||||
usage = 'unzip [-d directory] [-o] [-l] [-q] archive.zip';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
if (args.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
let archivePath = '';
|
||||
let extractDir = cwd;
|
||||
let overwrite = false;
|
||||
let listOnly = false;
|
||||
let quiet = false;
|
||||
|
||||
// Parse command line options
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '-d' && i + 1 < args.length) {
|
||||
// Extract to specific directory
|
||||
extractDir = args[i + 1];
|
||||
i++; // Skip next argument
|
||||
} else if (arg === '-o') {
|
||||
// Overwrite existing files
|
||||
overwrite = true;
|
||||
} else if (arg === '-l') {
|
||||
// List archive contents only
|
||||
listOnly = true;
|
||||
} else if (arg === '-q') {
|
||||
// Quiet mode - suppress output
|
||||
quiet = true;
|
||||
} else if (arg.startsWith('-')) {
|
||||
return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`);
|
||||
} else {
|
||||
// This should be the archive path
|
||||
archivePath = arg;
|
||||
}
|
||||
}
|
||||
|
||||
if (!archivePath) {
|
||||
return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Resolve archive path
|
||||
let absoluteArchivePath: string;
|
||||
if (archivePath.startsWith('/') || archivePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(archivePath)) {
|
||||
absoluteArchivePath = archivePath;
|
||||
} else {
|
||||
absoluteArchivePath = join(cwd, archivePath);
|
||||
}
|
||||
|
||||
// Check if archive exists
|
||||
try {
|
||||
const stats = await this.fs.stat(absoluteArchivePath);
|
||||
if (stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: Is a directory`);
|
||||
}
|
||||
} catch {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: No such file or directory`);
|
||||
}
|
||||
|
||||
// Read the ZIP file
|
||||
const zipData = await this.fs.readFile(absoluteArchivePath);
|
||||
const zip = await JSZip.loadAsync(zipData);
|
||||
|
||||
// Resolve extraction directory
|
||||
let absoluteExtractDir: string;
|
||||
if (extractDir.startsWith('/') || extractDir.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(extractDir)) {
|
||||
absoluteExtractDir = extractDir;
|
||||
} else {
|
||||
absoluteExtractDir = join(cwd, extractDir);
|
||||
}
|
||||
|
||||
// Security check: ensure extraction directory is within allowed paths
|
||||
if (!this.isPathAllowed(absoluteExtractDir, cwd)) {
|
||||
return createErrorResult(`${this.name}: extraction directory '${extractDir}' is outside allowed paths (cwd or /tmp)`);
|
||||
}
|
||||
|
||||
if (listOnly) {
|
||||
// List contents only
|
||||
const entries: string[] = [];
|
||||
zip.forEach((relativePath, file) => {
|
||||
const date = file.date || new Date();
|
||||
const type = file.dir ? 'd' : '-';
|
||||
const sizeStr = file.dir ? '0' : '?';
|
||||
|
||||
entries.push(`${type}rw-r--r-- 1 user user ${sizeStr.padStart(8)} ${date.toISOString().slice(0, 19).replace('T', ' ')} ${relativePath}`);
|
||||
});
|
||||
|
||||
return createSuccessResult(`Archive: ${archivePath}\n${entries.join('\n')}`);
|
||||
}
|
||||
|
||||
// Create extraction directory if it doesn't exist
|
||||
try {
|
||||
await this.fs.stat(absoluteExtractDir);
|
||||
} catch {
|
||||
await this.fs.mkdir(absoluteExtractDir, { recursive: true });
|
||||
}
|
||||
|
||||
const extractedFiles: string[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
// Extract all files
|
||||
for (const [relativePath, file] of Object.entries(zip.files)) {
|
||||
const extractPath = join(absoluteExtractDir, relativePath);
|
||||
|
||||
// Security check: ensure each file path is within allowed directories
|
||||
if (!this.isPathAllowed(extractPath, cwd)) {
|
||||
errors.push(`${this.name}: ${relativePath}: Path is outside allowed directories (skipped for security)`);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
if (file.dir) {
|
||||
// Create directory
|
||||
await this.fs.mkdir(extractPath, { recursive: true });
|
||||
if (!quiet) {
|
||||
extractedFiles.push(` creating: ${relativePath}`);
|
||||
}
|
||||
} else {
|
||||
// Check if file exists and handle overwrite
|
||||
if (!overwrite) {
|
||||
try {
|
||||
await this.fs.stat(extractPath);
|
||||
errors.push(`${this.name}: ${relativePath}: File exists (use -o to overwrite)`);
|
||||
continue;
|
||||
} catch {
|
||||
// File doesn't exist, proceed with extraction
|
||||
}
|
||||
}
|
||||
|
||||
// Create parent directories if needed
|
||||
const parentDir = dirname(extractPath);
|
||||
try {
|
||||
await this.fs.stat(parentDir);
|
||||
} catch {
|
||||
await this.fs.mkdir(parentDir, { recursive: true });
|
||||
}
|
||||
|
||||
// Extract file content
|
||||
const content = await file.async('uint8array');
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
if (!quiet) {
|
||||
extractedFiles.push(` inflating: ${relativePath}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
errors.push(`${this.name}: ${relativePath}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
let output = '';
|
||||
if (!quiet) {
|
||||
output = `Archive: ${archivePath}\n`;
|
||||
if (extractedFiles.length > 0) {
|
||||
output += extractedFiles.join('\n');
|
||||
}
|
||||
}
|
||||
|
||||
if (errors.length > 0) {
|
||||
if (!quiet && extractedFiles.length > 0) {
|
||||
output += '\n';
|
||||
}
|
||||
return createErrorResult(output + '\n' + errors.join('\n'));
|
||||
}
|
||||
|
||||
return createSuccessResult(output);
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('corrupted') || error.message.includes('invalid')) {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: Archive is corrupted or invalid`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${archivePath}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a path is within allowed extraction directories (cwd or /tmp and their subdirectories)
|
||||
*/
|
||||
private isPathAllowed(extractPath: string, cwd: string): boolean {
|
||||
// Normalize the paths without using resolve() since we're in browser environment
|
||||
const normalizedPath = normalize(extractPath);
|
||||
const normalizedCwd = normalize(cwd);
|
||||
const tmpPath = '/tmp';
|
||||
|
||||
// Ensure paths are absolute for comparison
|
||||
const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath));
|
||||
const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd;
|
||||
|
||||
// Check if path is within cwd or /tmp
|
||||
return absolutePath.startsWith(absoluteCwd + '/') ||
|
||||
absolutePath === absoluteCwd ||
|
||||
absolutePath.startsWith(tmpPath + '/') ||
|
||||
absolutePath === tmpPath;
|
||||
}
|
||||
}
|
||||
@@ -185,7 +185,7 @@ describe('configUtils', () => {
|
||||
|
||||
expect(result).toEqual({
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
});
|
||||
});
|
||||
|
||||
|
||||
@@ -135,7 +135,7 @@ async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise<GitS
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
const settings: GitSettings = {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://cors.isomorphic-git.org',
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
// Write to VFS and remove from localStorage
|
||||
@@ -158,7 +158,7 @@ async function migrateGitSettingsFromLocalStorage(fs: JSRuntimeFS): Promise<GitS
|
||||
export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
const defaultSettings: GitSettings = {
|
||||
credentials: {},
|
||||
corsProxy: 'https://cors.isomorphic-git.org',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
|
||||
// Try to read from VFS first
|
||||
@@ -169,7 +169,7 @@ export async function readGitSettings(fs: JSRuntimeFS): Promise<GitSettings> {
|
||||
if (parsed && typeof parsed === 'object' && 'credentials' in parsed) {
|
||||
return {
|
||||
credentials: parsed.credentials || {},
|
||||
corsProxy: parsed.corsProxy || 'https://cors.isomorphic-git.org',
|
||||
corsProxy: parsed.corsProxy || 'https://proxy.shakespeare.diy/?url={href}',
|
||||
};
|
||||
}
|
||||
} catch {
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { deployProject } from './deploy';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import type { NostrSigner } from '@nostrify/nostrify';
|
||||
|
||||
// Mock JSZip
|
||||
vi.mock('jszip', () => {
|
||||
return {
|
||||
default: vi.fn().mockImplementation(() => ({
|
||||
folder: vi.fn().mockReturnValue({
|
||||
file: vi.fn(),
|
||||
}),
|
||||
file: vi.fn(),
|
||||
generateAsync: vi.fn().mockResolvedValue(new Blob()),
|
||||
})),
|
||||
};
|
||||
});
|
||||
|
||||
// Mock NIP98Client
|
||||
vi.mock('@nostrify/nostrify', () => ({
|
||||
NIP98Client: vi.fn().mockImplementation(() => ({
|
||||
fetch: vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
status: 200,
|
||||
statusText: 'OK',
|
||||
}),
|
||||
})),
|
||||
}));
|
||||
|
||||
describe('deployProject', () => {
|
||||
let mockFS: JSRuntimeFS;
|
||||
let mockSigner: NostrSigner;
|
||||
|
||||
beforeEach(() => {
|
||||
mockFS = {
|
||||
readFile: vi.fn().mockResolvedValue('mock file content'),
|
||||
readdir: vi.fn().mockResolvedValue([]),
|
||||
writeFile: vi.fn().mockResolvedValue(undefined),
|
||||
mkdir: vi.fn().mockResolvedValue(undefined),
|
||||
stat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
|
||||
lstat: vi.fn().mockResolvedValue({ isDirectory: () => false, isFile: () => true }),
|
||||
unlink: vi.fn().mockResolvedValue(undefined),
|
||||
rmdir: vi.fn().mockResolvedValue(undefined),
|
||||
rename: vi.fn().mockResolvedValue(undefined),
|
||||
readlink: vi.fn().mockResolvedValue(''),
|
||||
symlink: vi.fn().mockResolvedValue(undefined),
|
||||
} as JSRuntimeFS;
|
||||
|
||||
mockSigner = {} as NostrSigner;
|
||||
});
|
||||
|
||||
it('should construct hostname from projectId and deployServer by default', async () => {
|
||||
const result = await deployProject({
|
||||
projectId: 'test-project',
|
||||
deployServer: 'shakespeare.wtf',
|
||||
fs: mockFS,
|
||||
projectPath: '/projects/test-project',
|
||||
signer: mockSigner,
|
||||
});
|
||||
|
||||
expect(result.hostname).toBe('test-project.shakespeare.wtf');
|
||||
expect(result.url).toBe('https://test-project.shakespeare.wtf');
|
||||
});
|
||||
|
||||
it('should use customHostname when provided', async () => {
|
||||
const result = await deployProject({
|
||||
projectId: 'test-project',
|
||||
deployServer: 'shakespeare.wtf',
|
||||
fs: mockFS,
|
||||
projectPath: '/projects/test-project',
|
||||
signer: mockSigner,
|
||||
customHostname: 'my-custom-domain.example.com',
|
||||
});
|
||||
|
||||
expect(result.hostname).toBe('my-custom-domain.example.com');
|
||||
expect(result.url).toBe('https://my-custom-domain.example.com');
|
||||
});
|
||||
|
||||
it('should handle custom subdomain with same deploy server', async () => {
|
||||
const result = await deployProject({
|
||||
projectId: 'original-id',
|
||||
deployServer: 'shakespeare.wtf',
|
||||
fs: mockFS,
|
||||
projectPath: '/projects/original-id',
|
||||
signer: mockSigner,
|
||||
customHostname: 'custom-name.shakespeare.wtf',
|
||||
});
|
||||
|
||||
expect(result.hostname).toBe('custom-name.shakespeare.wtf');
|
||||
expect(result.url).toBe('https://custom-name.shakespeare.wtf');
|
||||
});
|
||||
});
|
||||
+5
-3
@@ -14,6 +14,8 @@ export interface DeployOptions {
|
||||
projectPath: string;
|
||||
/** Nostr signer for NIP-98 authentication */
|
||||
signer: NostrSigner;
|
||||
/** Custom hostname to use instead of constructing from projectId.deployServer */
|
||||
customHostname?: string;
|
||||
}
|
||||
|
||||
export interface DeployResult {
|
||||
@@ -28,10 +30,10 @@ export interface DeployResult {
|
||||
* to the deployment server using NIP-98 authentication.
|
||||
*/
|
||||
export async function deployProject(options: DeployOptions): Promise<DeployResult> {
|
||||
const { projectId, deployServer, fs, projectPath, signer } = options;
|
||||
const { projectId, deployServer, fs, projectPath, signer, customHostname } = options;
|
||||
|
||||
// Construct hostname and URL
|
||||
const hostname = `${projectId}.${deployServer}`;
|
||||
// Use custom hostname if provided, otherwise construct from projectId.deployServer
|
||||
const hostname = customHostname || `${projectId}.${deployServer}`;
|
||||
const deployUrl = `https://${deployServer}/deploy`;
|
||||
const siteUrl = `https://${hostname}`;
|
||||
|
||||
|
||||
@@ -66,7 +66,6 @@ describe('Git', () => {
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
});
|
||||
@@ -81,7 +80,6 @@ describe('Git', () => {
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://gitlab.com/user/repo.git',
|
||||
});
|
||||
@@ -96,7 +94,6 @@ describe('Git', () => {
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://custom.example.com/user/repo.git',
|
||||
});
|
||||
@@ -111,7 +108,6 @@ describe('Git', () => {
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'http://github.com/user/repo.git',
|
||||
});
|
||||
@@ -130,7 +126,6 @@ describe('Git', () => {
|
||||
|
||||
expect(mockGit.getRemoteInfo).toHaveBeenCalledWith({
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
});
|
||||
});
|
||||
@@ -142,7 +137,6 @@ describe('Git', () => {
|
||||
|
||||
expect(mockGit.getRemoteInfo).toHaveBeenCalledWith({
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
url: 'https://custom.example.com/user/repo.git',
|
||||
});
|
||||
});
|
||||
@@ -165,7 +159,6 @@ describe('Git', () => {
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
remote: 'origin',
|
||||
});
|
||||
@@ -180,7 +173,6 @@ describe('Git', () => {
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://gitlab.com/user/repo.git',
|
||||
});
|
||||
@@ -232,7 +224,6 @@ describe('Git', () => {
|
||||
expect(mockGit.clone).toHaveBeenCalledWith({
|
||||
fs,
|
||||
http: expect.any(Object),
|
||||
corsProxy: 'https://cors.example.com',
|
||||
dir: '/test',
|
||||
url: 'https://github.com/user/repo.git',
|
||||
});
|
||||
|
||||
+103
-33
@@ -1,7 +1,7 @@
|
||||
import git from 'isomorphic-git';
|
||||
import http from 'isomorphic-git/http/web';
|
||||
import git, { GitHttpRequest, GitHttpResponse, HttpClient } from 'isomorphic-git';
|
||||
import { NIP05 } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { proxyUrl } from './proxyUrl';
|
||||
import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
|
||||
@@ -25,13 +25,13 @@ interface NostrCloneURI {
|
||||
*/
|
||||
export class Git {
|
||||
private fs: JSRuntimeFS;
|
||||
private http: HttpClient;
|
||||
private nostr: NPool;
|
||||
private corsProxy?: string;
|
||||
|
||||
constructor(options: GitOptions) {
|
||||
this.fs = options.fs;
|
||||
this.http = new GitHttp(options.corsProxy);
|
||||
this.nostr = options.nostr;
|
||||
this.corsProxy = options.corsProxy;
|
||||
}
|
||||
|
||||
// Repository initialization and configuration
|
||||
@@ -56,8 +56,7 @@ export class Git {
|
||||
// Regular Git URL
|
||||
return git.clone({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -178,8 +177,7 @@ export class Git {
|
||||
}
|
||||
|
||||
return git.getRemoteInfo({
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -197,8 +195,7 @@ export class Git {
|
||||
// Regular Git fetch
|
||||
return git.fetch({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -216,8 +213,7 @@ export class Git {
|
||||
// Regular Git pull
|
||||
return git.pull({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -237,8 +233,7 @@ export class Git {
|
||||
|
||||
return git.push({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -387,8 +382,7 @@ export class Git {
|
||||
|
||||
async getRemoteInfo2(options: Omit<Parameters<typeof git.getRemoteInfo2>[0], 'http' | 'corsProxy'>) {
|
||||
return git.getRemoteInfo2({
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -513,8 +507,7 @@ export class Git {
|
||||
|
||||
async listServerRefs(options: Omit<Parameters<typeof git.listServerRefs>[0], 'http' | 'corsProxy'>) {
|
||||
return git.listServerRefs({
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
});
|
||||
}
|
||||
@@ -618,8 +611,7 @@ export class Git {
|
||||
// Try to get remote info from the first clone URL
|
||||
try {
|
||||
const gitRemoteInfo = await git.getRemoteInfo({
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
url: cloneUrls[0],
|
||||
});
|
||||
|
||||
@@ -1016,8 +1008,7 @@ export class Git {
|
||||
// Get remote repository information to check if it has the expected commit
|
||||
const remoteInfo = await Promise.race([
|
||||
git.getRemoteInfo({
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
url: cloneUrl,
|
||||
}),
|
||||
new Promise<never>((_, reject) =>
|
||||
@@ -1035,8 +1026,7 @@ export class Git {
|
||||
await Promise.race([
|
||||
git.clone({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
url: cloneUrl,
|
||||
}),
|
||||
@@ -1093,8 +1083,7 @@ export class Git {
|
||||
await Promise.race([
|
||||
git.clone({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
...options,
|
||||
url: cloneUrl,
|
||||
}),
|
||||
@@ -1456,8 +1445,7 @@ export class Git {
|
||||
// Push to the temporary remote
|
||||
await git.push({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
dir,
|
||||
url: cloneUrl,
|
||||
...gitPushOptions,
|
||||
@@ -1510,8 +1498,7 @@ export class Git {
|
||||
// Fetch from the clone URL
|
||||
await git.fetch({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
dir,
|
||||
url: cloneUrl,
|
||||
});
|
||||
@@ -1588,8 +1575,7 @@ export class Git {
|
||||
// Fetch from the temporary remote
|
||||
const fetchResult = await git.fetch({
|
||||
fs: this.fs,
|
||||
http,
|
||||
corsProxy: this.corsProxy,
|
||||
http: this.http,
|
||||
dir,
|
||||
remote: tempRemoteName,
|
||||
});
|
||||
@@ -1626,4 +1612,88 @@ export class Git {
|
||||
|
||||
throw lastError || new Error('All fetch attempts failed');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
class GitHttp implements HttpClient {
|
||||
private proxy?: string;
|
||||
|
||||
constructor(proxy?: string) {
|
||||
this.proxy = proxy;
|
||||
}
|
||||
|
||||
async request(request: GitHttpRequest): Promise<GitHttpResponse> {
|
||||
const method = request.method ?? "GET";
|
||||
const url = new URL(request.url);
|
||||
|
||||
const target = this.proxy
|
||||
? proxyUrl(this.proxy, url)
|
||||
: url.href;
|
||||
|
||||
const init: RequestInit = {
|
||||
method,
|
||||
headers: request.headers,
|
||||
};
|
||||
|
||||
if (request.body) {
|
||||
const buffered = await collectToUint8Array(request.body);
|
||||
init.body = new Blob([new Uint8Array(buffered)]);
|
||||
}
|
||||
|
||||
const response = await fetch(target, init);
|
||||
const headers = Object.fromEntries(response.headers.entries());
|
||||
const body = response.body ? readableStreamToAsyncIterator(response.body) : undefined;
|
||||
|
||||
return {
|
||||
url: response.url,
|
||||
method,
|
||||
statusCode: response.status,
|
||||
statusMessage: response.statusText,
|
||||
body,
|
||||
headers,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Drain an async iterable of Uint8Array into one Uint8Array
|
||||
async function collectToUint8Array(
|
||||
src: AsyncIterable<Uint8Array> | AsyncIterableIterator<Uint8Array>
|
||||
): Promise<Uint8Array> {
|
||||
const chunks: Uint8Array[] = [];
|
||||
let total = 0;
|
||||
for await (const chunk of src) {
|
||||
chunks.push(chunk);
|
||||
total += chunk.byteLength;
|
||||
}
|
||||
const out = new Uint8Array(total);
|
||||
let offset = 0;
|
||||
for (const c of chunks) {
|
||||
out.set(c, offset);
|
||||
offset += c.byteLength;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
// Portable async iterator over a ReadableStream (works even if
|
||||
// ReadableStream doesn't implement [Symbol.asyncIterator])
|
||||
function readableStreamToAsyncIterator(
|
||||
stream: ReadableStream<Uint8Array>
|
||||
): AsyncIterableIterator<Uint8Array> {
|
||||
const reader = stream.getReader();
|
||||
return {
|
||||
async next() {
|
||||
const { value, done } = await reader.read();
|
||||
return done ? { value: undefined, done: true } : { value, done: false };
|
||||
},
|
||||
async return() {
|
||||
try {
|
||||
await reader.cancel();
|
||||
} catch {
|
||||
// Ignore cancel errors
|
||||
}
|
||||
return { value: undefined, done: true };
|
||||
},
|
||||
[Symbol.asyncIterator]() {
|
||||
return this;
|
||||
},
|
||||
};
|
||||
}
|
||||
+932
-36
File diff suppressed because it is too large.
Load diff
@@ -29,9 +29,9 @@ describe('parseProviderModel', () => {
|
||||
it('should parse simple provider/model format', () => {
|
||||
const result = parseProviderModel('openai/gpt-4o', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openai');
|
||||
expect(result.model).toBe('gpt-4o');
|
||||
expect(result.connection).toEqual({
|
||||
expect(result.provider).toEqual({
|
||||
id: 'openai',
|
||||
baseURL: mockProviders[0].baseURL,
|
||||
apiKey: mockProviders[0].apiKey,
|
||||
nostr: mockProviders[0].nostr,
|
||||
@@ -41,9 +41,9 @@ describe('parseProviderModel', () => {
|
||||
it('should parse complex model names with slashes', () => {
|
||||
const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('anthropic/claude-sonnet-4');
|
||||
expect(result.connection).toEqual({
|
||||
expect(result.provider).toEqual({
|
||||
id: 'openrouter',
|
||||
baseURL: mockProviders[1].baseURL,
|
||||
apiKey: mockProviders[1].apiKey,
|
||||
nostr: mockProviders[1].nostr,
|
||||
@@ -53,9 +53,9 @@ describe('parseProviderModel', () => {
|
||||
it('should handle model names with multiple slashes', () => {
|
||||
const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders);
|
||||
|
||||
expect(result.provider).toBe('openrouter');
|
||||
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
|
||||
expect(result.connection).toEqual({
|
||||
expect(result.provider).toEqual({
|
||||
id: 'openrouter',
|
||||
baseURL: mockProviders[1].baseURL,
|
||||
apiKey: mockProviders[1].apiKey,
|
||||
nostr: mockProviders[1].nostr,
|
||||
|
||||
@@ -1,13 +1,8 @@
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
export interface ParsedProviderModel {
|
||||
provider: string;
|
||||
model: string;
|
||||
connection: {
|
||||
baseURL: string;
|
||||
apiKey?: string;
|
||||
nostr?: boolean;
|
||||
};
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -25,25 +20,20 @@ export function parseProviderModel(
|
||||
throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")');
|
||||
}
|
||||
|
||||
const provider = providerModelString.substring(0, firstSlashIndex);
|
||||
const providerId = providerModelString.substring(0, firstSlashIndex);
|
||||
const model = providerModelString.substring(firstSlashIndex + 1);
|
||||
|
||||
if (!provider || !model) {
|
||||
if (!providerId || !model) {
|
||||
throw new Error('Invalid format. Both provider and model must be specified');
|
||||
}
|
||||
|
||||
const providerObj = providers.find(p => p.id === provider);
|
||||
if (!providerObj) {
|
||||
throw new Error(`Provider "${provider}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
|
||||
const provider = providers.find(p => p.id === providerId);
|
||||
if (!provider) {
|
||||
throw new Error(`Provider "${providerId}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`);
|
||||
}
|
||||
|
||||
return {
|
||||
provider,
|
||||
model,
|
||||
connection: {
|
||||
baseURL: providerObj.baseURL,
|
||||
apiKey: providerObj.apiKey,
|
||||
nostr: providerObj.nostr,
|
||||
},
|
||||
provider,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
import UriTemplate from 'uri-templates';
|
||||
|
||||
export function proxyUrl(template: string, url: string | URL): string {
|
||||
const u = new URL(url);
|
||||
return UriTemplate(template).fill({
|
||||
href: u.href,
|
||||
origin: u.origin,
|
||||
protocol: u.protocol,
|
||||
username: u.username,
|
||||
password: u.password,
|
||||
host: u.host,
|
||||
hostname: u.hostname,
|
||||
port: u.port,
|
||||
pathname: u.pathname,
|
||||
hash: u.hash,
|
||||
search: u.search,
|
||||
});
|
||||
}
|
||||
+1
-1
@@ -46,7 +46,7 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
|
||||
if (metadata?.nip05) userText += `\n- **NIP-05**: ${metadata.nip05}`;
|
||||
if (metadata?.lud16) userText += `\n- **Lightning Address**: ${metadata.lud16}`;
|
||||
|
||||
userText += `Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
userText += `\n\nSince the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
} else {
|
||||
userText = `The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.`;
|
||||
}
|
||||
|
||||
@@ -44,7 +44,7 @@ describe('ShellTool', () => {
|
||||
});
|
||||
|
||||
it('should have correct tool properties', () => {
|
||||
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators');
|
||||
expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators');
|
||||
expect(shellTool.inputSchema).toBeDefined();
|
||||
});
|
||||
|
||||
|
||||
@@ -18,6 +18,7 @@ import {
|
||||
GitCommand,
|
||||
GrepCommand,
|
||||
HeadCommand,
|
||||
HexdumpCommand,
|
||||
LsCommand,
|
||||
MkdirCommand,
|
||||
MvCommand,
|
||||
@@ -28,6 +29,7 @@ import {
|
||||
TouchCommand,
|
||||
TrCommand,
|
||||
UniqCommand,
|
||||
UnzipCommand,
|
||||
WcCommand,
|
||||
WhoamiCommand,
|
||||
WhichCommand
|
||||
@@ -46,7 +48,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private git: Git;
|
||||
private commands: Map<string, ShellCommand>;
|
||||
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators";
|
||||
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators";
|
||||
|
||||
readonly inputSchema = z.object({
|
||||
command: z.string().describe(
|
||||
@@ -75,6 +77,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd }));
|
||||
this.registerCommand(new GrepCommand(fs));
|
||||
this.registerCommand(new HeadCommand(fs));
|
||||
this.registerCommand(new HexdumpCommand(fs));
|
||||
this.registerCommand(new LsCommand(fs));
|
||||
this.registerCommand(new MkdirCommand(fs));
|
||||
this.registerCommand(new MvCommand(fs));
|
||||
@@ -85,6 +88,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new TouchCommand(fs));
|
||||
this.registerCommand(new TrCommand(fs));
|
||||
this.registerCommand(new UniqCommand(fs));
|
||||
this.registerCommand(new UnzipCommand(fs));
|
||||
this.registerCommand(new WcCommand(fs));
|
||||
this.registerCommand(new WhoamiCommand());
|
||||
|
||||
|
||||
@@ -144,8 +144,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<CreditsBadge
|
||||
providerId={provider.id}
|
||||
connection={{ baseURL: provider.baseURL, apiKey: provider.apiKey, nostr: provider.nostr }}
|
||||
provider={provider}
|
||||
onOpenDialog={() => onOpenCreditsDialog(provider.id)}
|
||||
/>
|
||||
<Button
|
||||
@@ -547,8 +546,7 @@ export function AISettings() {
|
||||
handleCloseCreditsDialog();
|
||||
}
|
||||
}}
|
||||
providerId={activeCreditsDialog}
|
||||
connection={{ baseURL: provider.baseURL, apiKey: provider.apiKey, nostr: provider.nostr }}
|
||||
provider={provider}
|
||||
/>
|
||||
);
|
||||
})()}
|
||||
|
||||
+6
-4
@@ -1,4 +1,4 @@
|
||||
import { useState, useEffect, useCallback } from 'react';
|
||||
import { useState, useEffect, useCallback, useRef } from 'react';
|
||||
import { useNavigate, useSearchParams } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
@@ -19,6 +19,7 @@ export default function Clone() {
|
||||
const [searchParams] = useSearchParams();
|
||||
const projectsManager = useProjectsManager();
|
||||
const { toast } = useToast();
|
||||
const autoCloneInitiatedRef = useRef(false);
|
||||
|
||||
useSeoMeta({
|
||||
title: `${t('importRepository')} - Shakespeare`,
|
||||
@@ -115,8 +116,8 @@ export default function Clone() {
|
||||
description: successDescription,
|
||||
});
|
||||
|
||||
// Navigate to the new project
|
||||
navigate(`/project/${project.id}`);
|
||||
// Navigate to the new project with build parameter
|
||||
navigate(`/project/${project.id}?build`);
|
||||
} catch (error) {
|
||||
console.error('Failed to clone repository:', error);
|
||||
|
||||
@@ -160,9 +161,10 @@ export default function Clone() {
|
||||
// Initialize repoUrl from URL parameters and auto-import if URL is provided
|
||||
useEffect(() => {
|
||||
const urlParam = searchParams.get('url');
|
||||
if (urlParam) {
|
||||
if (urlParam && !autoCloneInitiatedRef.current) {
|
||||
const decodedUrl = decodeURIComponent(urlParam);
|
||||
setRepoUrl(decodedUrl);
|
||||
autoCloneInitiatedRef.current = true;
|
||||
|
||||
// Automatically start the clone process with the URL directly
|
||||
handleClone(decodedUrl);
|
||||
|
||||
+1
-180
@@ -1,18 +1,14 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Settings } from 'lucide-react';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { RadioGroup, RadioGroupItem } from '@/components/ui/radio-group';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface StorageUsageDetails {
|
||||
@@ -36,22 +32,8 @@ export function DataSettings() {
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const [deployServer, setDeployServer] = useState(config.deployServer);
|
||||
const [filesystemType, setFilesystemType] = useState(config.filesystemType);
|
||||
const [opfsAvailable, setOpfsAvailable] = useState(false);
|
||||
|
||||
// Check OPFS availability on mount
|
||||
useEffect(() => {
|
||||
const checkOPFSAvailability = () => {
|
||||
const available = 'storage' in navigator && !!((navigator.storage as unknown as { getDirectory: () => FileSystemDirectoryHandle }).getDirectory);
|
||||
setOpfsAvailable(available);
|
||||
};
|
||||
|
||||
checkOPFSAvailability();
|
||||
}, []);
|
||||
|
||||
// Format bytes to human readable format
|
||||
const formatBytes = (bytes: number): string => {
|
||||
@@ -214,53 +196,6 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleSaveSettings = () => {
|
||||
// Validate deploy server
|
||||
if (!deployServer.trim()) {
|
||||
toast({
|
||||
title: "Invalid deploy server",
|
||||
description: "Deploy server cannot be empty.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Validate filesystem type
|
||||
if (filesystemType === 'opfs' && !opfsAvailable) {
|
||||
toast({
|
||||
title: "OPFS not available",
|
||||
description: "OPFS is not supported in your browser. Please use LightningFS instead.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Remove protocol if present
|
||||
const cleanDeployServer = deployServer.replace(/^https?:\/\//, '');
|
||||
|
||||
updateConfig((current) => ({
|
||||
...current,
|
||||
deployServer: cleanDeployServer,
|
||||
filesystemType,
|
||||
}));
|
||||
|
||||
toast({
|
||||
title: "Settings saved",
|
||||
description: "Your settings have been updated. The page will refresh to apply the new filesystem.",
|
||||
});
|
||||
|
||||
// Refresh the page to apply filesystem changes
|
||||
setTimeout(() => {
|
||||
window.location.reload();
|
||||
}, 1000);
|
||||
};
|
||||
|
||||
const handleCancelSettings = () => {
|
||||
// Reset to current config
|
||||
setDeployServer(config.deployServer);
|
||||
setFilesystemType(config.filesystemType);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
@@ -333,109 +268,6 @@ export function DataSettings() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Filesystem Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Settings className="h-5 w-5" />
|
||||
{t('filesystem')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label>{t('filesystemType')}</Label>
|
||||
<RadioGroup
|
||||
value={filesystemType}
|
||||
onValueChange={(value) => setFilesystemType(value as 'lightningfs' | 'opfs')}
|
||||
className="grid grid-cols-1 gap-3"
|
||||
>
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem value="lightningfs" id="lightningfs" />
|
||||
<Label htmlFor="lightningfs" className="cursor-pointer">
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium">LightningFS (IndexedDB)</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
Uses IndexedDB for storage. Works in all modern browsers.
|
||||
</span>
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center space-x-2">
|
||||
<RadioGroupItem
|
||||
value="opfs"
|
||||
id="opfs"
|
||||
disabled={!opfsAvailable}
|
||||
/>
|
||||
<Label htmlFor="opfs" className={`cursor-pointer ${!opfsAvailable ? 'opacity-50' : ''}`}>
|
||||
<div className="flex flex-col">
|
||||
<span className="font-medium flex items-center gap-2">
|
||||
OPFS (Origin Private File System)
|
||||
{!opfsAvailable && (
|
||||
<AlertTriangle className="h-4 w-4 text-orange-500" />
|
||||
)}
|
||||
</span>
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{opfsAvailable
|
||||
? "Modern browser API with better performance and larger storage limits. Note: May have compatibility issues with Git operations."
|
||||
: "Not available in this browser. Use Chrome, Edge, or Firefox 111+."
|
||||
}
|
||||
</span>
|
||||
</div>
|
||||
</Label>
|
||||
</div>
|
||||
</RadioGroup>
|
||||
</div>
|
||||
|
||||
{!opfsAvailable && filesystemType === 'opfs' && (
|
||||
<div className="flex items-center gap-2 p-3 bg-orange-50 dark:bg-orange-950/20 rounded-md border border-orange-200 dark:border-orange-800">
|
||||
<AlertTriangle className="h-4 w-4 text-orange-600 dark:text-orange-400" />
|
||||
<span className="text-sm text-orange-800 dark:text-orange-200">
|
||||
OPFS is not available in your browser. Please use LightningFS or upgrade to a modern browser.
|
||||
</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{opfsAvailable && filesystemType === 'opfs' && (
|
||||
<div className="flex items-center gap-2 p-3 bg-blue-50 dark:bg-blue-950/20 rounded-md border border-blue-200 dark:border-blue-800">
|
||||
<Info className="h-4 w-4 text-blue-600 dark:text-blue-400" />
|
||||
<div className="text-sm text-blue-800 dark:text-blue-200">
|
||||
<p><strong>Git Compatibility Note:</strong> OPFS may have compatibility issues with Git clone operations. If you experience problems creating projects, switch to LightningFS for better Git support.</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
<p><strong>Note:</strong> Changing filesystem type will refresh the page and may cause data loss if not properly exported first.</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Deployment Settings */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Settings className="h-5 w-5" />
|
||||
{t('deployment')}
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="deployServer">{t('deployServer')}</Label>
|
||||
<Input
|
||||
id="deployServer"
|
||||
value={deployServer}
|
||||
onChange={(e) => setDeployServer(e.target.value)}
|
||||
placeholder="shakespeare.wtf"
|
||||
className="font-mono"
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('deployServerDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Export Files */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
@@ -535,17 +367,6 @@ export function DataSettings() {
|
||||
</AlertDialog>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Save/Cancel Buttons */}
|
||||
<div className="flex justify-end space-x-2">
|
||||
<Button variant="outline" onClick={handleCancelSettings}>
|
||||
{t('cancel')}
|
||||
</Button>
|
||||
<Button onClick={handleSaveSettings}>
|
||||
<Download className="h-4 w-4 mr-2" />
|
||||
{t('saveSettings')}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -0,0 +1,301 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { ArrowLeft, Mail, CheckCircle } from 'lucide-react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export function EmailSettings() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { user } = useCurrentUser();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [email, setEmail] = useState('');
|
||||
const [isSubmitting, setIsSubmitting] = useState(false);
|
||||
const [isSubmitted, setIsSubmitted] = useState(false);
|
||||
|
||||
// Check localStorage on component mount
|
||||
useEffect(() => {
|
||||
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
|
||||
if (hasSubscribed === 'true') {
|
||||
setIsSubmitted(true);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
if (!email.trim()) {
|
||||
toast({
|
||||
title: "Email required",
|
||||
description: "Please enter your email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
// Basic email validation
|
||||
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
|
||||
if (!emailRegex.test(email)) {
|
||||
toast({
|
||||
title: "Invalid email",
|
||||
description: "Please enter a valid email address",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsSubmitting(true);
|
||||
|
||||
try {
|
||||
// Prepare form data
|
||||
const formData = new FormData();
|
||||
formData.append('email', email.trim());
|
||||
formData.append('tag_id', '8982396');
|
||||
|
||||
// Include npub if user is signed in
|
||||
if (user?.pubkey) {
|
||||
const npub = nip19.npubEncode(user.pubkey);
|
||||
formData.append('npub', npub);
|
||||
}
|
||||
|
||||
// Submit to Mailchimp using the same setup as soapbox2
|
||||
const form = document.createElement('form');
|
||||
form.method = 'POST';
|
||||
form.action = 'https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0';
|
||||
form.target = '_blank'; // Open in new tab
|
||||
form.style.display = 'none';
|
||||
|
||||
// Add email field
|
||||
const emailInput = document.createElement('input');
|
||||
emailInput.type = 'email';
|
||||
emailInput.name = 'EMAIL';
|
||||
emailInput.value = email.trim();
|
||||
form.appendChild(emailInput);
|
||||
|
||||
// Add tag field with the new Shakespeare tag ID
|
||||
const tagInput = document.createElement('input');
|
||||
tagInput.type = 'hidden';
|
||||
tagInput.name = 'tags';
|
||||
tagInput.value = '8982396';
|
||||
form.appendChild(tagInput);
|
||||
|
||||
// Add npub if available
|
||||
if (user?.pubkey) {
|
||||
const npubInput = document.createElement('input');
|
||||
npubInput.type = 'text';
|
||||
npubInput.name = 'NPUB';
|
||||
npubInput.value = nip19.npubEncode(user.pubkey);
|
||||
npubInput.style.display = 'none';
|
||||
form.appendChild(npubInput);
|
||||
}
|
||||
|
||||
// Add honeypot field
|
||||
const honeypotInput = document.createElement('input');
|
||||
honeypotInput.type = 'text';
|
||||
honeypotInput.name = 'b_f1f718a93795f42a604d558d8_f7271442a0';
|
||||
honeypotInput.tabIndex = -1;
|
||||
honeypotInput.style.position = 'absolute';
|
||||
honeypotInput.style.left = '-5000px';
|
||||
form.appendChild(honeypotInput);
|
||||
|
||||
// Add form to document and submit
|
||||
document.body.appendChild(form);
|
||||
form.submit();
|
||||
|
||||
// Clean up after a short delay
|
||||
setTimeout(() => {
|
||||
document.body.removeChild(form);
|
||||
}, 1000);
|
||||
|
||||
// Save subscription status to localStorage
|
||||
localStorage.setItem('shakespeare-email-subscribed', 'true');
|
||||
|
||||
setIsSubmitted(true);
|
||||
toast({
|
||||
title: "Successfully subscribed!",
|
||||
description: "You'll receive Shakespeare updates and resources occasionally.",
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Email signup error:', error);
|
||||
toast({
|
||||
title: "Subscription failed",
|
||||
description: "There was an error subscribing you to updates. Please try again.",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsSubmitting(false);
|
||||
}
|
||||
};
|
||||
|
||||
if (isSubmitted) {
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardContent className="pt-6">
|
||||
<div className="text-center space-y-4">
|
||||
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
|
||||
<div className="space-y-2">
|
||||
<h3 className="text-lg font-semibold">
|
||||
Thanks for subscribing!
|
||||
</h3>
|
||||
<p className="text-muted-foreground text-sm">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
<div className="space-y-2">
|
||||
<Button
|
||||
onClick={() => navigate('/settings')}
|
||||
className="w-full"
|
||||
>
|
||||
Back to Settings
|
||||
</Button>
|
||||
<Button
|
||||
onClick={() => {
|
||||
localStorage.removeItem('shakespeare-email-subscribed');
|
||||
setIsSubmitted(false);
|
||||
setEmail('');
|
||||
}}
|
||||
variant="outline"
|
||||
className="w-full text-xs"
|
||||
>
|
||||
Subscribe with different email
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
{isMobile && (
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => navigate('/settings')}
|
||||
className="h-8 w-auto px-2 -ml-2"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4 mr-2" />
|
||||
{t('backToSettings')}
|
||||
</Button>
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!isMobile && (
|
||||
<div className="space-y-2">
|
||||
<h1 className="text-2xl font-bold flex items-center gap-3">
|
||||
<Mail className="h-6 w-6 text-primary" />
|
||||
{t('emailUpdates')}
|
||||
</h1>
|
||||
<p className="text-muted-foreground">
|
||||
{t('emailUpdatesDescriptionLong')}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="max-w-md">
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="text-lg">
|
||||
Stay Updated with Shakespeare
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="email">
|
||||
Email Address
|
||||
</Label>
|
||||
<Input
|
||||
id="email"
|
||||
type="email"
|
||||
placeholder="[email protected]"
|
||||
value={email}
|
||||
onChange={(e) => setEmail(e.target.value)}
|
||||
disabled={isSubmitting}
|
||||
required
|
||||
/>
|
||||
</div>
|
||||
|
||||
|
||||
|
||||
<div className="space-y-3">
|
||||
<Button
|
||||
type="submit"
|
||||
className="w-full"
|
||||
disabled={isSubmitting}
|
||||
>
|
||||
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
|
||||
</Button>
|
||||
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
You can opt out at any time using the unsubscribe link in our emails.
|
||||
</p>
|
||||
</div>
|
||||
</form>
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export default EmailSettings;
|
||||
+15
-20
@@ -11,6 +11,7 @@ import { useGitHubOAuth } from '@/hooks/useGitHubOAuth';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
@@ -191,9 +192,8 @@ export function GitSettings() {
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${origin}-password`}>{t('password')}</Label>
|
||||
<Input
|
||||
<PasswordInput
|
||||
id={`${origin}-password`}
|
||||
type="password"
|
||||
placeholder={t('enterPassword')}
|
||||
value={credential?.password || ''}
|
||||
onChange={(e) => handleUpdateCredential(origin, { password: e.target.value })}
|
||||
@@ -260,9 +260,8 @@ export function GitSettings() {
|
||||
</div>
|
||||
) : (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
<PasswordInput
|
||||
placeholder={t('enterToken')}
|
||||
type="password"
|
||||
className="flex-1"
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => setPresetTokens(prev => ({
|
||||
@@ -287,9 +286,8 @@ export function GitSettings() {
|
||||
) : (
|
||||
// Standard rendering for other providers
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
<PasswordInput
|
||||
placeholder={t('enterToken')}
|
||||
type="password"
|
||||
className="flex-1"
|
||||
value={presetTokens[preset.id] || ''}
|
||||
onChange={(e) => setPresetTokens(prev => ({
|
||||
@@ -346,9 +344,8 @@ export function GitSettings() {
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="custom-password">{t('password')}</Label>
|
||||
<Input
|
||||
<PasswordInput
|
||||
id="custom-password"
|
||||
type="password"
|
||||
placeholder={t('enterPassword')}
|
||||
value={customPassword}
|
||||
onChange={(e) => setCustomPassword(e.target.value)}
|
||||
@@ -385,18 +382,16 @@ export function GitSettings() {
|
||||
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Input
|
||||
id="cors-proxy"
|
||||
placeholder="https://cors.isomorphic-git.org"
|
||||
value={settings.corsProxy}
|
||||
onChange={(e) => updateSettings({ corsProxy: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('corsProxyDescription')}
|
||||
</p>
|
||||
</div>
|
||||
<div className="py-1 space-y-2">
|
||||
<Input
|
||||
id="cors-proxy"
|
||||
placeholder="https://proxy.shakespeare.diy/?url={href}"
|
||||
value={settings.corsProxy}
|
||||
onChange={(e) => updateSettings({ corsProxy: e.target.value })}
|
||||
/>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('corsProxyDescription')}
|
||||
</p>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
|
||||
+84
-7
@@ -7,15 +7,20 @@ import { useFS } from '@/hooks/useFS';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { AppLayout } from '@/components/AppLayout';
|
||||
import { OnboardingDialog } from '@/components/OnboardingDialog';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
import { parseProviderModel } from '@/lib/parseProviderModel';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { ModelSelector } from '@/components/ModelSelector';
|
||||
import { FileAttachment } from '@/components/ui/file-attachment';
|
||||
import { ToastAction } from '@/components/ui/toast';
|
||||
import { Plus } from 'lucide-react';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
|
||||
@@ -30,6 +35,7 @@ export default function Index() {
|
||||
const { fs } = useFS();
|
||||
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
|
||||
const { settings, addRecentlyUsedModel } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
const [providerModel, setProviderModel] = useState(() => {
|
||||
// Initialize with first recently used model if available, otherwise empty
|
||||
return settings.recentlyUsedModels?.[0] || '';
|
||||
@@ -41,6 +47,41 @@ export default function Index() {
|
||||
// Check if any providers are configured
|
||||
const hasProvidersConfigured = settings.providers.length > 0;
|
||||
|
||||
// Check for API key failures and show appropriate toast
|
||||
const checkForKeyFailure = (error: unknown): boolean => {
|
||||
// Check for authentication errors
|
||||
// Note: useAIProjectId re-throws OpenAI errors as generic Error objects
|
||||
const isAuthError = error instanceof Error && error.message === '401 No auth credentials found';
|
||||
|
||||
if (isAuthError) {
|
||||
// Get provider name inline
|
||||
let providerName = 'Provider';
|
||||
try {
|
||||
const { provider } = parseProviderModel(providerModel, settings.providers);
|
||||
providerName = provider.id.charAt(0).toUpperCase() + provider.id.slice(1);
|
||||
} catch {
|
||||
// Keep default 'Provider'
|
||||
}
|
||||
|
||||
toast({
|
||||
title: t('apiAuthenticationFailed'),
|
||||
description: t('invalidApiKey', { provider: providerName }),
|
||||
variant: 'destructive',
|
||||
action: (
|
||||
<ToastAction
|
||||
altText={t('checkApiKeySettings')}
|
||||
onClick={() => navigate('/settings/ai')}
|
||||
>
|
||||
{t('checkApiKeySettings')}
|
||||
</ToastAction>
|
||||
),
|
||||
});
|
||||
}
|
||||
|
||||
return isAuthError;
|
||||
};
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (!providerModel && settings.recentlyUsedModels?.length) {
|
||||
setProviderModel(settings.recentlyUsedModels[0]);
|
||||
@@ -164,13 +205,48 @@ export default function Index() {
|
||||
// Create project with AI-generated ID
|
||||
const project = await projectsManager.createProject(prompt.trim(), projectId);
|
||||
|
||||
// Build message content as text parts (same as ChatPane)
|
||||
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
||||
|
||||
// Add user input as text part if present
|
||||
if (prompt.trim()) {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: prompt.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Process attached files and add as separate text parts
|
||||
if (attachedFiles.length > 0) {
|
||||
const filePromises = attachedFiles.map(async (file) => {
|
||||
try {
|
||||
const savedPath = await saveFileToTmp(fs, file);
|
||||
return `Added file: ${savedPath}`;
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
return `Failed to save file: ${file.name}`;
|
||||
}
|
||||
});
|
||||
|
||||
const fileResults = await Promise.all(filePromises);
|
||||
|
||||
// Add each file as a separate text part
|
||||
fileResults.forEach(fileResult => {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: fileResult
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Store the initial message in chat history using DotAI
|
||||
const dotAI = new DotAI(fs, `/projects/${project.id}`);
|
||||
const sessionName = DotAI.generateSessionName();
|
||||
// Create initial message with content parts
|
||||
|
||||
// Create initial message with content parts (same format as ChatPane)
|
||||
const initialMessage: AIMessage = {
|
||||
role: 'user',
|
||||
content: prompt.trim()
|
||||
content: contentParts.length === 1 ? contentParts[0].text : contentParts
|
||||
};
|
||||
await dotAI.setHistory(sessionName, [initialMessage]);
|
||||
|
||||
@@ -180,11 +256,13 @@ export default function Index() {
|
||||
// Navigate to the project with autostart parameter and model
|
||||
const searchParams = new URLSearchParams({
|
||||
autostart: 'true',
|
||||
build: 'true',
|
||||
...(providerModel.trim() && { model: providerModel.trim() })
|
||||
});
|
||||
navigate(`/project/${project.id}?${searchParams.toString()}`);
|
||||
} catch (error) {
|
||||
console.error('Failed to create project:', error);
|
||||
checkForKeyFailure(error);
|
||||
} finally {
|
||||
setIsCreating(false);
|
||||
}
|
||||
@@ -209,9 +287,8 @@ export default function Index() {
|
||||
<div className="mb-8 md:mb-12">
|
||||
{/* Chat Input Container - matching the ChatPane style */}
|
||||
<div
|
||||
className={`relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${
|
||||
isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
}`}
|
||||
className={`relative rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2 transition-all ${isDragOver ? 'border-primary bg-primary/5 ring-2 ring-primary/20' : ''
|
||||
}`}
|
||||
onDragEnter={handleDragEnter}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
@@ -222,8 +299,8 @@ export default function Index() {
|
||||
!hasProvidersConfigured
|
||||
? t('examplePrompt')
|
||||
: !providerModel.trim()
|
||||
? t('selectModelToDescribe')
|
||||
: t('examplePrompt')
|
||||
? t('selectModelToDescribe')
|
||||
: t('examplePrompt')
|
||||
}
|
||||
value={prompt}
|
||||
onChange={handlePromptChange}
|
||||
|
||||
+69
-172
@@ -6,25 +6,19 @@ import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ChatPane, type ChatPaneRef } from '@/components/Shakespeare/ChatPane';
|
||||
import { PreviewPane } from '@/components/Shakespeare/PreviewPane';
|
||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||
import { ProjectInfoDialog } from '@/components/ProjectInfoDialog';
|
||||
import { ProjectDetailsDialog } from '@/components/ProjectDetailsDialog';
|
||||
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { ActionsMenu } from '@/components/ActionsMenu';
|
||||
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useKeepAlive } from '@/hooks/useKeepAlive';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
|
||||
import { buildProject } from "@/lib/build";
|
||||
import { deployProject } from "@/lib/deploy";
|
||||
import { useCurrentUser } from "@/hooks/useCurrentUser";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
import { useToast } from "@/hooks/useToast";
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -33,33 +27,17 @@ export function ProjectView() {
|
||||
const [isLoading, setIsLoading] = useState(true);
|
||||
const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview');
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isBuildLoading, setIsBuildLoading] = useState(false);
|
||||
const [isDeployLoading, setIsDeployLoading] = useState(false);
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectInfoOpen, setIsProjectInfoOpen] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
const projectsManager = useProjectsManager();
|
||||
const chatPaneRef = useRef<ChatPaneRef>(null);
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const { fs } = useFS();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
const { toast } = useToast();
|
||||
|
||||
const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile);
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
enabled: isAILoading || isBuildLoading || isDeployLoading,
|
||||
title: 'Shakespeare',
|
||||
artist: project ? `Working on ${project.name}...` : 'Working...',
|
||||
artwork: [
|
||||
{
|
||||
src: '/favicon.png',
|
||||
sizes: '512x512',
|
||||
type: 'image/png'
|
||||
}
|
||||
]
|
||||
});
|
||||
const build = useBuildProject(projectId!);
|
||||
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
|
||||
|
||||
const loadProject = useCallback(async () => {
|
||||
if (!projectId) return;
|
||||
@@ -78,73 +56,25 @@ export function ProjectView() {
|
||||
loadProject();
|
||||
}, [loadProject]);
|
||||
|
||||
const runBuild = async () => {
|
||||
if (isBuildLoading || !project) return;
|
||||
|
||||
setIsBuildLoading(true);
|
||||
updateMetadata('Shakespeare', `Building ${project.name}...`);
|
||||
|
||||
try {
|
||||
const result = await buildProject({
|
||||
fs,
|
||||
projectPath: `/projects/${project.id}`,
|
||||
domParser: new DOMParser(),
|
||||
});
|
||||
|
||||
console.log('Build completed:', result);
|
||||
} catch (error) {
|
||||
console.error('Build failed:', error);
|
||||
} finally {
|
||||
setIsBuildLoading(false);
|
||||
// Reset view state when projectId changes
|
||||
useEffect(() => {
|
||||
if (projectId) {
|
||||
// Reset to preview tab if the new project is previewable, otherwise code
|
||||
setActiveTab(isPreviewable ? 'preview' : 'code');
|
||||
// Reset mobile view to chat when switching projects
|
||||
setMobileView('chat');
|
||||
}
|
||||
};
|
||||
}, [projectId, isPreviewable]);
|
||||
|
||||
const runDeploy = async () => {
|
||||
if (isDeployLoading || !project) return;
|
||||
|
||||
// Check if user is logged in
|
||||
if (!user || !user.signer) {
|
||||
toast({
|
||||
title: "Authentication required",
|
||||
description: "Please log in to deploy your project.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
// Switch away from preview mode if project is not previewable
|
||||
useEffect(() => {
|
||||
if (mobileView === 'preview' && !isPreviewable) {
|
||||
setMobileView('code');
|
||||
}
|
||||
|
||||
setIsDeployLoading(true);
|
||||
updateMetadata('Shakespeare', `Deploying ${project.name}...`);
|
||||
|
||||
try {
|
||||
const result = await deployProject({
|
||||
projectId: project.id,
|
||||
deployServer: config.deployServer,
|
||||
fs,
|
||||
projectPath: `/projects/${project.id}`,
|
||||
signer: user.signer,
|
||||
});
|
||||
|
||||
console.log('Project deployed:', result.url);
|
||||
|
||||
toast({
|
||||
title: "Deployment successful!",
|
||||
description: `Your project is now live at ${result.hostname}`,
|
||||
});
|
||||
|
||||
// Open the deployed site in a new tab
|
||||
window.open(result.url, '_blank');
|
||||
} catch (error) {
|
||||
console.error('Deploy failed:', error);
|
||||
|
||||
toast({
|
||||
title: "Deployment failed",
|
||||
description: error instanceof Error ? error.message : "An unexpected error occurred",
|
||||
variant: "destructive",
|
||||
});
|
||||
} finally {
|
||||
setIsDeployLoading(false);
|
||||
if (activeTab === 'preview' && !isPreviewable) {
|
||||
setActiveTab('code');
|
||||
}
|
||||
};
|
||||
}, [isPreviewable, mobileView, activeTab]);
|
||||
|
||||
const handleNewChat = () => {
|
||||
// Reset to chat view on mobile when starting new chat
|
||||
@@ -203,7 +133,7 @@ export function ProjectView() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="block p-0 h-auto text-sm font-semibold truncate hover:bg-transparent hover:text-primary"
|
||||
onClick={() => setIsProjectInfoOpen(true)}
|
||||
onClick={() => setIsProjectDetailsOpen(true)}
|
||||
>
|
||||
{project.name}
|
||||
</Button>
|
||||
@@ -225,13 +155,10 @@ export function ProjectView() {
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onDeploy={runDeploy}
|
||||
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={isBuildLoading}
|
||||
isDeployLoading={isDeployLoading}
|
||||
isBuildLoading={build.isPending}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
@@ -278,13 +205,10 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onDeploy={runDeploy}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={isBuildLoading}
|
||||
isDeployLoading={isDeployLoading}
|
||||
isBuildLoading={build.isPending}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
@@ -300,6 +224,8 @@ export function ProjectView() {
|
||||
<PreviewPane
|
||||
projectId={project.id}
|
||||
activeTab={mobileView}
|
||||
projectName={project.name}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
@@ -322,16 +248,18 @@ export function ProjectView() {
|
||||
<MessageSquare className="h-4 w-4 mr-1" />
|
||||
{t('chat')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={mobileView === 'preview' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setMobileView('preview')}
|
||||
className="flex-1 rounded-none"
|
||||
disabled={!project}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-1" />
|
||||
{t('preview')}
|
||||
</Button>
|
||||
{isPreviewable && (
|
||||
<Button
|
||||
variant={mobileView === 'preview' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setMobileView('preview')}
|
||||
className="flex-1 rounded-none"
|
||||
disabled={!project}
|
||||
>
|
||||
<Eye className="h-4 w-4 mr-1" />
|
||||
{t('preview')}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
variant={mobileView === 'code' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
@@ -348,12 +276,13 @@ export function ProjectView() {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Project Info Dialog */}
|
||||
{/* Project Details Dialog */}
|
||||
{project && (
|
||||
<ProjectInfoDialog
|
||||
<ProjectDetailsDialog
|
||||
project={project}
|
||||
open={isProjectInfoOpen}
|
||||
onOpenChange={setIsProjectInfoOpen}
|
||||
open={isProjectDetailsOpen}
|
||||
onOpenChange={setIsProjectDetailsOpen}
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
@@ -409,7 +338,7 @@ export function ProjectView() {
|
||||
<Button
|
||||
variant="ghost"
|
||||
className="block p-0 h-auto font-semibold text-lg truncate hover:bg-transparent hover:text-primary"
|
||||
onClick={() => setIsProjectInfoOpen(true)}
|
||||
onClick={() => setIsProjectDetailsOpen(true)}
|
||||
>
|
||||
{project.name}
|
||||
</Button>
|
||||
@@ -432,13 +361,10 @@ export function ProjectView() {
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onDeploy={runDeploy}
|
||||
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={isBuildLoading}
|
||||
isDeployLoading={isDeployLoading}
|
||||
isBuildLoading={build.isPending}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
</>
|
||||
) : (
|
||||
@@ -458,13 +384,10 @@ export function ProjectView() {
|
||||
ref={chatPaneRef}
|
||||
projectId={project.id}
|
||||
onNewChat={handleNewChat}
|
||||
onBuild={runBuild}
|
||||
onDeploy={runDeploy}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={isBuildLoading}
|
||||
isDeployLoading={isDeployLoading}
|
||||
isBuildLoading={build.isPending}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
@@ -483,61 +406,35 @@ export function ProjectView() {
|
||||
|
||||
{/* Preview/Code Panel */}
|
||||
<ResizablePanel defaultSize={60} minSize={30}>
|
||||
<div className="h-full flex flex-col">
|
||||
{/* Preview Header */}
|
||||
<div className="h-12 px-4 border-b flex-shrink-0">
|
||||
<div className="flex items-center justify-between h-12">
|
||||
<div className="flex space-x-2">
|
||||
<Button
|
||||
variant={activeTab === 'preview' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setActiveTab('preview')}
|
||||
disabled={!project}
|
||||
>
|
||||
{t('preview')}
|
||||
</Button>
|
||||
<Button
|
||||
variant={activeTab === 'code' ? 'default' : 'ghost'}
|
||||
size="sm"
|
||||
onClick={() => setActiveTab('code')}
|
||||
className="gap-2"
|
||||
disabled={!project}
|
||||
>
|
||||
{t('code')}
|
||||
{activeTab !== 'code' && project && (
|
||||
<GitStatusIndicator projectId={project.id} />
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
<div className="h-full">
|
||||
{project ? (
|
||||
<PreviewPane
|
||||
projectId={project.id}
|
||||
activeTab={isPreviewable ? activeTab : 'code'}
|
||||
onToggleView={isPreviewable ? () => setActiveTab(activeTab === 'preview' ? 'code' : 'preview') : undefined}
|
||||
projectName={project.name}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
isPreviewable={isPreviewable}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
<Skeleton className="h-8 w-32" />
|
||||
<Skeleton className="h-full w-full" />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Preview Content */}
|
||||
<div className="flex-1 overflow-hidden">
|
||||
{project ? (
|
||||
<PreviewPane
|
||||
projectId={project.id}
|
||||
activeTab={activeTab}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
<Skeleton className="h-8 w-32" />
|
||||
<Skeleton className="h-full w-full" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</ResizablePanel>
|
||||
</ResizablePanelGroup>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Project Info Dialog */}
|
||||
{/* Project Details Dialog */}
|
||||
{project && (
|
||||
<ProjectInfoDialog
|
||||
<ProjectDetailsDialog
|
||||
project={project}
|
||||
open={isProjectInfoOpen}
|
||||
onOpenChange={setIsProjectInfoOpen}
|
||||
open={isProjectDetailsOpen}
|
||||
onOpenChange={setIsProjectDetailsOpen}
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react';
|
||||
import { Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
|
||||
interface SettingsItem {
|
||||
@@ -48,7 +48,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
|
||||
icon: Database,
|
||||
href: '/settings/data',
|
||||
},
|
||||
|
||||
{
|
||||
id: 'email',
|
||||
title: t('emailUpdates'),
|
||||
description: t('emailUpdatesDescription'),
|
||||
icon: Mail,
|
||||
href: '/settings/email',
|
||||
},
|
||||
{
|
||||
id: 'about',
|
||||
title: t('aboutShakespeare'),
|
||||
|
||||
Loaded 100 of 102 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user