mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 16:03:34 +00:00
Compare commits
3
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
bdb73252eb | ||
|
|
e709dca735 | ||
|
|
6f2ccb0b5a |
No files matched your search
@@ -0,0 +1,348 @@
|
||||
# Emoji Reactions for Comments
|
||||
|
||||
This document describes the implementation of emoji reactions for comments on showcase app pages, allowing users to express their feelings about comments using emoji reactions like 👍, ❤️, 😂, etc.
|
||||
|
||||
## Overview
|
||||
|
||||
The emoji reactions system provides:
|
||||
- **Quick Engagement**: React to comments without writing full replies
|
||||
- **Visual Feedback**: See popular reactions and participation levels
|
||||
- **Real-time Updates**: Reactions appear instantly with optimistic updates
|
||||
- **Social Context**: Tooltips show who reacted with each emoji
|
||||
- **Toggle Functionality**: Click reactions to add/remove your reaction
|
||||
|
||||
## Implementation Architecture
|
||||
|
||||
### 1. Core Hook: `useCommentReactions`
|
||||
|
||||
**File**: `src/hooks/useCommentReactions.ts`
|
||||
|
||||
**Features:**
|
||||
- Fetches kind 7 reactions for specific comments
|
||||
- Groups reactions by emoji with user tracking
|
||||
- Handles reaction addition/removal with optimistic updates
|
||||
- Supports real-time synchronization
|
||||
|
||||
**Key Functions:**
|
||||
```typescript
|
||||
// Fetch reactions for a comment
|
||||
useCommentReactions(commentId: string)
|
||||
|
||||
// Add/toggle reactions
|
||||
useAddCommentReaction()
|
||||
```
|
||||
|
||||
**Reaction Data Structure:**
|
||||
```typescript
|
||||
interface CommentReaction {
|
||||
emoji: string; // The emoji (e.g., "👍")
|
||||
count: number; // Number of users who reacted
|
||||
userReacted: boolean; // Whether current user reacted
|
||||
users: string[]; // Pubkeys of users who reacted
|
||||
}
|
||||
```
|
||||
|
||||
### 2. UI Component: `EmojiReactions`
|
||||
|
||||
**File**: `src/components/comments/EmojiReactions.tsx`
|
||||
|
||||
**Features:**
|
||||
- Displays existing reactions as clickable badges
|
||||
- Provides emoji picker for adding new reactions
|
||||
- Shows tooltips with reaction context
|
||||
- Handles loading states and user authentication
|
||||
|
||||
**Component Structure:**
|
||||
```typescript
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
className="pt-2"
|
||||
/>
|
||||
```
|
||||
|
||||
### 3. Integration with Comments
|
||||
|
||||
**File**: `src/components/comments/Comment.tsx`
|
||||
|
||||
The emoji reactions are seamlessly integrated into the existing comment component, appearing between the comment content and action buttons.
|
||||
|
||||
## Predefined Emoji Set
|
||||
|
||||
The system includes 8 carefully chosen emoji reactions:
|
||||
|
||||
| Emoji | Label | Use Case |
|
||||
|-------|-------|----------|
|
||||
| 👍 | thumbs up | General approval/agreement |
|
||||
| ❤️ | heart | Love/strong positive feeling |
|
||||
| 😂 | laugh | Funny/humorous content |
|
||||
| 😮 | wow | Surprise/amazement |
|
||||
| 😢 | sad | Sadness/empathy |
|
||||
| 😡 | angry | Disagreement/frustration |
|
||||
| 🎉 | celebrate | Celebration/excitement |
|
||||
| 🔥 | fire | Impressive/awesome content |
|
||||
|
||||
## Nostr Protocol Integration
|
||||
|
||||
### Event Structure
|
||||
|
||||
Emoji reactions use **kind 7 events** (reactions) with specific formatting:
|
||||
|
||||
**Adding a Reaction:**
|
||||
```json
|
||||
{
|
||||
"kind": 7,
|
||||
"content": "👍",
|
||||
"tags": [
|
||||
["e", "comment-event-id"],
|
||||
["p", "comment-author-pubkey"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
**Removing a Reaction:**
|
||||
```json
|
||||
{
|
||||
"kind": 7,
|
||||
"content": "-👍",
|
||||
"tags": [
|
||||
["e", "comment-event-id"],
|
||||
["p", "comment-author-pubkey"]
|
||||
]
|
||||
}
|
||||
```
|
||||
|
||||
### Reaction Processing Logic
|
||||
|
||||
1. **Fetch**: Query kind 7 events referencing the comment
|
||||
2. **Group**: Organize by emoji and user (latest reaction wins)
|
||||
3. **Filter**: Remove reactions with "-" prefix (removals)
|
||||
4. **Aggregate**: Count active reactions per emoji
|
||||
5. **Display**: Show sorted by popularity
|
||||
|
||||
## User Experience Features
|
||||
|
||||
### Optimistic Updates
|
||||
|
||||
**Immediate Feedback:**
|
||||
- Reactions appear instantly when clicked
|
||||
- UI updates before network confirmation
|
||||
- Smooth animations and visual feedback
|
||||
|
||||
**Error Recovery:**
|
||||
- Failed reactions automatically revert
|
||||
- Clear error messages for network issues
|
||||
- Graceful degradation when offline
|
||||
|
||||
### Visual Design
|
||||
|
||||
**Reaction Badges:**
|
||||
- Highlighted when user has reacted
|
||||
- Shows emoji + count in compact format
|
||||
- Hover effects for better interactivity
|
||||
|
||||
**Emoji Picker:**
|
||||
- Grid layout with all available emojis
|
||||
- Accessible with keyboard navigation
|
||||
- Auto-closes after selection
|
||||
|
||||
### Accessibility
|
||||
|
||||
**Keyboard Support:**
|
||||
- Tab navigation through reactions
|
||||
- Enter/Space to toggle reactions
|
||||
- Escape to close emoji picker
|
||||
|
||||
**Screen Reader Support:**
|
||||
- Descriptive labels for all buttons
|
||||
- Reaction counts announced properly
|
||||
- Tooltip content accessible
|
||||
|
||||
## Real-time Synchronization
|
||||
|
||||
### Cache Management
|
||||
|
||||
**Automatic Invalidation:**
|
||||
```typescript
|
||||
// In useNostrPublish hook
|
||||
if (kind === 7) {
|
||||
const eTag = tags.find(([name]) => name === 'e')?.[1];
|
||||
if (eTag) {
|
||||
queryClient.invalidateQueries({ queryKey: ['comment-reactions', eTag] });
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
**Background Refresh:**
|
||||
- 10 second stale time for fresh data
|
||||
- 30 second background refetch interval
|
||||
- Catches external reactions from other users
|
||||
|
||||
### Optimistic Update Flow
|
||||
|
||||
1. **User clicks reaction** → UI updates immediately
|
||||
2. **Event published** to Nostr network
|
||||
3. **On success** → Cache invalidated for real data
|
||||
4. **On error** → Optimistic update reverted
|
||||
|
||||
## Performance Optimizations
|
||||
|
||||
### Efficient Queries
|
||||
|
||||
**Targeted Fetching:**
|
||||
- Only fetch reactions for visible comments
|
||||
- Limit to 500 reactions per comment (reasonable max)
|
||||
- 3-second timeout for network requests
|
||||
|
||||
**Smart Caching:**
|
||||
- Per-comment reaction caching
|
||||
- Automatic cleanup of unused data
|
||||
- Optimized re-renders with React.memo
|
||||
|
||||
### Network Efficiency
|
||||
|
||||
**Batch Operations:**
|
||||
- Single query for all comment reactions
|
||||
- Efficient event filtering and processing
|
||||
- Minimal redundant network requests
|
||||
|
||||
## Integration Examples
|
||||
|
||||
### Basic Usage
|
||||
|
||||
```tsx
|
||||
import { EmojiReactions } from '@/components/comments/EmojiReactions';
|
||||
|
||||
function CommentCard({ comment }) {
|
||||
return (
|
||||
<div>
|
||||
<p>{comment.content}</p>
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
### Custom Styling
|
||||
|
||||
```tsx
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
className="mt-3 border-t pt-3"
|
||||
/>
|
||||
```
|
||||
|
||||
## Demo Component
|
||||
|
||||
**File**: `src/components/EmojiReactionsDemo.tsx`
|
||||
|
||||
Provides interactive demonstration of:
|
||||
- Reaction toggling functionality
|
||||
- Emoji picker interface
|
||||
- Real-time update behavior
|
||||
- Available emoji set
|
||||
|
||||
## Testing Strategy
|
||||
|
||||
### Unit Tests
|
||||
|
||||
**Hook Testing:**
|
||||
- Reaction fetching and processing
|
||||
- Optimistic update logic
|
||||
- Error handling scenarios
|
||||
|
||||
**Component Testing:**
|
||||
- Emoji picker functionality
|
||||
- Reaction badge interactions
|
||||
- Loading and error states
|
||||
|
||||
### Integration Tests
|
||||
|
||||
**Real-time Flow:**
|
||||
- End-to-end reaction posting
|
||||
- Cache invalidation verification
|
||||
- Cross-user reaction visibility
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
### Potential Improvements
|
||||
|
||||
**Custom Emojis:**
|
||||
- Support for custom emoji reactions
|
||||
- Unicode emoji search functionality
|
||||
- Reaction categories and organization
|
||||
|
||||
**Enhanced Analytics:**
|
||||
- Reaction trend analysis
|
||||
- Popular emoji tracking
|
||||
- User engagement metrics
|
||||
|
||||
**Advanced Features:**
|
||||
- Reaction notifications
|
||||
- Bulk reaction operations
|
||||
- Reaction history viewing
|
||||
|
||||
### Scalability Considerations
|
||||
|
||||
**Large Comment Threads:**
|
||||
- Pagination for reactions
|
||||
- Virtual scrolling for performance
|
||||
- Lazy loading of reaction data
|
||||
|
||||
**High-Traffic Scenarios:**
|
||||
- Rate limiting for reactions
|
||||
- Debounced optimistic updates
|
||||
- Efficient WebSocket integration
|
||||
|
||||
## Security Considerations
|
||||
|
||||
### Spam Prevention
|
||||
|
||||
**Rate Limiting:**
|
||||
- Client-side debouncing
|
||||
- Reasonable reaction frequency limits
|
||||
- User authentication requirements
|
||||
|
||||
**Content Validation:**
|
||||
- Emoji format validation
|
||||
- Maximum reaction count per user
|
||||
- Malicious content filtering
|
||||
|
||||
### Privacy
|
||||
|
||||
**User Data:**
|
||||
- Reaction anonymity options
|
||||
- Configurable visibility settings
|
||||
- GDPR compliance considerations
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Common Issues
|
||||
|
||||
**Reactions Not Appearing:**
|
||||
- Check user authentication status
|
||||
- Verify network connectivity
|
||||
- Confirm relay accessibility
|
||||
|
||||
**Performance Problems:**
|
||||
- Monitor query cache size
|
||||
- Check for memory leaks
|
||||
- Optimize re-render frequency
|
||||
|
||||
**Synchronization Issues:**
|
||||
- Validate event publishing
|
||||
- Check cache invalidation logic
|
||||
- Verify real-time polling intervals
|
||||
|
||||
### Debug Tools
|
||||
|
||||
**Development Helpers:**
|
||||
- React Query DevTools integration
|
||||
- Console logging for cache operations
|
||||
- Network request monitoring
|
||||
|
||||
This emoji reactions system enhances user engagement while maintaining excellent performance and real-time synchronization across the Nostr network.
|
||||
@@ -34,6 +34,7 @@ Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The p
|
||||
Shakespeare is available on the following URLs:
|
||||
|
||||
- [shakespeare.diy](https://shakespeare.diy)
|
||||
- [shakespeare.soapbox.dev](https://shakespeare.soapbox.dev)
|
||||
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
|
||||
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
|
||||
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
# Real-Time Updates Implementation
|
||||
|
||||
This document describes the implementation of real-time updates for ratings and comments on showcase app pages, eliminating the need for users to refresh the page to see their updates.
|
||||
|
||||
## Overview
|
||||
|
||||
The implementation uses a combination of:
|
||||
- **Optimistic Updates**: Immediate UI updates before server confirmation
|
||||
- **Automatic Cache Invalidation**: Smart query refreshing after publishing events
|
||||
- **Background Polling**: Periodic data refreshing to catch external changes
|
||||
- **Error Handling**: Graceful rollback of failed optimistic updates
|
||||
|
||||
## Key Components Modified
|
||||
|
||||
### 1. `useNostrPublish` Hook (`src/hooks/useNostrPublish.ts`)
|
||||
|
||||
**Enhanced with automatic query invalidation:**
|
||||
- Detects event types (comments, ratings, moderation) based on `kind` and `tags`
|
||||
- Automatically invalidates relevant TanStack Query caches after successful publishing
|
||||
- Supports multiple query patterns for comprehensive cache updates
|
||||
|
||||
**Invalidation Logic:**
|
||||
```typescript
|
||||
// Comments (kind 1111)
|
||||
if (kind === 1111) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'comments'] });
|
||||
}
|
||||
|
||||
// Ratings (kind 7)
|
||||
if (kind === 7) {
|
||||
const eTag = tags.find(([name]) => name === 'e')?.[1];
|
||||
if (eTag) {
|
||||
queryClient.invalidateQueries({ queryKey: ['ratings', eTag] });
|
||||
}
|
||||
}
|
||||
|
||||
// App submissions and moderation
|
||||
if (kind === 31733 || kind === 30267 || kind === 1984) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
}
|
||||
```
|
||||
|
||||
### 2. Comments System
|
||||
|
||||
**`useComments` Hook (`src/hooks/useComments.ts`):**
|
||||
- Reduced stale time to 10 seconds for fresher data
|
||||
- Background refetch every 30 seconds
|
||||
- Maintains existing query structure for compatibility
|
||||
|
||||
**`usePostComment` Hook (`src/hooks/usePostComment.ts`):**
|
||||
- **Optimistic Updates**: Comments appear immediately in UI
|
||||
- **Error Recovery**: Failed comments are automatically removed from UI
|
||||
- **Cache Management**: Proper handling of comment threading and structure
|
||||
|
||||
**Optimistic Update Flow:**
|
||||
1. User submits comment
|
||||
2. Comment appears immediately in UI (optimistic)
|
||||
3. Event published to Nostr network
|
||||
4. On success: Cache invalidated, real data fetched
|
||||
5. On error: Optimistic update reverted, error shown
|
||||
|
||||
### 3. Ratings System
|
||||
|
||||
**Enhanced Ratings in `ShowcasePage.tsx`:**
|
||||
- **Immediate Visual Feedback**: Stars update instantly when clicked
|
||||
- **Optimistic Rating Updates**: New ratings appear before network confirmation
|
||||
- **Loading States**: Visual indicators during submission
|
||||
- **Error Handling**: Failed ratings revert with error message
|
||||
|
||||
**Optimistic Rating Flow:**
|
||||
```typescript
|
||||
const handleRate = (rating: number) => {
|
||||
// 1. Update cache optimistically
|
||||
queryClient.setQueryData(['ratings', appEvent.id], (oldRatings) => {
|
||||
const filteredRatings = oldRatings.filter(r => r.pubkey !== user.pubkey);
|
||||
return [...filteredRatings, optimisticRating];
|
||||
});
|
||||
|
||||
// 2. Publish to network
|
||||
publishEvent({...}, {
|
||||
onSuccess: () => toast({ title: 'Rating Submitted!' }),
|
||||
onError: () => {
|
||||
queryClient.invalidateQueries(['ratings', appEvent.id]); // Revert
|
||||
toast({ title: 'Error', variant: 'destructive' });
|
||||
}
|
||||
});
|
||||
};
|
||||
```
|
||||
|
||||
### 4. Moderation Actions
|
||||
|
||||
**Enhanced in both `AppShowcaseCard.tsx` and `ShowcasePage.tsx`:**
|
||||
- Immediate cache invalidation after moderation actions
|
||||
- Multiple query invalidation for comprehensive updates
|
||||
- Visual feedback during pending actions
|
||||
|
||||
**Invalidation Pattern:**
|
||||
```typescript
|
||||
// After moderation action
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation', id] });
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
```
|
||||
|
||||
### 5. Background Refresh Intervals
|
||||
|
||||
**Optimized refresh rates for real-time feel:**
|
||||
- **Comments**: 10s stale time, 30s background refetch
|
||||
- **Ratings**: 10s stale time, 30s background refetch
|
||||
- **App Submissions**: 10s stale time, 30s background refetch
|
||||
- **Moderation Data**: 5s stale time, 15s background refetch
|
||||
|
||||
## User Experience Improvements
|
||||
|
||||
### Immediate Feedback
|
||||
- **Comments**: Appear instantly when submitted
|
||||
- **Ratings**: Stars update immediately on click
|
||||
- **Moderation**: Status changes reflect immediately
|
||||
|
||||
### Loading States
|
||||
- **Comment Form**: Shows "Posting comment..." during submission
|
||||
- **Rating Stars**: Animate with pulse effect during submission
|
||||
- **Moderation Menu**: Spinner icon during actions
|
||||
|
||||
### Error Handling
|
||||
- **Failed Comments**: Removed from UI with error toast
|
||||
- **Failed Ratings**: Reverted with descriptive error message
|
||||
- **Failed Moderation**: Clear error feedback with retry option
|
||||
|
||||
## Technical Benefits
|
||||
|
||||
### Performance
|
||||
- **Reduced Server Load**: Fewer unnecessary requests through smart caching
|
||||
- **Perceived Speed**: Optimistic updates make UI feel instant
|
||||
- **Efficient Polling**: Targeted background refreshes only for active data
|
||||
|
||||
### Reliability
|
||||
- **Graceful Degradation**: Falls back to polling if optimistic updates fail
|
||||
- **Conflict Resolution**: Latest server data always wins over optimistic updates
|
||||
- **Error Recovery**: Automatic rollback of failed operations
|
||||
|
||||
### Maintainability
|
||||
- **Centralized Logic**: Cache invalidation handled in `useNostrPublish`
|
||||
- **Type Safety**: Full TypeScript support with proper error handling
|
||||
- **Consistent Patterns**: Same approach across all real-time features
|
||||
|
||||
## Demo Component
|
||||
|
||||
**`RealTimeDemo.tsx`** provides a testing interface to demonstrate:
|
||||
- Optimistic comment updates
|
||||
- Instant rating feedback
|
||||
- Real-time moderation changes
|
||||
- Error handling scenarios
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
### Query Key Strategy
|
||||
Consistent query keys enable precise cache invalidation:
|
||||
- `['nostr', 'comments', eventId]` for comments
|
||||
- `['ratings', eventId]` for ratings
|
||||
- `['showcase-moderation', appId]` for moderation status
|
||||
|
||||
### Error Boundaries
|
||||
All optimistic updates include error handling to prevent inconsistent UI state:
|
||||
- Comments: Remove optimistic comment on error
|
||||
- Ratings: Invalidate ratings cache on error
|
||||
- Moderation: Show error toast with retry option
|
||||
|
||||
### Network Efficiency
|
||||
- **Batched Invalidations**: Multiple related queries updated together
|
||||
- **Smart Polling**: Background refreshes only for visible/active components
|
||||
- **Timeout Protection**: All network requests have reasonable timeouts
|
||||
|
||||
## Future Enhancements
|
||||
|
||||
Potential improvements for even better real-time experience:
|
||||
- **WebSocket Integration**: Real-time event streaming from relays
|
||||
- **Conflict Resolution**: Better handling of concurrent updates
|
||||
- **Offline Support**: Queue actions when network is unavailable
|
||||
- **Push Notifications**: Alert users to new comments/ratings on their apps
|
||||
|
||||
## Testing
|
||||
|
||||
The implementation includes:
|
||||
- **Unit Tests**: All hooks have comprehensive test coverage
|
||||
- **Integration Tests**: Real-time flow testing
|
||||
- **Error Scenarios**: Failed network requests and edge cases
|
||||
- **Performance Tests**: Cache invalidation efficiency
|
||||
|
||||
Run tests with: `npm run test`
|
||||
+1
-1
@@ -11,7 +11,7 @@
|
||||
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
|
||||
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
|
||||
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
|
||||
<link rel="icon" type="image/png" href="/shakespeare-192x192.png">
|
||||
<link rel="apple-touch-icon" href="/shakespeare-192x192.png" sizes="192x192">
|
||||
<meta name="theme-color" content="#2b0037">
|
||||
|
||||
Generated
+21
-745
File diff suppressed because it is too large.
Load diff
+1
-4
@@ -18,7 +18,7 @@
|
||||
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
|
||||
"typecheck": "npm i --silent && tsc --noEmit",
|
||||
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
|
||||
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && electron electron",
|
||||
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
|
||||
},
|
||||
"dependencies": {
|
||||
@@ -29,7 +29,6 @@
|
||||
"@getalby/sdk": "^6.0.1",
|
||||
"@hookform/resolvers": "^3.9.0",
|
||||
"@isomorphic-git/lightning-fs": "^4.6.2",
|
||||
"@modelcontextprotocol/sdk": "^1.22.0",
|
||||
"@mozilla/readability": "^0.6.0",
|
||||
"@nostrify/nostrify": "^0.47.1",
|
||||
"@nostrify/react": "^0.2.17",
|
||||
@@ -82,7 +81,6 @@
|
||||
"lucide-react": "^0.525.0",
|
||||
"mime": "^4.1.0",
|
||||
"nostr-tools": "^2.15.2",
|
||||
"nunjucks": "^3.2.4",
|
||||
"openai": "^5.15.0",
|
||||
"path-browserify": "^1.0.1",
|
||||
"prismjs": "^1.30.0",
|
||||
@@ -120,7 +118,6 @@
|
||||
"@testing-library/user-event": "^14.6.1",
|
||||
"@types/jszip": "^3.4.0",
|
||||
"@types/node": "^22.5.5",
|
||||
"@types/nunjucks": "^3.2.6",
|
||||
"@types/path-browserify": "^1.0.3",
|
||||
"@types/prismjs": "^1.26.5",
|
||||
"@types/qrcode": "^1.5.5",
|
||||
|
||||
+1
-2
@@ -1,2 +1 @@
|
||||
/assets/* /assets/:splat 200
|
||||
/* /index.html 200
|
||||
/* /index.html 200
|
||||
+1
-6
@@ -48,7 +48,7 @@ const queryClient = new QueryClient({
|
||||
});
|
||||
|
||||
// Get OS-specific default paths for Electron
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
|
||||
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string } {
|
||||
if (!globalThis.electron) {
|
||||
// Browser defaults - use virtual filesystem paths
|
||||
return {
|
||||
@@ -56,7 +56,6 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "/config",
|
||||
fsPathTmp: "/tmp",
|
||||
fsPathPlugins: "/plugins",
|
||||
fsPathTemplates: "/templates",
|
||||
};
|
||||
}
|
||||
|
||||
@@ -71,7 +70,6 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "~/AppData/Local/shakespeare",
|
||||
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
|
||||
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
|
||||
fsPathTemplates: "~/AppData/Local/shakespeare/templates",
|
||||
};
|
||||
} else if (platform.includes('mac')) {
|
||||
// macOS
|
||||
@@ -80,7 +78,6 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "~/Library/Application Support/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
|
||||
fsPathTemplates: "~/Library/Application Support/shakespeare/templates",
|
||||
};
|
||||
} else {
|
||||
// Linux and other Unix-like systems
|
||||
@@ -89,7 +86,6 @@ function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: stri
|
||||
fsPathConfig: "~/.config/shakespeare",
|
||||
fsPathTmp: "/tmp/shakespeare",
|
||||
fsPathPlugins: "~/.config/shakespeare/plugins",
|
||||
fsPathTemplates: "~/.config/shakespeare/templates",
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -118,7 +114,6 @@ const defaultConfig: AppConfig = {
|
||||
fsPathConfig: electronPaths.fsPathConfig,
|
||||
fsPathTmp: electronPaths.fsPathTmp,
|
||||
fsPathPlugins: electronPaths.fsPathPlugins,
|
||||
fsPathTemplates: electronPaths.fsPathTemplates,
|
||||
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
|
||||
sentryEnabled: true,
|
||||
};
|
||||
|
||||
@@ -21,6 +21,7 @@ import VercelOAuth from "./pages/VercelOAuth";
|
||||
import { NIP19Page } from "./pages/NIP19Page";
|
||||
import NotFound from "./pages/NotFound";
|
||||
import { ProjectView } from "./pages/ProjectView";
|
||||
import ShowcasePage from "./pages/ShowcasePage";
|
||||
import { SettingsLayout } from "./components/SettingsLayout";
|
||||
|
||||
export function AppRouter() {
|
||||
@@ -51,6 +52,7 @@ export function AppRouter() {
|
||||
<Route path="about" element={<AboutSettings />} />
|
||||
</Route>
|
||||
<Route path="/project/:projectId" element={<ProjectView />} />
|
||||
<Route path="/showcase/:id" element={<ShowcasePage />} />
|
||||
{/* NIP-19 route for npub1, note1, naddr1, nevent1, nprofile1 */}
|
||||
<Route path="/:nip19" element={<NIP19Page />} />
|
||||
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
|
||||
|
||||
@@ -7,8 +7,6 @@ import { UserMessage } from '@/components/UserMessage';
|
||||
import OpenAI from 'openai';
|
||||
import { useTheme } from '@/hooks/useTheme';
|
||||
import { isEmptyMessage } from '@/lib/isEmptyMessage';
|
||||
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
|
||||
import * as DialogPrimitive from '@radix-ui/react-dialog';
|
||||
|
||||
// Type guard to check if message has reasoning content
|
||||
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
|
||||
@@ -28,7 +26,6 @@ export const AIMessageItem = memo(({
|
||||
}: AIMessageItemProps) => {
|
||||
const [isToolExpanded, setIsToolExpanded] = useState(false);
|
||||
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
|
||||
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
|
||||
const { displayTheme } = useTheme();
|
||||
|
||||
// Get content to display
|
||||
@@ -298,90 +295,20 @@ export const AIMessageItem = memo(({
|
||||
// Regular rendering for non-tool messages
|
||||
if (message.role === 'user') {
|
||||
// User messages: right-aligned bubble without avatar/name
|
||||
// Extract text and image parts from message content
|
||||
const contentArray = Array.isArray(message.content) ? message.content : null;
|
||||
const textParts = contentArray
|
||||
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: [];
|
||||
const userContent = typeof message.content === 'string'
|
||||
? message.content
|
||||
: textParts.length > 0
|
||||
? textParts.map(part => part.text).join('\n')
|
||||
: Array.isArray(message.content)
|
||||
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
|
||||
: '';
|
||||
|
||||
// Extract image URLs from content array
|
||||
const imageUrls = contentArray
|
||||
? contentArray
|
||||
.filter(part => part.type === 'image_url')
|
||||
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
|
||||
: [];
|
||||
|
||||
return (
|
||||
<>
|
||||
<div className="flex justify-end py-6">
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm break-words space-y-2">
|
||||
{/* Render text content and attachments first */}
|
||||
{userContent && <UserMessage content={userContent} />}
|
||||
{/* Render images after text and attachments */}
|
||||
{imageUrls.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{imageUrls.map((url, index) => (
|
||||
<div
|
||||
key={index}
|
||||
className="rounded-lg overflow-hidden border border-border cursor-pointer hover:opacity-90 transition-opacity"
|
||||
onClick={() => setExpandedImageUrl(url)}
|
||||
>
|
||||
<img
|
||||
src={url}
|
||||
alt={`User uploaded image ${index + 1}`}
|
||||
className="max-w-full h-auto max-h-96 object-contain"
|
||||
loading="lazy"
|
||||
onError={(e) => {
|
||||
// Fallback if image fails to load
|
||||
const target = e.target as HTMLImageElement;
|
||||
target.style.display = 'none';
|
||||
const fallback = document.createElement('div');
|
||||
fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded';
|
||||
fallback.textContent = `Image failed to load: ${url}`;
|
||||
target.parentElement?.appendChild(fallback);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
<div className="flex justify-end py-6">
|
||||
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
|
||||
<div className="text-sm break-words">
|
||||
<UserMessage content={userContent} />
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Image expansion dialog */}
|
||||
<Dialog open={!!expandedImageUrl} onOpenChange={(open) => !open && setExpandedImageUrl(null)}>
|
||||
<DialogPortal>
|
||||
<DialogOverlay className="bg-black/95" />
|
||||
<DialogPrimitive.Content
|
||||
className={cn(
|
||||
"fixed left-[50%] top-[50%] z-50 max-w-[95vw] max-h-[95vh] translate-x-[-50%] translate-y-[-50%] p-0 bg-transparent border-0 shadow-none",
|
||||
"data-[state=open]:animate-in data-[state=closed]:animate-out",
|
||||
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
|
||||
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
|
||||
)}
|
||||
onPointerDownOutside={() => setExpandedImageUrl(null)}
|
||||
onEscapeKeyDown={() => setExpandedImageUrl(null)}
|
||||
>
|
||||
{expandedImageUrl && (
|
||||
<div className="relative flex items-center justify-center">
|
||||
<img
|
||||
src={expandedImageUrl}
|
||||
alt="Expanded image"
|
||||
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
</DialogPrimitive.Content>
|
||||
</DialogPortal>
|
||||
</Dialog>
|
||||
</>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { ReactNode, useState, useEffect } from 'react';
|
||||
import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { readAISettings, writeAISettings } from '@/lib/configUtils';
|
||||
@@ -12,7 +12,6 @@ interface AISettingsProviderProps {
|
||||
const DEFAULT_SETTINGS: AISettings = {
|
||||
providers: [],
|
||||
recentlyUsedModels: [],
|
||||
mcpServers: {},
|
||||
};
|
||||
|
||||
export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
@@ -129,27 +128,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
});
|
||||
};
|
||||
|
||||
const setMCPServer = (name: string, server: MCPServer) => {
|
||||
setSettings(prev => ({
|
||||
...prev,
|
||||
mcpServers: {
|
||||
...(prev.mcpServers || {}),
|
||||
[name]: server,
|
||||
},
|
||||
}));
|
||||
};
|
||||
|
||||
const removeMCPServer = (name: string) => {
|
||||
setSettings(prev => {
|
||||
const newMCPServers = { ...(prev.mcpServers || {}) };
|
||||
delete newMCPServers[name];
|
||||
return {
|
||||
...prev,
|
||||
mcpServers: newMCPServers,
|
||||
};
|
||||
});
|
||||
};
|
||||
|
||||
const isConfigured = settings.providers.length > 0;
|
||||
|
||||
const contextValue: AISettingsContextType = {
|
||||
@@ -159,8 +137,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
|
||||
removeProvider,
|
||||
setProviders,
|
||||
addRecentlyUsedModel,
|
||||
setMCPServer,
|
||||
removeMCPServer,
|
||||
isConfigured,
|
||||
};
|
||||
|
||||
|
||||
@@ -39,7 +39,6 @@ const AppConfigSchema = z.object({
|
||||
fsPathConfig: z.string().min(1),
|
||||
fsPathTmp: z.string().min(1),
|
||||
fsPathPlugins: z.string().min(1),
|
||||
fsPathTemplates: z.string().min(1),
|
||||
sentryDsn: z.string(),
|
||||
sentryEnabled: z.boolean(),
|
||||
}) satisfies z.ZodType<AppConfig>;
|
||||
@@ -77,11 +76,9 @@ export function AppProvider(props: AppProviderProps) {
|
||||
config.fsPathProjects = expandPath(config.fsPathProjects);
|
||||
config.fsPathTmp = expandPath(config.fsPathTmp);
|
||||
config.fsPathPlugins = expandPath(config.fsPathPlugins);
|
||||
config.fsPathTemplates = expandPath(config.fsPathTemplates);
|
||||
|
||||
const appContextValue: AppContextType = {
|
||||
config,
|
||||
defaultConfig,
|
||||
updateConfig,
|
||||
};
|
||||
|
||||
|
||||
@@ -35,51 +35,25 @@ export function AppShowcase() {
|
||||
}, [config.showcaseModerator]);
|
||||
const isModerator = user?.pubkey === MODERATOR_HEX;
|
||||
|
||||
// Categorize and organize submissions - single pass for efficiency
|
||||
const {
|
||||
displayedFeaturedApps,
|
||||
displayedTemplateApps,
|
||||
moreApps
|
||||
} = useMemo(() => {
|
||||
const DISPLAY_LIMIT = 6;
|
||||
|
||||
// Single pass categorization
|
||||
const templates: typeof submissions = [];
|
||||
const featured: typeof submissions = [];
|
||||
const approved: typeof submissions = [];
|
||||
|
||||
for (const app of submissions) {
|
||||
if (app.isHidden) continue;
|
||||
|
||||
const isTemplate = app.appTags.includes('Template');
|
||||
const isFeatured = app.isFeatured;
|
||||
const isApproved = app.isApproved;
|
||||
|
||||
if (isTemplate) {
|
||||
templates.push(app);
|
||||
} else if (isFeatured) {
|
||||
featured.push(app);
|
||||
} else if (isApproved) {
|
||||
approved.push(app);
|
||||
}
|
||||
}
|
||||
|
||||
// Shuffle each category once
|
||||
const shuffledTemplates = shuffleArray(templates);
|
||||
const shuffledFeatured = shuffleArray(featured);
|
||||
const shuffledApproved = shuffleArray(approved);
|
||||
|
||||
// Split into display and more sections
|
||||
// Filter and shuffle submissions - memoized with stable dependency
|
||||
const { templateApps, featuredApps, approvedApps } = useMemo(() => {
|
||||
// Filter visible submissions
|
||||
const visibleSubmissions = submissions.filter(app => !app.isHidden);
|
||||
|
||||
// Separate template apps from other apps
|
||||
const templates = shuffleArray(visibleSubmissions.filter(app => app.appTags.includes('Template')));
|
||||
const nonTemplateSubmissions = visibleSubmissions.filter(app => !app.appTags.includes('Template'));
|
||||
|
||||
// Shuffle featured and approved apps for random display order
|
||||
const featured = shuffleArray(nonTemplateSubmissions.filter(app => app.isFeatured));
|
||||
const approved = shuffleArray(nonTemplateSubmissions.filter(app => app.isApproved && !app.isFeatured));
|
||||
|
||||
return {
|
||||
displayedFeaturedApps: shuffledFeatured.slice(0, DISPLAY_LIMIT),
|
||||
displayedTemplateApps: shuffledTemplates.slice(0, DISPLAY_LIMIT),
|
||||
moreApps: [
|
||||
...shuffledFeatured.slice(DISPLAY_LIMIT),
|
||||
...shuffledTemplates.slice(DISPLAY_LIMIT),
|
||||
...shuffledApproved,
|
||||
],
|
||||
templateApps: templates,
|
||||
featuredApps: featured,
|
||||
approvedApps: approved,
|
||||
};
|
||||
}, [submissions]);
|
||||
}, [submissions]); // Only depend on submissions, not intermediate filtered arrays
|
||||
|
||||
// Don't show showcase if disabled in settings
|
||||
if (!config.showcaseEnabled) {
|
||||
@@ -150,7 +124,7 @@ export function AppShowcase() {
|
||||
{/* Apps Grid */}
|
||||
<div className="space-y-12">
|
||||
{/* Featured Apps */}
|
||||
{displayedFeaturedApps.length > 0 && (
|
||||
{featuredApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
|
||||
@@ -162,7 +136,7 @@ export function AppShowcase() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{displayedFeaturedApps.map((app) => (
|
||||
{featuredApps.slice(0, 6).map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
@@ -175,7 +149,7 @@ export function AppShowcase() {
|
||||
)}
|
||||
|
||||
{/* Templates Section */}
|
||||
{displayedTemplateApps.length > 0 && (
|
||||
{templateApps.length > 0 && (
|
||||
<div>
|
||||
<div className="flex items-start gap-3 mb-6">
|
||||
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
|
||||
@@ -187,7 +161,7 @@ export function AppShowcase() {
|
||||
</div>
|
||||
</div>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{displayedTemplateApps.map((app) => (
|
||||
{templateApps.slice(0, 6).map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
@@ -199,8 +173,8 @@ export function AppShowcase() {
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* More Apps (Remaining Featured, Templates, and Approved) - Collapsible */}
|
||||
{moreApps.length > 0 && (
|
||||
{/* More Apps (Approved) - Collapsible */}
|
||||
{approvedApps.length > 0 && (
|
||||
<div>
|
||||
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
|
||||
<CollapsibleTrigger asChild>
|
||||
@@ -211,7 +185,7 @@ export function AppShowcase() {
|
||||
</div>
|
||||
<div className="text-left">
|
||||
<h3 className="text-xl font-bold text-foreground">
|
||||
{t('moreAppsCount', { count: moreApps.length })}
|
||||
{t('moreAppsCount', { count: approvedApps.length })}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
|
||||
@@ -222,7 +196,7 @@ export function AppShowcase() {
|
||||
</CollapsibleTrigger>
|
||||
<CollapsibleContent>
|
||||
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{moreApps.map((app) => (
|
||||
{approvedApps.map((app) => (
|
||||
<AppShowcaseCard
|
||||
key={app.id}
|
||||
app={app}
|
||||
|
||||
@@ -346,8 +346,10 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
});
|
||||
}
|
||||
|
||||
// Invalidate queries to refresh the data
|
||||
// Invalidate queries to refresh the data immediately
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
|
||||
// If this is a Halloween app, also invalidate Halloween queries
|
||||
if (isHalloweenSubmission) {
|
||||
@@ -370,14 +372,28 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
}
|
||||
};
|
||||
|
||||
// Generate naddr for the app
|
||||
const appNaddr = React.useMemo(() => {
|
||||
const dTag = app.tags.find(tag => tag[0] === 'd')?.[1];
|
||||
if (!dTag) return null;
|
||||
|
||||
try {
|
||||
return nip19.naddrEncode({
|
||||
kind: app.kind,
|
||||
pubkey: app.pubkey,
|
||||
identifier: dTag,
|
||||
});
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}, [app.kind, app.pubkey, app.tags]);
|
||||
|
||||
return (
|
||||
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
|
||||
<div className="relative">
|
||||
{/* App Screenshot */}
|
||||
<a
|
||||
href={app.websiteUrl}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
<Link
|
||||
to={appNaddr ? `/showcase/${appNaddr}` : '#'}
|
||||
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
|
||||
>
|
||||
{!imageError ? (
|
||||
@@ -397,15 +413,15 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</a>
|
||||
</Link>
|
||||
|
||||
{/* Actions Menu */}
|
||||
{(isOwner || showModerationControls) && (
|
||||
<div className="absolute top-3 right-3">
|
||||
<DropdownMenu>
|
||||
<DropdownMenuTrigger asChild>
|
||||
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
|
||||
<MoreVertical className="w-4 h-4" />
|
||||
<Button variant="secondary" size="sm" className="h-8 w-8 p-0" disabled={isPending}>
|
||||
<MoreVertical className={`w-4 h-4 ${isPending ? 'animate-spin' : ''}`} />
|
||||
</Button>
|
||||
</DropdownMenuTrigger>
|
||||
<DropdownMenuContent align="end">
|
||||
|
||||
@@ -124,7 +124,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
const [isDeploying, setIsDeploying] = useState(false);
|
||||
const [deployResult, setDeployResult] = useState<{ url: string } | null>(null);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isShakespeareFormValid, setIsShakespeareFormValid] = useState(true);
|
||||
|
||||
// Provider-specific form data
|
||||
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
|
||||
@@ -295,10 +294,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
setShakespeareForm({ subdomain });
|
||||
}, []);
|
||||
|
||||
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
|
||||
setIsShakespeareFormValid(isValid);
|
||||
}, []);
|
||||
|
||||
const handleNsiteNsecChange = useCallback((nsec: string) => {
|
||||
setNsiteForm({ nsec });
|
||||
}, []);
|
||||
@@ -322,7 +317,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
host={shakespeareProvider.host}
|
||||
projectId={projectId}
|
||||
onSubdomainChange={handleShakespeareSubdomainChange}
|
||||
onValidationChange={handleShakespeareValidationChange}
|
||||
/>
|
||||
);
|
||||
}
|
||||
@@ -501,7 +495,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
|
||||
!selectedProvider ||
|
||||
isDeploying ||
|
||||
(selectedProvider.type === 'shakespeare' && !user) ||
|
||||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
|
||||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
|
||||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,112 @@
|
||||
import React from 'react';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { EmojiReactions } from '@/components/comments/EmojiReactions';
|
||||
import { EMOJI_REACTIONS } from '@/hooks/useCommentReactions';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { Smile, Heart, Zap } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Demo component showing emoji reactions functionality
|
||||
* This demonstrates how users can react to comments with emojis
|
||||
*/
|
||||
export function EmojiReactionsDemo() {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Smile className="h-5 w-5" />
|
||||
Emoji Reactions Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
This demo shows how emoji reactions work on comments.
|
||||
Please log in to test the functionality.
|
||||
</p>
|
||||
<LoginArea />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Smile className="h-5 w-5" />
|
||||
Emoji Reactions Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
Try out emoji reactions on this demo comment. Click existing reactions to toggle them, or add new ones!
|
||||
</p>
|
||||
|
||||
<div className="bg-muted/50 p-4 rounded-lg space-y-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<div className="w-8 h-8 bg-primary/20 rounded-full flex items-center justify-center">
|
||||
<span className="text-sm">👤</span>
|
||||
</div>
|
||||
<div>
|
||||
<p className="font-medium text-sm">Demo User</p>
|
||||
<p className="text-xs text-muted-foreground">2 minutes ago</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p className="text-sm">
|
||||
This is a demo comment to showcase emoji reactions!
|
||||
Try clicking the reactions below or adding your own.
|
||||
</p>
|
||||
|
||||
{/* Demo Emoji Reactions */}
|
||||
<EmojiReactions
|
||||
commentId="demo-comment-123"
|
||||
commentAuthor="demo-author-pubkey"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-6">
|
||||
<h4 className="font-medium mb-4 flex items-center gap-2">
|
||||
<Heart className="h-4 w-4" />
|
||||
Available Reactions
|
||||
</h4>
|
||||
<div className="grid grid-cols-4 gap-3">
|
||||
{EMOJI_REACTIONS.map(({ emoji, label }) => (
|
||||
<div key={emoji} className="flex flex-col items-center gap-1">
|
||||
<div className="text-2xl">{emoji}</div>
|
||||
<Badge variant="outline" className="text-xs">
|
||||
{label}
|
||||
</Badge>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted/50 p-4 rounded-lg">
|
||||
<h5 className="font-medium text-sm mb-2 flex items-center gap-2">
|
||||
<Zap className="h-4 w-4" />
|
||||
How it works:
|
||||
</h5>
|
||||
<ul className="text-sm text-muted-foreground space-y-1">
|
||||
<li>• <strong>Click existing reactions</strong> to toggle your reaction on/off</li>
|
||||
<li>• <strong>Use the smile button</strong> to add new emoji reactions</li>
|
||||
<li>• <strong>Hover over reactions</strong> to see who reacted</li>
|
||||
<li>• <strong>Real-time updates</strong> show reactions instantly</li>
|
||||
<li>• <strong>Optimistic UI</strong> makes interactions feel immediate</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
💡 Tip: Emoji reactions use Nostr kind 7 events and support real-time synchronization across all clients.
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -1,7 +1,6 @@
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ReactNode, useMemo } from 'react';
|
||||
import { ReactNode } from 'react';
|
||||
|
||||
interface ExternalFaviconProps {
|
||||
/** The URL to fetch the favicon for */
|
||||
@@ -26,28 +25,14 @@ export function ExternalFavicon({
|
||||
}: ExternalFaviconProps) {
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = useMemo(() => {
|
||||
try {
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
return faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
} catch {
|
||||
return;
|
||||
}
|
||||
}, [url, config.faviconUrl]);
|
||||
// Normalize the URL to ensure it has a protocol
|
||||
const normalizedUrl = normalizeUrl(url);
|
||||
|
||||
// If faviconSrc is not available, render the fallback directly
|
||||
if (!faviconSrc) {
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<span>{fallback}</span>
|
||||
</span>
|
||||
)
|
||||
}
|
||||
// Generate the favicon URL using the configured template
|
||||
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
|
||||
|
||||
return (
|
||||
<span className={cn('inline-flex items-center justify-center', className)}>
|
||||
<span className={`inline-flex items-center justify-center ${className}`}>
|
||||
<img
|
||||
src={faviconSrc}
|
||||
alt=""
|
||||
|
||||
@@ -25,7 +25,6 @@ const baseGitStatus = {
|
||||
},
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
|
||||
vi.mock('@/hooks/useGitStatus', () => ({
|
||||
@@ -83,16 +82,7 @@ describe('GitDialog', () => {
|
||||
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
|
||||
});
|
||||
|
||||
it('shows sync status when branch is published', () => {
|
||||
// Mock git status with published branch
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
it('shows sync status', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -143,17 +133,7 @@ describe('GitDialog', () => {
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead and branch is published', () => {
|
||||
// Mock git status with published branch and no commits ahead
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: true,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
it('disables push button when no commits ahead', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
@@ -167,38 +147,6 @@ describe('GitDialog', () => {
|
||||
expect(pushButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('enables push and disables pull when branch is not published', () => {
|
||||
// Mock git status with unpublished branch (has commits but no remote branch)
|
||||
mockUseGitStatus.mockReturnValue({
|
||||
data: {
|
||||
...baseGitStatus,
|
||||
ahead: 0,
|
||||
remoteBranchExists: false,
|
||||
totalCommits: 5,
|
||||
},
|
||||
refetch: mockRefetch,
|
||||
});
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
|
||||
<button>Open Git Dialog</button>
|
||||
</GitDialog>
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Sync Status')).toBeInTheDocument();
|
||||
expect(screen.getByText('Branch not published')).toBeInTheDocument();
|
||||
|
||||
const pushButton = screen.getByText('Push');
|
||||
expect(pushButton).toBeInTheDocument();
|
||||
expect(pushButton.closest('button')).not.toBeDisabled();
|
||||
|
||||
const pullButton = screen.getByText('Pull');
|
||||
expect(pullButton).toBeInTheDocument();
|
||||
expect(pullButton.closest('button')).toBeDisabled();
|
||||
});
|
||||
|
||||
it('does not show credentials warning when credentials are configured', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
|
||||
+64
-107
@@ -243,23 +243,13 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateBranchDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
await refetchGitStatus();
|
||||
} catch (error) {
|
||||
@@ -456,7 +446,50 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
throw new Error('Could not determine repository state. The repository might not have any commits or branches.');
|
||||
}
|
||||
|
||||
console.log('Repository has refs:', refTags);
|
||||
// Get HEAD reference
|
||||
let headRef: string | undefined;
|
||||
try {
|
||||
const currentBranch = await git.currentBranch({ dir: projectPath });
|
||||
if (currentBranch) {
|
||||
headRef = `ref: refs/heads/${currentBranch}`;
|
||||
console.log(`HEAD points to: ${headRef}`);
|
||||
} else {
|
||||
// HEAD is detached, use the commit ID directly
|
||||
const headValue = await git.resolveRef({
|
||||
dir: projectPath,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
if (headValue) {
|
||||
headRef = headValue;
|
||||
console.log(`HEAD is detached at: ${headRef}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Failed to resolve HEAD:', error);
|
||||
}
|
||||
|
||||
// Create repo state event (NIP-34 kind 30618)
|
||||
const stateEvent = {
|
||||
kind: 30618,
|
||||
content: '',
|
||||
tags: [
|
||||
['d', result.repoId],
|
||||
...refTags,
|
||||
...(headRef ? [['HEAD', headRef]] : []),
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
};
|
||||
|
||||
console.log('Creating repository state event:', stateEvent);
|
||||
|
||||
// Sign and publish the state event
|
||||
const signedStateEvent = await user.signer.signEvent(stateEvent);
|
||||
|
||||
// State events only go to the relays specified in the repo announcement
|
||||
console.log('Publishing repository state to relays:', result.relays);
|
||||
await nostr.event(signedStateEvent, { relays: result.relays });
|
||||
|
||||
console.log('Published repository state to Nostr relays');
|
||||
|
||||
// Set origin remote to Nostr URL
|
||||
// Format: nostr://<npub>/<repo-id>
|
||||
@@ -489,54 +522,13 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
console.log('Set nostr.repo config to:', result.naddr);
|
||||
|
||||
toast({
|
||||
title: 'Repository published to Nostr',
|
||||
description: 'Waiting for GRASP servers to update...',
|
||||
});
|
||||
|
||||
// Refresh git status to pick up the new remote
|
||||
await refetchGitStatus();
|
||||
|
||||
// Automatically push to the newly configured Nostr remote
|
||||
// Get the current branch fresh from git instead of using stale gitStatus
|
||||
console.log('Starting automatic push to Nostr...');
|
||||
|
||||
try {
|
||||
const currentBranch = await git.currentBranch({ dir: projectPath });
|
||||
console.log('Current branch:', currentBranch);
|
||||
|
||||
if (!currentBranch) {
|
||||
throw new Error('No current branch found');
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Repository published to Nostr',
|
||||
description: 'Pushing commits to ngit servers...',
|
||||
});
|
||||
|
||||
console.log('Calling git.push with:', { dir: projectPath, remote: 'origin', ref: currentBranch });
|
||||
|
||||
await git.push({
|
||||
dir: projectPath,
|
||||
remote: 'origin',
|
||||
ref: currentBranch,
|
||||
signer: user.signer,
|
||||
});
|
||||
|
||||
console.log('Push completed successfully');
|
||||
|
||||
toast({
|
||||
title: 'Push successful',
|
||||
description: 'Repository successfully pushed to Nostr',
|
||||
});
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
} catch (pushError) {
|
||||
console.error('Push error:', pushError);
|
||||
const pushErrorMessage = pushError instanceof Error ? pushError.message : 'Unknown error occurred';
|
||||
toast({
|
||||
title: 'Automatic push failed',
|
||||
description: pushErrorMessage,
|
||||
variant: 'destructive',
|
||||
duration: Infinity,
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred';
|
||||
toast({
|
||||
@@ -569,8 +561,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return;
|
||||
}
|
||||
|
||||
// Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch)
|
||||
if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) {
|
||||
if (gitStatus.ahead === 0) {
|
||||
toast({
|
||||
title: "Nothing to push",
|
||||
description: "No commits ahead of remote. Commit your changes first.",
|
||||
@@ -579,16 +570,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return;
|
||||
}
|
||||
|
||||
// Ensure we have commits to push when publishing a new branch
|
||||
if (!gitStatus.remoteBranchExists && gitStatus.totalCommits === 0) {
|
||||
toast({
|
||||
title: "Cannot publish branch",
|
||||
description: "No commits to push. Commit your changes first.",
|
||||
variant: "destructive",
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setIsPushing(true);
|
||||
|
||||
try {
|
||||
@@ -602,32 +583,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
signer: user?.signer, // For signing if pushing to Nostr
|
||||
});
|
||||
|
||||
// Set up upstream tracking if this is the first push for this branch
|
||||
if (!gitStatus.remoteBranchExists) {
|
||||
await git.setConfig({
|
||||
dir: projectPath,
|
||||
path: `branch.${gitStatus.currentBranch}.remote`,
|
||||
value: remote.name,
|
||||
});
|
||||
await git.setConfig({
|
||||
dir: projectPath,
|
||||
path: `branch.${gitStatus.currentBranch}.merge`,
|
||||
value: `refs/heads/${gitStatus.currentBranch}`,
|
||||
});
|
||||
}
|
||||
|
||||
// Show different messages for publishing new branches vs pushing commits
|
||||
if (gitStatus.remoteBranchExists) {
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
} else {
|
||||
toast({
|
||||
title: "Branch published",
|
||||
description: `New branch published to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
}
|
||||
toast({
|
||||
title: "Push successful",
|
||||
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`,
|
||||
});
|
||||
|
||||
// Refresh git status after push
|
||||
await refetchGitStatus();
|
||||
@@ -723,6 +683,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
const getFileStatusIcon = (status: string) => {
|
||||
switch (status) {
|
||||
case 'added':
|
||||
@@ -766,11 +728,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
return { status: 'no-remote', text: 'No remote configured', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
// Check if remote branch doesn't exist
|
||||
if (!gitStatus.remoteBranchExists && gitStatus.currentBranch) {
|
||||
return { status: 'not-published', text: 'Branch not published', icon: AlertCircle, color: 'text-yellow-600' };
|
||||
}
|
||||
|
||||
if (gitStatus.ahead > 0 && gitStatus.behind > 0) {
|
||||
return { status: 'diverged', text: `${gitStatus.ahead} ahead, ${gitStatus.behind} behind`, icon: AlertCircle, color: 'text-red-600' };
|
||||
}
|
||||
@@ -1138,11 +1095,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
)}
|
||||
</div>
|
||||
|
||||
{originUrl.trim() && (
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
onClick={handlePull}
|
||||
disabled={isPulling || isPushing || isPushingToNostr || !gitStatus.remoteBranchExists}
|
||||
disabled={isPulling || isPushing || isPushingToNostr}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
@@ -1157,7 +1114,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
|
||||
<Button
|
||||
onClick={handlePush}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || (gitStatus.ahead === 0 && gitStatus.remoteBranchExists)}
|
||||
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
className="flex-1"
|
||||
@@ -1172,7 +1129,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
</div>
|
||||
)}
|
||||
|
||||
{!originUrl.trim() && user && (
|
||||
{gitStatus.remotes.length === 0 && user && (
|
||||
<Button
|
||||
onClick={handlePushToNostr}
|
||||
disabled={isPushingToNostr || isPushing || isPulling}
|
||||
@@ -1185,7 +1142,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
) : (
|
||||
<Zap className="h-4 w-4 mr-2" />
|
||||
)}
|
||||
{isPushingToNostr ? 'Loading...' : 'Push to Nostr'}
|
||||
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
|
||||
</Button>
|
||||
)}
|
||||
|
||||
|
||||
@@ -1,339 +0,0 @@
|
||||
import { useState } from 'react';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Server, Trash2, Check, Plus, X } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
|
||||
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
function MCPConnectionStatus({ server }: { server: MCPServer }) {
|
||||
const status = useMCPServerStatus(server);
|
||||
|
||||
return (
|
||||
<div className="flex items-center gap-1.5 ml-auto mr-2">
|
||||
<div
|
||||
className={cn(
|
||||
'h-2 w-2 rounded-full',
|
||||
status === 'connected' && 'bg-green-500',
|
||||
status === 'offline' && 'bg-red-500',
|
||||
status === 'checking' && 'bg-yellow-500 animate-pulse'
|
||||
)}
|
||||
/>
|
||||
<span className="text-xs text-muted-foreground capitalize">
|
||||
{status}
|
||||
</span>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface HeadersEditorProps {
|
||||
headers: Record<string, string> | undefined;
|
||||
onChange: (headers: Record<string, string> | undefined) => void;
|
||||
}
|
||||
|
||||
function HeadersEditor({ headers, onChange }: HeadersEditorProps) {
|
||||
const { t } = useTranslation();
|
||||
const [newHeaderName, setNewHeaderName] = useState('');
|
||||
const [newHeaderValue, setNewHeaderValue] = useState('');
|
||||
|
||||
const headerEntries = Object.entries(headers || {});
|
||||
|
||||
const handleAddHeader = () => {
|
||||
if (!newHeaderName.trim() || !newHeaderValue.trim()) return;
|
||||
|
||||
const updatedHeaders = {
|
||||
...(headers || {}),
|
||||
[newHeaderName.trim()]: newHeaderValue.trim(),
|
||||
};
|
||||
|
||||
onChange(updatedHeaders);
|
||||
setNewHeaderName('');
|
||||
setNewHeaderValue('');
|
||||
};
|
||||
|
||||
const handleRemoveHeader = (name: string) => {
|
||||
const updatedHeaders = { ...(headers || {}) };
|
||||
delete updatedHeaders[name];
|
||||
|
||||
// If no headers left, set to undefined
|
||||
onChange(Object.keys(updatedHeaders).length > 0 ? updatedHeaders : undefined);
|
||||
};
|
||||
|
||||
const handleUpdateHeader = (oldName: string, newName: string, newValue: string) => {
|
||||
const updatedHeaders = { ...(headers || {}) };
|
||||
delete updatedHeaders[oldName];
|
||||
updatedHeaders[newName] = newValue;
|
||||
onChange(updatedHeaders);
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-3">
|
||||
<Label>{t('mcpServerHeaders')}</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{t('mcpServerHeadersDescription')}
|
||||
</p>
|
||||
|
||||
{/* Existing Headers */}
|
||||
{headerEntries.length > 0 && (
|
||||
<div className="space-y-2">
|
||||
{headerEntries.map(([name, value]) => (
|
||||
<div key={name} className="flex gap-2">
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e) => handleUpdateHeader(name, e.target.value, value)}
|
||||
placeholder="Header name"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={value}
|
||||
onChange={(e) => handleUpdateHeader(name, name, e.target.value)}
|
||||
placeholder="Header value"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="icon"
|
||||
onClick={() => handleRemoveHeader(name)}
|
||||
className="shrink-0"
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Add New Header */}
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={newHeaderName}
|
||||
onChange={(e) => setNewHeaderName(e.target.value)}
|
||||
placeholder="Header name (e.g., Authorization)"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Input
|
||||
value={newHeaderValue}
|
||||
onChange={(e) => setNewHeaderValue(e.target.value)}
|
||||
placeholder="Header value"
|
||||
className="flex-1"
|
||||
/>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="icon"
|
||||
onClick={handleAddHeader}
|
||||
disabled={!newHeaderName.trim() || !newHeaderValue.trim()}
|
||||
className="shrink-0"
|
||||
>
|
||||
<Plus className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
export function MCPServersSection() {
|
||||
const { t } = useTranslation();
|
||||
const { settings, setMCPServer, removeMCPServer } = useAISettings();
|
||||
const { toast } = useToast();
|
||||
const [serverName, setServerName] = useState('');
|
||||
const [serverUrl, setServerUrl] = useState('');
|
||||
const [serverHeaders, setServerHeaders] = useState<Record<string, string> | undefined>(undefined);
|
||||
const [serverType] = useState<'streamable-http'>('streamable-http'); // Only streamable-http is supported
|
||||
|
||||
const mcpServers = settings.mcpServers || {};
|
||||
const serverEntries = Object.entries(mcpServers);
|
||||
|
||||
const handleAddServer = () => {
|
||||
if (!serverName.trim() || !serverUrl.trim()) return;
|
||||
|
||||
if (mcpServers[serverName.trim()]) {
|
||||
toast({
|
||||
title: t('error'),
|
||||
description: t('mcpServerAddFailed'),
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
const newServer: MCPServer = {
|
||||
type: serverType,
|
||||
url: serverUrl.trim(),
|
||||
headers: serverHeaders,
|
||||
};
|
||||
|
||||
setMCPServer(serverName.trim(), newServer);
|
||||
|
||||
toast({
|
||||
title: t('mcpServerAdded'),
|
||||
description: t('mcpServerAddedDescription', { name: serverName.trim() }),
|
||||
});
|
||||
|
||||
setServerName('');
|
||||
setServerUrl('');
|
||||
setServerHeaders(undefined);
|
||||
};
|
||||
|
||||
const handleRemoveServer = (name: string) => {
|
||||
removeMCPServer(name);
|
||||
|
||||
toast({
|
||||
title: t('mcpServerDeleted'),
|
||||
description: t('mcpServerDeletedDescription', { name }),
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="space-y-4">
|
||||
{/* Divider */}
|
||||
<Separator className="my-6" />
|
||||
|
||||
{/* MCP Servers Header */}
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center gap-2">
|
||||
<Server className="h-5 w-5 text-primary" />
|
||||
<h3 className="text-lg font-semibold">{t('mcpServers')}</h3>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('mcpServersDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{/* Configured MCP Servers List */}
|
||||
{serverEntries.length > 0 ? (
|
||||
<div className="space-y-2">
|
||||
{serverEntries.map(([name, server]) => (
|
||||
<Accordion key={name} type="single" collapsible className="w-full">
|
||||
<AccordionItem value={name} className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2 w-full mr-3">
|
||||
<Server size={16} className="text-primary" />
|
||||
<span className="font-medium">{name}</span>
|
||||
<MCPConnectionStatus server={server} />
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-type`}>{t('mcpServerType')}</Label>
|
||||
<Select value={server.type} disabled>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor={`${name}-url`}>{t('mcpServerUrl')}</Label>
|
||||
<Input
|
||||
id={`${name}-url`}
|
||||
value={server.url}
|
||||
onChange={(e) => setMCPServer(name, { ...server, url: e.target.value })}
|
||||
placeholder="https://example.com/mcp"
|
||||
/>
|
||||
</div>
|
||||
<HeadersEditor
|
||||
headers={server.headers}
|
||||
onChange={(headers) => setMCPServer(name, { ...server, headers })}
|
||||
/>
|
||||
<Button
|
||||
variant="destructive"
|
||||
size="sm"
|
||||
onClick={() => handleRemoveServer(name)}
|
||||
>
|
||||
<Trash2 className="h-4 w-4 mr-2" />
|
||||
{t('delete')}
|
||||
</Button>
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
))}
|
||||
</div>
|
||||
) : (
|
||||
<Alert>
|
||||
<AlertDescription className="text-sm">
|
||||
{t('noMcpServersConfigured')}
|
||||
</AlertDescription>
|
||||
</Alert>
|
||||
)}
|
||||
|
||||
{/* Add New MCP Server */}
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
<AccordionItem value="add-server" className="border rounded-lg">
|
||||
<AccordionTrigger className="px-4 py-3 hover:no-underline">
|
||||
<div className="flex items-center gap-2">
|
||||
<Plus className="h-4 w-4" />
|
||||
<span className="text-sm font-medium">{t('addMcpServer')}</span>
|
||||
</div>
|
||||
</AccordionTrigger>
|
||||
<AccordionContent className="px-4 pb-4">
|
||||
<div className="space-y-3">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('mcpServerDescription')}
|
||||
</p>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-name">{t('mcpServerName')}</Label>
|
||||
<Input
|
||||
id="new-server-name"
|
||||
placeholder="e.g., my-mcp-server"
|
||||
value={serverName}
|
||||
onChange={(e) => setServerName(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-type">{t('mcpServerType')}</Label>
|
||||
<Select value={serverType} disabled>
|
||||
<SelectTrigger>
|
||||
<SelectValue />
|
||||
</SelectTrigger>
|
||||
<SelectContent>
|
||||
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Only Streamable HTTP transport is currently supported
|
||||
</p>
|
||||
</div>
|
||||
<div className="grid gap-2">
|
||||
<Label htmlFor="new-server-url">{t('mcpServerUrl')}</Label>
|
||||
<Input
|
||||
id="new-server-url"
|
||||
placeholder="https://example.com/mcp"
|
||||
value={serverUrl}
|
||||
onChange={(e) => setServerUrl(e.target.value)}
|
||||
/>
|
||||
</div>
|
||||
<HeadersEditor
|
||||
headers={serverHeaders}
|
||||
onChange={setServerHeaders}
|
||||
/>
|
||||
<Button
|
||||
onClick={handleAddServer}
|
||||
disabled={!serverName.trim() || !serverUrl.trim() || !!mcpServers[serverName.trim()]}
|
||||
className="gap-2 w-full"
|
||||
>
|
||||
<Check className="h-4 w-4" />
|
||||
{t('add')}
|
||||
</Button>
|
||||
{mcpServers[serverName.trim()] && (
|
||||
<p className="text-sm text-destructive">
|
||||
A server with this name already exists
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</AccordionContent>
|
||||
</AccordionItem>
|
||||
</Accordion>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -42,15 +42,14 @@ describe('ModelSelector', () => {
|
||||
vi.clearAllMocks();
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
mockUseProviderModels.mockReturnValue({
|
||||
@@ -88,8 +87,6 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
@@ -111,13 +108,11 @@ describe('ModelSelector', () => {
|
||||
// Recently used section should NOT be visible
|
||||
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
|
||||
|
||||
// provider1 should still be visible (models appear in both sections now)
|
||||
expect(screen.getByText('provider1')).toBeInTheDocument();
|
||||
expect(screen.getByText('model1')).toBeInTheDocument();
|
||||
expect(screen.getByText('model2')).toBeInTheDocument();
|
||||
// provider1 should be hidden since all its models are in recently used
|
||||
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
|
||||
|
||||
// provider2 should still show with model3
|
||||
expect(screen.getByText('model3')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
|
||||
@@ -145,8 +140,6 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
@@ -162,17 +155,11 @@ describe('ModelSelector', () => {
|
||||
|
||||
// Wait for the dropdown to open
|
||||
await waitFor(() => {
|
||||
// provider1 appears in both recently used and available sections
|
||||
const provider1Elements = screen.queryAllByText('provider1');
|
||||
expect(provider1Elements.length).toBeGreaterThan(0);
|
||||
expect(screen.getByText('provider1')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Recently used section SHOULD be visible
|
||||
expect(screen.getByText('Recently Used')).toBeInTheDocument();
|
||||
|
||||
// provider1 should appear in both sections (recently used and available)
|
||||
const provider1Elements = screen.queryAllByText('provider1');
|
||||
expect(provider1Elements.length).toBeGreaterThanOrEqual(1);
|
||||
});
|
||||
|
||||
it('shows recently used section when 5 or more models are available', async () => {
|
||||
@@ -202,8 +189,6 @@ describe('ModelSelector', () => {
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
@@ -225,22 +210,13 @@ describe('ModelSelector', () => {
|
||||
// Recently used section SHOULD be visible
|
||||
expect(screen.getByText('Recently Used')).toBeInTheDocument();
|
||||
|
||||
// provider1 should still be visible (models appear in both sections now)
|
||||
// Use queryAllByText since provider1 appears as a heading in both sections
|
||||
const provider1Elements = screen.queryAllByText('provider1');
|
||||
expect(provider1Elements.length).toBeGreaterThanOrEqual(1);
|
||||
|
||||
// Models should be visible (display text is just the model name, not full ID)
|
||||
// model1 and model2 appear in both recently used and available sections
|
||||
const model1Elements = screen.queryAllByText('model1');
|
||||
expect(model1Elements.length).toBeGreaterThanOrEqual(1);
|
||||
const model2Elements = screen.queryAllByText('model2');
|
||||
expect(model2Elements.length).toBeGreaterThanOrEqual(1);
|
||||
// provider1 should be hidden since all its models are in recently used
|
||||
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
|
||||
|
||||
// provider2 and provider3 should still show (only in available section)
|
||||
expect(screen.getByText('model3')).toBeInTheDocument();
|
||||
expect(screen.getByText('model4')).toBeInTheDocument();
|
||||
expect(screen.getByText('model5')).toBeInTheDocument();
|
||||
// provider2 and provider3 should still show
|
||||
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
|
||||
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('hides recently used section when no recently used models exist', async () => {
|
||||
@@ -257,15 +233,13 @@ describe('ModelSelector', () => {
|
||||
});
|
||||
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
|
||||
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
|
||||
addRecentlyUsedModel: mockAddRecentlyUsedModel,
|
||||
isConfigured: true,
|
||||
updateSettings: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
|
||||
});
|
||||
|
||||
|
||||
@@ -1,11 +1,10 @@
|
||||
import { useState, useMemo, useEffect, memo } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Decimal } from 'decimal.js';
|
||||
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { Dialog, DialogContent, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
|
||||
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
|
||||
@@ -15,72 +14,6 @@ import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { ModelPricing } from '@/components/ModelPricing';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
// Type for model (matches ProviderModel from useProviderModels)
|
||||
type ModelType = {
|
||||
id: string;
|
||||
name?: string;
|
||||
provider: string;
|
||||
fullId: string;
|
||||
description?: string;
|
||||
contextLength?: number;
|
||||
pricing?: {
|
||||
prompt: Decimal;
|
||||
completion: Decimal;
|
||||
};
|
||||
};
|
||||
|
||||
// Interface for grouped models by provider
|
||||
interface ModelGroup {
|
||||
provider: string;
|
||||
models: ModelType[];
|
||||
}
|
||||
|
||||
// Parse model ID into components (provider/company/model or provider/model)
|
||||
function parseModelId(fullId: string) {
|
||||
const parts = fullId.split('/');
|
||||
return {
|
||||
provider: parts[0] || '',
|
||||
company: parts.length >= 3 ? parts[1] : null,
|
||||
modelName: parts.length >= 3 ? parts.slice(2).join('/') : parts[1] || '',
|
||||
};
|
||||
}
|
||||
|
||||
// Group models by provider and sort
|
||||
function groupModelsByProvider(models: ModelType[], excludeIds: Set<string>): ModelGroup[] {
|
||||
const groups: Record<string, ModelType[]> = {};
|
||||
|
||||
// Group by provider
|
||||
models.forEach(model => {
|
||||
if (!excludeIds.has(model.fullId)) {
|
||||
const { provider } = parseModelId(model.fullId);
|
||||
if (!groups[provider]) groups[provider] = [];
|
||||
groups[provider].push(model);
|
||||
}
|
||||
});
|
||||
|
||||
// Sort models within each group and convert to array
|
||||
return Object.entries(groups)
|
||||
.map(([provider, models]) => ({
|
||||
provider,
|
||||
models: models.sort((a, b) => {
|
||||
const aParsed = parseModelId(a.fullId);
|
||||
const bParsed = parseModelId(b.fullId);
|
||||
// Sort by company, then model name
|
||||
if (aParsed.company && bParsed.company) {
|
||||
const diff = aParsed.company.localeCompare(bParsed.company);
|
||||
if (diff !== 0) return diff;
|
||||
}
|
||||
return aParsed.modelName.localeCompare(bParsed.modelName);
|
||||
}),
|
||||
}))
|
||||
.sort((a, b) => {
|
||||
// Shakespeare first, then alphabetical
|
||||
if (a.provider === 'shakespeare') return -1;
|
||||
if (b.provider === 'shakespeare') return 1;
|
||||
return a.provider.localeCompare(b.provider);
|
||||
});
|
||||
}
|
||||
|
||||
interface ModelSelectorProps {
|
||||
value: string;
|
||||
onChange: (value: string) => void;
|
||||
@@ -91,46 +24,6 @@ interface ModelSelectorProps {
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
// Render a model item in the list
|
||||
const ModelItem = memo(({ model, currentValue, onSelect, valuePrefix = '' }: {
|
||||
model: ModelType;
|
||||
currentValue: string;
|
||||
onSelect: (value: string) => void;
|
||||
valuePrefix?: string;
|
||||
}) => {
|
||||
const parsed = parseModelId(model.fullId);
|
||||
const displayText = parsed.company
|
||||
? `${parsed.company}/${parsed.modelName}`
|
||||
: parsed.modelName;
|
||||
|
||||
// Use prefix to make value unique (prevents both recently used and available from highlighting together)
|
||||
const uniqueValue = valuePrefix ? `${valuePrefix}-${model.fullId}` : model.fullId;
|
||||
|
||||
return (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={uniqueValue}
|
||||
keywords={[model.fullId]}
|
||||
onSelect={() => onSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
title={model.fullId}
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4 shrink-0",
|
||||
currentValue === model.fullId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="flex-1 min-w-0 truncate">
|
||||
{displayText}
|
||||
</span>
|
||||
{model.pricing && (
|
||||
<ModelPricing pricing={model.pricing} className="ml-2 shrink-0" />
|
||||
)}
|
||||
</CommandItem>
|
||||
);
|
||||
});
|
||||
|
||||
export const ModelSelector = memo(function ModelSelector({
|
||||
value,
|
||||
onChange,
|
||||
@@ -159,11 +52,25 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
|
||||
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
|
||||
|
||||
// Group models by provider (don't exclude recently used - they should appear in both sections)
|
||||
const modelGroups = useMemo(
|
||||
() => groupModelsByProvider(models, new Set()),
|
||||
[models]
|
||||
);
|
||||
// Create a Set of recently used model IDs for efficient lookup
|
||||
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
|
||||
|
||||
// Group models by provider, excluding models that are in the recently used section
|
||||
const modelsByProvider = useMemo(() => {
|
||||
const groups: Record<string, typeof models> = {};
|
||||
for (const model of models) {
|
||||
// Skip models that are already shown in recently used
|
||||
if (recentlyUsedSet.has(model.fullId)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (!groups[model.provider]) {
|
||||
groups[model.provider] = [];
|
||||
}
|
||||
groups[model.provider].push(model);
|
||||
}
|
||||
return groups;
|
||||
}, [models, recentlyUsedSet]);
|
||||
|
||||
// Determine if we should show the "Recently Used" section
|
||||
const shouldShowRecentlyUsed = useMemo(() => {
|
||||
@@ -188,15 +95,6 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
return !allRecentlyUsedAreAvailable;
|
||||
}, [recentlyUsedModels, models]);
|
||||
|
||||
// Group recently used models (same structure as available models)
|
||||
const recentlyUsedGroups = useMemo(() => {
|
||||
if (!shouldShowRecentlyUsed) return [];
|
||||
const recentModels = recentlyUsedModels
|
||||
.map(id => models.find(m => m.fullId === id))
|
||||
.filter((m): m is ModelType => m !== undefined);
|
||||
return groupModelsByProvider(recentModels, new Set());
|
||||
}, [recentlyUsedModels, models, shouldShowRecentlyUsed]);
|
||||
|
||||
// Check if the current model is free
|
||||
const isCurrentModelFree = useMemo(() => {
|
||||
if (!value) return false;
|
||||
@@ -373,8 +271,8 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
)}
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Popover open={open} onOpenChange={setOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
role="combobox"
|
||||
@@ -389,28 +287,13 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
</span>
|
||||
<ChevronDown className="size-3 shrink-0 opacity-50" />
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent
|
||||
className={cn(
|
||||
"p-0 max-w-[90vw] sm:max-w-lg md:max-w-2xl",
|
||||
"max-h-[85vh] overflow-hidden flex flex-col"
|
||||
)}
|
||||
onOpenAutoFocus={(e) => e.preventDefault()}
|
||||
>
|
||||
<Command
|
||||
className="flex flex-col h-full overflow-hidden"
|
||||
filter={(value, search, keywords) => {
|
||||
// Substring search: match if search appears anywhere in value or keywords
|
||||
const s = search.toLowerCase();
|
||||
if (value.toLowerCase().includes(s)) return 1;
|
||||
if (keywords?.some(k => typeof k === 'string' && k.toLowerCase().includes(s))) return 1;
|
||||
return 0;
|
||||
}}
|
||||
>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="p-0 w-80" align="end">
|
||||
<Command>
|
||||
{(isConfigured && models.length >= 5) && (
|
||||
<CommandInput placeholder={t('searchModels')} className="h-9" autoFocus={false} />
|
||||
<CommandInput placeholder={t('searchModels')} className="h-9" />
|
||||
)}
|
||||
<CommandList className="flex-1 overflow-y-auto overflow-x-hidden">
|
||||
<CommandList>
|
||||
<CommandEmpty>
|
||||
<div className="py-6 text-center text-sm text-muted-foreground">
|
||||
<p>{t('noModelsFound')}</p>
|
||||
@@ -418,31 +301,34 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
</div>
|
||||
</CommandEmpty>
|
||||
|
||||
{/* Recently Used section */}
|
||||
{shouldShowRecentlyUsed && (
|
||||
<>
|
||||
<CommandGroup heading={t('recentlyUsed')} />
|
||||
{recentlyUsedGroups.map((group) => (
|
||||
<CommandGroup key={`recent-${group.provider}`} heading={group.provider}>
|
||||
{group.models.map((model) => (
|
||||
<ModelItem
|
||||
key={model.fullId}
|
||||
model={model}
|
||||
currentValue={value}
|
||||
onSelect={handleSelect}
|
||||
valuePrefix="recent"
|
||||
<CommandGroup heading={t('recentlyUsed')}>
|
||||
{recentlyUsedModels.map((modelId) => {
|
||||
const modelData = models.find(m => m.fullId === modelId);
|
||||
return (
|
||||
<CommandItem
|
||||
key={modelId}
|
||||
value={modelId}
|
||||
onSelect={() => handleSelect(modelId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === modelId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
))}
|
||||
{modelGroups.length > 0 && <CommandSeparator />}
|
||||
</>
|
||||
<span className="truncate flex-1">{modelId}</span>
|
||||
{modelData?.pricing && (
|
||||
<ModelPricing pricing={modelData.pricing} className="ml-2" />
|
||||
)}
|
||||
</CommandItem>
|
||||
);
|
||||
})}
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* Available Models section */}
|
||||
{!isLoading && modelGroups.length > 0 && (
|
||||
<CommandGroup heading={t('availableModels')} />
|
||||
)}
|
||||
{shouldShowRecentlyUsed && <CommandSeparator />}
|
||||
|
||||
{/* Loading state */}
|
||||
{isLoading && (
|
||||
@@ -480,25 +366,32 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
</CommandGroup>
|
||||
)}
|
||||
|
||||
{/* No models available state */}
|
||||
{!isLoading && !error && !shouldShowRecentlyUsed && modelGroups.length === 0 && (
|
||||
<div className="py-12 text-center text-sm text-muted-foreground">
|
||||
<p>{t('noModelsFound')}</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Provider models */}
|
||||
{!isLoading && modelGroups.map((group) => (
|
||||
<CommandGroup key={group.provider} heading={group.provider}>
|
||||
{group.models.map((model) => (
|
||||
<ModelItem
|
||||
key={model.fullId}
|
||||
model={model}
|
||||
currentValue={value}
|
||||
onSelect={handleSelect}
|
||||
/>
|
||||
))}
|
||||
</CommandGroup>
|
||||
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
|
||||
<div key={provider}>
|
||||
<CommandSeparator />
|
||||
<CommandGroup heading={provider}>
|
||||
{providerModels.map((model) => (
|
||||
<CommandItem
|
||||
key={model.fullId}
|
||||
value={model.fullId}
|
||||
onSelect={() => handleSelect(model.fullId)}
|
||||
className="cursor-pointer"
|
||||
>
|
||||
<Check
|
||||
className={cn(
|
||||
"mr-2 h-4 w-4",
|
||||
value === model.fullId ? "opacity-100" : "opacity-0"
|
||||
)}
|
||||
/>
|
||||
<span className="truncate flex-1">{model.fullId}</span>
|
||||
{model.pricing && (
|
||||
<ModelPricing pricing={model.pricing} className="ml-2" />
|
||||
)}
|
||||
</CommandItem>
|
||||
))}
|
||||
</CommandGroup>
|
||||
</div>
|
||||
))}
|
||||
|
||||
{/* Custom model option and manage providers - moved to bottom */}
|
||||
@@ -525,8 +418,8 @@ export const ModelSelector = memo(function ModelSelector({
|
||||
</CommandGroup>
|
||||
</CommandList>
|
||||
</Command>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
|
||||
@@ -33,11 +33,9 @@ import {
|
||||
Loader2,
|
||||
Trash2,
|
||||
Save,
|
||||
DollarSign,
|
||||
} from 'lucide-react';
|
||||
import JSZip from 'jszip';
|
||||
import { Separator } from './ui/separator';
|
||||
import { DotAI } from '@/lib/DotAI';
|
||||
|
||||
interface ProjectDetailsDialogProps {
|
||||
project: Project;
|
||||
@@ -51,7 +49,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
const [isDeleting, setIsDeleting] = useState(false);
|
||||
const [isRenaming, setIsRenaming] = useState(false);
|
||||
const [newProjectName, setNewProjectName] = useState(project.id);
|
||||
const [totalCost, setTotalCost] = useState<number | null>(null);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
@@ -65,24 +62,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
setIsRenaming(false);
|
||||
}, [project.id]);
|
||||
|
||||
// Load total project cost
|
||||
useEffect(() => {
|
||||
const loadCost = async () => {
|
||||
try {
|
||||
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
|
||||
const cost = await dotAI.readCost();
|
||||
setTotalCost(cost);
|
||||
} catch (error) {
|
||||
console.warn('Failed to load project cost:', error);
|
||||
setTotalCost(null);
|
||||
}
|
||||
};
|
||||
|
||||
if (open) {
|
||||
loadCost();
|
||||
}
|
||||
}, [fs, projectsPath, project.id, open]);
|
||||
|
||||
const formatDistanceToNow = (date: Date) => {
|
||||
const now = new Date();
|
||||
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
|
||||
@@ -247,15 +226,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
|
||||
<span>{formatDistanceToNow(project.lastModified)}</span>
|
||||
</div>
|
||||
|
||||
{/* Total Cost */}
|
||||
{totalCost !== null && totalCost > 0 && (
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<DollarSign className="h-4 w-4 text-muted-foreground" />
|
||||
<span className="text-muted-foreground">Total Cost:</span>
|
||||
<span className="font-mono">${totalCost.toFixed(6)}</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project Name */}
|
||||
<div className="space-y-2">
|
||||
<Label htmlFor="project-name">Project Name</Label>
|
||||
|
||||
+24
-68
@@ -11,7 +11,6 @@ import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { useState } from 'react';
|
||||
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from '@/lib/errors/EmptyMessageError';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
|
||||
export interface QuillyProps {
|
||||
error: Error;
|
||||
@@ -31,20 +30,23 @@ interface ErrorBody {
|
||||
}>;
|
||||
}
|
||||
|
||||
interface QuillyContentProps {
|
||||
error: Error;
|
||||
onDismiss: () => void;
|
||||
onNewChat: () => void;
|
||||
onOpenModelSelector: () => void;
|
||||
onTryAgain?: () => void;
|
||||
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
|
||||
provider: AIProvider | undefined;
|
||||
}
|
||||
|
||||
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const navigate = useNavigate();
|
||||
const { settings } = useAISettings();
|
||||
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
|
||||
// Handle empty provider model gracefully
|
||||
let provider;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
const credits = useAICredits(provider || { id: '', name: '', apiKey: '', nostr: false });
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
|
||||
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody => {
|
||||
// Handle Project Preview Console Errors
|
||||
if (error instanceof ProjectPreviewConsoleError) {
|
||||
return {
|
||||
@@ -67,7 +69,7 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
onClick: onOpenModelSelector,
|
||||
}],
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
if (error instanceof EmptyMessageError) {
|
||||
return {
|
||||
@@ -99,12 +101,13 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
};
|
||||
|
||||
case error.code === 'insufficient_quota': {
|
||||
// Only show credits dialog if we have a provider with nostr enabled
|
||||
if (provider?.nostr) {
|
||||
if (credits.data) {
|
||||
return {
|
||||
message: 'Your account is low on credits. Please add credits to keep creating.',
|
||||
showCreditsButton: true,
|
||||
actions: [],
|
||||
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
|
||||
actions: [{
|
||||
label: 'Add credits',
|
||||
onClick: () => setShowCreditsDialog(true),
|
||||
}],
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
@@ -201,7 +204,7 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
};
|
||||
};
|
||||
|
||||
const { message, actions = [], showCreditsButton } = renderBody(error);
|
||||
const { message, actions = [] } = renderBody(error);
|
||||
|
||||
return (
|
||||
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
|
||||
@@ -214,12 +217,6 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
</h4>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{message}
|
||||
{showCreditsButton && provider && (
|
||||
<>
|
||||
{' '}
|
||||
<QuillyCreditsButton provider={provider} />
|
||||
</>
|
||||
)}
|
||||
{actions.length > 0 && (
|
||||
<>
|
||||
{' '}
|
||||
@@ -245,53 +242,12 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
interface QuillyCreditsButtonProps {
|
||||
provider: AIProvider;
|
||||
}
|
||||
|
||||
function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
const credits = useAICredits(provider);
|
||||
|
||||
return (
|
||||
<>
|
||||
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
|
||||
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
|
||||
</button>
|
||||
<CreditsDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={setShowCreditsDialog}
|
||||
provider={provider}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
|
||||
const { settings } = useAISettings();
|
||||
|
||||
// Handle empty provider model gracefully
|
||||
let provider: AIProvider | undefined;
|
||||
try {
|
||||
provider = parseProviderModel(providerModel, settings.providers).provider;
|
||||
} catch {
|
||||
// If no valid provider model, use a default or undefined
|
||||
provider = undefined;
|
||||
}
|
||||
|
||||
return (
|
||||
<QuillyContent
|
||||
error={error}
|
||||
onDismiss={onDismiss}
|
||||
onNewChat={onNewChat}
|
||||
onOpenModelSelector={onOpenModelSelector}
|
||||
onTryAgain={onTryAgain}
|
||||
onRequestConsoleErrorHelp={onRequestConsoleErrorHelp}
|
||||
provider={provider}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,195 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { LoginArea } from '@/components/auth/LoginArea';
|
||||
import { RefreshCw, MessageSquare, Star, Heart } from 'lucide-react';
|
||||
|
||||
/**
|
||||
* Demo component showing real-time updates for showcase ratings and comments
|
||||
* This demonstrates the optimistic updates and automatic cache invalidation
|
||||
*/
|
||||
export function RealTimeDemo() {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: publishEvent, isPending } = useNostrPublish();
|
||||
const { toast } = useToast();
|
||||
const [demoCounter, setDemoCounter] = useState(0);
|
||||
|
||||
const handleDemoAction = (actionType: 'comment' | 'rating' | 'moderation') => {
|
||||
if (!user) {
|
||||
toast({
|
||||
title: 'Login Required',
|
||||
description: 'Please log in to test real-time updates',
|
||||
variant: 'destructive',
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
setDemoCounter(prev => prev + 1);
|
||||
|
||||
switch (actionType) {
|
||||
case 'comment': {
|
||||
// Simulate posting a comment (kind 1111)
|
||||
publishEvent({
|
||||
kind: 1111,
|
||||
content: `Demo comment #${demoCounter + 1} - This demonstrates real-time comment updates!`,
|
||||
tags: [
|
||||
['E', 'demo-event-id'],
|
||||
['K', '1'],
|
||||
['P', 'demo-author-pubkey'],
|
||||
],
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'rating': {
|
||||
// Simulate posting a rating (kind 7)
|
||||
const rating = Math.floor(Math.random() * 5) + 1;
|
||||
publishEvent({
|
||||
kind: 7,
|
||||
content: rating.toString(),
|
||||
tags: [
|
||||
['e', 'demo-app-event-id'],
|
||||
['p', 'demo-app-author-pubkey'],
|
||||
],
|
||||
});
|
||||
break;
|
||||
}
|
||||
|
||||
case 'moderation': {
|
||||
// Simulate moderation action (kind 30267 list update)
|
||||
publishEvent({
|
||||
kind: 30267,
|
||||
content: 'Demo moderation list update',
|
||||
tags: [
|
||||
['d', 'demo-featured-apps'],
|
||||
['title', 'Demo Featured Apps'],
|
||||
['a', `31733:demo-pubkey:demo-app-${demoCounter + 1}`],
|
||||
],
|
||||
});
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
toast({
|
||||
title: 'Demo Action Triggered!',
|
||||
description: `${actionType} action will update in real-time across all components`,
|
||||
});
|
||||
};
|
||||
|
||||
if (!user) {
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<RefreshCw className="h-5 w-5" />
|
||||
Real-Time Updates Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
This demo shows how ratings and comments update in real-time without page refreshes.
|
||||
Please log in to test the functionality.
|
||||
</p>
|
||||
<LoginArea />
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<RefreshCw className="h-5 w-5" />
|
||||
Real-Time Updates Demo
|
||||
</CardTitle>
|
||||
</CardHeader>
|
||||
<CardContent className="space-y-6">
|
||||
<div className="space-y-4">
|
||||
<p className="text-muted-foreground">
|
||||
Test real-time updates by triggering demo actions. These will demonstrate:
|
||||
</p>
|
||||
|
||||
<div className="grid gap-4">
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline">
|
||||
<MessageSquare className="h-3 w-3 mr-1" />
|
||||
Comments
|
||||
</Badge>
|
||||
<span className="text-sm">Optimistic updates + automatic refresh</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline">
|
||||
<Star className="h-3 w-3 mr-1" />
|
||||
Ratings
|
||||
</Badge>
|
||||
<span className="text-sm">Instant UI updates + cache invalidation</span>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-3">
|
||||
<Badge variant="outline">
|
||||
<Heart className="h-3 w-3 mr-1" />
|
||||
Moderation
|
||||
</Badge>
|
||||
<span className="text-sm">Real-time status changes</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border-t pt-6">
|
||||
<h4 className="font-medium mb-4">Test Actions</h4>
|
||||
<div className="flex flex-wrap gap-3">
|
||||
<Button
|
||||
onClick={() => handleDemoAction('comment')}
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<MessageSquare className="h-4 w-4 mr-2" />
|
||||
Demo Comment
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => handleDemoAction('rating')}
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<Star className="h-4 w-4 mr-2" />
|
||||
Demo Rating
|
||||
</Button>
|
||||
|
||||
<Button
|
||||
onClick={() => handleDemoAction('moderation')}
|
||||
disabled={isPending}
|
||||
variant="outline"
|
||||
size="sm"
|
||||
>
|
||||
<Heart className="h-4 w-4 mr-2" />
|
||||
Demo Moderation
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted/50 p-4 rounded-lg">
|
||||
<h5 className="font-medium text-sm mb-2">How it works:</h5>
|
||||
<ul className="text-sm text-muted-foreground space-y-1">
|
||||
<li>• <strong>Optimistic Updates:</strong> UI updates immediately before server confirmation</li>
|
||||
<li>• <strong>Cache Invalidation:</strong> Related queries refresh automatically after publishing</li>
|
||||
<li>• <strong>Error Handling:</strong> Failed actions revert optimistic changes</li>
|
||||
<li>• <strong>Real-time Sync:</strong> Background polling keeps data fresh (10-30s intervals)</li>
|
||||
</ul>
|
||||
</div>
|
||||
|
||||
<div className="text-xs text-muted-foreground">
|
||||
Demo counter: {demoCounter} actions triggered
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -39,11 +39,10 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -76,11 +75,10 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -114,11 +112,10 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
@@ -155,11 +152,10 @@ describe('SentryProvider', () => {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
};
|
||||
|
||||
render(
|
||||
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
|
||||
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
|
||||
<SentryProvider>
|
||||
<div>Test</div>
|
||||
</SentryProvider>
|
||||
|
||||
@@ -1,12 +1,12 @@
|
||||
import { ReactNode, useEffect, useRef } from 'react';
|
||||
import { ReactNode, useMemo, useEffect } from 'react';
|
||||
import { SessionManagerContext } from '@/contexts/SessionManagerContext';
|
||||
import { SessionManager } from '@/lib/SessionManager';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
|
||||
interface SessionManagerProviderProps {
|
||||
children: ReactNode;
|
||||
@@ -17,80 +17,30 @@ interface SessionManagerProviderProps {
|
||||
*/
|
||||
export function SessionManagerProvider({ children }: SessionManagerProviderProps) {
|
||||
const { fs } = useFS();
|
||||
const { projectsPath, pluginsPath } = useFSPaths();
|
||||
const { settings } = useAISettings();
|
||||
const { models } = useProviderModels();
|
||||
const { user, metadata } = useCurrentUser();
|
||||
const { config, defaultConfig } = useAppContext();
|
||||
const { nostr } = useNostr();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Create SessionManager instance only once
|
||||
const sessionManager = useRef<SessionManager | undefined>(undefined);
|
||||
|
||||
// Use refs so SessionManager always has the latest data
|
||||
const configRef = useRef(config);
|
||||
const defaultConfigRef = useRef(defaultConfig);
|
||||
const settingsRef = useRef(settings);
|
||||
const modelsRef = useRef(models);
|
||||
const userRef = useRef(user);
|
||||
const metadataRef = useRef(metadata);
|
||||
|
||||
// Update refs when values change
|
||||
useEffect(() => {
|
||||
configRef.current = config;
|
||||
}, [config]);
|
||||
|
||||
useEffect(() => {
|
||||
defaultConfigRef.current = defaultConfig;
|
||||
}, [defaultConfig]);
|
||||
|
||||
useEffect(() => {
|
||||
settingsRef.current = settings;
|
||||
}, [settings]);
|
||||
|
||||
useEffect(() => {
|
||||
modelsRef.current = models;
|
||||
}, [models]);
|
||||
|
||||
useEffect(() => {
|
||||
userRef.current = user;
|
||||
}, [user]);
|
||||
|
||||
useEffect(() => {
|
||||
metadataRef.current = metadata;
|
||||
}, [metadata]);
|
||||
|
||||
// Initialize SessionManager only once
|
||||
if (!sessionManager.current) {
|
||||
// Callbacks access refs to get latest values
|
||||
const getProviderModels = () => modelsRef.current;
|
||||
const getCurrentUser = () => ({ user: userRef.current, metadata: metadataRef.current });
|
||||
const getConfig = () => configRef.current;
|
||||
const getDefaultConfig = () => defaultConfigRef.current;
|
||||
const getSettings = () => settingsRef.current;
|
||||
|
||||
sessionManager.current = new SessionManager(
|
||||
fs,
|
||||
nostr,
|
||||
getSettings,
|
||||
getConfig,
|
||||
getDefaultConfig,
|
||||
getProviderModels,
|
||||
getCurrentUser,
|
||||
);
|
||||
}
|
||||
const sessionManager = useMemo(() => {
|
||||
const getProviderModels = () => models;
|
||||
const getCurrentUser = () => ({ user, metadata });
|
||||
return new SessionManager(fs, settings, getProviderModels, getCurrentUser, config.corsProxy, projectsPath, pluginsPath);
|
||||
}, [fs, settings, models, user, metadata, config.corsProxy, projectsPath, pluginsPath]);
|
||||
|
||||
// Cleanup on unmount
|
||||
useEffect(() => {
|
||||
return () => {
|
||||
// Fire and forget cleanup - we don't need to await in useEffect cleanup
|
||||
sessionManager.current?.cleanup().catch(error => {
|
||||
sessionManager.cleanup().catch(error => {
|
||||
console.warn('Failed to cleanup session manager:', error);
|
||||
});
|
||||
};
|
||||
}, []);
|
||||
}, [sessionManager]);
|
||||
|
||||
return (
|
||||
<SessionManagerContext.Provider value={sessionManager.current}>
|
||||
<SessionManagerContext.Provider value={sessionManager}>
|
||||
{children}
|
||||
</SessionManagerContext.Provider>
|
||||
);
|
||||
|
||||
@@ -14,7 +14,6 @@ import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { useAIChat } from '@/hooks/useAIChat';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { useSessionManager } from '@/hooks/useSessionManager';
|
||||
import { useMCPTools } from '@/hooks/useMCPTools';
|
||||
import { AIMessageItem } from '@/components/AIMessageItem';
|
||||
import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool';
|
||||
import { TextEditorWriteTool } from '@/lib/tools/TextEditorWriteTool';
|
||||
@@ -36,16 +35,15 @@ import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { TypecheckTool } from '@/lib/tools/TypecheckTool';
|
||||
import { ReadConsoleMessagesTool } from '@/lib/tools/ReadConsoleMessagesTool';
|
||||
import { SkillTool } from '@/lib/tools/SkillTool';
|
||||
import { createMCPTools } from '@/lib/tools/MCPTool';
|
||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||
import { Tool } from '@/lib/tools/Tool';
|
||||
import OpenAI from 'openai';
|
||||
import { saveFileToTmp } from '@/lib/fileUtils';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { Quilly } from '@/components/Quilly';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { ChatInput } from '@/components/Shakespeare/ChatInput';
|
||||
import { buildMessageContent } from '@/lib/buildMessageContent';
|
||||
|
||||
// Clean interfaces now handled by proper hooks
|
||||
|
||||
@@ -150,12 +148,8 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
sessionManager.emit('fileChanged', projectId, filePath);
|
||||
}, [sessionManager, projectId]);
|
||||
|
||||
// Fetch MCP tools
|
||||
const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools();
|
||||
|
||||
// Separate built-in tools from MCP tools for clarity
|
||||
const builtInTools = useMemo(() => {
|
||||
const tools: Record<string, Tool<unknown>> = {
|
||||
const customTools = useMemo(() => {
|
||||
const baseTools = {
|
||||
git_commit: new GitCommitTool(fs, cwd, git),
|
||||
text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }),
|
||||
text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }),
|
||||
@@ -172,42 +166,30 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
nostr_read_nips_index: new NostrReadNipsIndexTool(),
|
||||
nostr_generate_kind: new NostrGenerateKindTool(),
|
||||
nostr_publish_events: new NostrPublishEventsTool(),
|
||||
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
|
||||
shell: new ShellTool(fs, cwd, git, projectsPath, user?.signer),
|
||||
read_console_messages: new ReadConsoleMessagesTool(),
|
||||
skill: new SkillTool(fs, pluginsPath),
|
||||
};
|
||||
|
||||
// Add deploy tool only if user is logged in
|
||||
if (user && user.signer) {
|
||||
tools.deploy_project = new DeployProjectTool(fs, cwd, user.signer, projectId);
|
||||
return {
|
||||
...baseTools,
|
||||
deploy_project: new DeployProjectTool(fs, cwd, user.signer, projectId),
|
||||
};
|
||||
}
|
||||
|
||||
return tools;
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
|
||||
return baseTools;
|
||||
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
|
||||
|
||||
// MCP tools wrapped for execution
|
||||
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||
|
||||
// Combined tool executors (for SessionManager to call)
|
||||
const customTools = useMemo(() => ({
|
||||
...builtInTools,
|
||||
...mcpToolWrappers,
|
||||
}), [builtInTools, mcpToolWrappers]);
|
||||
|
||||
// Convert tools to OpenAI format for AI provider
|
||||
// Convert tools to OpenAI format
|
||||
const tools = useMemo(() => {
|
||||
const result: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||
|
||||
// Convert built-in tools to OpenAI format
|
||||
for (const [name, tool] of Object.entries(builtInTools)) {
|
||||
for (const [name, tool] of Object.entries(customTools)) {
|
||||
result[name] = toolToOpenAI(name, tool as Tool<unknown>);
|
||||
}
|
||||
|
||||
// Add MCP tools (already in OpenAI format from useMCPTools)
|
||||
Object.assign(result, mcpOpenAITools);
|
||||
|
||||
return result;
|
||||
}, [builtInTools, mcpOpenAITools]);
|
||||
}, [customTools]);
|
||||
|
||||
// Keep-alive functionality to prevent tab throttling during AI processing
|
||||
const { updateMetadata } = useKeepAlive({
|
||||
@@ -456,18 +438,45 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
|
||||
const modelToUse = providerModel.trim();
|
||||
|
||||
// Build message content from input and attached files
|
||||
// Images are converted to base64-encoded data URLs
|
||||
const messageContent = await buildMessageContent(
|
||||
input,
|
||||
attachedFiles,
|
||||
fs,
|
||||
tmpPath
|
||||
);
|
||||
// Build message content as text parts
|
||||
const contentParts: Array<OpenAI.Chat.Completions.ChatCompletionContentPartText> = [];
|
||||
|
||||
// Add user input as text part if present
|
||||
if (input.trim()) {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: input.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, tmpPath);
|
||||
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
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Add model to recently used when sending a message
|
||||
addRecentlyUsedModel(modelToUse);
|
||||
|
||||
// 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, tmpPath]);
|
||||
|
||||
|
||||
@@ -3,10 +3,9 @@ import { useTranslation } from 'react-i18next';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Textarea } from '@/components/ui/textarea';
|
||||
import { CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Save, Loader2, ImageOff } from 'lucide-react';
|
||||
import { Save, Loader2 } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { isMediaFile } from '@/lib/fileUtils';
|
||||
|
||||
interface FileEditorProps {
|
||||
filePath: string;
|
||||
@@ -94,7 +93,6 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
||||
// Get git status for the current file
|
||||
const currentFileGitStatus = getFileGitStatus(filePath);
|
||||
const gitStatusClasses = getGitStatusClasses(currentFileGitStatus);
|
||||
const isMedia = isMediaFile(filePath);
|
||||
|
||||
return (
|
||||
<div className="h-full flex flex-col">
|
||||
@@ -102,36 +100,32 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
||||
<div className="flex items-center justify-between">
|
||||
<CardTitle className={cn("text-sm sm:text-base truncate flex-1 mr-2", gitStatusClasses)}>{filePath}</CardTitle>
|
||||
<div className="flex items-center space-x-1 sm:space-x-2">
|
||||
{hasChanges && !isMedia && (
|
||||
{hasChanges && (
|
||||
<span className="text-xs sm:text-sm text-muted-foreground hidden sm:inline">{t('unsavedChanges')}</span>
|
||||
)}
|
||||
{!isMedia && (
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || isSaving || isLoading}
|
||||
size="sm"
|
||||
className="focus-ring"
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
|
||||
<span className="hidden sm:inline">{t('saving')}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="sm:mr-2 h-4 w-4" />
|
||||
<span className="hidden sm:inline">{t('save')}</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
)}
|
||||
<Button
|
||||
onClick={handleSave}
|
||||
disabled={!hasChanges || isSaving || isLoading}
|
||||
size="sm"
|
||||
className="focus-ring"
|
||||
>
|
||||
{isSaving ? (
|
||||
<>
|
||||
<Loader2 className="mr-1 sm:mr-2 h-4 w-4 animate-spin" />
|
||||
<span className="hidden sm:inline">{t('saving')}</span>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Save className="sm:mr-2 h-4 w-4" />
|
||||
<span className="hidden sm:inline">{t('save')}</span>
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
{!isMedia && (
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{t('languageLabel')}: {getLanguageFromPath(filePath)}
|
||||
</div>
|
||||
)}
|
||||
<div className="text-xs text-muted-foreground mt-1">
|
||||
{t('languageLabel')}: {getLanguageFromPath(filePath)}
|
||||
</div>
|
||||
</CardHeader>
|
||||
|
||||
<CardContent className="flex-1 p-0">
|
||||
@@ -139,10 +133,6 @@ export function FileEditor({ filePath, content, onSave, isLoading, projectId }:
|
||||
<div className="flex items-center justify-center h-full">
|
||||
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
|
||||
</div>
|
||||
) : isMedia ? (
|
||||
<div className="flex flex-col items-center justify-center h-full p-8 text-center">
|
||||
<ImageOff className="h-16 w-16 text-muted-foreground" />
|
||||
</div>
|
||||
) : (
|
||||
<Textarea
|
||||
value={editedContent}
|
||||
|
||||
@@ -32,7 +32,6 @@ import { DeployDialog } from '@/components/DeployDialog';
|
||||
import { Terminal as TerminalComponent } from '@/components/Terminal';
|
||||
import { useSearchParams } from 'react-router-dom';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { isMediaFile } from '@/lib/fileUtils';
|
||||
|
||||
interface PreviewPaneProps {
|
||||
projectId: string;
|
||||
@@ -131,13 +130,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
}, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]);
|
||||
|
||||
const loadFileContent = useCallback(async (filePath: string) => {
|
||||
// Skip loading media files - they can't be edited as text
|
||||
if (isMediaFile(filePath)) {
|
||||
setFileContent('');
|
||||
setIsLoading(false);
|
||||
return;
|
||||
}
|
||||
|
||||
setIsLoading(true);
|
||||
try {
|
||||
const content = await projectsManager.readFile(projectId, filePath);
|
||||
@@ -801,7 +793,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
</h3>
|
||||
</div>
|
||||
<div className="flex-1 min-h-0">
|
||||
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
</>
|
||||
) : (
|
||||
@@ -895,7 +887,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<div className="flex-1 flex min-h-0">
|
||||
{desktopCodeView === 'terminal' ? (
|
||||
<div className="flex-1">
|
||||
<TerminalComponent cwd={`${projectsPath}/${projectId}`} />
|
||||
<TerminalComponent projectId={projectId} />
|
||||
</div>
|
||||
) : (
|
||||
<>
|
||||
|
||||
@@ -5,13 +5,13 @@ import { Copy } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useGit } from '@/hooks/useGit';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { ansiToHtml, containsAnsiCodes } from '@/lib/ansiToHtml';
|
||||
|
||||
interface TerminalProps {
|
||||
cwd: string;
|
||||
projectId: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
@@ -22,7 +22,7 @@ interface TerminalLine {
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
export function Terminal({ cwd, className }: TerminalProps) {
|
||||
export function Terminal({ projectId, className }: TerminalProps) {
|
||||
const [lines, setLines] = useState<TerminalLine[]>([]);
|
||||
const [currentInput, setCurrentInput] = useState('');
|
||||
const [isExecuting, setIsExecuting] = useState(false);
|
||||
@@ -34,13 +34,13 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
const shellToolRef = useRef<ShellTool | null>(null);
|
||||
|
||||
const { fs } = useFS();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { git } = useGit();
|
||||
const { user } = useCurrentUser();
|
||||
const { config } = useAppContext();
|
||||
|
||||
// Initialize ShellTool
|
||||
useEffect(() => {
|
||||
shellToolRef.current = new ShellTool(fs, cwd, git, config.corsProxy, user?.signer);
|
||||
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
|
||||
|
||||
// Add welcome message
|
||||
setLines([{
|
||||
@@ -49,7 +49,7 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
|
||||
timestamp: new Date()
|
||||
}]);
|
||||
}, [cwd, fs, git, config.corsProxy, user?.signer]);
|
||||
}, [projectId, fs, git, projectsPath, user?.signer]);
|
||||
|
||||
// Auto-scroll to bottom when new lines are added or execution state changes
|
||||
useEffect(() => {
|
||||
@@ -106,8 +106,10 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
|
||||
// Check if running in Electron - use real shell
|
||||
if (window.electron?.shell) {
|
||||
// Use the provided cwd (Electron will expand ~ if present)
|
||||
const result = await window.electron.shell.exec(command, cwd);
|
||||
// Use the full path (with ~ if present) - Electron will expand it
|
||||
const fullCwd = `${projectsPath}/${projectId}`;
|
||||
|
||||
const result = await window.electron.shell.exec(command, fullCwd);
|
||||
|
||||
// Format output
|
||||
let output = '';
|
||||
@@ -155,7 +157,7 @@ export function Terminal({ cwd, className }: TerminalProps) {
|
||||
} finally {
|
||||
setIsExecuting(false);
|
||||
}
|
||||
}, [addLine, commandHistory, cwd]);
|
||||
}, [addLine, commandHistory, projectId, projectsPath]);
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
@@ -6,7 +6,7 @@ import { Terminal } from './Terminal';
|
||||
export function TerminalTest() {
|
||||
return (
|
||||
<div className="h-[500px] w-full">
|
||||
<Terminal cwd="/projects/test" />
|
||||
<Terminal projectId="test" />
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -16,11 +16,8 @@ describe('UserMessage', () => {
|
||||
|
||||
render(<UserMessage content={content} />);
|
||||
|
||||
// When using string content, it should parse and separate file attachments
|
||||
expect(screen.getByText('Here is my file:')).toBeInTheDocument();
|
||||
expect(screen.getByText('test.txt')).toBeInTheDocument();
|
||||
// Full path should not be displayed
|
||||
expect(screen.queryByText('/tmp/test.txt')).not.toBeInTheDocument();
|
||||
// When using string content, it should still work but won't separate file attachments
|
||||
expect(screen.getByText(content)).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('renders file attachment badges for single file with text parts', () => {
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { Paperclip } from 'lucide-react';
|
||||
import { FileText, File } from 'lucide-react';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
@@ -18,60 +18,21 @@ export function UserMessage({ content }: UserMessageProps) {
|
||||
: content.filter(part => part.type === 'text') as Array<{ type: 'text'; text: string }>;
|
||||
|
||||
// Regular expression to match "Added file: /tmp/<filename>" patterns
|
||||
// Matches the pattern anywhere in the text
|
||||
const filePattern = /Added file:\s*(\/tmp\/[^\s\n]+)/g;
|
||||
const filePattern = /^Added file: (\/tmp\/[^\s\n]+)$/;
|
||||
|
||||
// Process each content part and categorize as text or file
|
||||
const processedParts: Array<{ type: 'text' | 'file'; content: string; filepath?: string }> = [];
|
||||
|
||||
contentParts.forEach(part => {
|
||||
const text = part.text.trim();
|
||||
|
||||
// Find all file patterns in this text part
|
||||
const fileMatches: Array<{ filepath: string; index: number; length: number }> = [];
|
||||
let match;
|
||||
filePattern.lastIndex = 0; // Reset regex
|
||||
|
||||
while ((match = filePattern.exec(text)) !== null) {
|
||||
fileMatches.push({
|
||||
filepath: match[1], // "/tmp/filename.txt"
|
||||
index: match.index,
|
||||
length: match[0].length
|
||||
});
|
||||
}
|
||||
const match = text.match(filePattern);
|
||||
|
||||
if (fileMatches.length > 0) {
|
||||
// Split text around file patterns and process each segment
|
||||
let lastIndex = 0;
|
||||
|
||||
fileMatches.forEach((fileMatch) => {
|
||||
// Add text before the file pattern
|
||||
if (fileMatch.index > lastIndex) {
|
||||
const textBefore = text.substring(lastIndex, fileMatch.index).trim();
|
||||
if (textBefore) {
|
||||
processedParts.push({ type: 'text', content: textBefore });
|
||||
}
|
||||
}
|
||||
|
||||
// Add the file attachment badge (without showing "Added file:" text)
|
||||
processedParts.push({
|
||||
type: 'file',
|
||||
content: '', // Empty - badge will show filename only
|
||||
filepath: fileMatch.filepath
|
||||
});
|
||||
|
||||
lastIndex = fileMatch.index + fileMatch.length;
|
||||
});
|
||||
|
||||
// Add remaining text after the last file pattern
|
||||
if (lastIndex < text.length) {
|
||||
const textAfter = text.substring(lastIndex).trim();
|
||||
if (textAfter) {
|
||||
processedParts.push({ type: 'text', content: textAfter });
|
||||
}
|
||||
}
|
||||
if (match) {
|
||||
// This is a file attachment
|
||||
const filepath = match[1]; // "/tmp/filename.txt"
|
||||
processedParts.push({ type: 'file', content: text, filepath });
|
||||
} else if (text) {
|
||||
// No file patterns found, treat as regular text
|
||||
// This is regular text content
|
||||
processedParts.push({ type: 'text', content: text });
|
||||
}
|
||||
});
|
||||
@@ -81,6 +42,19 @@ export function UserMessage({ content }: UserMessageProps) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const getFileIcon = (filename: string) => {
|
||||
const extension = filename.split('.').pop()?.toLowerCase();
|
||||
|
||||
// Return FileText icon for text-like files, File icon for others
|
||||
const textExtensions = ['txt', 'md', 'json', 'js', 'ts', 'jsx', 'tsx', 'css', 'html', 'xml', 'yml', 'yaml'];
|
||||
|
||||
if (extension && textExtensions.includes(extension)) {
|
||||
return <FileText className="h-3 w-3" />;
|
||||
}
|
||||
|
||||
return <File className="h-3 w-3" />;
|
||||
};
|
||||
|
||||
const getFileName = (filepath: string) => {
|
||||
return filepath.split('/').pop() || filepath;
|
||||
};
|
||||
@@ -89,25 +63,18 @@ export function UserMessage({ content }: UserMessageProps) {
|
||||
<div className="space-y-2">
|
||||
{processedParts.map((part, index) => {
|
||||
if (part.type === 'text') {
|
||||
// Only render text if it has content
|
||||
if (!part.content.trim()) return null;
|
||||
return (
|
||||
<div key={index} className="whitespace-pre-wrap">
|
||||
{part.content}
|
||||
</div>
|
||||
);
|
||||
} else {
|
||||
// Render file attachment badge (no "Added file:" text)
|
||||
const filename = getFileName(part.filepath!);
|
||||
return (
|
||||
<div key={index} className="flex items-center gap-2 max-w-full min-w-0">
|
||||
<Badge variant="secondary" className="inline-flex items-center gap-1.5 px-2 py-1 max-w-full">
|
||||
<span className="flex-shrink-0">
|
||||
<Paperclip className="h-3 w-3" />
|
||||
</span>
|
||||
<span className="text-xs font-medium truncate min-w-0" title={filename}>
|
||||
{filename}
|
||||
</span>
|
||||
<div key={index} className="flex items-center gap-2">
|
||||
<Badge variant="secondary" className="flex items-center gap-1.5 px-2 py-1">
|
||||
{getFileIcon(filename)}
|
||||
<span className="text-xs font-medium">{filename}</span>
|
||||
</Badge>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -5,6 +5,7 @@ import { nip19 } from 'nostr-tools';
|
||||
import { useAuthor } from '@/hooks/useAuthor';
|
||||
import { useComments } from '@/hooks/useComments';
|
||||
import { CommentForm } from './CommentForm';
|
||||
import { EmojiReactions } from './EmojiReactions';
|
||||
import { NoteContent } from '@/components/NoteContent';
|
||||
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
|
||||
import { Button } from '@/components/ui/button';
|
||||
@@ -26,10 +27,10 @@ interface CommentProps {
|
||||
export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: CommentProps) {
|
||||
const [showReplyForm, setShowReplyForm] = useState(false);
|
||||
const [showReplies, setShowReplies] = useState(depth < 2); // Auto-expand first 2 levels
|
||||
|
||||
|
||||
const author = useAuthor(comment.pubkey);
|
||||
const { data: commentsData } = useComments(root, limit);
|
||||
|
||||
|
||||
const metadata = author.data?.metadata;
|
||||
const displayName = metadata?.name ?? genUserName(comment.pubkey)
|
||||
const timeAgo = formatDistanceToNow(new Date(comment.created_at * 1000), { addSuffix: true });
|
||||
@@ -55,7 +56,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
|
||||
</Avatar>
|
||||
</Link>
|
||||
<div>
|
||||
<Link
|
||||
<Link
|
||||
to={`/${nip19.npubEncode(comment.pubkey)}`}
|
||||
className="font-medium text-sm hover:text-primary transition-colors"
|
||||
>
|
||||
@@ -71,6 +72,13 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
|
||||
<NoteContent event={comment} className="text-sm" />
|
||||
</div>
|
||||
|
||||
{/* Emoji Reactions */}
|
||||
<EmojiReactions
|
||||
commentId={comment.id}
|
||||
commentAuthor={comment.pubkey}
|
||||
className="pt-2"
|
||||
/>
|
||||
|
||||
{/* Comment Actions */}
|
||||
<div className="flex items-center justify-between pt-2">
|
||||
<div className="flex items-center space-x-2">
|
||||
@@ -83,7 +91,7 @@ export function Comment({ root, comment, depth = 0, maxDepth = 3, limit }: Comme
|
||||
<MessageSquare className="h-3 w-3 mr-1" />
|
||||
Reply
|
||||
</Button>
|
||||
|
||||
|
||||
{hasReplies && (
|
||||
<Collapsible open={showReplies} onOpenChange={setShowReplies}>
|
||||
<CollapsibleTrigger asChild>
|
||||
|
||||
@@ -19,9 +19,9 @@ interface CommentFormProps {
|
||||
export function CommentForm({
|
||||
root,
|
||||
reply,
|
||||
onSuccess,
|
||||
onSuccess,
|
||||
placeholder = "Write a comment...",
|
||||
compact = false
|
||||
compact = false
|
||||
}: CommentFormProps) {
|
||||
const [content, setContent] = useState('');
|
||||
const { user } = useCurrentUser();
|
||||
@@ -29,7 +29,7 @@ export function CommentForm({
|
||||
|
||||
const handleSubmit = (e: React.FormEvent) => {
|
||||
e.preventDefault();
|
||||
|
||||
|
||||
if (!content.trim() || !user) return;
|
||||
|
||||
postComment(
|
||||
@@ -72,10 +72,13 @@ export function CommentForm({
|
||||
/>
|
||||
<div className="flex justify-between items-center">
|
||||
<span className="text-sm text-muted-foreground">
|
||||
{reply ? 'Replying to comment' : 'Adding to the discussion'}
|
||||
{isPending
|
||||
? (reply ? 'Posting reply...' : 'Posting comment...')
|
||||
: (reply ? 'Replying to comment' : 'Adding to the discussion')
|
||||
}
|
||||
</span>
|
||||
<Button
|
||||
type="submit"
|
||||
<Button
|
||||
type="submit"
|
||||
disabled={!content.trim() || isPending}
|
||||
size={compact ? "sm" : "default"}
|
||||
>
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import React, { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import {
|
||||
Popover,
|
||||
PopoverContent,
|
||||
PopoverTrigger,
|
||||
} from '@/components/ui/popover';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import {
|
||||
useCommentReactions,
|
||||
useAddCommentReaction,
|
||||
EMOJI_REACTIONS,
|
||||
type CommentReaction
|
||||
} from '@/hooks/useCommentReactions';
|
||||
import { Smile, Plus } from 'lucide-react';
|
||||
|
||||
interface EmojiReactionsProps {
|
||||
commentId: string;
|
||||
commentAuthor: string;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
export function EmojiReactions({ commentId, commentAuthor, className }: EmojiReactionsProps) {
|
||||
const { user } = useCurrentUser();
|
||||
const { data: reactions = [], isLoading } = useCommentReactions(commentId);
|
||||
const { mutate: addReaction, isPending: isAddingReaction } = useAddCommentReaction();
|
||||
const [isPopoverOpen, setIsPopoverOpen] = useState(false);
|
||||
|
||||
const handleReactionToggle = (emoji: string) => {
|
||||
if (!user) return;
|
||||
|
||||
addReaction({
|
||||
commentId,
|
||||
emoji,
|
||||
commentAuthor,
|
||||
isToggle: true,
|
||||
});
|
||||
};
|
||||
|
||||
const handleEmojiSelect = (emoji: string) => {
|
||||
addReaction({
|
||||
commentId,
|
||||
emoji,
|
||||
commentAuthor,
|
||||
isToggle: false, // Always add when selecting from picker
|
||||
});
|
||||
setIsPopoverOpen(false);
|
||||
};
|
||||
|
||||
if (isLoading) {
|
||||
return (
|
||||
<div className={`flex items-center gap-1 ${className}`}>
|
||||
<div className="flex gap-1">
|
||||
{[1, 2, 3].map((i) => (
|
||||
<div
|
||||
key={i}
|
||||
className="h-6 w-12 bg-muted animate-pulse rounded-full"
|
||||
/>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<TooltipProvider>
|
||||
<div className={`flex items-center gap-1 flex-wrap ${className}`}>
|
||||
{/* Existing Reactions */}
|
||||
{reactions.map((reaction) => (
|
||||
<ReactionBadge
|
||||
key={reaction.emoji}
|
||||
reaction={reaction}
|
||||
onToggle={() => handleReactionToggle(reaction.emoji)}
|
||||
disabled={isAddingReaction}
|
||||
/>
|
||||
))}
|
||||
|
||||
{/* Add Reaction Button */}
|
||||
<Popover open={isPopoverOpen} onOpenChange={setIsPopoverOpen}>
|
||||
<PopoverTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 px-2 text-xs hover:bg-muted/50"
|
||||
disabled={!user || isAddingReaction}
|
||||
>
|
||||
<Smile className="h-3 w-3 mr-1" />
|
||||
<Plus className="h-2 w-2" />
|
||||
</Button>
|
||||
</PopoverTrigger>
|
||||
<PopoverContent className="w-auto p-2" align="start">
|
||||
<div className="grid grid-cols-4 gap-1">
|
||||
{EMOJI_REACTIONS.map(({ emoji, label }) => (
|
||||
<Button
|
||||
key={emoji}
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-10 w-10 p-0 hover:bg-muted/50"
|
||||
onClick={() => handleEmojiSelect(emoji)}
|
||||
title={label}
|
||||
>
|
||||
<span className="text-lg">{emoji}</span>
|
||||
</Button>
|
||||
))}
|
||||
</div>
|
||||
</PopoverContent>
|
||||
</Popover>
|
||||
</div>
|
||||
</TooltipProvider>
|
||||
);
|
||||
}
|
||||
|
||||
interface ReactionBadgeProps {
|
||||
reaction: CommentReaction;
|
||||
onToggle: () => void;
|
||||
disabled?: boolean;
|
||||
}
|
||||
|
||||
function ReactionBadge({ reaction, onToggle, disabled }: ReactionBadgeProps) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return (
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant={reaction.userReacted ? "default" : "secondary"}
|
||||
size="sm"
|
||||
className={`h-6 px-2 text-xs gap-1 ${
|
||||
reaction.userReacted
|
||||
? 'bg-primary/10 text-primary border-primary/20 hover:bg-primary/20'
|
||||
: 'hover:bg-muted/50'
|
||||
}`}
|
||||
onClick={onToggle}
|
||||
disabled={!user || disabled}
|
||||
>
|
||||
<span>{reaction.emoji}</span>
|
||||
<span className="text-xs">{reaction.count}</span>
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<ReactionTooltip reaction={reaction} />
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
);
|
||||
}
|
||||
|
||||
function ReactionTooltip({ reaction }: { reaction: CommentReaction }) {
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
// Simple tooltip for now - we'll show count and emoji
|
||||
// In the future, we could create a separate component to fetch user names
|
||||
const tooltipText = user && reaction.users.includes(user.pubkey)
|
||||
? `You and ${reaction.count - 1} other${reaction.count > 2 ? 's' : ''} reacted with ${reaction.emoji}`
|
||||
: `${reaction.count} ${reaction.count === 1 ? 'person' : 'people'} reacted with ${reaction.emoji}`;
|
||||
|
||||
return <span className="text-sm">{tooltipText}</span>;
|
||||
}
|
||||
@@ -1,35 +1,24 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { AlertCircle } from 'lucide-react';
|
||||
|
||||
interface ShakespeareDeployFormProps {
|
||||
host?: string;
|
||||
projectId: string;
|
||||
onSubdomainChange: (subdomain: string) => void;
|
||||
onValidationChange?: (isValid: boolean) => void;
|
||||
}
|
||||
|
||||
export function ShakespeareDeployForm({
|
||||
host = 'shakespeare.wtf',
|
||||
projectId,
|
||||
onSubdomainChange,
|
||||
onValidationChange,
|
||||
}: ShakespeareDeployFormProps) {
|
||||
const [subdomain, setSubdomain] = useState(projectId);
|
||||
|
||||
// Validate subdomain: no periods allowed (only single-level subdomains)
|
||||
const hasPeriod = subdomain.includes('.');
|
||||
const isValid = subdomain.trim() !== '' && !hasPeriod;
|
||||
|
||||
useEffect(() => {
|
||||
onSubdomainChange(subdomain);
|
||||
}, [subdomain, onSubdomainChange]);
|
||||
|
||||
useEffect(() => {
|
||||
onValidationChange?.(isValid);
|
||||
}, [isValid, onValidationChange]);
|
||||
|
||||
const fullDomain = subdomain ? `${subdomain}.${host}` : `${projectId}.${host}`;
|
||||
|
||||
return (
|
||||
@@ -41,14 +30,7 @@ export function ShakespeareDeployForm({
|
||||
value={subdomain}
|
||||
onChange={(e) => setSubdomain(e.target.value)}
|
||||
placeholder={projectId}
|
||||
className={hasPeriod ? 'border-destructive' : ''}
|
||||
/>
|
||||
{hasPeriod && (
|
||||
<div className="flex items-start gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4 mt-0.5 flex-shrink-0" />
|
||||
<span>Subdomain cannot contain periods. Use hyphens instead (e.g., "nostr-radar").</span>
|
||||
</div>
|
||||
)}
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Will deploy to: <span className="font-mono">{fullDomain}</span>
|
||||
</p>
|
||||
|
||||
@@ -410,7 +410,7 @@ export function AnnounceRepositoryDialog({
|
||||
</DialogHeader>
|
||||
|
||||
<ScrollArea className="max-h-[60vh]">
|
||||
<div className="space-y-6 p-1 pr-4">
|
||||
<div className="space-y-6 pr-4">
|
||||
{/* Error alert */}
|
||||
{error && (
|
||||
<Alert variant="destructive">
|
||||
|
||||
@@ -187,23 +187,13 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
// Automatically check out the new branch
|
||||
await git.checkout({
|
||||
dir: projectPath,
|
||||
ref: newBranchName.trim(),
|
||||
force: true,
|
||||
toast({
|
||||
title: 'Branch created',
|
||||
description: `Created branch "${newBranchName}"`,
|
||||
});
|
||||
|
||||
// Close the dialog before showing the toast
|
||||
setNewBranchName('');
|
||||
setIsCreateDialogOpen(false);
|
||||
|
||||
// Show success toast indicating the branch was created and checked out
|
||||
toast({
|
||||
title: 'Branch created and checked out',
|
||||
description: `Switched to new branch "${newBranchName.trim()}"`,
|
||||
});
|
||||
|
||||
await loadBranches();
|
||||
onBranchChange?.();
|
||||
} catch (error) {
|
||||
|
||||
@@ -8,20 +8,9 @@ export interface AIProvider {
|
||||
proxy?: boolean;
|
||||
}
|
||||
|
||||
export interface MCPServer {
|
||||
type: 'streamable-http';
|
||||
url: string;
|
||||
headers?: Record<string, string>;
|
||||
}
|
||||
|
||||
export interface MCPServers {
|
||||
[key: string]: MCPServer;
|
||||
}
|
||||
|
||||
export interface AISettings {
|
||||
providers: AIProvider[];
|
||||
recentlyUsedModels: string[];
|
||||
mcpServers?: MCPServers;
|
||||
}
|
||||
|
||||
export interface AISettingsContextType {
|
||||
@@ -31,8 +20,6 @@ export interface AISettingsContextType {
|
||||
removeProvider: (id: string) => void;
|
||||
setProviders: (providers: AIProvider[]) => void;
|
||||
addRecentlyUsedModel: (modelId: string) => void;
|
||||
setMCPServer: (name: string, server: MCPServer) => void;
|
||||
removeMCPServer: (name: string) => void;
|
||||
isConfigured: boolean;
|
||||
}
|
||||
|
||||
|
||||
@@ -40,21 +40,15 @@ export interface AppConfig {
|
||||
fsPathTmp: string;
|
||||
/** VFS path for plugins directory */
|
||||
fsPathPlugins: string;
|
||||
/** VFS path for templates directory */
|
||||
fsPathTemplates: string;
|
||||
/** Sentry DSN for error reporting (empty string = disabled) */
|
||||
sentryDsn: string;
|
||||
/** Whether the user has enabled Sentry error reporting */
|
||||
sentryEnabled: boolean;
|
||||
/** System prompt EJS template */
|
||||
systemPrompt?: string;
|
||||
}
|
||||
|
||||
export interface AppContextType {
|
||||
/** Current application configuration */
|
||||
config: AppConfig;
|
||||
/** Default application configuration */
|
||||
defaultConfig: AppConfig;
|
||||
/** Update configuration using a callback that receives current config and returns new config */
|
||||
updateConfig: (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => void;
|
||||
}
|
||||
|
||||
@@ -114,10 +114,7 @@ export function useAIChat({
|
||||
}, [projectId]);
|
||||
|
||||
// Actions
|
||||
const sendMessage = useCallback(async (
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||
providerModel: string
|
||||
) => {
|
||||
const sendMessage = useCallback(async (content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string) => {
|
||||
try {
|
||||
await initSession();
|
||||
await sessionManager.sendMessage(projectId, content, providerModel);
|
||||
|
||||
@@ -38,31 +38,28 @@ describe('useAIProjectId', () => {
|
||||
});
|
||||
|
||||
// Mock useAppContext
|
||||
const config = {
|
||||
theme: 'dark' as const,
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://github.com/example/template',
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
mockUseAppContext.mockReturnValue({
|
||||
config,
|
||||
defaultConfig: config,
|
||||
config: {
|
||||
theme: 'dark',
|
||||
relayMetadata: {
|
||||
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://github.com/example/template',
|
||||
esmUrl: 'https://esm.sh',
|
||||
corsProxy: 'https://proxy.example.com/{href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
},
|
||||
updateConfig: vi.fn(),
|
||||
});
|
||||
|
||||
@@ -94,15 +91,13 @@ describe('useAIProjectId', () => {
|
||||
|
||||
it('should return not configured when AI settings are not configured', () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
removeProvider: vi.fn(),
|
||||
setProviders: vi.fn(),
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
@@ -113,7 +108,7 @@ describe('useAIProjectId', () => {
|
||||
|
||||
it('should throw error when trying to generate ID without configuration', async () => {
|
||||
mockUseAISettings.mockReturnValue({
|
||||
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
|
||||
settings: { providers: [], recentlyUsedModels: [] },
|
||||
isConfigured: false,
|
||||
updateSettings: vi.fn(),
|
||||
setProvider: vi.fn(),
|
||||
@@ -121,8 +116,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
@@ -147,8 +140,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
@@ -173,8 +164,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
@@ -198,8 +187,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
@@ -232,8 +219,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI response - returns a project name that already exists
|
||||
@@ -287,8 +272,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return a project name that already exists
|
||||
@@ -344,8 +327,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return a very long project name (over 50 characters)
|
||||
@@ -396,8 +377,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return an invalid project name (doesn't match regex)
|
||||
@@ -448,8 +427,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
// Mock AI to return a project name that already exists
|
||||
@@ -507,8 +484,6 @@ describe('useAIProjectId', () => {
|
||||
setProviders: vi.fn(),
|
||||
|
||||
addRecentlyUsedModel: vi.fn(),
|
||||
setMCPServer: vi.fn(),
|
||||
removeMCPServer: vi.fn(),
|
||||
});
|
||||
|
||||
const { result } = renderHook(() => useAIProjectId());
|
||||
|
||||
@@ -223,8 +223,8 @@ export function useAppSubmissions() {
|
||||
|
||||
return submissions;
|
||||
},
|
||||
staleTime: 30000, // 30 seconds
|
||||
refetchInterval: 60000, // 1 minute
|
||||
staleTime: 10000, // 10 seconds
|
||||
refetchInterval: 30000, // 30 seconds
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,231 @@
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
// Predefined emoji reactions
|
||||
export const EMOJI_REACTIONS = [
|
||||
{ emoji: '👍', label: 'thumbs up' },
|
||||
{ emoji: '❤️', label: 'heart' },
|
||||
{ emoji: '😂', label: 'laugh' },
|
||||
{ emoji: '😮', label: 'wow' },
|
||||
{ emoji: '😢', label: 'sad' },
|
||||
{ emoji: '😡', label: 'angry' },
|
||||
{ emoji: '🎉', label: 'celebrate' },
|
||||
{ emoji: '🔥', label: 'fire' },
|
||||
] as const;
|
||||
|
||||
export type EmojiReaction = typeof EMOJI_REACTIONS[number];
|
||||
|
||||
export interface CommentReaction {
|
||||
emoji: string;
|
||||
count: number;
|
||||
userReacted: boolean;
|
||||
users: string[]; // pubkeys of users who reacted
|
||||
}
|
||||
|
||||
export interface CommentReactions {
|
||||
[emoji: string]: CommentReaction;
|
||||
}
|
||||
|
||||
export function useCommentReactions(commentId: string) {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['comment-reactions', commentId],
|
||||
queryFn: async () => {
|
||||
// Fetch kind 7 reactions that reference this comment
|
||||
const reactions = await nostr.query(
|
||||
[
|
||||
{
|
||||
kinds: [7],
|
||||
'#e': [commentId],
|
||||
limit: 500,
|
||||
},
|
||||
],
|
||||
{ signal: AbortSignal.timeout(3000) }
|
||||
);
|
||||
|
||||
// Group reactions by emoji and user, keeping only the latest reaction from each user
|
||||
const userReactions = new Map<string, Map<string, NostrEvent>>();
|
||||
|
||||
for (const reaction of reactions) {
|
||||
let emoji = reaction.content;
|
||||
const isRemoval = emoji.startsWith('-');
|
||||
|
||||
if (isRemoval) {
|
||||
emoji = emoji.slice(1); // Remove the "-" prefix
|
||||
}
|
||||
|
||||
if (!emoji || emoji.length > 10) continue; // Skip invalid emojis
|
||||
|
||||
if (!userReactions.has(emoji)) {
|
||||
userReactions.set(emoji, new Map());
|
||||
}
|
||||
|
||||
const emojiReactions = userReactions.get(emoji)!;
|
||||
const existingReaction = emojiReactions.get(reaction.pubkey);
|
||||
|
||||
// Keep only the latest reaction from each user
|
||||
if (!existingReaction || reaction.created_at > existingReaction.created_at) {
|
||||
emojiReactions.set(reaction.pubkey, reaction);
|
||||
}
|
||||
}
|
||||
|
||||
// Build the final reaction map
|
||||
const reactionMap: { [emoji: string]: CommentReaction } = {};
|
||||
|
||||
for (const [emoji, userReactionMap] of userReactions) {
|
||||
const activeUsers: string[] = [];
|
||||
let userReacted = false;
|
||||
|
||||
for (const [pubkey, reaction] of userReactionMap) {
|
||||
const isRemoval = reaction.content.startsWith('-');
|
||||
|
||||
if (!isRemoval) {
|
||||
activeUsers.push(pubkey);
|
||||
if (user && pubkey === user.pubkey) {
|
||||
userReacted = true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (activeUsers.length > 0) {
|
||||
reactionMap[emoji] = {
|
||||
emoji,
|
||||
count: activeUsers.length,
|
||||
userReacted,
|
||||
users: activeUsers,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Sort by count (most popular first)
|
||||
const sortedReactions = Object.values(reactionMap)
|
||||
.filter(reaction => reaction.count > 0)
|
||||
.sort((a, b) => b.count - a.count);
|
||||
|
||||
return sortedReactions;
|
||||
},
|
||||
enabled: !!commentId,
|
||||
staleTime: 10000, // 10 seconds
|
||||
refetchInterval: 30000, // 30 seconds
|
||||
});
|
||||
}
|
||||
|
||||
export function useAddCommentReaction() {
|
||||
const { user } = useCurrentUser();
|
||||
const { mutate: publishEvent } = useNostrPublish();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async ({ commentId, emoji, commentAuthor, isToggle = false }: {
|
||||
commentId: string;
|
||||
emoji: string;
|
||||
commentAuthor: string;
|
||||
isToggle?: boolean;
|
||||
}) => {
|
||||
if (!user) {
|
||||
throw new Error('User must be logged in to react');
|
||||
}
|
||||
|
||||
// Get current reactions to determine if this is an add or remove
|
||||
const currentReactions = queryClient.getQueryData(['comment-reactions', commentId]) as CommentReaction[] | undefined;
|
||||
const existingReaction = currentReactions?.find(r => r.emoji === emoji && r.userReacted);
|
||||
|
||||
const content = (isToggle && existingReaction) ? `-${emoji}` : emoji;
|
||||
|
||||
// Publish kind 7 reaction event
|
||||
return new Promise<NostrEvent>((resolve, reject) => {
|
||||
publishEvent({
|
||||
kind: 7,
|
||||
content,
|
||||
tags: [
|
||||
['e', commentId],
|
||||
['p', commentAuthor],
|
||||
],
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
}, {
|
||||
onSuccess: (event) => resolve(event),
|
||||
onError: (error) => reject(error),
|
||||
});
|
||||
});
|
||||
},
|
||||
onMutate: async ({ commentId, emoji, isToggle = false }) => {
|
||||
if (!user) return;
|
||||
|
||||
const queryKey = ['comment-reactions', commentId];
|
||||
|
||||
// Cancel any outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousReactions = queryClient.getQueryData(queryKey);
|
||||
|
||||
// Optimistically update the cache
|
||||
queryClient.setQueryData(queryKey, (old: CommentReaction[] = []) => {
|
||||
const newReactions = [...old];
|
||||
|
||||
// Find existing reaction for this emoji
|
||||
const existingReactionIndex = newReactions.findIndex(r => r.emoji === emoji);
|
||||
|
||||
if (existingReactionIndex >= 0) {
|
||||
// Update existing reaction
|
||||
const existingReaction = newReactions[existingReactionIndex];
|
||||
|
||||
if (isToggle && existingReaction.userReacted) {
|
||||
// User is removing their reaction
|
||||
newReactions[existingReactionIndex] = {
|
||||
...existingReaction,
|
||||
count: Math.max(0, existingReaction.count - 1),
|
||||
userReacted: false,
|
||||
users: existingReaction.users.filter(pubkey => pubkey !== user.pubkey),
|
||||
};
|
||||
|
||||
// Remove reaction if count reaches 0
|
||||
if (newReactions[existingReactionIndex].count === 0) {
|
||||
newReactions.splice(existingReactionIndex, 1);
|
||||
}
|
||||
} else if (!existingReaction.userReacted) {
|
||||
// User is adding their reaction
|
||||
newReactions[existingReactionIndex] = {
|
||||
...existingReaction,
|
||||
count: existingReaction.count + 1,
|
||||
userReacted: true,
|
||||
users: [...existingReaction.users, user.pubkey],
|
||||
};
|
||||
}
|
||||
} else {
|
||||
// Add new reaction
|
||||
newReactions.push({
|
||||
emoji,
|
||||
count: 1,
|
||||
userReacted: true,
|
||||
users: [user.pubkey],
|
||||
});
|
||||
}
|
||||
|
||||
// Sort by count (most popular first)
|
||||
return newReactions
|
||||
.filter(reaction => reaction.count > 0)
|
||||
.sort((a, b) => b.count - a.count);
|
||||
});
|
||||
|
||||
return { previousReactions };
|
||||
},
|
||||
onError: (err, { commentId }, context) => {
|
||||
// If the mutation fails, use the context returned from onMutate to roll back
|
||||
const queryKey = ['comment-reactions', commentId];
|
||||
queryClient.setQueryData(queryKey, context?.previousReactions);
|
||||
},
|
||||
onSuccess: (_, { commentId }) => {
|
||||
// Invalidate and refetch to get the real data
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['comment-reactions', commentId]
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
@@ -57,7 +57,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
});
|
||||
|
||||
const allDescendants = [...directReplies];
|
||||
|
||||
|
||||
// Recursively get descendants of each direct reply
|
||||
for (const reply of directReplies) {
|
||||
allDescendants.push(...getDescendants(reply.id));
|
||||
@@ -94,5 +94,7 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
|
||||
};
|
||||
},
|
||||
enabled: !!root,
|
||||
staleTime: 10000, // 10 seconds
|
||||
refetchInterval: 30000, // 30 seconds
|
||||
});
|
||||
}
|
||||
@@ -17,7 +17,5 @@ export function useFSPaths() {
|
||||
tmpPath: config.fsPathTmp,
|
||||
/** Plugins directory path (default: /plugins) */
|
||||
pluginsPath: config.fsPathPlugins,
|
||||
/** Templates directory path (default: /templates) */
|
||||
templatesPath: config.fsPathTemplates,
|
||||
};
|
||||
}
|
||||
@@ -49,7 +49,6 @@ function createWrapper(corsProxy: string) {
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
|
||||
+23
-648
@@ -1,24 +1,32 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useGitFetch } from './useGitFetch';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Create mocks that can be reconfigured per test
|
||||
const mockGit = {
|
||||
findRoot: vi.fn(),
|
||||
listRemotes: vi.fn(),
|
||||
currentBranch: vi.fn(),
|
||||
resolveRef: vi.fn(),
|
||||
fetch: vi.fn(),
|
||||
};
|
||||
|
||||
const mockToast = vi.fn();
|
||||
const mockInvalidateQueries = vi.fn();
|
||||
|
||||
// Mock the git operations
|
||||
vi.mock('./useGit', () => ({
|
||||
useGit: () => ({
|
||||
git: mockGit,
|
||||
git: {
|
||||
findRoot: vi.fn().mockResolvedValue('/projects/test-project'),
|
||||
listRemotes: vi.fn().mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]),
|
||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
||||
getRemoteInfo: vi.fn().mockResolvedValue({
|
||||
refs: {
|
||||
HEAD: {
|
||||
type: 'symref',
|
||||
target: 'refs/heads/main',
|
||||
},
|
||||
},
|
||||
}),
|
||||
resolveRef: vi.fn()
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'), // after current
|
||||
fetch: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
@@ -36,30 +44,7 @@ vi.mock('./useFSPaths', () => ({
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useToast', () => ({
|
||||
useToast: () => ({
|
||||
toast: mockToast,
|
||||
}),
|
||||
}));
|
||||
|
||||
// Mock QueryClient to track invalidateQueries calls
|
||||
vi.mock('@tanstack/react-query', async () => {
|
||||
const actual = await vi.importActual('@tanstack/react-query');
|
||||
return {
|
||||
...actual,
|
||||
useQueryClient: () => ({
|
||||
invalidateQueries: mockInvalidateQueries,
|
||||
}),
|
||||
};
|
||||
});
|
||||
|
||||
describe('useGitFetch', () => {
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
mockToast.mockClear();
|
||||
mockInvalidateQueries.mockClear();
|
||||
});
|
||||
|
||||
it('returns null state when projectId is null', async () => {
|
||||
const { result } = renderHook(() => useGitFetch(null), {
|
||||
wrapper: TestApp,
|
||||
@@ -72,28 +57,7 @@ describe('useGitFetch', () => {
|
||||
expect(result.current.isSuccess).toBe(false);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully when default branch is checked out', async () => {
|
||||
// Setup mocks for default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'); // after current (same as default)
|
||||
|
||||
it('fetches remote updates successfully', async () => {
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
@@ -108,207 +72,9 @@ describe('useGitFetch', () => {
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully when non-default branch is checked out', async () => {
|
||||
// Setup mocks for non-default branch scenario
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef calls in order:
|
||||
// 1. Read symbolic ref for default branch (returns the ref path)
|
||||
// 2. Get default branch OID before fetch
|
||||
// 3. Get current branch OID before fetch
|
||||
// 4. Get default branch OID after fetch
|
||||
// 5. Get current branch OID after fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default (main)
|
||||
.mockResolvedValueOnce('def456') // before current (feature-branch)
|
||||
.mockResolvedValueOnce('abc123') // after default (main)
|
||||
.mockResolvedValueOnce('def456'); // after current (feature-branch)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
|
||||
// Verify fetch was called
|
||||
expect(mockGit.fetch).toHaveBeenCalledWith(
|
||||
expect.objectContaining({
|
||||
dir: '/projects/test-project',
|
||||
remote: 'origin',
|
||||
})
|
||||
);
|
||||
});
|
||||
|
||||
it('detects changes on default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current (same as default)
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on non-default branch when checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on non-default branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default (no change)
|
||||
.mockResolvedValueOnce('xyz789'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on current branch
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on both default and non-default branches', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('new111') // after default (changed!)
|
||||
.mockResolvedValueOnce('new222'); // after current (changed!)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on both branches
|
||||
});
|
||||
});
|
||||
|
||||
it('detects changes on default branch when non-default branch is checked out', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef to simulate changes on default branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main') // symbolic ref
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('def456') // before current
|
||||
.mockResolvedValueOnce('xyz789') // after default (changed!)
|
||||
.mockResolvedValueOnce('def456'); // after current (no change)
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'feature-branch',
|
||||
hasChanges: true, // Changes detected on default branch
|
||||
});
|
||||
});
|
||||
|
||||
it('can be manually refetched', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Mock resolveRef for initial fetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
@@ -319,402 +85,11 @@ describe('useGitFetch', () => {
|
||||
|
||||
const firstFetchTime = result.current.data?.fetchedAt;
|
||||
|
||||
// Setup mocks for refetch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Manually trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
|
||||
});
|
||||
|
||||
// Verify fetch was called twice (initial + refetch)
|
||||
expect(mockGit.fetch).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
describe('Toast Notifications', () => {
|
||||
it('shows toast when default branch changes (on default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed!
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when non-default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on feature branch
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123') // main unchanged
|
||||
.mockResolvedValueOnce('xyz789'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for feature branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows toast when default branch changes (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on main branch only
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('xyz789') // main changed!
|
||||
.mockResolvedValueOnce('def456'); // feature-branch unchanged
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Verify toast message for main branch
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
expect(gitStatusCalls[0][0]).toEqual({
|
||||
queryKey: ['git-status', 'test-project'],
|
||||
});
|
||||
});
|
||||
|
||||
it('shows two toasts when both branches change (on non-default branch)', async () => {
|
||||
// Setup mocks for initial fetch (no changes)
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('feature-branch');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Setup for refetch with changes on both branches
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('def456')
|
||||
.mockResolvedValueOnce('new111') // main changed!
|
||||
.mockResolvedValueOnce('new222'); // feature-branch changed!
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
// Verify both toast messages
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The feature-branch branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Verify git status was invalidated twice (once per toast)
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('does not show toast on initial load', async () => {
|
||||
// Setup mocks
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch with changes detected in the fetch itself
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789') // Changed from before to after fetch
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Should report changes in data
|
||||
expect(result.current.data?.hasChanges).toBe(true);
|
||||
|
||||
// But no toast on initial load
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('does not show toast when no changes detected', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// No toast should be shown
|
||||
expect(mockToast).not.toHaveBeenCalled();
|
||||
|
||||
// Verify git status was not invalidated (filter out other queries like 'nostr')
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('does not show duplicate toast for same branch when default equals current', async () => {
|
||||
// Setup mocks for initial fetch
|
||||
mockGit.findRoot.mockResolvedValue('/projects/test-project');
|
||||
mockGit.listRemotes.mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]);
|
||||
mockGit.currentBranch.mockResolvedValue('main');
|
||||
mockGit.fetch.mockResolvedValue(undefined);
|
||||
|
||||
// Initial fetch - no changes
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123');
|
||||
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
// Setup for refetch with changes (both default and current are 'main')
|
||||
mockGit.resolveRef
|
||||
.mockResolvedValueOnce('ref: refs/remotes/origin/main')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('abc123')
|
||||
.mockResolvedValueOnce('xyz789')
|
||||
.mockResolvedValueOnce('xyz789');
|
||||
|
||||
// Trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockToast).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
// Should only show one toast (for default branch), not two
|
||||
expect(mockToast).toHaveBeenCalledWith({
|
||||
title: 'Remote changes detected',
|
||||
description: 'The main branch has new commits available.',
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Should only invalidate once
|
||||
const gitStatusCalls = mockInvalidateQueries.mock.calls.filter(
|
||||
(call) => call[0]?.queryKey?.[0] === 'git-status'
|
||||
);
|
||||
expect(gitStatusCalls).toHaveLength(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
+18
-45
@@ -131,31 +131,25 @@ export function useGitFetch(projectId: string | null) {
|
||||
let beforeDefaultOid: string | null = null;
|
||||
let beforeCurrentOid: string | null = null;
|
||||
|
||||
// Get default branch from local symbolic ref
|
||||
// Get remote info to find default branch
|
||||
let defaultBranch: string | null = null;
|
||||
try {
|
||||
console.log('Reading default branch from local symbolic ref...');
|
||||
console.log('Fetching remote info...');
|
||||
const remoteInfo = await git.getRemoteInfo({
|
||||
url: remoteUrl,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
// Read the symbolic ref file directly
|
||||
// The file contains something like: "ref: refs/remotes/origin/main"
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
} else {
|
||||
console.log('Could not get default branch from local symbolic ref value:', refValue);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
// Extract default branch from symbolic ref
|
||||
if (remoteInfo.refs?.HEAD?.type === 'symref') {
|
||||
const symref = remoteInfo.refs.HEAD.target;
|
||||
defaultBranch = symref?.replace('refs/heads/', '') || null;
|
||||
console.log('Default branch from remote:', defaultBranch);
|
||||
}
|
||||
|
||||
// If we have a default branch, try to get its OID before fetch
|
||||
@@ -171,7 +165,7 @@ export function useGitFetch(projectId: string | null) {
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not read default branch from local data:', error);
|
||||
console.warn('Could not get remote info:', error);
|
||||
}
|
||||
|
||||
// Get current branch OID before fetch
|
||||
@@ -210,27 +204,6 @@ export function useGitFetch(projectId: string | null) {
|
||||
let afterDefaultOid: string | null = null;
|
||||
let afterCurrentOid: string | null = null;
|
||||
|
||||
// Re-read default branch from symbolic ref in case it was just created by fetch
|
||||
if (!defaultBranch) {
|
||||
try {
|
||||
const symbolicRefContent = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `remotes/${remote.remote}/HEAD`,
|
||||
depth: 1,
|
||||
});
|
||||
// Remove "ref: " prefix and extract the branch name
|
||||
// Content looks like: "ref: refs/remotes/origin/main"
|
||||
const refValue = symbolicRefContent.replace(/^ref:\s*/, '').trim();
|
||||
const match = refValue.match(/refs\/remotes\/[^/]+\/(.+)/);
|
||||
if (match) {
|
||||
defaultBranch = match[1].trim();
|
||||
console.log('Default branch from local symbolic ref:', defaultBranch);
|
||||
}
|
||||
} catch {
|
||||
console.log('No local symbolic ref found, will be set after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
afterDefaultOid = await git.resolveRef({
|
||||
@@ -346,7 +319,7 @@ export function useGitFetch(projectId: string | null) {
|
||||
if (currentBranchChanged && query.data.currentBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.currentBranch} branch has ${query.data.currentBranchOid === null ? 'been deleted' : 'new commits available'}.`,
|
||||
description: `The ${query.data.currentBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
|
||||
@@ -38,7 +38,6 @@ interface GitStatus {
|
||||
branches: string[];
|
||||
ahead: number;
|
||||
behind: number;
|
||||
remoteBranchExists: boolean;
|
||||
}
|
||||
|
||||
export function useGitStatus(projectId: string | null) {
|
||||
@@ -60,7 +59,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -82,7 +80,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -203,7 +200,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
// Calculate ahead/behind
|
||||
let ahead = 0;
|
||||
let behind = 0;
|
||||
let remoteBranchExists = false;
|
||||
try {
|
||||
if (currentBranch && remotes.length > 0) {
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
@@ -228,9 +224,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
ref: currentBranch,
|
||||
});
|
||||
|
||||
// Remote branch exists!
|
||||
remoteBranchExists = true;
|
||||
|
||||
if (remoteRef && localRef && remoteRef !== localRef) {
|
||||
// Get commits between local and remote
|
||||
const localCommits = await git.log({
|
||||
@@ -254,8 +247,11 @@ export function useGitStatus(projectId: string | null) {
|
||||
behind = remoteOnlyCommits.length;
|
||||
}
|
||||
} catch {
|
||||
// Remote branch doesn't exist
|
||||
remoteBranchExists = false;
|
||||
// Remote branch might not exist or other issues
|
||||
// If we can't find remote branch, assume we're ahead if we have commits
|
||||
if (totalCommits > 0) {
|
||||
ahead = totalCommits;
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
@@ -273,7 +269,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches,
|
||||
ahead,
|
||||
behind,
|
||||
remoteBranchExists,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error('Error checking git status:', error);
|
||||
@@ -288,7 +283,6 @@ export function useGitStatus(projectId: string | null) {
|
||||
branches: [],
|
||||
ahead: 0,
|
||||
behind: 0,
|
||||
remoteBranchExists: false,
|
||||
};
|
||||
}
|
||||
},
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
import { useEffect, useState } from 'react';
|
||||
import { MCPClient } from '@/lib/MCPClient';
|
||||
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||
|
||||
/**
|
||||
* Hook to check the connection status of an MCP server.
|
||||
* Returns 'connected', 'offline', or 'checking'.
|
||||
*/
|
||||
export function useMCPServerStatus(server: MCPServer): 'connected' | 'offline' | 'checking' {
|
||||
const [status, setStatus] = useState<'connected' | 'offline' | 'checking'>('checking');
|
||||
|
||||
useEffect(() => {
|
||||
let cancelled = false;
|
||||
|
||||
async function checkConnection() {
|
||||
setStatus('checking');
|
||||
|
||||
try {
|
||||
const client = new MCPClient(server);
|
||||
await client.connect();
|
||||
|
||||
// Try to list tools to verify the connection is working
|
||||
await client.listTools();
|
||||
|
||||
await client.close();
|
||||
|
||||
if (!cancelled) {
|
||||
setStatus('connected');
|
||||
}
|
||||
} catch {
|
||||
if (!cancelled) {
|
||||
setStatus('offline');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
checkConnection();
|
||||
|
||||
return () => {
|
||||
cancelled = true;
|
||||
};
|
||||
}, [server]); // Re-check when server config changes
|
||||
|
||||
return status;
|
||||
}
|
||||
@@ -1,39 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useAISettings } from './useAISettings';
|
||||
import { discoverMCPTools } from '@/lib/MCPClient';
|
||||
import type OpenAI from 'openai';
|
||||
import type { MCPClient } from '@/lib/MCPClient';
|
||||
|
||||
interface UseMCPToolsResult {
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
clients: Record<string, MCPClient>;
|
||||
isLoading: boolean;
|
||||
error: Error | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to discover and manage MCP tools from configured servers.
|
||||
*/
|
||||
export function useMCPTools(): UseMCPToolsResult {
|
||||
const { settings } = useAISettings();
|
||||
const mcpServers = settings.mcpServers || {};
|
||||
|
||||
const { data, isLoading, error } = useQuery({
|
||||
queryKey: ['mcp-tools', mcpServers],
|
||||
queryFn: async () => {
|
||||
if (Object.keys(mcpServers).length === 0) {
|
||||
return { tools: {}, clients: {} };
|
||||
}
|
||||
return await discoverMCPTools(mcpServers);
|
||||
},
|
||||
staleTime: 5 * 60 * 1000, // Cache for 5 minutes
|
||||
retry: 1,
|
||||
});
|
||||
|
||||
return {
|
||||
tools: data?.tools || {},
|
||||
clients: data?.clients || {},
|
||||
isLoading,
|
||||
error: error as Error | null,
|
||||
};
|
||||
}
|
||||
@@ -1,5 +1,5 @@
|
||||
import { useNostr } from "@nostrify/react";
|
||||
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
|
||||
import { useMutation, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
|
||||
|
||||
import { useCurrentUser } from "./useCurrentUser";
|
||||
|
||||
@@ -8,6 +8,7 @@ import type { NostrEvent } from "@nostrify/nostrify";
|
||||
export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
const { nostr } = useNostr();
|
||||
const { user } = useCurrentUser();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
mutationFn: async (t: Omit<NostrEvent, 'id' | 'pubkey' | 'sig'>) => {
|
||||
@@ -37,6 +38,52 @@ export function useNostrPublish(): UseMutationResult<NostrEvent> {
|
||||
},
|
||||
onSuccess: (data) => {
|
||||
console.log("Event published successfully:", data);
|
||||
|
||||
// Invalidate relevant queries based on event kind and tags
|
||||
const kind = data.kind;
|
||||
const tags = data.tags || [];
|
||||
|
||||
// Comments (kind 1111)
|
||||
if (kind === 1111) {
|
||||
// Invalidate all comment queries
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'comments'] });
|
||||
}
|
||||
|
||||
// Ratings and Emoji Reactions (kind 7)
|
||||
if (kind === 7) {
|
||||
// Invalidate rating queries for the target event
|
||||
const eTag = tags.find(([name]) => name === 'e')?.[1];
|
||||
if (eTag) {
|
||||
queryClient.invalidateQueries({ queryKey: ['ratings', eTag] });
|
||||
// Also invalidate comment reactions if this is a reaction to a comment
|
||||
queryClient.invalidateQueries({ queryKey: ['comment-reactions', eTag] });
|
||||
}
|
||||
}
|
||||
|
||||
// App submissions (kind 31733)
|
||||
if (kind === 31733) {
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
}
|
||||
|
||||
// Moderation lists (kind 30267)
|
||||
if (kind === 30267) {
|
||||
const dTag = tags.find(([name]) => name === 'd')?.[1];
|
||||
if (dTag?.includes('soapbox-')) {
|
||||
// Invalidate app submissions and showcase queries
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
}
|
||||
}
|
||||
|
||||
// Reports (kind 1984)
|
||||
if (kind === 1984) {
|
||||
// Invalidate app submissions and moderation queries
|
||||
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
|
||||
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
|
||||
}
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -1,5 +1,6 @@
|
||||
import { useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useNostrPublish } from '@/hooks/useNostrPublish';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { NKinds, type NostrEvent } from '@nostrify/nostrify';
|
||||
|
||||
interface PostCommentParams {
|
||||
@@ -11,6 +12,7 @@ interface PostCommentParams {
|
||||
/** Post a NIP-22 (kind 1111) comment on an event. */
|
||||
export function usePostComment() {
|
||||
const { mutateAsync: publishEvent } = useNostrPublish();
|
||||
const { user } = useCurrentUser();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
return useMutation({
|
||||
@@ -82,10 +84,61 @@ export function usePostComment() {
|
||||
|
||||
return event;
|
||||
},
|
||||
onMutate: async ({ root, reply, content }) => {
|
||||
if (!user) return;
|
||||
|
||||
const queryKey = ['nostr', 'comments', root instanceof URL ? root.toString() : root.id];
|
||||
|
||||
// Cancel any outgoing refetches
|
||||
await queryClient.cancelQueries({ queryKey });
|
||||
|
||||
// Snapshot the previous value
|
||||
const previousComments = queryClient.getQueryData(queryKey);
|
||||
|
||||
// Optimistically update the cache
|
||||
queryClient.setQueryData(queryKey, (old: unknown) => {
|
||||
if (!old || typeof old !== 'object') return old;
|
||||
|
||||
const commentsData = old as { allComments?: NostrEvent[]; topLevelComments?: NostrEvent[] };
|
||||
|
||||
// Create optimistic comment
|
||||
const optimisticComment: NostrEvent = {
|
||||
id: `temp-${Date.now()}`,
|
||||
pubkey: user.pubkey,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 1111,
|
||||
tags: [], // Tags will be filled properly by the actual event
|
||||
content,
|
||||
sig: ''
|
||||
};
|
||||
|
||||
// Add to allComments
|
||||
const newAllComments = [...(commentsData.allComments || []), optimisticComment];
|
||||
|
||||
// Add to topLevelComments if it's a top-level comment (no reply)
|
||||
const newTopLevelComments = !reply
|
||||
? [optimisticComment, ...(commentsData.topLevelComments || [])]
|
||||
: commentsData.topLevelComments;
|
||||
|
||||
return {
|
||||
...commentsData,
|
||||
allComments: newAllComments,
|
||||
topLevelComments: newTopLevelComments,
|
||||
};
|
||||
});
|
||||
|
||||
// Return a context object with the snapshotted value
|
||||
return { previousComments };
|
||||
},
|
||||
onError: (err, variables, context) => {
|
||||
// If the mutation fails, use the context returned from onMutate to roll back
|
||||
const queryKey = ['nostr', 'comments', variables.root instanceof URL ? variables.root.toString() : variables.root.id];
|
||||
queryClient.setQueryData(queryKey, context?.previousComments);
|
||||
},
|
||||
onSuccess: (_, { root }) => {
|
||||
// Invalidate and refetch comments
|
||||
// Invalidate and refetch comments to get the real data
|
||||
queryClient.invalidateQueries({
|
||||
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
|
||||
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
@@ -11,11 +11,11 @@ import { useGit } from './useGit';
|
||||
export function useProjectsManager() {
|
||||
const { fs } = useFS();
|
||||
const { git } = useGit();
|
||||
const { projectsPath, templatesPath } = useFSPaths();
|
||||
const { projectsPath } = useFSPaths();
|
||||
|
||||
const projectsManager = useMemo(() => {
|
||||
return new ProjectsManager({ fs, git, projectsPath, templatesPath });
|
||||
}, [fs, git, projectsPath, templatesPath]);
|
||||
return new ProjectsManager({ fs, git, projectsPath });
|
||||
}, [fs, git, projectsPath]);
|
||||
|
||||
return projectsManager;
|
||||
}
|
||||
@@ -113,16 +113,11 @@
|
||||
border-color: hsl(var(--border));
|
||||
}
|
||||
|
||||
html {
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
body {
|
||||
background-color: hsl(var(--background));
|
||||
color: hsl(var(--foreground));
|
||||
font-family: 'Inter Variable', 'Inter', 'system-ui', 'sans-serif';
|
||||
font-feature-settings: "rlig" 1, "calt" 1;
|
||||
overscroll-behavior: none;
|
||||
}
|
||||
|
||||
/* GitHub-style scrollbars */
|
||||
|
||||
@@ -260,67 +260,4 @@ invalid json line
|
||||
expect(sessionName1).not.toBe(sessionName2);
|
||||
});
|
||||
});
|
||||
|
||||
describe('readCost', () => {
|
||||
it('should return 0 when COST file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('File not found'));
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0);
|
||||
});
|
||||
|
||||
it('should read and parse cost from COST file', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('0.123456\n');
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0.123456);
|
||||
});
|
||||
|
||||
it('should return 0 for invalid cost value', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('invalid\n');
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0);
|
||||
});
|
||||
|
||||
it('should handle cost with whitespace', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(' 0.050000 \n');
|
||||
|
||||
const cost = await dotAI.readCost();
|
||||
expect(cost).toBe(0.05);
|
||||
});
|
||||
});
|
||||
|
||||
describe('writeCost', () => {
|
||||
it('should create shakespeare directory if it does not exist', async () => {
|
||||
await dotAI.writeCost(0.123456);
|
||||
|
||||
expect(mockFS.mkdir).toHaveBeenCalledWith('/test-project/.git/shakespeare', { recursive: true });
|
||||
});
|
||||
|
||||
it('should write cost with 6 decimal places', async () => {
|
||||
await dotAI.writeCost(0.123456789);
|
||||
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.git/shakespeare/COST',
|
||||
'0.123457\n'
|
||||
);
|
||||
});
|
||||
|
||||
it('should write zero cost correctly', async () => {
|
||||
await dotAI.writeCost(0);
|
||||
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
'/test-project/.git/shakespeare/COST',
|
||||
'0.000000\n'
|
||||
);
|
||||
});
|
||||
|
||||
it('should handle write errors gracefully', async () => {
|
||||
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Write failed'));
|
||||
|
||||
// Should not throw
|
||||
await expect(dotAI.writeCost(0.123456)).resolves.toBeUndefined();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -278,38 +278,4 @@ export class DotAI {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Read the accumulated cost from .git/shakespeare/COST file
|
||||
* @returns The accumulated cost as a number, or 0 if the file doesn't exist
|
||||
*/
|
||||
async readCost(): Promise<number> {
|
||||
try {
|
||||
const costPath = join(this.workingDir, ".git", "shakespeare", "COST");
|
||||
const content = await this.fs.readFile(costPath, "utf8");
|
||||
const cost = parseFloat(content.trim());
|
||||
return isNaN(cost) ? 0 : cost;
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Write the accumulated cost to .git/shakespeare/COST file
|
||||
* @param cost The accumulated cost in USD
|
||||
*/
|
||||
async writeCost(cost: number): Promise<void> {
|
||||
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
|
||||
const costPath = join(shakespeareDir, "COST");
|
||||
|
||||
try {
|
||||
// Ensure .git/shakespeare directory exists
|
||||
await this.fs.mkdir(shakespeareDir, { recursive: true });
|
||||
|
||||
// Write the cost with 6 decimal places for precision
|
||||
await this.fs.writeFile(costPath, cost.toFixed(6) + "\n");
|
||||
} catch (error) {
|
||||
console.warn(`Failed to write .git/shakespeare/COST file: ${error}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,167 +0,0 @@
|
||||
import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
||||
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
||||
import type { MCPServer } from '@/contexts/AISettingsContext';
|
||||
import type OpenAI from 'openai';
|
||||
|
||||
/**
|
||||
* MCP (Model Context Protocol) Client for discovering and executing tools from MCP servers.
|
||||
* Uses the official @modelcontextprotocol/sdk library.
|
||||
*/
|
||||
export class MCPClient {
|
||||
private client: Client;
|
||||
private transport: StreamableHTTPClientTransport;
|
||||
private connected = false;
|
||||
|
||||
constructor(server: MCPServer) {
|
||||
// Create the client
|
||||
this.client = new Client({
|
||||
name: 'shakespeare',
|
||||
version: '1.0.0',
|
||||
}, {
|
||||
capabilities: {}
|
||||
});
|
||||
|
||||
// Create HTTP transport with optional custom headers
|
||||
this.transport = new StreamableHTTPClientTransport(new URL(server.url), {
|
||||
requestInit: server.headers ? {
|
||||
headers: server.headers,
|
||||
} : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Connect to the MCP server.
|
||||
*/
|
||||
async connect(): Promise<void> {
|
||||
if (this.connected) return;
|
||||
|
||||
await this.client.connect(this.transport);
|
||||
this.connected = true;
|
||||
}
|
||||
|
||||
/**
|
||||
* List all available tools from the MCP server.
|
||||
*/
|
||||
async listTools(): Promise<Array<{
|
||||
name: string;
|
||||
description?: string;
|
||||
inputSchema: {
|
||||
type: 'object';
|
||||
properties?: Record<string, object>;
|
||||
required?: string[];
|
||||
};
|
||||
}>> {
|
||||
await this.connect();
|
||||
|
||||
const result = await this.client.listTools();
|
||||
return result.tools;
|
||||
}
|
||||
|
||||
/**
|
||||
* Call a tool on the MCP server.
|
||||
*/
|
||||
async callTool(name: string, args: Record<string, unknown>): Promise<string> {
|
||||
await this.connect();
|
||||
|
||||
const result = await this.client.callTool({
|
||||
name,
|
||||
arguments: args,
|
||||
});
|
||||
|
||||
const content = Array.isArray(result.content) ? result.content : [];
|
||||
|
||||
if (result.isError) {
|
||||
const errorText = content
|
||||
.filter((c): c is { type: 'text'; text: string } => c.type === 'text')
|
||||
.map(c => c.text)
|
||||
.join('\n');
|
||||
throw new Error(`MCP tool error: ${errorText}`);
|
||||
}
|
||||
|
||||
// Concatenate all text content from the response
|
||||
return content
|
||||
.filter((c): c is { type: 'text'; text: string } => c.type === 'text')
|
||||
.map(c => c.text)
|
||||
.join('\n');
|
||||
}
|
||||
|
||||
/**
|
||||
* Close the connection to the MCP server.
|
||||
*/
|
||||
async close(): Promise<void> {
|
||||
if (!this.connected) return;
|
||||
|
||||
await this.client.close();
|
||||
this.connected = false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert MCP tools to OpenAI tool format.
|
||||
*/
|
||||
static toOpenAITools(mcpTools: Array<{
|
||||
name: string;
|
||||
description?: string;
|
||||
inputSchema: {
|
||||
type: 'object';
|
||||
properties?: Record<string, object>;
|
||||
required?: string[];
|
||||
};
|
||||
}>): Record<string, OpenAI.Chat.Completions.ChatCompletionTool> {
|
||||
const tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||
|
||||
for (const tool of mcpTools) {
|
||||
tools[tool.name] = {
|
||||
type: 'function',
|
||||
function: {
|
||||
name: tool.name,
|
||||
description: tool.description || '',
|
||||
parameters: tool.inputSchema as Record<string, unknown>,
|
||||
},
|
||||
} as OpenAI.Chat.Completions.ChatCompletionTool;
|
||||
}
|
||||
|
||||
return tools;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Discover tools from all configured MCP servers.
|
||||
*/
|
||||
export async function discoverMCPTools(
|
||||
mcpServers: Record<string, MCPServer>
|
||||
): Promise<{
|
||||
tools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool>;
|
||||
clients: Record<string, MCPClient>;
|
||||
}> {
|
||||
const allTools: Record<string, OpenAI.Chat.Completions.ChatCompletionTool> = {};
|
||||
const clients: Record<string, MCPClient> = {};
|
||||
|
||||
for (const [serverName, serverConfig] of Object.entries(mcpServers)) {
|
||||
try {
|
||||
const client = new MCPClient(serverConfig);
|
||||
const mcpTools = await client.listTools();
|
||||
const openAITools = MCPClient.toOpenAITools(mcpTools);
|
||||
|
||||
// Store tools with server prefix to avoid name collisions
|
||||
for (const [toolName, tool] of Object.entries(openAITools)) {
|
||||
const prefixedName = `${serverName}__${toolName}`;
|
||||
const functionTool = tool as OpenAI.Chat.Completions.ChatCompletionTool & {
|
||||
function: { name: string; description: string; parameters: Record<string, unknown> }
|
||||
};
|
||||
allTools[prefixedName] = {
|
||||
type: 'function',
|
||||
function: {
|
||||
...functionTool.function,
|
||||
name: prefixedName,
|
||||
description: `[${serverName}] ${functionTool.function.description}`,
|
||||
},
|
||||
} as OpenAI.Chat.Completions.ChatCompletionTool;
|
||||
clients[prefixedName] = client;
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Failed to discover tools from MCP server "${serverName}":`, error);
|
||||
}
|
||||
}
|
||||
|
||||
return { tools: allTools, clients };
|
||||
}
|
||||
@@ -219,7 +219,7 @@ describe('ProjectsManager', () => {
|
||||
fs = new MockFS() as unknown as JSRuntimeFS;
|
||||
nostr = createMockNostr();
|
||||
git = new Git({ fs, nostr });
|
||||
projectsManager = new ProjectsManager({ fs, git, projectsPath: '/projects', templatesPath: '/templates' });
|
||||
projectsManager = new ProjectsManager({ fs, git });
|
||||
});
|
||||
|
||||
describe('getProjects', () => {
|
||||
|
||||
+36
-221
@@ -20,22 +20,18 @@ export interface ProjectsManagerOptions {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
/** Projects directory path (default: /projects) */
|
||||
projectsPath: string;
|
||||
/** Templates directory path (default: /templates) */
|
||||
templatesPath: string;
|
||||
projectsPath?: string;
|
||||
}
|
||||
|
||||
export class ProjectsManager {
|
||||
fs: JSRuntimeFS;
|
||||
git: Git;
|
||||
dir: string;
|
||||
templatesDir: string;
|
||||
|
||||
constructor(options: ProjectsManagerOptions) {
|
||||
this.fs = options.fs;
|
||||
this.git = options.git;
|
||||
this.dir = options.projectsPath;
|
||||
this.templatesDir = options.templatesPath;
|
||||
this.dir = options.projectsPath || '/projects';
|
||||
}
|
||||
|
||||
async init() {
|
||||
@@ -44,239 +40,58 @@ export class ProjectsManager {
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
try {
|
||||
await this.fs.mkdir(this.templatesDir);
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Ensure a template is cached locally and up-to-date.
|
||||
* Returns the path to the cached template.
|
||||
*
|
||||
* @param templateUrl - Git repository URL of the template
|
||||
* @param onUpdateError - Optional callback when template update fails (non-critical)
|
||||
* @returns Path to the cached template directory
|
||||
*/
|
||||
async updateTemplate(templateUrl: string, onUpdateError?: (error: Error) => void): Promise<string> {
|
||||
// Generate a safe directory name from the template URL
|
||||
const templateName = this.getTemplateNameFromUrl(templateUrl);
|
||||
const templatePath = `${this.templatesDir}/${templateName}`;
|
||||
async createProject(name: string, templateUrl: string, customId?: string): Promise<Project> {
|
||||
const project = await this.cloneProject(name, templateUrl, customId, { depth: 1 });
|
||||
|
||||
// Delete README.md if it exists
|
||||
try {
|
||||
// Check if template already exists
|
||||
await this.fs.stat(templatePath);
|
||||
|
||||
// Template exists, try to update it with force pull
|
||||
try {
|
||||
await this.forcePullTemplate(templatePath);
|
||||
} catch (updateError) {
|
||||
// Update failed, but we can continue with the existing template
|
||||
console.warn(`Failed to update template at ${templatePath}:`, updateError);
|
||||
if (onUpdateError) {
|
||||
onUpdateError(updateError instanceof Error ? updateError : new Error(String(updateError)));
|
||||
}
|
||||
}
|
||||
await this.fs.unlink(`${project.path}/README.md`);
|
||||
} catch {
|
||||
// Template doesn't exist, clone it shallowly
|
||||
await this.fs.mkdir(templatePath, { recursive: true });
|
||||
|
||||
try {
|
||||
await this.git.clone({
|
||||
dir: templatePath,
|
||||
url: templateUrl,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
});
|
||||
} catch (cloneError) {
|
||||
// Clean up on clone failure
|
||||
try {
|
||||
await this.deleteDirectory(templatePath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
throw cloneError;
|
||||
}
|
||||
// README.md might not exist, ignore error
|
||||
}
|
||||
|
||||
return templatePath;
|
||||
}
|
||||
// Delete .git directory and reinitialize
|
||||
try {
|
||||
await this.deleteDirectory(`${project.path}/.git`);
|
||||
} catch {
|
||||
// .git directory might not exist, ignore error
|
||||
}
|
||||
|
||||
/**
|
||||
* Force pull the template repository to match remote, discarding any local changes.
|
||||
* This ensures the template is always up-to-date with the remote.
|
||||
*/
|
||||
private async forcePullTemplate(templatePath: string): Promise<void> {
|
||||
// Fetch the latest changes from remote
|
||||
const fetchResult = await this.git.fetch({
|
||||
dir: templatePath,
|
||||
singleBranch: true,
|
||||
depth: 1,
|
||||
// Initialize new git repository
|
||||
await this.git.init({
|
||||
dir: project.path,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Get the current branch name
|
||||
const branch = fetchResult.defaultBranch;
|
||||
|
||||
if (!branch) {
|
||||
throw new Error('Could not determine current branch');
|
||||
}
|
||||
|
||||
// Reset hard to the remote branch, discarding all local changes
|
||||
await this.git.checkout({
|
||||
dir: templatePath,
|
||||
ref: branch,
|
||||
force: true,
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Generate a safe directory name from a template URL
|
||||
*/
|
||||
private getTemplateNameFromUrl(url: string): string {
|
||||
// Extract a meaningful name from the URL
|
||||
// e.g., "https://gitlab.com/soapbox-pub/mkstack.git" -> "mkstack"
|
||||
// e.g., "nostr://[email protected]/shakespeare.diy/mkstack" -> "mkstack"
|
||||
|
||||
let name = url;
|
||||
|
||||
// Remove .git suffix if present
|
||||
name = name.replace(/\.git$/, '');
|
||||
|
||||
// Remove trailing slash
|
||||
name = name.replace(/\/$/, '');
|
||||
|
||||
// Extract the last part of the path
|
||||
const parts = name.split('/');
|
||||
name = parts[parts.length - 1] || '';
|
||||
|
||||
// Sanitize the name to be filesystem-safe
|
||||
name = name
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
|
||||
if (!name) {
|
||||
throw new Error(`Could not derive template name from URL: ${url}`);
|
||||
}
|
||||
|
||||
return name;
|
||||
}
|
||||
|
||||
/**
|
||||
* Copy a directory recursively from source to destination
|
||||
*/
|
||||
private async copyDirectory(sourcePath: string, destPath: string): Promise<void> {
|
||||
// Ensure destination directory exists
|
||||
await this.fs.mkdir(destPath, { recursive: true });
|
||||
|
||||
const entries = await this.fs.readdir(sourcePath);
|
||||
|
||||
for (const entry of entries) {
|
||||
// Add all files to git
|
||||
const files = await this.getAllFiles(project.path);
|
||||
for (const file of files) {
|
||||
// Skip .git directory
|
||||
if (entry === '.git') continue;
|
||||
|
||||
const sourceFullPath = `${sourcePath}/${entry}`;
|
||||
const destFullPath = `${destPath}/${entry}`;
|
||||
|
||||
try {
|
||||
const stat = await this.fs.lstat(sourceFullPath);
|
||||
|
||||
if (stat.isDirectory()) {
|
||||
// Recursively copy subdirectories
|
||||
await this.copyDirectory(sourceFullPath, destFullPath);
|
||||
} else if (stat.isFile()) {
|
||||
// Copy file
|
||||
const content = await this.fs.readFile(sourceFullPath);
|
||||
await this.fs.writeFile(destFullPath, content);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to copy ${sourceFullPath}:`, error);
|
||||
// Continue copying other files
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: project.path,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void): Promise<Project> {
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
// Check if project with this ID already exists when using custom ID
|
||||
if (customId && await this.projectExists(id)) {
|
||||
throw new Error(`Project with ID "${id}" already exists`);
|
||||
}
|
||||
|
||||
const projectPath = `${this.dir}/${id}`;
|
||||
|
||||
// Ensure template is cached and up-to-date
|
||||
const templatePath = await this.updateTemplate(templateUrl, onTemplateUpdateError);
|
||||
|
||||
// Create project directory
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: project.path,
|
||||
message: 'New project created with Shakespeare',
|
||||
});
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
// Copy template to project directory (excluding .git)
|
||||
await this.copyDirectory(templatePath, projectPath);
|
||||
|
||||
// Delete README.md if it exists
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/README.md`);
|
||||
} catch {
|
||||
// README.md might not exist, ignore error
|
||||
}
|
||||
|
||||
// Initialize new git repository
|
||||
await this.git.init({
|
||||
dir: projectPath,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
const files = await this.getAllFiles(projectPath);
|
||||
for (const file of files) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: 'New project created with Shakespeare',
|
||||
});
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id),
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Clean up the directory that was created if project creation fails
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch (cleanupError) {
|
||||
// Log cleanup error but don't mask the original error
|
||||
console.warn('Failed to clean up directory after project creation failure:', cleanupError);
|
||||
}
|
||||
// Re-throw the original error
|
||||
throw error;
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||
|
||||
@@ -1,8 +1,6 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { SessionManager, type AIMessage } from './SessionManager';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type { AppConfig } from '@/contexts/AppContext';
|
||||
|
||||
// Mock the filesystem
|
||||
const mockFS: JSRuntimeFS = {
|
||||
@@ -24,40 +22,6 @@ const mockFS: JSRuntimeFS = {
|
||||
realpath: vi.fn(),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
// Mock NPool
|
||||
const mockNostr: NPool = {
|
||||
query: vi.fn(),
|
||||
req: vi.fn(),
|
||||
event: vi.fn(),
|
||||
} as unknown as NPool;
|
||||
|
||||
// Test configuration
|
||||
const testConfig: AppConfig = {
|
||||
theme: 'light',
|
||||
relayMetadata: {
|
||||
relays: [
|
||||
{ url: 'wss://relay.nostr.band', read: true, write: true },
|
||||
],
|
||||
updatedAt: 0,
|
||||
},
|
||||
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
|
||||
esmUrl: 'https://esm.shakespeare.diy',
|
||||
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
|
||||
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
|
||||
previewDomain: 'local-shakespeare.dev',
|
||||
language: 'en',
|
||||
showcaseEnabled: true,
|
||||
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
|
||||
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
|
||||
fsPathProjects: '/projects',
|
||||
fsPathConfig: '/config',
|
||||
fsPathTmp: '/tmp',
|
||||
fsPathPlugins: '/plugins',
|
||||
fsPathTemplates: '/templates',
|
||||
sentryDsn: '',
|
||||
sentryEnabled: false,
|
||||
};
|
||||
|
||||
describe('SessionManager', () => {
|
||||
let sessionManager: SessionManager;
|
||||
const mockAISettings = {
|
||||
@@ -71,10 +35,7 @@ describe('SessionManager', () => {
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
const getSettings = () => mockAISettings;
|
||||
const getConfig = () => testConfig;
|
||||
const getDefaultConfig = () => testConfig;
|
||||
sessionManager = new SessionManager(mockFS, mockNostr, getSettings, getConfig, getDefaultConfig);
|
||||
sessionManager = new SessionManager(mockFS, mockAISettings);
|
||||
});
|
||||
|
||||
it('should initialize streaming message with reasoning content', async () => {
|
||||
@@ -156,25 +117,4 @@ describe('SessionManager', () => {
|
||||
expect(updatedSession?.messages).toHaveLength(1); // Only the user message
|
||||
expect(updatedSession?.messages[0].role).toBe('user');
|
||||
});
|
||||
|
||||
it('should track when images are not supported and strip them on subsequent requests', async () => {
|
||||
const projectId = 'test-project';
|
||||
const tools = {};
|
||||
const customTools = {};
|
||||
|
||||
// Load a session
|
||||
const session = await sessionManager.loadSession(projectId, tools, customTools);
|
||||
|
||||
// Initially, images should not be marked as unsupported
|
||||
expect(session.imagesNotSupported).toBeUndefined();
|
||||
|
||||
// Simulate marking images as not supported (this would happen after an API error)
|
||||
session.imagesNotSupported = true;
|
||||
|
||||
// Verify the flag is set
|
||||
expect(session.imagesNotSupported).toBe(true);
|
||||
|
||||
// On subsequent requests, the SessionManager should proactively strip images
|
||||
// This prevents retrying with images on every message/tool call
|
||||
});
|
||||
});
|
||||
+31
-198
@@ -11,9 +11,6 @@ import { NostrMetadata } from '@nostrify/nostrify';
|
||||
import { MalformedToolCallError } from './errors/MalformedToolCallError';
|
||||
import { EmptyMessageError } from './errors/EmptyMessageError';
|
||||
import { isEmptyMessage } from './isEmptyMessage';
|
||||
import { Git } from './git';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type { AppConfig } from '@/contexts/AppContext';
|
||||
|
||||
export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | {
|
||||
role: 'assistant';
|
||||
@@ -40,7 +37,6 @@ export interface SessionState {
|
||||
abortController?: AbortController;
|
||||
totalCost?: number; // Total cost in USD for this session
|
||||
lastInputTokens?: number; // Input tokens from the last AI request
|
||||
imagesNotSupported?: boolean; // Track if this session's model doesn't support images
|
||||
}
|
||||
|
||||
export interface SessionManagerEvents {
|
||||
@@ -62,34 +58,29 @@ export class SessionManager {
|
||||
private sessions = new Map<string, SessionState>();
|
||||
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
|
||||
private fs: JSRuntimeFS;
|
||||
private nostr: NPool;
|
||||
private getSettings: () => { providers: AIProvider[] };
|
||||
private getConfig: () => AppConfig;
|
||||
private getDefaultConfig: () => AppConfig;
|
||||
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?: () => { user?: NUser; metadata?: NostrMetadata };
|
||||
private corsProxy?: string;
|
||||
private projectsPath: string;
|
||||
private pluginsPath?: string;
|
||||
|
||||
constructor(
|
||||
fs: JSRuntimeFS,
|
||||
nostr: NPool,
|
||||
getSettings: () => { providers: AIProvider[] },
|
||||
getConfig: () => AppConfig,
|
||||
getDefaultConfig: () => AppConfig,
|
||||
aiSettings: { providers: AIProvider[] },
|
||||
getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>,
|
||||
getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata },
|
||||
corsProxy?: string,
|
||||
projectsPath = '/projects',
|
||||
pluginsPath?: string,
|
||||
) {
|
||||
this.fs = fs;
|
||||
this.nostr = nostr;
|
||||
this.getSettings = getSettings;
|
||||
this.getConfig = getConfig;
|
||||
this.getDefaultConfig = getDefaultConfig;
|
||||
this.aiSettings = aiSettings;
|
||||
this.getProviderModels = getProviderModels;
|
||||
this.getCurrentUser = getCurrentUser;
|
||||
}
|
||||
|
||||
private get git(): Git {
|
||||
const config = this.getConfig();
|
||||
return new Git({ fs: this.fs, nostr: this.nostr, corsProxy: config.corsProxy });
|
||||
this.projectsPath = projectsPath;
|
||||
this.pluginsPath = pluginsPath;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -106,8 +97,7 @@ export class SessionManager {
|
||||
|
||||
// Try to load existing history
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
|
||||
const lastSession = await dotAI.readLastSessionHistory();
|
||||
if (lastSession) {
|
||||
messages = lastSession.messages;
|
||||
@@ -164,7 +154,7 @@ export class SessionManager {
|
||||
*/
|
||||
async deleteSession(projectId: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
session?.abortController?.abort('Session deleted');
|
||||
session?.abortController?.abort();
|
||||
|
||||
this.sessions.delete(projectId);
|
||||
|
||||
@@ -188,11 +178,7 @@ export class SessionManager {
|
||||
/**
|
||||
* Send a message and start AI generation
|
||||
*/
|
||||
async sendMessage(
|
||||
projectId: string,
|
||||
content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage>,
|
||||
providerModel: string
|
||||
): Promise<void> {
|
||||
async sendMessage(projectId: string, content: string | Array<OpenAI.Chat.Completions.ChatCompletionContentPartText>, providerModel: string): Promise<void> {
|
||||
const session = this.sessions.get(projectId);
|
||||
|
||||
if (!session || session.isLoading) return;
|
||||
@@ -223,19 +209,14 @@ export class SessionManager {
|
||||
this.emit('loadingChanged', projectId, true);
|
||||
|
||||
try {
|
||||
// Get latest config and settings
|
||||
const config = this.getConfig();
|
||||
const defaultConfig = this.getDefaultConfig();
|
||||
const settings = this.getSettings();
|
||||
|
||||
// Parse provider and model
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const provider = parsed.provider;
|
||||
const model = parsed.model;
|
||||
|
||||
// Initialize OpenAI client
|
||||
const { user, metadata } = this.getCurrentUser?.() ?? {};
|
||||
const openai = createAIClient(provider, user, config.corsProxy);
|
||||
const openai = createAIClient(provider, user, this.corsProxy);
|
||||
|
||||
let stepCount = 0;
|
||||
const maxSteps = session.maxSteps || 50;
|
||||
@@ -257,95 +238,22 @@ export class SessionManager {
|
||||
tool_calls: undefined
|
||||
};
|
||||
|
||||
// Get repository URL if available
|
||||
let repositoryUrl: string | undefined;
|
||||
try {
|
||||
const remoteUrl = await this.git.getRemoteURL(`${config.fsPathProjects}/${projectId}`, 'origin');
|
||||
repositoryUrl = remoteUrl || undefined;
|
||||
} catch {
|
||||
// No repository URL available
|
||||
}
|
||||
|
||||
const systemPrompt = await makeSystemPrompt({
|
||||
cwd: `${config.fsPathProjects}/${projectId}`,
|
||||
cwd: `${this.projectsPath}/${projectId}`,
|
||||
fs: this.fs,
|
||||
mode: "agent",
|
||||
name: "Shakespeare",
|
||||
profession: "software extraordinaire",
|
||||
tools: Object.values(session.tools),
|
||||
config,
|
||||
defaultConfig,
|
||||
pluginsPath: this.pluginsPath,
|
||||
user,
|
||||
metadata,
|
||||
repositoryUrl,
|
||||
template: config.systemPrompt,
|
||||
});
|
||||
|
||||
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
|
||||
const filterSupportedImages = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
|
||||
return msgs.map(msg => {
|
||||
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
|
||||
const filteredContent = msg.content.filter(part => {
|
||||
if (part.type !== 'image_url') return true;
|
||||
|
||||
const imagePart = part as OpenAI.Chat.Completions.ChatCompletionContentPartImage;
|
||||
const url = imagePart.image_url.url.toLowerCase();
|
||||
|
||||
// Keep only JPG/JPEG/PNG images
|
||||
// Check file extension or data URL MIME type
|
||||
return /\.(jpg|jpeg|png)(\?|$)/.test(url) ||
|
||||
url.startsWith('data:image/jpeg') ||
|
||||
url.startsWith('data:image/png') ||
|
||||
url.startsWith('data:image/jpg');
|
||||
});
|
||||
|
||||
return {
|
||||
...msg,
|
||||
content: filteredContent
|
||||
};
|
||||
}
|
||||
return msg;
|
||||
});
|
||||
};
|
||||
|
||||
// Helper function to strip all image_url parts but keep text parts (including VFS paths)
|
||||
const stripImageUrls = (msgs: OpenAI.Chat.Completions.ChatCompletionMessageParam[]): OpenAI.Chat.Completions.ChatCompletionMessageParam[] => {
|
||||
return msgs.map(msg => {
|
||||
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
|
||||
// Keep only text parts (this includes "Added file: /tmp/..." paths)
|
||||
const textParts = msg.content.filter(part => part.type === 'text');
|
||||
|
||||
// If we had images, convert to string content (or empty if no text)
|
||||
if (textParts.length > 0) {
|
||||
return {
|
||||
...msg,
|
||||
content: textParts.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartText).text).join('\n')
|
||||
};
|
||||
}
|
||||
|
||||
// If no text parts, return empty string
|
||||
return {
|
||||
...msg,
|
||||
content: ''
|
||||
};
|
||||
}
|
||||
return msg;
|
||||
});
|
||||
};
|
||||
|
||||
// Prepare messages for AI
|
||||
// Note: User messages with image_url content parts are valid ChatCompletionMessageParam types
|
||||
// The AIMessage type includes ChatCompletionMessageParam, so this cast is safe
|
||||
let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = (systemPrompt
|
||||
const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt
|
||||
? [{ role: 'system', content: systemPrompt }, ...session.messages]
|
||||
: session.messages) as OpenAI.Chat.Completions.ChatCompletionMessageParam[];
|
||||
|
||||
// Filter out unsupported image formats (keep only JPG/JPEG/PNG for API)
|
||||
// This ensures the UI shows all image types, but API only receives supported formats
|
||||
messages = filterSupportedImages(messages);
|
||||
|
||||
// If this session has already determined images aren't supported, strip them proactively
|
||||
if (session.imagesNotSupported) {
|
||||
messages = stripImageUrls(messages);
|
||||
}
|
||||
: session.messages;
|
||||
|
||||
// Prepare completion options
|
||||
const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
@@ -358,56 +266,11 @@ export class SessionManager {
|
||||
},
|
||||
};
|
||||
|
||||
// Check if messages contain any images (for retry logic)
|
||||
const hasImages = messages.some(msg => {
|
||||
if (msg.role === 'user' && typeof msg.content !== 'string' && Array.isArray(msg.content)) {
|
||||
return msg.content.some(part => part.type === 'image_url');
|
||||
}
|
||||
return false;
|
||||
// Generate streaming response
|
||||
const stream = await openai.chat.completions.create(completionOptions, {
|
||||
signal: session.abortController?.signal
|
||||
});
|
||||
|
||||
// Generate streaming response with retry logic for models that don't support images
|
||||
let stream: AsyncIterable<OpenAI.Chat.Completions.ChatCompletionChunk>;
|
||||
let retriedWithoutImages = false;
|
||||
|
||||
try {
|
||||
stream = await openai.chat.completions.create(completionOptions, {
|
||||
signal: session.abortController?.signal
|
||||
});
|
||||
} catch (error) {
|
||||
// Check if this might be an image-related error and we have images to strip
|
||||
const errorObj = error as Record<string, unknown>;
|
||||
const errorStatus = typeof errorObj?.status === 'number' ? errorObj.status : undefined;
|
||||
const isPotentialImageError = errorStatus === 400 || errorStatus === 404 || errorStatus === 500;
|
||||
|
||||
if (isPotentialImageError && hasImages && !retriedWithoutImages) {
|
||||
console.warn('API call failed, retrying without image_url parts (keeping VFS paths):', error);
|
||||
retriedWithoutImages = true;
|
||||
|
||||
// Strip image_url parts but keep text parts (including VFS paths)
|
||||
const messagesWithoutImages = stripImageUrls(messages);
|
||||
|
||||
// Update completion options with stripped messages
|
||||
const retryOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = {
|
||||
...completionOptions,
|
||||
messages: messagesWithoutImages
|
||||
};
|
||||
|
||||
// Retry the API call - if this succeeds, we know images were the problem
|
||||
stream = await openai.chat.completions.create(retryOptions, {
|
||||
signal: session.abortController?.signal
|
||||
});
|
||||
|
||||
// SUCCESS: The retry without images worked, so this model doesn't support images
|
||||
// Mark this session as not supporting images to avoid future retries
|
||||
session.imagesNotSupported = true;
|
||||
console.log('Retry without images succeeded - marking this session as not supporting images');
|
||||
} else {
|
||||
// Re-throw if not a potential image error or already retried
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
let accumulatedContent = '';
|
||||
let accumulatedReasoningContent = '';
|
||||
const accumulatedToolCalls: OpenAI.Chat.Completions.ChatCompletionMessageToolCall[] = [];
|
||||
@@ -617,7 +480,7 @@ export class SessionManager {
|
||||
const session = this.sessions.get(projectId);
|
||||
if (!session) return;
|
||||
|
||||
session.abortController?.abort('User stopped generation');
|
||||
session.abortController?.abort();
|
||||
session.isLoading = false;
|
||||
session.streamingMessage = undefined;
|
||||
session.abortController = undefined;
|
||||
@@ -661,7 +524,7 @@ export class SessionManager {
|
||||
/**
|
||||
* Update session cost and context usage based on usage data
|
||||
*/
|
||||
private async updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): Promise<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);
|
||||
@@ -671,16 +534,12 @@ export class SessionManager {
|
||||
if (typeof usage.cost === 'number') {
|
||||
session.totalCost = (session.totalCost || 0) + usage.cost;
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
|
||||
// Accumulate cost to project total
|
||||
await this.accumulateProjectCost(projectId, usage.cost);
|
||||
return;
|
||||
}
|
||||
|
||||
// Otherwise, get the cost from the models endpoint
|
||||
try {
|
||||
const settings = this.getSettings();
|
||||
const parsed = parseProviderModel(providerModel, settings.providers);
|
||||
const parsed = parseProviderModel(providerModel, this.aiSettings.providers);
|
||||
const modelName = parsed.model;
|
||||
const provider = parsed.provider;
|
||||
|
||||
@@ -704,9 +563,6 @@ export class SessionManager {
|
||||
// Update session total cost
|
||||
session.totalCost = (session.totalCost || 0) + requestCost;
|
||||
this.emit('costUpdated', projectId, session.totalCost);
|
||||
|
||||
// Accumulate cost to project total
|
||||
await this.accumulateProjectCost(projectId, requestCost);
|
||||
} catch (error) {
|
||||
console.warn('Failed to calculate session cost:', error);
|
||||
}
|
||||
@@ -720,36 +576,13 @@ export class SessionManager {
|
||||
if (!session) return;
|
||||
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${session.projectId}`);
|
||||
// Cast to ChatCompletionMessageParam[] - user messages with image arrays are valid
|
||||
await dotAI.setHistory(session.sessionName, session.messages as OpenAI.Chat.Completions.ChatCompletionMessageParam[]);
|
||||
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`);
|
||||
await dotAI.setHistory(session.sessionName, session.messages);
|
||||
} catch (error) {
|
||||
console.warn('Failed to save session history:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Accumulate request cost to the project's total cost file
|
||||
*/
|
||||
private async accumulateProjectCost(projectId: string, requestCost: number): Promise<void> {
|
||||
try {
|
||||
const config = this.getConfig();
|
||||
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
|
||||
|
||||
// Read current project total
|
||||
const currentTotal = await dotAI.readCost();
|
||||
|
||||
// Add this request's cost
|
||||
const newTotal = currentTotal + requestCost;
|
||||
|
||||
// Write back the new total
|
||||
await dotAI.writeCost(newTotal);
|
||||
} catch (error) {
|
||||
console.warn('Failed to accumulate project cost:', error);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Simplified event system
|
||||
*/
|
||||
|
||||
@@ -243,12 +243,14 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
|
||||
// Handle bare imports like "react"
|
||||
build.onResolve({ filter: /^[^./].*/ }, (args) => {
|
||||
const [path, query] = args.path.split("?");
|
||||
const params = new URLSearchParams(query);
|
||||
// HACK: https://github.com/esm-dev/esm.sh/issues/1217
|
||||
if (args.path === "yet-another-react-lightbox/styles.css") {
|
||||
args.path = "yet-another-react-lightbox/dist/styles.css";
|
||||
}
|
||||
|
||||
const packageName = path.startsWith("@")
|
||||
? path.split("/").slice(0, 2).join("/")
|
||||
: path.split("/")[0];
|
||||
const packageName = args.path.startsWith("@")
|
||||
? args.path.split("/").slice(0, 2).join("/")
|
||||
: args.path.split("/")[0];
|
||||
|
||||
// If the importer is CSS, ignore (no JS deps)
|
||||
try {
|
||||
@@ -317,7 +319,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
}
|
||||
}
|
||||
|
||||
const packagePath = path.slice(packageName.length);
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
const specifier = version
|
||||
? `${cdnName}@${version}${packagePath}`
|
||||
: `${cdnName}${packagePath}`;
|
||||
@@ -337,14 +339,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
};
|
||||
}
|
||||
|
||||
// https://vite.dev/guide/assets#explicit-url-imports
|
||||
if (params.has("url")) {
|
||||
return {
|
||||
path: urlStr,
|
||||
namespace: "esm-file-external",
|
||||
};
|
||||
}
|
||||
|
||||
return {
|
||||
path: urlStr,
|
||||
namespace: "esm",
|
||||
@@ -432,8 +426,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
loader = "js";
|
||||
} else if (contentType === "text/css") {
|
||||
loader = "css";
|
||||
} else if (contentType === "application/wasm") {
|
||||
loader = "binary";
|
||||
} else {
|
||||
loader = "text";
|
||||
}
|
||||
@@ -446,14 +438,6 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
|
||||
loader,
|
||||
};
|
||||
});
|
||||
|
||||
// Convert `?url` imports to URL strings pointing to the ESM CDN
|
||||
build.onLoad({ filter: /.*/, namespace: "esm-file-external" }, (args) => {
|
||||
return {
|
||||
contents: `export default ${JSON.stringify(args.path)};`,
|
||||
loader: "js",
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
@@ -24,7 +24,7 @@ async function bundle(
|
||||
options: BuildProjectOptions,
|
||||
): Promise<Record<string, Uint8Array>> {
|
||||
const { fs, projectPath, domParser, target = "esnext", esmUrl } = options;
|
||||
const esbuild = await getEsbuild();
|
||||
const esbuild = await getEsbuild(esmUrl);
|
||||
|
||||
const indexHtmlText = await fs.readFile(
|
||||
`${projectPath}/index.html`,
|
||||
|
||||
@@ -1,95 +0,0 @@
|
||||
import type OpenAI from 'openai';
|
||||
import type { JSRuntimeFS } from '@/lib/JSRuntime';
|
||||
import { saveFileToTmp } from './fileUtils';
|
||||
import { fileToUrl } from './imageUtils';
|
||||
|
||||
type ContentPart = OpenAI.Chat.Completions.ChatCompletionContentPartText | OpenAI.Chat.Completions.ChatCompletionContentPartImage;
|
||||
|
||||
/**
|
||||
* Builds message content from text input and attached files.
|
||||
*
|
||||
* - All image formats are included in the message content for UI display
|
||||
* - SessionManager filters to only pass JPG/JPEG/PNG to the OpenAI API
|
||||
* - All files are saved to VFS and get a text part with the path
|
||||
* - Images are converted to base64-encoded data URLs for API consumption
|
||||
*
|
||||
* Returns content as either a string (for simple text) or an array of content parts.
|
||||
*
|
||||
* @param input - User text input
|
||||
* @param attachedFiles - Array of files to attach
|
||||
* @param fs - Filesystem instance for saving files
|
||||
* @param tmpPath - Temporary directory path for file storage
|
||||
* @returns Promise resolving to message content (string or array of content parts)
|
||||
*/
|
||||
export async function buildMessageContent(
|
||||
input: string,
|
||||
attachedFiles: File[],
|
||||
fs: JSRuntimeFS,
|
||||
tmpPath = '/tmp'
|
||||
): Promise<string | ContentPart[]> {
|
||||
const contentParts: ContentPart[] = [];
|
||||
|
||||
// Add user input as text part if present
|
||||
if (input.trim()) {
|
||||
contentParts.push({
|
||||
type: 'text',
|
||||
text: input.trim()
|
||||
});
|
||||
}
|
||||
|
||||
// Process attached files: save to VFS and add image_url for UI display (all image types)
|
||||
if (attachedFiles.length > 0) {
|
||||
const filePromises = attachedFiles.map(async (file) => {
|
||||
try {
|
||||
// Save file to VFS (always do this)
|
||||
const savedPath = await saveFileToTmp(fs, file, tmpPath);
|
||||
|
||||
// Always add text part with VFS path
|
||||
const textPart: ContentPart = {
|
||||
type: 'text',
|
||||
text: `Added file: ${savedPath}`
|
||||
};
|
||||
|
||||
// For all image types, also add as image_url for UI display with base64 encoding
|
||||
const isImage = file.type.startsWith('image/');
|
||||
if (isImage) {
|
||||
try {
|
||||
const imageUrl = await fileToUrl(file);
|
||||
// Return both parts: image_url for UI display and text for VFS path
|
||||
return [textPart, {
|
||||
type: 'image_url' as const,
|
||||
image_url: { url: imageUrl }
|
||||
}];
|
||||
} catch (error) {
|
||||
// If URL conversion fails, just use text part
|
||||
console.warn('Failed to convert image to base64, using text part only:', error);
|
||||
}
|
||||
}
|
||||
|
||||
return [textPart];
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
return [{
|
||||
type: 'text' as const,
|
||||
text: `Failed to save file: ${file.name}`
|
||||
}];
|
||||
}
|
||||
});
|
||||
|
||||
const fileResults = await Promise.all(filePromises);
|
||||
|
||||
// Flatten the results (each file can return multiple parts)
|
||||
for (const parts of fileResults) {
|
||||
contentParts.push(...parts);
|
||||
}
|
||||
}
|
||||
|
||||
// Return as string if single text part, otherwise return array
|
||||
if (contentParts.length === 1 && contentParts[0].type === 'text') {
|
||||
return contentParts[0].text;
|
||||
}
|
||||
|
||||
// Return array for multiple parts or if contains image URLs
|
||||
return contentParts;
|
||||
}
|
||||
|
||||
@@ -609,7 +609,7 @@ Commands are executed through the `ShellTool` which handles:
|
||||
import { ShellTool } from '@/lib/tools/ShellTool';
|
||||
|
||||
// Create shell tool with filesystem and working directory
|
||||
const shell = new ShellTool(fs, '/project/root', ...rest);
|
||||
const shell = new ShellTool(fs, '/project/root');
|
||||
|
||||
// Execute commands
|
||||
const result = await shell.execute({ command: 'cat package.json' });
|
||||
|
||||
@@ -23,10 +23,9 @@ const mockFS: JSRuntimeFS = {
|
||||
|
||||
describe('CurlCommand', () => {
|
||||
let curlCommand: CurlCommand;
|
||||
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
|
||||
|
||||
beforeEach(() => {
|
||||
curlCommand = new CurlCommand(mockFS, testCorsProxy);
|
||||
curlCommand = new CurlCommand(mockFS);
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
|
||||
@@ -3,7 +3,6 @@ import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
import { isAbsolutePath, validateWritePath } from "../security";
|
||||
import { proxyUrl } from "../proxyUrl";
|
||||
|
||||
/**
|
||||
* Parsed curl options
|
||||
@@ -36,11 +35,9 @@ export class CurlCommand implements ShellCommand {
|
||||
usage = 'curl [options] <url>';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
private corsProxy: string;
|
||||
|
||||
constructor(fs: JSRuntimeFS, corsProxy: string) {
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
this.corsProxy = corsProxy;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
|
||||
@@ -64,9 +61,9 @@ export class CurlCommand implements ShellCommand {
|
||||
return createErrorResult(`${this.name}: unsupported protocol: ${url.protocol}`);
|
||||
}
|
||||
|
||||
// Proxy the URL through configured CorsProxy
|
||||
// Proxy the URL through CorsProxy
|
||||
const originalUrl = url.toString();
|
||||
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
|
||||
const proxiedUrl = `https://proxy.shakespeare.diy/?url=${encodeURIComponent(originalUrl)}`;
|
||||
|
||||
// Prepare request
|
||||
const requestInit: RequestInit = {
|
||||
@@ -96,7 +93,7 @@ export class CurlCommand implements ShellCommand {
|
||||
let timeoutId: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
if (options.timeout) {
|
||||
timeoutId = setTimeout(() => controller.abort('Request timeout'), options.timeout * 1000);
|
||||
timeoutId = setTimeout(() => controller.abort(), options.timeout * 1000);
|
||||
requestInit.signal = controller.signal;
|
||||
}
|
||||
|
||||
|
||||
@@ -28,12 +28,13 @@ export interface GitSubcommand {
|
||||
name: string;
|
||||
description: string;
|
||||
usage: string;
|
||||
execute(args: string[], cwd: string): Promise<ShellCommandResult>;
|
||||
execute(args: string[]): Promise<ShellCommandResult>;
|
||||
}
|
||||
|
||||
export interface GitSubcommandOptions {
|
||||
git: Git;
|
||||
fs: JSRuntimeFS;
|
||||
pwd: string;
|
||||
signer?: NostrSigner;
|
||||
}
|
||||
|
||||
@@ -70,6 +71,7 @@ export class GitCommand implements ShellCommand {
|
||||
const subcommandOptions: GitSubcommandOptions = {
|
||||
git: this.git,
|
||||
fs: this.fs,
|
||||
pwd: this.cwd,
|
||||
signer: this.signer,
|
||||
};
|
||||
|
||||
@@ -97,7 +99,7 @@ export class GitCommand implements ShellCommand {
|
||||
this.subcommands.set(subcommand.name, subcommand);
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[], _cwd: string, _input?: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Handle no arguments or help
|
||||
if (args.length === 0 || args[0] === '--help' || args[0] === '-h') {
|
||||
@@ -118,9 +120,8 @@ export class GitCommand implements ShellCommand {
|
||||
return createErrorResult(`git: '${subcommandName}' is not a git command. See 'git --help'.`);
|
||||
}
|
||||
|
||||
// Execute the subcommand, passing the current working directory
|
||||
// This ensures git commands use the correct directory after 'cd' commands
|
||||
return await subcommand.execute(subcommandArgs, cwd);
|
||||
// Execute the subcommand
|
||||
return await subcommand.execute(subcommandArgs);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`git: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
|
||||
@@ -57,6 +57,7 @@ describe('GitAddCommand', () => {
|
||||
addCommand = new GitAddCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -70,14 +71,14 @@ describe('GitAddCommand', () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await addCommand.execute(['file.txt'], testCwd);
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should return error when no files specified', async () => {
|
||||
const result = await addCommand.execute([], testCwd);
|
||||
const result = await addCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Nothing specified, nothing added');
|
||||
@@ -94,7 +95,7 @@ describe('GitAddCommand', () => {
|
||||
['staged.txt', 1, 2, 2], // Already staged file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all'], testCwd);
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe(''); // Git add is silent on success
|
||||
@@ -117,7 +118,7 @@ describe('GitAddCommand', () => {
|
||||
['deleted.txt', 1, 0, 1], // Deleted file (not staged)
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all'], testCwd);
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
@@ -131,7 +132,7 @@ describe('GitAddCommand', () => {
|
||||
});
|
||||
|
||||
it('should add specific file', async () => {
|
||||
const result = await addCommand.execute(['file.txt'], testCwd);
|
||||
const result = await addCommand.execute(['file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
@@ -150,7 +151,7 @@ describe('GitAddCommand', () => {
|
||||
['deleted.txt', 1, 0, 1], // Deleted file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['.'], testCwd);
|
||||
const result = await addCommand.execute(['.']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
@@ -173,7 +174,7 @@ describe('GitAddCommand', () => {
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await addCommand.execute(['/absolute/path/file.txt'], testCwd);
|
||||
const result = await addCommand.execute(['/absolute/path/file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
@@ -204,7 +205,7 @@ describe('GitAddCommand', () => {
|
||||
// Mock git.remove to also throw error (file doesn't exist in git either)
|
||||
vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found'));
|
||||
|
||||
const result = await addCommand.execute(['nonexistent.txt'], testCwd);
|
||||
const result = await addCommand.execute(['nonexistent.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files');
|
||||
@@ -215,7 +216,7 @@ describe('GitAddCommand', () => {
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['-A'], testCwd);
|
||||
const result = await addCommand.execute(['-A']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
@@ -232,7 +233,7 @@ describe('GitAddCommand', () => {
|
||||
['modified.txt', 1, 2, 1], // Modified file
|
||||
]);
|
||||
|
||||
const result = await addCommand.execute(['--all', 'specific.txt'], testCwd);
|
||||
const result = await addCommand.execute(['--all', 'specific.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
|
||||
@@ -241,7 +242,7 @@ describe('GitAddCommand', () => {
|
||||
});
|
||||
|
||||
it('should handle double dash separator', async () => {
|
||||
const result = await addCommand.execute(['--', 'file.txt'], testCwd);
|
||||
const result = await addCommand.execute(['--', 'file.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
@@ -266,7 +267,7 @@ describe('GitAddCommand', () => {
|
||||
return Promise.resolve();
|
||||
});
|
||||
|
||||
const result = await addCommand.execute(['--all'], testCwd);
|
||||
const result = await addCommand.execute(['--all']);
|
||||
|
||||
expect(result.exitCode).toBe(0); // Should still succeed overall
|
||||
expect(mockGit.add).toHaveBeenCalledTimes(2);
|
||||
|
||||
+31
-21
@@ -12,17 +12,19 @@ export class GitAddCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -31,12 +33,12 @@ export class GitAddCommand implements GitSubcommand {
|
||||
|
||||
if (options.all) {
|
||||
// Add all files (git add -A)
|
||||
return await this.addAllFiles(cwd);
|
||||
return await this.addAllFiles();
|
||||
} else if (paths.length === 0) {
|
||||
return createErrorResult('Nothing specified, nothing added.\nMaybe you wanted to say \'git add .\'?');
|
||||
} else {
|
||||
// Add specific files
|
||||
return await this.addSpecificFiles(paths, cwd);
|
||||
return await this.addSpecificFiles(paths);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -68,11 +70,11 @@ export class GitAddCommand implements GitSubcommand {
|
||||
return { options, paths };
|
||||
}
|
||||
|
||||
private async addAllFiles(cwd: string): Promise<ShellCommandResult> {
|
||||
private async addAllFiles(): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Get status to find all changed files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
@@ -80,13 +82,15 @@ export class GitAddCommand implements GitSubcommand {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted in working directory
|
||||
await this.git.remove({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
await this.git.add({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
}
|
||||
@@ -104,7 +108,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async addSpecificFiles(paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async addSpecificFiles(paths: string[]): Promise<ShellCommandResult> {
|
||||
const addedFiles: string[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
@@ -113,7 +117,8 @@ export class GitAddCommand implements GitSubcommand {
|
||||
if (path === '.') {
|
||||
// Add current directory (all files in it)
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
@@ -121,14 +126,16 @@ export class GitAddCommand implements GitSubcommand {
|
||||
if (workdirStatus === 0 && headStatus === 1) {
|
||||
// File was deleted in working directory
|
||||
await this.git.remove({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedFiles.push(filepath);
|
||||
} else if (workdirStatus === 2 && stageStatus !== 2) {
|
||||
// File exists and has changes that aren't staged yet
|
||||
await this.git.add({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
addedFiles.push(filepath);
|
||||
@@ -144,7 +151,7 @@ export class GitAddCommand implements GitSubcommand {
|
||||
continue;
|
||||
}
|
||||
|
||||
const absolutePath = join(cwd, path);
|
||||
const absolutePath = join(this.pwd, path);
|
||||
|
||||
// Check if file/directory exists
|
||||
try {
|
||||
@@ -152,11 +159,12 @@ export class GitAddCommand implements GitSubcommand {
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
// Add all files in directory
|
||||
await this.addDirectory(path, addedFiles, cwd);
|
||||
await this.addDirectory(path, addedFiles);
|
||||
} else {
|
||||
// Add single file
|
||||
await this.git.add({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
addedFiles.push(path);
|
||||
@@ -165,7 +173,8 @@ export class GitAddCommand implements GitSubcommand {
|
||||
// Check if it's a deleted file
|
||||
try {
|
||||
await this.git.remove({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: path,
|
||||
});
|
||||
addedFiles.push(path);
|
||||
@@ -187,8 +196,8 @@ export class GitAddCommand implements GitSubcommand {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
private async addDirectory(dirPath: string, addedFiles: string[], cwd: string): Promise<void> {
|
||||
const absolutePath = join(cwd, dirPath);
|
||||
private async addDirectory(dirPath: string, addedFiles: string[]): Promise<void> {
|
||||
const absolutePath = join(this.pwd, dirPath);
|
||||
const entries = await this.fs.readdir(absolutePath, { withFileTypes: true });
|
||||
|
||||
for (const entry of entries) {
|
||||
@@ -199,11 +208,12 @@ export class GitAddCommand implements GitSubcommand {
|
||||
const entryPath = join(dirPath, entry.name);
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
await this.addDirectory(entryPath, addedFiles, cwd);
|
||||
await this.addDirectory(entryPath, addedFiles);
|
||||
} else {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: entryPath,
|
||||
});
|
||||
addedFiles.push(entryPath);
|
||||
@@ -213,4 +223,4 @@ export class GitAddCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,19 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -30,13 +32,13 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
return await this.listBranches(cwd);
|
||||
return await this.listBranches();
|
||||
case 'create':
|
||||
return await this.createBranch(branchName!, cwd);
|
||||
return await this.createBranch(branchName!);
|
||||
case 'delete':
|
||||
return await this.deleteBranch(branchName!, options.force, cwd);
|
||||
return await this.deleteBranch(branchName!, options.force);
|
||||
default:
|
||||
return await this.listBranches(cwd);
|
||||
return await this.listBranches();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -81,10 +83,10 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
return { action, branchName, options };
|
||||
}
|
||||
|
||||
private async listBranches(cwd: string): Promise<ShellCommandResult> {
|
||||
private async listBranches(): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const branches = await this.git.listBranches({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (branches.length === 0) {
|
||||
@@ -96,7 +98,7 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
// Might be in detached HEAD state
|
||||
@@ -118,11 +120,11 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async createBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async createBranch(branchName: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if branch already exists
|
||||
const branches = await this.git.listBranches({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (branches.includes(branchName)) {
|
||||
@@ -134,7 +136,7 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
try {
|
||||
currentRef = await this.git.resolveRef({
|
||||
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
} catch {
|
||||
@@ -143,7 +145,7 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
|
||||
// Create the new branch
|
||||
await this.git.branch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: branchName,
|
||||
object: currentRef,
|
||||
});
|
||||
@@ -155,11 +157,11 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteBranch(branchName: string, force: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||
private async deleteBranch(branchName: string, force: boolean): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if branch exists
|
||||
const branches = await this.git.listBranches({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (!branches.includes(branchName)) {
|
||||
@@ -171,19 +173,19 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
// Continue
|
||||
}
|
||||
|
||||
if (currentBranch === branchName) {
|
||||
return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${cwd}'`);
|
||||
return createErrorResult(`error: Cannot delete branch '${branchName}' checked out at '${this.pwd}'`);
|
||||
}
|
||||
|
||||
// Delete the branch
|
||||
await this.git.deleteBranch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: branchName,
|
||||
});
|
||||
|
||||
@@ -196,4 +198,4 @@ export class GitBranchCommand implements GitSubcommand {
|
||||
return createErrorResult(`Failed to delete branch: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,19 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -30,11 +32,11 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
|
||||
switch (action) {
|
||||
case 'switch':
|
||||
return await this.switchBranch(target!, cwd);
|
||||
return await this.switchBranch(target!);
|
||||
case 'create':
|
||||
return await this.createAndSwitchBranch(target!, cwd);
|
||||
return await this.createAndSwitchBranch(target!);
|
||||
case 'restore':
|
||||
return await this.restoreFiles(target!, cwd);
|
||||
return await this.restoreFiles(target!);
|
||||
default:
|
||||
return createErrorResult('error: pathspec did not match any file(s) known to git');
|
||||
}
|
||||
@@ -80,11 +82,11 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
return { action, target, options };
|
||||
}
|
||||
|
||||
private async switchBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async switchBranch(branchName: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if branch exists
|
||||
const branches = await this.git.listBranches({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (!branches.includes(branchName)) {
|
||||
@@ -95,7 +97,8 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
// Continue
|
||||
@@ -107,7 +110,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
|
||||
// Check for uncommitted changes
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
|
||||
@@ -120,7 +123,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
|
||||
// Switch to the branch
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: branchName,
|
||||
force: true,
|
||||
});
|
||||
@@ -132,11 +135,11 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async createAndSwitchBranch(branchName: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async createAndSwitchBranch(branchName: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if branch already exists
|
||||
const branches = await this.git.listBranches({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (branches.includes(branchName)) {
|
||||
@@ -147,7 +150,8 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
let currentRef: string;
|
||||
try {
|
||||
currentRef = await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
} catch {
|
||||
@@ -156,14 +160,14 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
|
||||
// Create the branch
|
||||
await this.git.branch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: branchName,
|
||||
object: currentRef,
|
||||
});
|
||||
|
||||
// Switch to the new branch
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: branchName,
|
||||
force: true,
|
||||
});
|
||||
@@ -175,7 +179,7 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async restoreFiles(filePath: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async restoreFiles(filePath: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// This is a simplified implementation
|
||||
// In a full git implementation, this would restore files from the index or HEAD
|
||||
@@ -183,7 +187,8 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
// Get the file from HEAD
|
||||
try {
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
filepaths: [filePath],
|
||||
});
|
||||
@@ -200,4 +205,4 @@ export class GitCheckoutCommand implements GitSubcommand {
|
||||
return createErrorResult(`Failed to restore file: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,13 +12,15 @@ export class GitCloneCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const { options, repository, directory } = this.parseArgs(args);
|
||||
|
||||
@@ -35,7 +37,7 @@ export class GitCloneCommand implements GitSubcommand {
|
||||
targetDir = repoName.replace(/\.git$/, ''); // Remove .git suffix if present
|
||||
}
|
||||
|
||||
const targetPath = `${cwd}/${targetDir}`;
|
||||
const targetPath = `${this.pwd}/${targetDir}`;
|
||||
|
||||
// Check if target directory already exists
|
||||
try {
|
||||
@@ -115,4 +117,4 @@ export class GitCloneCommand implements GitSubcommand {
|
||||
|
||||
return { options, repository, directory };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -75,11 +75,12 @@ describe('GitCommitCommand', () => {
|
||||
commitCommand = new GitCommitCommand({
|
||||
git: mockGit as Git,
|
||||
fs: mockFS as JSRuntimeFS,
|
||||
pwd: mockPwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should commit with a message', async () => {
|
||||
const result = await commitCommand.execute(['-m', 'Test commit'], mockPwd);
|
||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
@@ -91,7 +92,7 @@ describe('GitCommitCommand', () => {
|
||||
});
|
||||
|
||||
it('should fail without a message', async () => {
|
||||
const result = await commitCommand.execute([], mockPwd);
|
||||
const result = await commitCommand.execute([]);
|
||||
|
||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||
|
||||
@@ -100,7 +101,7 @@ describe('GitCommitCommand', () => {
|
||||
});
|
||||
|
||||
it('should handle --amend flag', async () => {
|
||||
const result = await commitCommand.execute(['--amend', '-m', 'Amended commit'], mockPwd);
|
||||
const result = await commitCommand.execute(['--amend', '-m', 'Amended commit']);
|
||||
|
||||
expect(mockGit.log).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
@@ -118,7 +119,7 @@ describe('GitCommitCommand', () => {
|
||||
});
|
||||
|
||||
it('should handle --amend flag without message', async () => {
|
||||
const result = await commitCommand.execute(['--amend'], mockPwd);
|
||||
const result = await commitCommand.execute(['--amend']);
|
||||
|
||||
expect(mockGit.log).toHaveBeenCalledWith({
|
||||
dir: mockPwd,
|
||||
@@ -134,7 +135,7 @@ describe('GitCommitCommand', () => {
|
||||
});
|
||||
|
||||
it('should handle -a flag to stage all tracked modified files', async () => {
|
||||
const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage'], mockPwd);
|
||||
const result = await commitCommand.execute(['-a', '-m', 'Commit with auto-stage']);
|
||||
|
||||
// Should call add for the modified tracked file
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
@@ -164,7 +165,7 @@ describe('GitCommitCommand', () => {
|
||||
});
|
||||
|
||||
it('should handle -am flag for combined auto-stage and message', async () => {
|
||||
const result = await commitCommand.execute(['-am', 'Combined flag commit'], mockPwd);
|
||||
const result = await commitCommand.execute(['-am', 'Combined flag commit']);
|
||||
|
||||
// Should call add for the modified tracked file
|
||||
expect(mockGit.add).toHaveBeenCalledWith({
|
||||
@@ -191,7 +192,7 @@ describe('GitCommitCommand', () => {
|
||||
// Mock empty status
|
||||
mockGit.statusMatrix = vi.fn().mockResolvedValue([]);
|
||||
|
||||
const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit'], mockPwd);
|
||||
const result = await commitCommand.execute(['--allow-empty', '-m', 'Empty commit']);
|
||||
|
||||
expect(mockGit.commit).toHaveBeenCalledWith(expect.objectContaining({
|
||||
dir: mockPwd,
|
||||
@@ -208,7 +209,7 @@ describe('GitCommitCommand', () => {
|
||||
['file1.txt', 1, 2, 1], // modified in workdir only
|
||||
]);
|
||||
|
||||
const result = await commitCommand.execute(['-m', 'Should fail'], mockPwd);
|
||||
const result = await commitCommand.execute(['-m', 'Should fail']);
|
||||
|
||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||
|
||||
@@ -219,7 +220,7 @@ describe('GitCommitCommand', () => {
|
||||
it('should handle not being in a git repository', async () => {
|
||||
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
||||
|
||||
const result = await commitCommand.execute(['-m', 'Test commit'], mockPwd);
|
||||
const result = await commitCommand.execute(['-m', 'Test commit']);
|
||||
|
||||
expect(mockGit.commit).not.toHaveBeenCalled();
|
||||
|
||||
|
||||
@@ -11,17 +11,19 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -34,12 +36,12 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
|
||||
// If -a flag is provided, stage all tracked files with modifications
|
||||
if (options.addAll) {
|
||||
await this.stageTrackedChanges(cwd);
|
||||
await this.stageTrackedChanges();
|
||||
}
|
||||
|
||||
// Get current status
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Check for staged changes
|
||||
@@ -56,7 +58,8 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
// Get the last commit message if amending
|
||||
try {
|
||||
const commits = await this.git.log({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
depth: 1,
|
||||
});
|
||||
if (commits.length > 0 && !message) {
|
||||
@@ -74,7 +77,8 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
let currentBranch = 'main';
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
}) || 'main';
|
||||
} catch {
|
||||
// Use default
|
||||
@@ -86,7 +90,7 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
message: string;
|
||||
parent?: string[];
|
||||
} = {
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
message: commitMessage || 'Empty commit',
|
||||
};
|
||||
|
||||
@@ -94,7 +98,7 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
// For amend, we need to reset to the parent of the current commit
|
||||
try {
|
||||
const commits = await this.git.log({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
depth: 2,
|
||||
});
|
||||
if (commits.length > 1) {
|
||||
@@ -147,11 +151,11 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
* Stage all tracked files with modifications
|
||||
* This is used when the -a flag is provided
|
||||
*/
|
||||
private async stageTrackedChanges(cwd: string): Promise<void> {
|
||||
private async stageTrackedChanges(): Promise<void> {
|
||||
try {
|
||||
// Get the status matrix
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Process each file based on its status
|
||||
@@ -161,13 +165,13 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
if (workdirStatus === 0) {
|
||||
// File was deleted, use remove
|
||||
await this.git.remove({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
} else {
|
||||
// File was modified, use add
|
||||
await this.git.add({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
}
|
||||
@@ -214,4 +218,4 @@ export class GitCommitCommand implements GitSubcommand {
|
||||
|
||||
return { options, message };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,20 +11,22 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const { action, key, value, options } = this.parseArgs(args);
|
||||
|
||||
// Check if we're in a git repository (unless --global is used)
|
||||
if (!options.global) {
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -32,11 +34,11 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
return await this.listConfig(options.global, cwd);
|
||||
return await this.listConfig(options.global);
|
||||
case 'get':
|
||||
return await this.getConfig(key!, options.global, cwd);
|
||||
return await this.getConfig(key!, options.global);
|
||||
case 'set':
|
||||
return await this.setConfig(key!, value!, options.global, cwd);
|
||||
return await this.setConfig(key!, value!, options.global);
|
||||
default:
|
||||
return createErrorResult('usage: git config [--global] <name> [<value>] | git config [--global] --list');
|
||||
}
|
||||
@@ -78,7 +80,7 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
return { action, key, value, options };
|
||||
}
|
||||
|
||||
private async listConfig(global: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||
private async listConfig(global: boolean): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// For simplicity, we'll only show the most common config values
|
||||
// isomorphic-git doesn't have a direct way to list all config
|
||||
@@ -95,7 +97,8 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
for (const key of commonKeys) {
|
||||
try {
|
||||
const value = await this.git.getConfig({
|
||||
dir: global ? undefined : cwd,
|
||||
|
||||
dir: global ? undefined : this.pwd,
|
||||
path: key,
|
||||
});
|
||||
if (value !== undefined) {
|
||||
@@ -113,10 +116,11 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async getConfig(key: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||
private async getConfig(key: string, global: boolean): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const value = await this.git.getConfig({
|
||||
dir: global ? undefined : cwd,
|
||||
|
||||
dir: global ? undefined : this.pwd,
|
||||
path: key,
|
||||
});
|
||||
|
||||
@@ -131,10 +135,10 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async setConfig(key: string, value: string, global: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||
private async setConfig(key: string, value: string, global: boolean): Promise<ShellCommandResult> {
|
||||
try {
|
||||
await this.git.setConfig({
|
||||
dir: global ? undefined : cwd,
|
||||
dir: global ? undefined : this.pwd,
|
||||
path: key,
|
||||
value: value,
|
||||
});
|
||||
@@ -145,4 +149,4 @@ export class GitConfigCommand implements GitSubcommand {
|
||||
return createErrorResult(`Failed to set config: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -50,6 +50,7 @@ const mockFS = {
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitDiffCommand', () => {
|
||||
@@ -105,14 +106,14 @@ describe('GitDiffCommand', () => {
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([], '/test/repo');
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show working directory diff for modified files', async () => {
|
||||
const result = await command.execute([], '/test/repo');
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||
@@ -124,7 +125,7 @@ describe('GitDiffCommand', () => {
|
||||
});
|
||||
|
||||
it('should NOT show untracked files in diff', async () => {
|
||||
const result = await command.execute([], '/test/repo');
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
// Untracked files should not appear in git diff output
|
||||
@@ -134,7 +135,7 @@ describe('GitDiffCommand', () => {
|
||||
});
|
||||
|
||||
it('should show deleted files in diff', async () => {
|
||||
const result = await command.execute([], '/test/repo');
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/deleted.txt b/deleted.txt');
|
||||
@@ -145,7 +146,7 @@ describe('GitDiffCommand', () => {
|
||||
});
|
||||
|
||||
it('should show staged diff with --cached option', async () => {
|
||||
const result = await command.execute(['--cached'], '/test/repo');
|
||||
const result = await command.execute(['--cached']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/staged.txt b/staged.txt');
|
||||
@@ -165,7 +166,7 @@ describe('GitDiffCommand', () => {
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithStagedNew.execute(['--cached'], '/test/repo');
|
||||
const result = await commandWithStagedNew.execute(['--cached']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/new-staged.txt b/new-staged.txt');
|
||||
@@ -183,14 +184,14 @@ describe('GitDiffCommand', () => {
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNoChanges.execute([], '/test/repo');
|
||||
const result = await commandWithNoChanges.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should filter by path when specified', async () => {
|
||||
const result = await command.execute(['--', 'modified.txt'], '/test/repo');
|
||||
const result = await command.execute(['--', 'modified.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||
|
||||
@@ -12,17 +12,19 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -31,16 +33,16 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
if (options.cached || options.staged) {
|
||||
// Show staged changes (index vs HEAD)
|
||||
return await this.showStagedDiff(paths, cwd);
|
||||
return await this.showStagedDiff(paths);
|
||||
} else if (commits.length === 0) {
|
||||
// Show working directory changes vs index
|
||||
return await this.showWorkingDirectoryDiff(paths, cwd);
|
||||
return await this.showWorkingDirectoryDiff(paths);
|
||||
} else if (commits.length === 1) {
|
||||
// Show changes between commit and working directory
|
||||
return await this.showCommitDiff(commits[0], paths, cwd);
|
||||
return await this.showCommitDiff(commits[0], paths);
|
||||
} else if (commits.length === 2) {
|
||||
// Show changes between two commits
|
||||
return await this.showCommitRangeDiff(commits[0], commits[1], paths, cwd);
|
||||
return await this.showCommitRangeDiff(commits[0], commits[1], paths);
|
||||
} else {
|
||||
return createErrorResult('usage: git diff [<commit>] [<commit>] [-- <path>...]');
|
||||
}
|
||||
@@ -80,11 +82,11 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
return { commits, paths, options };
|
||||
}
|
||||
|
||||
private async showWorkingDirectoryDiff(paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async showWorkingDirectoryDiff(paths: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Get status to find changed files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Filter for files with working directory changes
|
||||
@@ -118,7 +120,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
// For files in the index, read from HEAD as the baseline
|
||||
// This represents the last committed version for comparison
|
||||
const headBlob = await this.git.readBlob({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: 'HEAD',
|
||||
filepath,
|
||||
});
|
||||
@@ -133,7 +135,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
let workdirContent = '';
|
||||
if (workdirStatus === 2) {
|
||||
try {
|
||||
workdirContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8');
|
||||
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
// File might be deleted
|
||||
workdirContent = '';
|
||||
@@ -154,12 +156,12 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
|
||||
// Deleted file
|
||||
diffLines.push('deleted file mode 100644');
|
||||
diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..0000000`);
|
||||
diffLines.push(`index ${this.getShortHash(indexContent)}..0000000`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push('+++ /dev/null');
|
||||
} else {
|
||||
// Modified file
|
||||
diffLines.push(`index ${this.getShortHash(indexContent, cwd)}..${this.getShortHash(workdirContent, cwd)} 100644`);
|
||||
diffLines.push(`index ${this.getShortHash(indexContent)}..${this.getShortHash(workdirContent)} 100644`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
}
|
||||
@@ -209,11 +211,12 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async showCommitDiff(commit: string, _paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async showCommitDiff(commit: string, _paths: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// For simplicity, show the commit message and changed files
|
||||
const commits = await this.git.log({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
depth: 1,
|
||||
ref: commit,
|
||||
});
|
||||
@@ -242,16 +245,16 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[], _cwd: string): Promise<ShellCommandResult> {
|
||||
private async showCommitRangeDiff(_commit1: string, _commit2: string, _paths: string[]): Promise<ShellCommandResult> {
|
||||
// This would require complex implementation to compare two commits
|
||||
return createErrorResult('Commit range diff is not implemented in this git command');
|
||||
}
|
||||
|
||||
private async showStagedDiff(paths: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async showStagedDiff(paths: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Get status to find staged files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Filter for files with staged changes (index differs from HEAD)
|
||||
@@ -279,7 +282,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
if (headStatus === 1) {
|
||||
try {
|
||||
const headBlob = await this.git.readBlob({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: 'HEAD',
|
||||
filepath,
|
||||
});
|
||||
@@ -293,7 +296,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
let stagedContent = '';
|
||||
if (stageStatus === 1 || stageStatus === 2) {
|
||||
try {
|
||||
stagedContent = await this.fs.readFile(`${cwd}/${filepath}`, 'utf8');
|
||||
stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
stagedContent = '';
|
||||
}
|
||||
@@ -305,18 +308,18 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
// New file staged
|
||||
diffLines.push('new file mode 100644');
|
||||
diffLines.push(`index 0000000..${this.getShortHash(stagedContent, cwd)}`);
|
||||
diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`);
|
||||
diffLines.push('--- /dev/null');
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
} else if (headStatus === 1 && stageStatus === 0) {
|
||||
// File deleted from stage
|
||||
diffLines.push('deleted file mode 100644');
|
||||
diffLines.push(`index ${this.getShortHash(headContent, cwd)}..0000000`);
|
||||
diffLines.push(`index ${this.getShortHash(headContent)}..0000000`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push('+++ /dev/null');
|
||||
} else {
|
||||
// Modified file
|
||||
diffLines.push(`index ${this.getShortHash(headContent, cwd)}..${this.getShortHash(stagedContent, cwd)} 100644`);
|
||||
diffLines.push(`index ${this.getShortHash(headContent)}..${this.getShortHash(stagedContent)} 100644`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
}
|
||||
@@ -364,7 +367,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private getShortHash(content: string, _cwd: string): string {
|
||||
private getShortHash(content: string): string {
|
||||
// Simple hash for demo purposes - not a real git hash
|
||||
let hash = 0;
|
||||
for (let i = 0; i < content.length; i++) {
|
||||
@@ -374,4 +377,4 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
}
|
||||
return Math.abs(hash).toString(16).substring(0, 7).padStart(7, '0');
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -26,6 +26,7 @@ const mockFS = {
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitFetchCommand', () => {
|
||||
@@ -143,21 +144,21 @@ describe('GitFetchCommand', () => {
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([], '/test/repo');
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should fail when remote does not exist', async () => {
|
||||
const result = await command.execute(['nonexistent'], '/test/repo');
|
||||
const result = await command.execute(['nonexistent']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository");
|
||||
});
|
||||
|
||||
it('should fetch from default remote successfully', async () => {
|
||||
const result = await command.execute([], '/test/repo');
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
@@ -165,7 +166,7 @@ describe('GitFetchCommand', () => {
|
||||
});
|
||||
|
||||
it('should fetch from specific remote successfully', async () => {
|
||||
const result = await command.execute(['upstream'], '/test/repo');
|
||||
const result = await command.execute(['upstream']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/upstream/repo.git');
|
||||
@@ -173,7 +174,7 @@ describe('GitFetchCommand', () => {
|
||||
});
|
||||
|
||||
it('should fetch specific refs successfully', async () => {
|
||||
const result = await command.execute(['origin', 'main'], '/test/repo');
|
||||
const result = await command.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
@@ -181,7 +182,7 @@ describe('GitFetchCommand', () => {
|
||||
});
|
||||
|
||||
it('should fetch multiple specific refs successfully', async () => {
|
||||
const result = await command.execute(['origin', 'main', 'develop'], '/test/repo');
|
||||
const result = await command.execute(['origin', 'main', 'develop']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
@@ -200,7 +201,7 @@ describe('GitFetchCommand', () => {
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithAuthError.execute([], '/test/repo');
|
||||
const result = await commandWithAuthError.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: Authentication failed');
|
||||
@@ -217,7 +218,7 @@ describe('GitFetchCommand', () => {
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNetworkError.execute([], '/test/repo');
|
||||
const result = await commandWithNetworkError.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: unable to access remote repository');
|
||||
|
||||
@@ -11,17 +11,19 @@ export class GitFetchCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -32,7 +34,7 @@ export class GitFetchCommand implements GitSubcommand {
|
||||
let remoteUrl: string;
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const targetRemote = remotes.find(r => r.remote === remote);
|
||||
@@ -50,7 +52,7 @@ export class GitFetchCommand implements GitSubcommand {
|
||||
// Fetch specific refs
|
||||
for (const ref of refs) {
|
||||
await this.git.fetch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
ref: ref,
|
||||
});
|
||||
@@ -58,7 +60,7 @@ export class GitFetchCommand implements GitSubcommand {
|
||||
} else {
|
||||
// Fetch all refs (default behavior)
|
||||
await this.git.fetch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
});
|
||||
}
|
||||
@@ -72,7 +74,7 @@ export class GitFetchCommand implements GitSubcommand {
|
||||
for (const ref of refs) {
|
||||
try {
|
||||
await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: `refs/remotes/${remote}/${ref}`,
|
||||
});
|
||||
lines.push(` * branch ${ref} -> ${remote}/${ref}`);
|
||||
@@ -168,4 +170,4 @@ export class GitFetchCommand implements GitSubcommand {
|
||||
|
||||
return { remote, refs, options };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,19 @@ export class GitInitCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Parse arguments
|
||||
const { options, directory } = this.parseArgs(args);
|
||||
const targetDir = directory || cwd;
|
||||
const targetDir = directory || this.pwd;
|
||||
|
||||
// Check if directory exists, create if needed
|
||||
if (directory) {
|
||||
@@ -86,4 +88,4 @@ export class GitInitCommand implements GitSubcommand {
|
||||
|
||||
return { options, directory };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -11,17 +11,19 @@ export class GitLogCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -30,7 +32,8 @@ export class GitLogCommand implements GitSubcommand {
|
||||
|
||||
try {
|
||||
const commits = await this.git.log({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
depth: limit,
|
||||
});
|
||||
|
||||
@@ -39,9 +42,9 @@ export class GitLogCommand implements GitSubcommand {
|
||||
}
|
||||
|
||||
if (options.oneline) {
|
||||
return this.formatOnelineLog(commits, cwd);
|
||||
return this.formatOnelineLog(commits);
|
||||
} else {
|
||||
return this.formatFullLog(commits, options.graph, cwd);
|
||||
return this.formatFullLog(commits, options.graph);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -100,7 +103,7 @@ export class GitLogCommand implements GitSubcommand {
|
||||
return { options, limit };
|
||||
}
|
||||
|
||||
private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>, _cwd: string): ShellCommandResult {
|
||||
private formatOnelineLog(commits: Array<{ oid: string; commit: { message: string } }>): ShellCommandResult {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const commit of commits) {
|
||||
@@ -112,7 +115,7 @@ export class GitLogCommand implements GitSubcommand {
|
||||
return createSuccessResult(lines.join('\n') + '\n');
|
||||
}
|
||||
|
||||
private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean, _cwd: string): ShellCommandResult {
|
||||
private formatFullLog(commits: Array<{ oid: string; commit: { message: string; author: { name: string; email: string; timestamp: number } } }>, showGraph: boolean): ShellCommandResult {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (let i = 0; i < commits.length; i++) {
|
||||
|
||||
@@ -21,6 +21,7 @@ const mockFS = {
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitPullCommand', () => {
|
||||
@@ -106,9 +107,10 @@ describe('GitPullCommand', () => {
|
||||
const commandWithChanges = new GitPullCommand({
|
||||
git: mockGitWithChanges,
|
||||
fs: mockFSWithGit,
|
||||
pwd: '/test/repo',
|
||||
});
|
||||
|
||||
const result = await commandWithChanges.execute(['origin', 'main'], '/test/repo');
|
||||
const result = await commandWithChanges.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('error: Your local changes to the following files would be overwritten by merge:');
|
||||
|
||||
@@ -11,17 +11,19 @@ export class GitPullCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -33,7 +35,8 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
if (!targetBranch) {
|
||||
targetBranch = currentBranch || 'main';
|
||||
@@ -48,7 +51,8 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remoteUrl: string;
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const targetRemote = remotes.find(r => r.remote === remote);
|
||||
@@ -62,7 +66,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
|
||||
// Check for uncommitted changes
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const modifiedFiles = statusMatrix
|
||||
@@ -80,7 +84,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
try {
|
||||
// Fetch from remote
|
||||
await this.git.fetch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
ref: targetBranch,
|
||||
});
|
||||
@@ -90,7 +94,8 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remoteOid: string;
|
||||
try {
|
||||
remoteOid = await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: remoteRef,
|
||||
});
|
||||
} catch {
|
||||
@@ -101,13 +106,15 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let currentOid: string;
|
||||
try {
|
||||
currentOid = await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
} catch {
|
||||
// Empty repository, just checkout the remote branch
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: targetBranch,
|
||||
});
|
||||
return createSuccessResult(`From ${remoteUrl}\n * branch ${targetBranch} -> FETCH_HEAD\nUpdating empty repository\nFast-forward\n`);
|
||||
@@ -120,7 +127,8 @@ export class GitPullCommand implements GitSubcommand {
|
||||
|
||||
// Perform fast-forward merge (simplified)
|
||||
await this.git.merge({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ours: currentBranch || 'HEAD',
|
||||
theirs: remoteRef,
|
||||
fastForwardOnly: true,
|
||||
@@ -164,4 +172,4 @@ export class GitPullCommand implements GitSubcommand {
|
||||
|
||||
return { remote, branch };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -25,6 +25,7 @@ describe('GitPushCommand', () => {
|
||||
pushCommand = new GitPushCommand({
|
||||
git: mockGit as Git,
|
||||
fs: mockFS as JSRuntimeFS,
|
||||
pwd: mockPwd,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -36,16 +37,17 @@ describe('GitPushCommand', () => {
|
||||
const cmd = new GitPushCommand({
|
||||
git: mockGit as Git,
|
||||
fs: mockFSNoRepo as JSRuntimeFS,
|
||||
pwd: '/non-existent',
|
||||
});
|
||||
|
||||
const result = await cmd.execute(['origin', 'main'], mockPwd);
|
||||
const result = await cmd.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('not a git repository');
|
||||
});
|
||||
|
||||
it('should fail when no remote is configured', async () => {
|
||||
const result = await pushCommand.execute(['origin', 'main'], mockPwd);
|
||||
const result = await pushCommand.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('does not appear to be a git repository');
|
||||
@@ -57,7 +59,7 @@ describe('GitPushCommand', () => {
|
||||
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
||||
]);
|
||||
|
||||
await pushCommand.execute(['origin', 'main', '--force'], mockPwd);
|
||||
await pushCommand.execute(['origin', 'main', '--force']);
|
||||
|
||||
// Verify that git.push was called with force: true
|
||||
expect(mockGit.push).toHaveBeenCalledWith(
|
||||
@@ -73,7 +75,7 @@ describe('GitPushCommand', () => {
|
||||
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
||||
]);
|
||||
|
||||
await pushCommand.execute(['origin', 'main', '-f'], mockPwd);
|
||||
await pushCommand.execute(['origin', 'main', '-f']);
|
||||
|
||||
// Verify that git.push was called with force: true
|
||||
expect(mockGit.push).toHaveBeenCalledWith(
|
||||
@@ -89,7 +91,7 @@ describe('GitPushCommand', () => {
|
||||
{ remote: 'origin', url: 'https://example.com/repo.git' },
|
||||
]);
|
||||
|
||||
await pushCommand.execute(['origin', 'main'], mockPwd);
|
||||
await pushCommand.execute(['origin', 'main']);
|
||||
|
||||
// Verify that git.push was called with force: false
|
||||
expect(mockGit.push).toHaveBeenCalledWith(
|
||||
|
||||
@@ -14,19 +14,21 @@ export class GitPushCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
private signer?: NostrSigner;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
this.signer = options.signer;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -38,7 +40,8 @@ export class GitPushCommand implements GitSubcommand {
|
||||
if (!targetBranch) {
|
||||
try {
|
||||
targetBranch = await this.git.currentBranch({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
}) || undefined;
|
||||
if (!targetBranch) {
|
||||
return createErrorResult('fatal: You are not currently on a branch.');
|
||||
@@ -52,7 +55,7 @@ export class GitPushCommand implements GitSubcommand {
|
||||
let remoteUrl: string;
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const targetRemote = remotes.find(r => r.remote === remote);
|
||||
@@ -68,7 +71,7 @@ export class GitPushCommand implements GitSubcommand {
|
||||
|
||||
try {
|
||||
await this.git.push({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
ref: targetBranch,
|
||||
remoteRef: targetBranch,
|
||||
@@ -135,4 +138,4 @@ export class GitPushCommand implements GitSubcommand {
|
||||
|
||||
return { remote, branch, options };
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -12,17 +12,19 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -31,13 +33,13 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
return await this.listRemotes(options.verbose, cwd);
|
||||
return await this.listRemotes(options.verbose);
|
||||
case 'add':
|
||||
return await this.addRemote(name!, url!, cwd);
|
||||
return await this.addRemote(name!, url!);
|
||||
case 'remove':
|
||||
return await this.removeRemote(name!, cwd);
|
||||
return await this.removeRemote(name!);
|
||||
default:
|
||||
return await this.listRemotes(options.verbose, cwd);
|
||||
return await this.listRemotes(options.verbose);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -83,10 +85,10 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
return { action, name, url, options };
|
||||
}
|
||||
|
||||
private async listRemotes(verbose: boolean, cwd: string): Promise<ShellCommandResult> {
|
||||
private async listRemotes(verbose: boolean): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (remotes.length === 0) {
|
||||
@@ -113,7 +115,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async addRemote(name: string, url: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async addRemote(name: string, url: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
if (!name || !url) {
|
||||
return createErrorResult('usage: git remote add <name> <url>');
|
||||
@@ -123,7 +125,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const existingRemote = remotes.find(r => r.remote === name);
|
||||
@@ -136,7 +138,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
|
||||
// Add the remote
|
||||
await this.git.addRemote({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
remote: name,
|
||||
url: url,
|
||||
});
|
||||
@@ -148,7 +150,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async removeRemote(name: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async removeRemote(name: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
if (!name) {
|
||||
return createErrorResult('usage: git remote remove <name>');
|
||||
@@ -158,7 +160,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const existingRemote = remotes.find(r => r.remote === name);
|
||||
@@ -171,7 +173,7 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
|
||||
// Remove the remote
|
||||
await this.git.deleteRemote({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
remote: name,
|
||||
});
|
||||
|
||||
@@ -181,4 +183,4 @@ export class GitRemoteCommand implements GitSubcommand {
|
||||
return createErrorResult(`Failed to remove remote: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -56,6 +56,7 @@ const mockFS = {
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitResetCommand', () => {
|
||||
@@ -145,14 +146,14 @@ describe('GitResetCommand', () => {
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([], '/test/repo');
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should unstage all files when called without arguments', async () => {
|
||||
const result = await command.execute([], '/test/repo');
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
@@ -164,7 +165,7 @@ describe('GitResetCommand', () => {
|
||||
});
|
||||
|
||||
it('should unstage all files when called with HEAD', async () => {
|
||||
const result = await command.execute(['HEAD'], '/test/repo');
|
||||
const result = await command.execute(['HEAD']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
@@ -173,7 +174,7 @@ describe('GitResetCommand', () => {
|
||||
});
|
||||
|
||||
it('should unstage specific files when called with HEAD and file paths', async () => {
|
||||
const result = await command.execute(['HEAD', 'staged.txt'], '/test/repo');
|
||||
const result = await command.execute(['HEAD', 'staged.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
@@ -193,7 +194,7 @@ describe('GitResetCommand', () => {
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNoStaged.execute([], '/test/repo');
|
||||
const result = await commandWithNoStaged.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
@@ -213,35 +214,35 @@ describe('GitResetCommand', () => {
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithError.execute(['HEAD', 'nonexistent.txt'], '/test/repo');
|
||||
const result = await commandWithError.execute(['HEAD', 'nonexistent.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("error: pathspec 'nonexistent.txt' did not match any file(s) known to git");
|
||||
});
|
||||
|
||||
it('should handle commit reset with hard mode', async () => {
|
||||
const result = await command.execute(['--hard', 'HEAD~1'], '/test/repo');
|
||||
const result = await command.execute(['--hard', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||
});
|
||||
|
||||
it('should handle commit reset with mixed mode', async () => {
|
||||
const result = await command.execute(['--mixed', 'HEAD~1'], '/test/repo');
|
||||
const result = await command.execute(['--mixed', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||
});
|
||||
|
||||
it('should return error for soft reset (not implemented)', async () => {
|
||||
const result = await command.execute(['--soft', 'HEAD~1'], '/test/repo');
|
||||
const result = await command.execute(['--soft', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('--soft reset is not implemented');
|
||||
});
|
||||
|
||||
it('should handle invalid commit reference', async () => {
|
||||
const result = await command.execute(['abcdef12345'], '/test/repo');
|
||||
const result = await command.execute(['abcdef12345']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("fatal: ambiguous argument 'abcdef12345'");
|
||||
|
||||
@@ -12,17 +12,19 @@ export class GitResetCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -31,10 +33,10 @@ export class GitResetCommand implements GitSubcommand {
|
||||
|
||||
if (isFileReset) {
|
||||
// Reset specific files or all files (unstage)
|
||||
return await this.resetFiles(files, cwd);
|
||||
return await this.resetFiles(files);
|
||||
} else {
|
||||
// Reset to commit
|
||||
return await this.resetToCommit(target, mode, cwd);
|
||||
return await this.resetToCommit(target, mode);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -87,7 +89,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
return { mode, target, files, isFileReset };
|
||||
}
|
||||
|
||||
private async resetFiles(files: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async resetFiles(files: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const resetFiles: string[] = [];
|
||||
const errors: string[] = [];
|
||||
@@ -97,7 +99,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
try {
|
||||
// Get the status matrix to find all staged files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Find files that are staged (differ from HEAD)
|
||||
@@ -115,7 +117,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
for (const file of stagedFiles) {
|
||||
try {
|
||||
await this.git.resetIndex({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
resetFiles.push(file);
|
||||
@@ -132,7 +134,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
try {
|
||||
// Remove from staging area (reset to HEAD)
|
||||
await this.git.resetIndex({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
resetFiles.push(file);
|
||||
@@ -157,13 +159,14 @@ export class GitResetCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async resetToCommit(target: string, mode: 'soft' | 'mixed' | 'hard', cwd: string): Promise<ShellCommandResult> {
|
||||
private async resetToCommit(target: string, mode: 'soft' | 'mixed' | 'hard'): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Resolve the target commit
|
||||
let targetOid: string;
|
||||
try {
|
||||
targetOid = await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: target,
|
||||
});
|
||||
} catch {
|
||||
@@ -174,7 +177,8 @@ export class GitResetCommand implements GitSubcommand {
|
||||
let currentOid: string;
|
||||
try {
|
||||
currentOid = await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
} catch {
|
||||
@@ -201,7 +205,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
// Detached HEAD state
|
||||
@@ -211,14 +215,14 @@ export class GitResetCommand implements GitSubcommand {
|
||||
if (currentOid !== targetOid) {
|
||||
if (currentBranch) {
|
||||
await this.git.writeRef({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: `refs/heads/${currentBranch}`,
|
||||
value: targetOid,
|
||||
force: true,
|
||||
});
|
||||
} else {
|
||||
await this.git.writeRef({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
value: targetOid,
|
||||
force: true,
|
||||
@@ -229,7 +233,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
// Reset the index only (not the working directory)
|
||||
// Using noCheckout: true to only update the index, not the working directory
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: targetOid,
|
||||
noCheckout: true,
|
||||
noUpdateHead: true,
|
||||
@@ -249,7 +253,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
|
||||
// Get the commit object to ensure it exists
|
||||
await this.git.readCommit({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: targetOid,
|
||||
});
|
||||
|
||||
@@ -257,7 +261,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
// Detached HEAD state
|
||||
@@ -268,14 +272,14 @@ export class GitResetCommand implements GitSubcommand {
|
||||
if (currentOid !== targetOid) {
|
||||
if (currentBranch) {
|
||||
await this.git.writeRef({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: `refs/heads/${currentBranch}`,
|
||||
value: targetOid,
|
||||
force: true,
|
||||
});
|
||||
} else {
|
||||
await this.git.writeRef({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
value: targetOid,
|
||||
force: true,
|
||||
@@ -287,7 +291,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
// Using noUpdateHead: true because we already updated HEAD above
|
||||
// Using force: true to overwrite any local changes
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: targetOid,
|
||||
force: true,
|
||||
noUpdateHead: true,
|
||||
@@ -306,4 +310,4 @@ export class GitResetCommand implements GitSubcommand {
|
||||
return createErrorResult(`Failed to reset: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,11 +319,12 @@ describe('GitShowCommand', () => {
|
||||
showCommand = new GitShowCommand({
|
||||
git: mockGit as Git,
|
||||
fs: mockFS as JSRuntimeFS,
|
||||
pwd: mockPwd,
|
||||
});
|
||||
});
|
||||
|
||||
it('should show basic commit information', async () => {
|
||||
const result = await showCommand.execute(['simple-commit'], mockPwd);
|
||||
const result = await showCommand.execute(['simple-commit']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('commit simple-commit');
|
||||
@@ -332,7 +333,7 @@ describe('GitShowCommand', () => {
|
||||
});
|
||||
|
||||
it('should handle initial commits properly', async () => {
|
||||
const result = await showCommand.execute(['initial-commit'], mockPwd);
|
||||
const result = await showCommand.execute(['initial-commit']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Initial commit');
|
||||
@@ -343,7 +344,7 @@ describe('GitShowCommand', () => {
|
||||
|
||||
it('should resolve HEAD~1 correctly', async () => {
|
||||
// First, check that the implementation correctly resolves HEAD~1
|
||||
const result = await showCommand.execute(['HEAD~1'], mockPwd);
|
||||
const result = await showCommand.execute(['HEAD~1']);
|
||||
|
||||
// Verify that resolveRef was called with HEAD
|
||||
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
||||
@@ -362,7 +363,7 @@ describe('GitShowCommand', () => {
|
||||
});
|
||||
|
||||
it('should resolve HEAD^2 correctly', async () => {
|
||||
const result = await showCommand.execute(['HEAD^2'], mockPwd);
|
||||
const result = await showCommand.execute(['HEAD^2']);
|
||||
|
||||
// Verify that resolveRef was called with HEAD
|
||||
expect(mockGit.resolveRef).toHaveBeenCalledWith({
|
||||
@@ -410,7 +411,7 @@ describe('GitShowCommand', () => {
|
||||
});
|
||||
|
||||
// Execute the command
|
||||
const result = await showCommand.execute(['simple-commit'], mockPwd);
|
||||
const result = await showCommand.execute(['simple-commit']);
|
||||
|
||||
// Check that the command output contains the commit message
|
||||
expect(result.stdout).toContain('Simple changes');
|
||||
@@ -568,7 +569,7 @@ describe('GitShowCommand', () => {
|
||||
});
|
||||
|
||||
// Execute the command
|
||||
const result = await showCommand.execute(['diff-test-commit'], mockPwd);
|
||||
const result = await showCommand.execute(['diff-test-commit']);
|
||||
|
||||
// Debug output
|
||||
console.log('Test output:', result.stdout);
|
||||
@@ -595,7 +596,7 @@ describe('GitShowCommand', () => {
|
||||
});
|
||||
|
||||
it('should return an error for invalid references', async () => {
|
||||
const result = await showCommand.execute(['non-existent-ref'], mockPwd);
|
||||
const result = await showCommand.execute(['non-existent-ref']);
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.stderr).toContain('bad revision');
|
||||
@@ -604,7 +605,7 @@ describe('GitShowCommand', () => {
|
||||
it('should return an error when not in a git repository', async () => {
|
||||
mockFS.stat = vi.fn().mockRejectedValue(new Error('Not a directory'));
|
||||
|
||||
const result = await showCommand.execute([], mockPwd);
|
||||
const result = await showCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).not.toBe(0);
|
||||
expect(result.stderr).toContain('not a git repository');
|
||||
|
||||
@@ -11,17 +11,19 @@ export class GitShowCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -29,12 +31,12 @@ export class GitShowCommand implements GitSubcommand {
|
||||
const { commit } = this.parseArgs(args);
|
||||
|
||||
// Resolve the commit reference (handling relative refs like HEAD~1)
|
||||
const resolvedCommit = await this.resolveCommitRef(commit, cwd);
|
||||
const resolvedCommit = await this.resolveCommitRef(commit);
|
||||
if (!resolvedCommit) {
|
||||
return createErrorResult(`fatal: bad revision '${commit}'`);
|
||||
}
|
||||
|
||||
return await this.showCommit(resolvedCommit, cwd);
|
||||
return await this.showCommit(resolvedCommit);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`git show: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
@@ -57,7 +59,7 @@ export class GitShowCommand implements GitSubcommand {
|
||||
/**
|
||||
* Resolve a commit reference, handling special syntax like HEAD~N and HEAD^N
|
||||
*/
|
||||
private async resolveCommitRef(ref: string, cwd: string): Promise<string | null> {
|
||||
private async resolveCommitRef(ref: string): Promise<string | null> {
|
||||
try {
|
||||
// Handle HEAD~N syntax (ancestor)
|
||||
const tildeMatch = ref.match(/^(.+)~(\d+)$/);
|
||||
@@ -67,17 +69,17 @@ export class GitShowCommand implements GitSubcommand {
|
||||
|
||||
if (numSteps === 0) {
|
||||
// ~0 is the commit itself
|
||||
return this.resolveCommitRef(baseRef, cwd);
|
||||
return this.resolveCommitRef(baseRef);
|
||||
}
|
||||
|
||||
// First resolve the base reference
|
||||
const baseCommit = await this.resolveCommitRef(baseRef, cwd);
|
||||
const baseCommit = await this.resolveCommitRef(baseRef);
|
||||
if (!baseCommit) {
|
||||
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
||||
}
|
||||
|
||||
// Walk back N steps in history
|
||||
return this.walkBackNCommits(baseCommit, numSteps, cwd);
|
||||
return this.walkBackNCommits(baseCommit, numSteps);
|
||||
}
|
||||
|
||||
// Handle HEAD^N syntax (Nth parent)
|
||||
@@ -87,19 +89,19 @@ export class GitShowCommand implements GitSubcommand {
|
||||
const parentIndex = parentNum ? parseInt(parentNum, 10) - 1 : 0; // Default to first parent
|
||||
|
||||
// First resolve the base reference
|
||||
const baseCommit = await this.resolveCommitRef(baseRef, cwd);
|
||||
const baseCommit = await this.resolveCommitRef(baseRef);
|
||||
if (!baseCommit) {
|
||||
throw new Error(`Could not resolve base reference: ${baseRef}`);
|
||||
}
|
||||
|
||||
// Get the specified parent
|
||||
return this.getNthParent(baseCommit, parentIndex, cwd);
|
||||
return this.getNthParent(baseCommit, parentIndex);
|
||||
}
|
||||
|
||||
// Handle simple reference (direct resolution)
|
||||
try {
|
||||
return await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref,
|
||||
});
|
||||
} catch (error) {
|
||||
@@ -117,14 +119,14 @@ export class GitShowCommand implements GitSubcommand {
|
||||
/**
|
||||
* Walk back N commits from the given commit
|
||||
*/
|
||||
private async walkBackNCommits(startCommit: string, steps: number, cwd: string): Promise<string | null> {
|
||||
private async walkBackNCommits(startCommit: string, steps: number): Promise<string | null> {
|
||||
try {
|
||||
let currentCommit = startCommit;
|
||||
|
||||
for (let i = 0; i < steps; i++) {
|
||||
// Get the commit object
|
||||
const commit = await this.git.readCommit({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: currentCommit,
|
||||
});
|
||||
|
||||
@@ -147,11 +149,11 @@ export class GitShowCommand implements GitSubcommand {
|
||||
/**
|
||||
* Get the Nth parent of the given commit
|
||||
*/
|
||||
private async getNthParent(commit: string, parentIndex: number, cwd: string): Promise<string | null> {
|
||||
private async getNthParent(commit: string, parentIndex: number): Promise<string | null> {
|
||||
try {
|
||||
// Get the commit object
|
||||
const commitObj = await this.git.readCommit({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: commit,
|
||||
});
|
||||
|
||||
@@ -173,11 +175,11 @@ export class GitShowCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async showCommit(commitRef: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async showCommit(commitRef: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Get the commit
|
||||
const commits = await this.git.log({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
depth: 1,
|
||||
ref: commitRef,
|
||||
});
|
||||
@@ -218,7 +220,7 @@ export class GitShowCommand implements GitSubcommand {
|
||||
|
||||
// Get the tree for this commit
|
||||
const tree = await this.git.readTree({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: commit.oid,
|
||||
});
|
||||
|
||||
@@ -235,12 +237,12 @@ export class GitShowCommand implements GitSubcommand {
|
||||
|
||||
// Get the trees for both commits
|
||||
const parentTree = await this.git.readTree({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: parentCommit,
|
||||
});
|
||||
|
||||
const commitTree = await this.git.readTree({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: commit.oid,
|
||||
});
|
||||
|
||||
@@ -283,7 +285,7 @@ export class GitShowCommand implements GitSubcommand {
|
||||
const result = new Map<string, TreeEntry>();
|
||||
try {
|
||||
const tree = await this.git.readTree({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid,
|
||||
});
|
||||
|
||||
@@ -433,7 +435,7 @@ export class GitShowCommand implements GitSubcommand {
|
||||
let parentContent = '';
|
||||
try {
|
||||
const parentBlob = await this.git.readBlob({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: parentCommit,
|
||||
filepath: change.path,
|
||||
});
|
||||
@@ -447,7 +449,7 @@ export class GitShowCommand implements GitSubcommand {
|
||||
let currentContent = '';
|
||||
try {
|
||||
const currentBlob = await this.git.readBlob({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
oid: commit.oid,
|
||||
filepath: change.path,
|
||||
});
|
||||
@@ -687,4 +689,4 @@ export class GitShowCommand implements GitSubcommand {
|
||||
return createErrorResult(`Failed to show commit: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -65,6 +65,7 @@ describe('GitStashCommand', () => {
|
||||
stashCommand = new GitStashCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -77,14 +78,14 @@ describe('GitStashCommand', () => {
|
||||
it('should return error when not in a git repository', async () => {
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['push'], testCwd);
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show help with --help flag', async () => {
|
||||
const result = await stashCommand.execute(['--help'], testCwd);
|
||||
const result = await stashCommand.execute(['--help']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('git stash list');
|
||||
@@ -98,7 +99,7 @@ describe('GitStashCommand', () => {
|
||||
['unchanged.txt', 1, 1, 1], // No changes
|
||||
]);
|
||||
|
||||
const result = await stashCommand.execute(['push'], testCwd);
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No local changes to save');
|
||||
@@ -118,7 +119,7 @@ describe('GitStashCommand', () => {
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push'], testCwd);
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory and index state');
|
||||
@@ -144,7 +145,7 @@ describe('GitStashCommand', () => {
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push', '-m', 'my custom message'], testCwd);
|
||||
const result = await stashCommand.execute(['push', '-m', 'my custom message']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('my custom message');
|
||||
@@ -164,7 +165,7 @@ describe('GitStashCommand', () => {
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push', '-u'], testCwd);
|
||||
const result = await stashCommand.execute(['push', '-u']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory');
|
||||
@@ -182,7 +183,7 @@ describe('GitStashCommand', () => {
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push'], testCwd);
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockGit.checkout).toHaveBeenCalledWith({
|
||||
@@ -206,7 +207,7 @@ describe('GitStashCommand', () => {
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['push'], testCwd);
|
||||
const result = await stashCommand.execute(['push']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockGit.resetIndex).toHaveBeenCalledWith({
|
||||
@@ -220,7 +221,7 @@ describe('GitStashCommand', () => {
|
||||
it('should return empty when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['list'], testCwd);
|
||||
const result = await stashCommand.execute(['list']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
@@ -233,7 +234,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['list'], testCwd);
|
||||
const result = await stashCommand.execute(['list']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('stash@{0}: first stash');
|
||||
@@ -245,7 +246,7 @@ describe('GitStashCommand', () => {
|
||||
it('should return error when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['show'], testCwd);
|
||||
const result = await stashCommand.execute(['show']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No stash entries found');
|
||||
@@ -266,7 +267,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['show'], testCwd);
|
||||
const result = await stashCommand.execute(['show']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('M\tmodified.txt');
|
||||
@@ -292,7 +293,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['show', 'stash@{1}'], testCwd);
|
||||
const result = await stashCommand.execute(['show', 'stash@{1}']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('file1.txt');
|
||||
@@ -304,7 +305,7 @@ describe('GitStashCommand', () => {
|
||||
it('should return error when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['apply'], testCwd);
|
||||
const result = await stashCommand.execute(['apply']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No stash entries found');
|
||||
@@ -324,7 +325,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['apply'], testCwd);
|
||||
const result = await stashCommand.execute(['apply']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('test stash');
|
||||
@@ -357,7 +358,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['apply', 'stash@{1}'], testCwd);
|
||||
const result = await stashCommand.execute(['apply', 'stash@{1}']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
@@ -378,7 +379,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['apply'], testCwd);
|
||||
const result = await stashCommand.execute(['apply']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.unlink).toHaveBeenCalledWith(expect.stringContaining('deleted.txt'));
|
||||
@@ -398,7 +399,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['pop'], testCwd);
|
||||
const result = await stashCommand.execute(['pop']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
@@ -417,7 +418,7 @@ describe('GitStashCommand', () => {
|
||||
it('should return error when no stashes', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT'));
|
||||
|
||||
const result = await stashCommand.execute(['drop'], testCwd);
|
||||
const result = await stashCommand.execute(['drop']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No stash entries found');
|
||||
@@ -430,7 +431,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['drop'], testCwd);
|
||||
const result = await stashCommand.execute(['drop']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Dropped stash@{0}');
|
||||
@@ -448,7 +449,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['drop', 'stash@{1}'], testCwd);
|
||||
const result = await stashCommand.execute(['drop', 'stash@{1}']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Dropped stash@{1}');
|
||||
@@ -460,7 +461,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['drop', 'stash@{5}'], testCwd);
|
||||
const result = await stashCommand.execute(['drop', 'stash@{5}']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('is not a valid reference');
|
||||
@@ -475,7 +476,7 @@ describe('GitStashCommand', () => {
|
||||
];
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(mockStashes));
|
||||
|
||||
const result = await stashCommand.execute(['clear'], testCwd);
|
||||
const result = await stashCommand.execute(['clear']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith(
|
||||
@@ -500,7 +501,7 @@ describe('GitStashCommand', () => {
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute(['save'], testCwd);
|
||||
const result = await stashCommand.execute(['save']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory');
|
||||
@@ -520,7 +521,7 @@ describe('GitStashCommand', () => {
|
||||
return Promise.resolve('');
|
||||
});
|
||||
|
||||
const result = await stashCommand.execute([], testCwd);
|
||||
const result = await stashCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Saved working directory');
|
||||
|
||||
@@ -24,17 +24,19 @@ export class GitStashCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -45,26 +47,26 @@ export class GitStashCommand implements GitSubcommand {
|
||||
switch (subcommand) {
|
||||
case 'push':
|
||||
case 'save':
|
||||
return await this.stashPush(subcommandArgs, cwd);
|
||||
return await this.stashPush(subcommandArgs);
|
||||
case 'list':
|
||||
return await this.stashList(cwd);
|
||||
return await this.stashList();
|
||||
case 'apply':
|
||||
return await this.stashApply(subcommandArgs, cwd);
|
||||
return await this.stashApply(subcommandArgs);
|
||||
case 'pop':
|
||||
return await this.stashPop(subcommandArgs, cwd);
|
||||
return await this.stashPop(subcommandArgs);
|
||||
case 'drop':
|
||||
return await this.stashDrop(subcommandArgs, cwd);
|
||||
return await this.stashDrop(subcommandArgs);
|
||||
case 'clear':
|
||||
return await this.stashClear(cwd);
|
||||
return await this.stashClear();
|
||||
case 'show':
|
||||
return await this.stashShow(subcommandArgs, cwd);
|
||||
return await this.stashShow(subcommandArgs);
|
||||
case '--help':
|
||||
case '-h':
|
||||
return this.showHelp(cwd);
|
||||
return this.showHelp();
|
||||
default:
|
||||
// If first arg doesn't look like a subcommand, treat it as 'push'
|
||||
if (subcommand.startsWith('-')) {
|
||||
return await this.stashPush(args, cwd);
|
||||
return await this.stashPush(args);
|
||||
}
|
||||
return createErrorResult(`git stash: '${subcommand}' is not a stash command. See 'git stash --help'.`);
|
||||
}
|
||||
@@ -74,7 +76,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async stashPush(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async stashPush(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Parse arguments
|
||||
let message = 'WIP on';
|
||||
@@ -94,13 +96,13 @@ export class GitStashCommand implements GitSubcommand {
|
||||
// Get current branch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({ dir: cwd }) || null;
|
||||
currentBranch = await this.git.currentBranch({ dir: this.pwd }) || null;
|
||||
} catch {
|
||||
currentBranch = 'HEAD';
|
||||
}
|
||||
|
||||
// Get status to find changed files
|
||||
const statusMatrix = await this.git.statusMatrix({ dir: cwd });
|
||||
const statusMatrix = await this.git.statusMatrix({ dir: this.pwd });
|
||||
|
||||
const filesToStash: StashEntry['files'] = [];
|
||||
const stagedFiles: string[] = [];
|
||||
@@ -122,7 +124,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
|
||||
// Untracked files (only with -u flag)
|
||||
if (includeUntracked && headStatus === 0 && stageStatus === 0 && workdirStatus === 2) {
|
||||
const content = await this.fs.readFile(join(cwd, filepath), 'utf8');
|
||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
||||
filesToStash.push({
|
||||
filepath,
|
||||
content,
|
||||
@@ -139,7 +141,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
// Staged new files or modified files (staged changes)
|
||||
else if (hasStagedChanges && workdirStatus === 2) {
|
||||
const content = await this.fs.readFile(join(cwd, filepath), 'utf8');
|
||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
||||
const status = headStatus === 0 ? 'added' : 'modified';
|
||||
filesToStash.push({
|
||||
filepath,
|
||||
@@ -149,7 +151,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
// Unstaged modifications in working directory
|
||||
else if (hasWorkdirChanges && workdirStatus === 2) {
|
||||
const content = await this.fs.readFile(join(cwd, filepath), 'utf8');
|
||||
const content = await this.fs.readFile(join(this.pwd, filepath), 'utf8');
|
||||
filesToStash.push({
|
||||
filepath,
|
||||
content,
|
||||
@@ -175,7 +177,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
};
|
||||
|
||||
// Save stash
|
||||
await this.saveStash(stashEntry, cwd);
|
||||
await this.saveStash(stashEntry);
|
||||
|
||||
// Revert changes in working directory
|
||||
for (const file of filesToStash) {
|
||||
@@ -183,21 +185,21 @@ export class GitStashCommand implements GitSubcommand {
|
||||
if (file.status === 'deleted') {
|
||||
// Restore deleted file from HEAD
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepaths: [file.filepath],
|
||||
force: true,
|
||||
});
|
||||
} else if (file.status === 'modified') {
|
||||
// Restore file from HEAD using checkout
|
||||
await this.git.checkout({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepaths: [file.filepath],
|
||||
force: true,
|
||||
});
|
||||
} else if (file.status === 'added') {
|
||||
// Delete new file (it doesn't exist in HEAD)
|
||||
try {
|
||||
await this.fs.unlink(join(cwd, file.filepath));
|
||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
||||
} catch {
|
||||
// File might already be gone
|
||||
}
|
||||
@@ -211,7 +213,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
for (const file of stagedFiles) {
|
||||
try {
|
||||
await this.git.resetIndex({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
@@ -226,9 +228,9 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async stashList(cwd: string): Promise<ShellCommandResult> {
|
||||
private async stashList(): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes(cwd);
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createSuccessResult('');
|
||||
@@ -245,9 +247,9 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async stashApply(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async stashApply(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes(cwd);
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createErrorResult('No stash entries found.');
|
||||
@@ -255,7 +257,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
|
||||
// Parse stash reference (e.g., stash@{0} or just 0)
|
||||
const stashRef = args[0] || 'stash@{0}';
|
||||
const index = this.parseStashRef(stashRef, cwd);
|
||||
const index = this.parseStashRef(stashRef);
|
||||
|
||||
if (index < 0 || index >= stashes.length) {
|
||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||
@@ -269,19 +271,19 @@ export class GitStashCommand implements GitSubcommand {
|
||||
if (file.status === 'deleted') {
|
||||
// Delete the file
|
||||
try {
|
||||
await this.fs.unlink(join(cwd, file.filepath));
|
||||
await this.fs.unlink(join(this.pwd, file.filepath));
|
||||
} catch {
|
||||
// File might not exist
|
||||
}
|
||||
} else {
|
||||
// Create file with stashed content
|
||||
const dir = join(cwd, file.filepath, '..');
|
||||
const dir = join(this.pwd, file.filepath, '..');
|
||||
try {
|
||||
await this.fs.mkdir(dir, { recursive: true });
|
||||
} catch {
|
||||
// Directory might exist
|
||||
}
|
||||
await this.fs.writeFile(join(cwd, file.filepath), file.content);
|
||||
await this.fs.writeFile(join(this.pwd, file.filepath), file.content);
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn(`Failed to apply ${file.filepath}:`, error);
|
||||
@@ -292,7 +294,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
for (const filepath of stash.stagedFiles) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
filepath,
|
||||
});
|
||||
} catch {
|
||||
@@ -307,17 +309,17 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async stashPop(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async stashPop(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Apply the stash first
|
||||
const result = await this.stashApply(args, cwd);
|
||||
const result = await this.stashApply(args);
|
||||
|
||||
if (result.exitCode !== 0) {
|
||||
return result;
|
||||
}
|
||||
|
||||
// If apply succeeded, drop the stash
|
||||
const dropResult = await this.stashDrop(args, cwd);
|
||||
const dropResult = await this.stashDrop(args);
|
||||
|
||||
if (dropResult.exitCode !== 0) {
|
||||
return createErrorResult(`Applied stash successfully but failed to drop: ${dropResult.stderr}`);
|
||||
@@ -330,9 +332,9 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async stashDrop(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async stashDrop(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes(cwd);
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createErrorResult('No stash entries found.');
|
||||
@@ -340,7 +342,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
|
||||
// Parse stash reference
|
||||
const stashRef = args[0] || 'stash@{0}';
|
||||
const index = this.parseStashRef(stashRef, cwd);
|
||||
const index = this.parseStashRef(stashRef);
|
||||
|
||||
if (index < 0 || index >= stashes.length) {
|
||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||
@@ -348,7 +350,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
|
||||
// Remove the stash
|
||||
stashes.splice(index, 1);
|
||||
await this.saveStashes(stashes, cwd);
|
||||
await this.saveStashes(stashes);
|
||||
|
||||
return createSuccessResult(`Dropped stash@{${index}}\n`);
|
||||
|
||||
@@ -357,9 +359,9 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async stashClear(cwd: string): Promise<ShellCommandResult> {
|
||||
private async stashClear(): Promise<ShellCommandResult> {
|
||||
try {
|
||||
await this.saveStashes([], cwd);
|
||||
await this.saveStashes([]);
|
||||
return createSuccessResult('');
|
||||
|
||||
} catch (error) {
|
||||
@@ -367,9 +369,9 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async stashShow(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
private async stashShow(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const stashes = await this.loadStashes(cwd);
|
||||
const stashes = await this.loadStashes();
|
||||
|
||||
if (stashes.length === 0) {
|
||||
return createErrorResult('No stash entries found.');
|
||||
@@ -377,7 +379,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
|
||||
// Parse stash reference
|
||||
const stashRef = args[0] || 'stash@{0}';
|
||||
const index = this.parseStashRef(stashRef, cwd);
|
||||
const index = this.parseStashRef(stashRef);
|
||||
|
||||
if (index < 0 || index >= stashes.length) {
|
||||
return createErrorResult(`stash@{${index}} is not a valid reference`);
|
||||
@@ -403,7 +405,7 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private parseStashRef(ref: string, _cwd: string): number {
|
||||
private parseStashRef(ref: string): number {
|
||||
// Parse stash@{N} or just N
|
||||
const match = ref.match(/^(?:stash@\{)?(\d+)\}?$/);
|
||||
if (match) {
|
||||
@@ -412,9 +414,9 @@ export class GitStashCommand implements GitSubcommand {
|
||||
return 0; // Default to stash@{0}
|
||||
}
|
||||
|
||||
private async loadStashes(cwd: string): Promise<StashEntry[]> {
|
||||
private async loadStashes(): Promise<StashEntry[]> {
|
||||
try {
|
||||
const stashPath = join(cwd, '.git', 'shakespeare_stash.json');
|
||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
||||
const data = await this.fs.readFile(stashPath, 'utf8');
|
||||
return JSON.parse(data) as StashEntry[];
|
||||
} catch {
|
||||
@@ -422,18 +424,18 @@ export class GitStashCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async saveStash(stash: StashEntry, cwd: string): Promise<void> {
|
||||
const stashes = await this.loadStashes(cwd);
|
||||
private async saveStash(stash: StashEntry): Promise<void> {
|
||||
const stashes = await this.loadStashes();
|
||||
stashes.unshift(stash); // Add to beginning of array
|
||||
await this.saveStashes(stashes, cwd);
|
||||
await this.saveStashes(stashes);
|
||||
}
|
||||
|
||||
private async saveStashes(stashes: StashEntry[], cwd: string): Promise<void> {
|
||||
const stashPath = join(cwd, '.git', 'shakespeare_stash.json');
|
||||
private async saveStashes(stashes: StashEntry[]): Promise<void> {
|
||||
const stashPath = join(this.pwd, '.git', 'shakespeare_stash.json');
|
||||
await this.fs.writeFile(stashPath, JSON.stringify(stashes, null, 2));
|
||||
}
|
||||
|
||||
private showHelp(_cwd: string): ShellCommandResult {
|
||||
private showHelp(): ShellCommandResult {
|
||||
const helpText = `usage: git stash list [<options>]
|
||||
or: git stash show [<stash>]
|
||||
or: git stash drop [<stash>]
|
||||
@@ -444,4 +446,4 @@ export class GitStashCommand implements GitSubcommand {
|
||||
|
||||
return createSuccessResult(helpText);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -52,6 +52,7 @@ describe('GitStatusCommand', () => {
|
||||
statusCommand = new GitStatusCommand({
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: testCwd,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -65,7 +66,7 @@ describe('GitStatusCommand', () => {
|
||||
// Mock stat to throw error for .git directory
|
||||
vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT'));
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
@@ -76,7 +77,7 @@ describe('GitStatusCommand', () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
@@ -92,7 +93,7 @@ describe('GitStatusCommand', () => {
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
@@ -108,7 +109,7 @@ describe('GitStatusCommand', () => {
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
@@ -124,7 +125,7 @@ describe('GitStatusCommand', () => {
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
@@ -140,7 +141,7 @@ describe('GitStatusCommand', () => {
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch main');
|
||||
@@ -158,7 +159,7 @@ describe('GitStatusCommand', () => {
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--porcelain'], testCwd);
|
||||
const result = await statusCommand.execute(['--porcelain']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
@@ -174,7 +175,7 @@ describe('GitStatusCommand', () => {
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('main');
|
||||
|
||||
const result = await statusCommand.execute(['--short'], testCwd);
|
||||
const result = await statusCommand.execute(['--short']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('?? untracked.txt');
|
||||
@@ -190,7 +191,7 @@ describe('GitStatusCommand', () => {
|
||||
]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch');
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('On branch feature-branch');
|
||||
@@ -208,7 +209,7 @@ describe('GitStatusCommand', () => {
|
||||
vi.mocked(mockGit.statusMatrix).mockResolvedValue([]);
|
||||
vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined);
|
||||
|
||||
const result = await statusCommand.execute([], testCwd);
|
||||
const result = await statusCommand.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD detached at unknown');
|
||||
|
||||
@@ -11,18 +11,19 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -31,23 +32,23 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
|
||||
// Get the status matrix
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
// Get current branch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
} catch {
|
||||
// Might be an empty repository
|
||||
}
|
||||
|
||||
if (options.porcelain || options.short) {
|
||||
return this.formatPorcelainStatus(statusMatrix, cwd);
|
||||
return this.formatPorcelainStatus(statusMatrix);
|
||||
} else {
|
||||
return this.formatHumanStatus(statusMatrix, currentBranch, cwd);
|
||||
return this.formatHumanStatus(statusMatrix, currentBranch);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -69,7 +70,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
return options;
|
||||
}
|
||||
|
||||
private formatPorcelainStatus(statusMatrix: Array<[string, number, number, number]>, _cwd: string): ShellCommandResult {
|
||||
private formatPorcelainStatus(statusMatrix: Array<[string, number, number, number]>): ShellCommandResult {
|
||||
const lines: string[] = [];
|
||||
|
||||
for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) {
|
||||
@@ -107,7 +108,7 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
return createSuccessResult(lines.join('\n') + (lines.length > 0 ? '\n' : ''));
|
||||
}
|
||||
|
||||
private formatHumanStatus(statusMatrix: Array<[string, number, number, number]>, currentBranch: string | null, _cwd: string): ShellCommandResult {
|
||||
private formatHumanStatus(statusMatrix: Array<[string, number, number, number]>, currentBranch: string | null): ShellCommandResult {
|
||||
const lines: string[] = [];
|
||||
|
||||
// Show current branch
|
||||
@@ -185,4 +186,4 @@ export class GitStatusCommand implements GitSubcommand {
|
||||
lines.push('');
|
||||
return createSuccessResult(lines.join('\n'));
|
||||
}
|
||||
}
|
||||
}
|
||||
+21
-16
@@ -12,17 +12,19 @@ export class GitTagCommand implements GitSubcommand {
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string): Promise<ShellCommandResult> {
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${cwd}/.git`);
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
@@ -31,13 +33,13 @@ export class GitTagCommand implements GitSubcommand {
|
||||
|
||||
switch (action) {
|
||||
case 'list':
|
||||
return await this.listTags(cwd);
|
||||
return await this.listTags();
|
||||
case 'create':
|
||||
return await this.createTag(tagName!, cwd, commit);
|
||||
return await this.createTag(tagName!, commit);
|
||||
case 'delete':
|
||||
return await this.deleteTag(tagName!, cwd);
|
||||
return await this.deleteTag(tagName!);
|
||||
default:
|
||||
return await this.listTags(cwd);
|
||||
return await this.listTags();
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
@@ -82,10 +84,10 @@ export class GitTagCommand implements GitSubcommand {
|
||||
return { action, tagName, commit, options };
|
||||
}
|
||||
|
||||
private async listTags(cwd: string): Promise<ShellCommandResult> {
|
||||
private async listTags(): Promise<ShellCommandResult> {
|
||||
try {
|
||||
const tags = await this.git.listTags({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (tags.length === 0) {
|
||||
@@ -102,7 +104,7 @@ export class GitTagCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async createTag(tagName: string, cwd: string, commit?: string): Promise<ShellCommandResult> {
|
||||
private async createTag(tagName: string, commit?: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
if (!tagName) {
|
||||
return createErrorResult('usage: git tag <tagname> [<commit>]');
|
||||
@@ -111,7 +113,8 @@ export class GitTagCommand implements GitSubcommand {
|
||||
// Check if tag already exists
|
||||
try {
|
||||
const tags = await this.git.listTags({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (tags.includes(tagName)) {
|
||||
@@ -125,7 +128,8 @@ export class GitTagCommand implements GitSubcommand {
|
||||
let targetOid: string;
|
||||
try {
|
||||
targetOid = await this.git.resolveRef({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
ref: commit || 'HEAD',
|
||||
});
|
||||
} catch {
|
||||
@@ -134,7 +138,7 @@ export class GitTagCommand implements GitSubcommand {
|
||||
|
||||
// Create the tag
|
||||
await this.git.tag({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: tagName,
|
||||
object: targetOid,
|
||||
});
|
||||
@@ -146,7 +150,7 @@ export class GitTagCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
private async deleteTag(tagName: string, cwd: string): Promise<ShellCommandResult> {
|
||||
private async deleteTag(tagName: string): Promise<ShellCommandResult> {
|
||||
try {
|
||||
if (!tagName) {
|
||||
return createErrorResult('usage: git tag -d <tagname>');
|
||||
@@ -155,7 +159,8 @@ export class GitTagCommand implements GitSubcommand {
|
||||
// Check if tag exists
|
||||
try {
|
||||
const tags = await this.git.listTags({
|
||||
dir: cwd,
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
if (!tags.includes(tagName)) {
|
||||
@@ -167,7 +172,7 @@ export class GitTagCommand implements GitSubcommand {
|
||||
|
||||
// Delete the tag
|
||||
await this.git.deleteTag({
|
||||
dir: cwd,
|
||||
dir: this.pwd,
|
||||
ref: tagName,
|
||||
});
|
||||
|
||||
@@ -177,4 +182,4 @@ export class GitTagCommand implements GitSubcommand {
|
||||
return createErrorResult(`Failed to delete tag: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Loaded 100 of 125 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user