Compare commits

..
Author SHA1 Message Date
lemonknowsall 91ab79bb39 improved performance for excessive console logs 2025-11-18 23:01:12 -08:00
lemonknowsall 8f148e48c0 update languages and add console end indicator 2025-11-17 00:02:07 -08:00
lemonknowsall 3e230d425f console log in pane view 2025-11-16 23:22:21 -08:00
Alex Gleason a6caf93e8b Display "Push to Nostr" when origin URL is empty 2025-11-14 21:19:01 -06:00
Alex Gleason b55fd857e1 Treat Vite ?url imports as external ESM CDN links 2025-11-14 13:20:46 -06:00
Alex Gleason 65c51e865a Treat wasm import as binary, remove nonstandard import attribute on esbuild.wasm 2025-11-14 12:39:52 -06:00
Alex Gleason 8ecf460140 Don't redirect /assets/* in netlify redirects file 2025-11-13 22:11:32 -06:00
Alex Gleason 8ee4efdee3 Remove outdated soapbox.dev mirror 2025-11-13 21:23:12 -06:00
Alex Gleason 5ac5fcc212 systemPromptDescription: EJS -> Jinja-like 2025-11-13 20:07:08 -06:00
Alex Gleason 58c24f615d Swap out eta for nunjucks 2025-11-13 19:49:15 -06:00
Alex Gleason d1cbcda5d5 Minor simplifications to system prompt template 2025-11-13 19:27:45 -06:00
Alex Gleason c30ed35c67 Fix eta CSP issue, disable autoTrim 2025-11-13 19:20:53 -06:00
Alex Gleason dea364c2a6 Use esbuild worker, emit wasm file in build 2025-11-13 18:50:46 -06:00
Alex Gleason eabba1ecec Expose full config and defaultConfig to systemPrompt template 2025-11-13 18:12:45 -06:00
Alex Gleason db02b9fb94 Let system prompt be configurable in System Settings (EJS template) 2025-11-13 17:36:04 -06:00
DanConwayDev 4d88823c2d Improve toast message for new branch push 2025-11-13 16:41:48 -06:00
Alex Gleason 933530a96c Add Edit with Shakespeare scaling note to system prompt 2025-11-13 16:40:51 -06:00
DanConwayDev 43f4e0d15d Auto-switch to newly crated branch 2025-11-13 16:22:50 -06:00
DanConwayDev 21e522cba7 Fix git fetch handle deteled refs 2025-11-13 16:11:39 -06:00
Alex Gleason d8bfa10b43 Indicate non-default System Settings, allow clicking to restore to default 2025-11-13 16:10:19 -06:00
Alex Gleason 7a000a80f0 Add system prompt test 2025-11-13 15:55:52 -06:00
Alex Gleason 866155d907 Add "Edit with Shakespeare" info to system prompt 2025-11-13 15:39:18 -06:00
Alex Gleason 72439d4ec9 Merge branch 'fix/periods-in-name-break-deployment' into 'main'
fix/periods-in-name-break-deployment

See merge request soapbox-pub/shakespeare!70
2025-11-13 04:03:25 +00:00
sam 51f079696a detect and block deployment when the target contains periods 2025-11-13 10:53:52 +07:00
Alex Gleason abe3368115 Add error handling to favicon URL 2025-11-12 14:34:46 -06:00
Alex Gleason 16d357364d Add abort reasons to abort controllers 2025-11-12 14:24:41 -06:00
Alex Gleason 2d505588c7 Refactor Quilly to fix conditional hook usage 2025-11-12 14:01:46 -06:00
Alex Gleason a9ab551ca2 Sentry remove unnecessary mode fallback 2025-11-12 13:51:04 -06:00
DanConwayDev 075d6aba2d Fix git fetch default branch identification
calling remote via getRemoteInfo is not needed and results in null
for nostr remotes.

default branch is used here to trigger git fetch toast notifications

improved test coverage to test whether toast mis-fire when there is
no update
2025-11-12 13:42:18 -06:00
DanConwayDev a1f571b2d8 Fix git push publish state to repo relays
instead of hardcoded default
2025-11-12 13:40:06 -06:00
DanConwayDev d4eca86ec6 Fix retain prior state during git push to nostr remote
otherwise git push to a feature branch removes all other branches
including main and sets HEAD to feature branch.
2025-11-12 13:39:31 -06:00
DanConwayDev 44a208aed5 Fix don't unwrap symrefs in nostr remote
this was causing `refs/remotes/origin/HEAD` to be a commit id rather
than a symbolic reference like in the nostr state event
2025-11-12 13:38:51 -06:00
DanConwayDev ccc3613c83 Fix git status when branch not published
instead using status 'X commits ahead' it says 'Branch not published' and disables pull disabled.
2025-11-12 13:38:20 -06:00
Alex Gleason fd309e0aab Merge branch 'pr/fix-npm-run-electron(8edc8583)' 2025-11-12 13:36:27 -06:00
Alex Gleason 3d06e0cb57 Accumulate and persist total project cost and display in Project Details dialog 2025-11-12 12:09:42 -06:00
Alex Gleason dbf5cfe0a3 Make curl virtual command use configured corsProxy instead of hardcoded 2025-11-12 11:10:30 -06:00
Alex Gleason 0b66f81bfc Make "Push to Nostr" actually push without requiring another click to "Push" 2025-11-12 11:02:01 -06:00
Alex Gleason 35a85c18bd Add CORS proxy to system prompt 2025-11-11 18:03:21 -06:00
DanConwayDev 465bef91e8 fix npm run electron by generating package.json
The electron package.json needs to exist for this command to succeed.
If `prepare-electron-publish.js` has never been run then it hasn't been generated yet. Solution, run that everytime.
2025-11-03 11:35:20 +00:00
63 changed files with 3220 additions and 3050 deletions

No files matched your search

-348
View File
@@ -1,348 +0,0 @@
# 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.
-1
View File
@@ -34,7 +34,6 @@ 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)
-191
View File
@@ -1,191 +0,0 @@
# 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
View File
@@ -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' '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:">
<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:">
<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">
+86 -11
View File
@@ -68,6 +68,7 @@
"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",
@@ -105,6 +106,7 @@
"@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",
@@ -193,6 +195,7 @@
"integrity": "sha512-e7jT4DxYvIDLk1ZHmU/m/mB19rex9sv0c2ftBtjSBv+kVM/902eh0fINUzD7UwLLNR+jU585GxUJ8/EBfAM5fw==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/code-frame": "^7.27.1",
"@babel/generator": "^7.28.5",
@@ -1828,6 +1831,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
},
@@ -1851,6 +1855,7 @@
}
],
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18"
}
@@ -1872,6 +1877,7 @@
"resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz",
"integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@dnd-kit/accessibility": "^3.1.1",
"@dnd-kit/utilities": "^3.2.2",
@@ -5402,8 +5408,7 @@
"resolved": "https://registry.npmjs.org/@types/aria-query/-/aria-query-5.0.4.tgz",
"integrity": "sha512-rfT93uj5s0PRL7EzccGMs3brplhcrghnDoV26NqKhCAS1hVo+WdNsPvE/yb6ilfr5hi2MEk6d5EWJTKdxg8jVw==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/@types/cacheable-request": {
"version": "6.0.3",
@@ -5603,6 +5608,13 @@
"undici-types": "~6.21.0"
}
},
"node_modules/@types/nunjucks": {
"version": "3.2.6",
"resolved": "https://registry.npmjs.org/@types/nunjucks/-/nunjucks-3.2.6.tgz",
"integrity": "sha512-pHiGtf83na1nCzliuAdq8GowYiXvH5l931xZ0YEHaLMNFgynpEqx+IPStlu7UaDkehfvl01e4x/9Tpwhy7Ue3w==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/path-browserify": {
"version": "1.0.3",
"resolved": "https://registry.npmjs.org/@types/path-browserify/-/path-browserify-1.0.3.tgz",
@@ -5638,6 +5650,7 @@
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.20.tgz",
"integrity": "sha512-IPaCZN7PShZK/3t6Q87pfTkRm6oLTd4vztyoj+cbHUF1g3FfVb2tFIL79uCRKEfv16AhqDMBywP2VW3KIZUvcg==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.0.2"
@@ -5649,6 +5662,7 @@
"integrity": "sha512-MEe3UeoENYVFXzoXEWsvcpg6ZvlrFNlOQ7EOsvhI3CfAXwzPfO8Qwuxd40nepsYKqyyVQnTdEfv68q91yLcKrQ==",
"devOptional": true,
"license": "MIT",
"peer": true,
"peerDependencies": {
"@types/react": "^18.0.0"
}
@@ -5753,6 +5767,7 @@
"integrity": "sha512-oU/OtYVydhXnumd0BobL9rkJg7wFJ9bFFPmSmB/bf/XWN85hlViji59ko6bSKBXyseT9V8l+CN1nwmlbiN0G7Q==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@typescript-eslint/scope-manager": "8.31.1",
"@typescript-eslint/types": "8.31.1",
@@ -6088,11 +6103,18 @@
"url": "https://opencollective.com/vitest"
}
},
"node_modules/a-sync-waterfall": {
"version": "1.0.1",
"resolved": "https://registry.npmjs.org/a-sync-waterfall/-/a-sync-waterfall-1.0.1.tgz",
"integrity": "sha512-RYTOHHdWipFUliRFMCS4X2Yn2X8M87V/OpSqWzKKOGhzqyUxzyVmhHDH9sAvG+ZuQf/TAOFsLCpMw09I1ufUnA==",
"license": "MIT"
},
"node_modules/acorn": {
"version": "8.15.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.15.0.tgz",
"integrity": "sha512-NZyJarBfL7nWwIq+FDL6Zp/yHEhePMNnnJ0y3qfieCrmNvYct8uvtiV41UvlSe6apAfk0fY1FbWx+NwfmpvtTg==",
"license": "MIT",
"peer": true,
"bin": {
"acorn": "bin/acorn"
},
@@ -6257,6 +6279,12 @@
"url": "https://github.com/sponsors/ljharb"
}
},
"node_modules/asap": {
"version": "2.0.6",
"resolved": "https://registry.npmjs.org/asap/-/asap-2.0.6.tgz",
"integrity": "sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA==",
"license": "MIT"
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
@@ -6531,6 +6559,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"baseline-browser-mapping": "^2.8.19",
"caniuse-lite": "^1.0.30001751",
@@ -6790,6 +6819,7 @@
"resolved": "https://registry.npmjs.org/chokidar/-/chokidar-3.6.0.tgz",
"integrity": "sha512-7VT13fmjotKpGipCW9JEQAusEPE+Ei8nl6/g4FBAmIm0GOOLMua9NDDo/DWp0ZAxCr3cPq5ZpBqmPAQgDda2Pw==",
"license": "MIT",
"peer": true,
"dependencies": {
"anymatch": "~3.1.2",
"braces": "~3.0.2",
@@ -7528,8 +7558,7 @@
"resolved": "https://registry.npmjs.org/dom-accessibility-api/-/dom-accessibility-api-0.5.16.tgz",
"integrity": "sha512-X7BJ2yElsnOJ30pZF4uIIDfBEVgF4XEBxL9Bxhy6dnrm5hkzqmsWHGTiHqRiITNhMyFLyAiWndIJP7Z1NTteDg==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/dom-helpers": {
"version": "5.2.1",
@@ -7607,7 +7636,8 @@
"version": "8.6.0",
"resolved": "https://registry.npmjs.org/embla-carousel/-/embla-carousel-8.6.0.tgz",
"integrity": "sha512-SjWyZBHJPbqxHOzckOfo8lHisEaJWmwd23XppYFYVh10bU66/Pn5tkVkbkCMZVdbUE5eTCI2nD8OyIP4Z+uwkA==",
"license": "MIT"
"license": "MIT",
"peer": true
},
"node_modules/embla-carousel-react": {
"version": "8.6.0",
@@ -7906,6 +7936,7 @@
"integrity": "sha512-QldCVh/ztyKJJZLr4jXNUByx3gR+TDYZCRXEktiZoUR3PGy4qCmSbkxcIle8GEwGpb5JBZazlaJ/CxLidXdEbQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@eslint-community/eslint-utils": "^4.2.0",
"@eslint-community/regexpp": "^4.12.1",
@@ -9253,6 +9284,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"@babel/runtime": "^7.27.6"
},
@@ -10022,6 +10054,7 @@
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"cssstyle": "^4.2.1",
"data-urls": "^5.0.0",
@@ -10418,7 +10451,6 @@
"integrity": "sha512-h5bgJWpxJNswbU7qCrV0tIKQCaS3blPDrqKWx+QxzuzL1zGUzij9XCWLrSLsJPu5t+eWA/ycetzYAO5IOMcWAQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"lz-string": "bin/bin.js"
}
@@ -11685,6 +11717,40 @@
"integrity": "sha512-78BTryCLcLYv96ONU8Ws3Q1JzjlAt+43pWQhIl86xZmWeegYCNLPml7yQ+gG3vR6V5h4XGj+TxO+SS5dsThQIA==",
"license": "MIT"
},
"node_modules/nunjucks": {
"version": "3.2.4",
"resolved": "https://registry.npmjs.org/nunjucks/-/nunjucks-3.2.4.tgz",
"integrity": "sha512-26XRV6BhkgK0VOxfbU5cQI+ICFUtMLixv1noZn1tGU38kQH5A5nmmbk/O45xdyBhD1esk47nKrY0mvQpZIhRjQ==",
"license": "BSD-2-Clause",
"dependencies": {
"a-sync-waterfall": "^1.0.0",
"asap": "^2.0.3",
"commander": "^5.1.0"
},
"bin": {
"nunjucks-precompile": "bin/precompile"
},
"engines": {
"node": ">= 6.9.0"
},
"peerDependencies": {
"chokidar": "^3.3.0"
},
"peerDependenciesMeta": {
"chokidar": {
"optional": true
}
}
},
"node_modules/nunjucks/node_modules/commander": {
"version": "5.1.0",
"resolved": "https://registry.npmjs.org/commander/-/commander-5.1.0.tgz",
"integrity": "sha512-P0CysNDQ7rtVw4QIQtm+MRxV66vKFSvlsQvGYXZWR3qFU0jlMKHZZZgw8e+8DSah4UDKMqnknRDQz+xuQXQ/Zg==",
"license": "MIT",
"engines": {
"node": ">= 6"
}
},
"node_modules/nwsapi": {
"version": "2.2.20",
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.20.tgz",
@@ -12088,6 +12154,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.8",
"picocolors": "^1.1.1",
@@ -12255,7 +12322,6 @@
"integrity": "sha512-Qb1gy5OrP5+zDf2Bvnzdl3jsTf1qXVMazbvCoKhtKqVs4/YK4ozX4gKQJJVyNe+cajNPn0KoC0MC3FUmaHWEmQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"ansi-regex": "^5.0.1",
"ansi-styles": "^5.0.0",
@@ -12271,7 +12337,6 @@
"integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=8"
}
@@ -12282,7 +12347,6 @@
"integrity": "sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=10"
},
@@ -12295,8 +12359,7 @@
"resolved": "https://registry.npmjs.org/react-is/-/react-is-17.0.2.tgz",
"integrity": "sha512-w2GsyukL62IJnlaff/nRegPQR94C/XXamvMWmSHRJ4y7Ts/4ocGRmTHvOs8PSE6pB3dWOrD/nueuU5sduBsQ4w==",
"dev": true,
"license": "MIT",
"peer": true
"license": "MIT"
},
"node_modules/prismjs": {
"version": "1.30.0",
@@ -12436,6 +12499,7 @@
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0"
},
@@ -12462,6 +12526,7 @@
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"peer": true,
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
@@ -12487,6 +12552,7 @@
"resolved": "https://registry.npmjs.org/react-hook-form/-/react-hook-form-7.56.1.tgz",
"integrity": "sha512-qWAVokhSpshhcEuQDSANHx3jiAEFzu2HAaaQIzi/r9FNPm1ioAvuJSD4EuZzWd7Al7nTRKcKPnBKO7sRn+zavQ==",
"license": "MIT",
"peer": true,
"engines": {
"node": ">=18.0.0"
},
@@ -12535,6 +12601,7 @@
"resolved": "https://registry.npmjs.org/react-markdown/-/react-markdown-10.1.0.tgz",
"integrity": "sha512-qKxVopLT/TyA6BX3Ue5NwabOsAzm0Q7kAPwq6L+wWDwisYs7R8vZ0nRXqq6rkueboxpkjvLGU9fWifiX/ZZFxQ==",
"license": "MIT",
"peer": true,
"dependencies": {
"@types/hast": "^3.0.0",
"@types/mdast": "^4.0.0",
@@ -13117,6 +13184,7 @@
"integrity": "sha512-C5VvvgCCyfyotVITIAv+4efVytl5F7wt+/I2i9q9GZcEXW9BP52YYOXC58igUi+LFZVHukErIIqQSWwv/M3WRw==",
"devOptional": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.7"
},
@@ -14168,6 +14236,7 @@
"resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-3.4.17.tgz",
"integrity": "sha512-w33E2aCvSDP0tW9RZuNXadXlkHXqFzSkQew/aIa2i/Sj8fThxwovwlXHSPXTbAHwEIhBFXAedUhP2tueAKP8Og==",
"license": "MIT",
"peer": true,
"dependencies": {
"@alloc/quick-lru": "^5.2.0",
"arg": "^5.0.2",
@@ -14371,6 +14440,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -14643,6 +14713,7 @@
"integrity": "sha512-p1diW6TqL9L07nNxvRMM7hMMw4c5XOo/1ibL4aAIGmSAt9slTE1Xgw5KWuof2uTOvCg9BY7ZRi+GaF+7sfgPeQ==",
"devOptional": true,
"license": "Apache-2.0",
"peer": true,
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
@@ -15152,6 +15223,7 @@
"integrity": "sha512-cZn6NDFE7wdTpINgs++ZJ4N49W2vRp8LCKrn3Ob1kYNtOo21vfDoaV5GzBfLU4MovSAB8uNRm4jgzVQZ+mBzPQ==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.25.0",
"fdir": "^6.4.4",
@@ -15296,6 +15368,7 @@
"integrity": "sha512-M7BAV6Rlcy5u+m6oPhAPFgJTzAioX/6B0DxyvDlo9l8+T3nLKbrczg2WLUyzd45L8RqfUMyGPzekbMvX2Ldkwg==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -15766,6 +15839,7 @@
"integrity": "sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"fast-deep-equal": "^3.1.3",
"fast-uri": "^3.0.1",
@@ -15842,6 +15916,7 @@
"integrity": "sha512-fS6iqSPZDs3dr/y7Od6y5nha8dW1YnbgtsyotCVvoFGKbERG++CVRFv1meyGDE1SNItQA8BrnCw7ScdAhRJ3XQ==",
"dev": true,
"license": "MIT",
"peer": true,
"bin": {
"rollup": "dist/bin/rollup"
},
+3 -1
View File
@@ -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 && electron electron",
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
},
"dependencies": {
@@ -81,6 +81,7 @@
"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",
@@ -118,6 +119,7 @@
"@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",
+2 -1
View File
@@ -1 +1,2 @@
/* /index.html 200
/assets/* /assets/:splat 200
/* /index.html 200
-2
View File
@@ -21,7 +21,6 @@ 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() {
@@ -52,7 +51,6 @@ 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 */}
+1
View File
@@ -79,6 +79,7 @@ export function AppProvider(props: AppProviderProps) {
const appContextValue: AppContextType = {
config,
defaultConfig,
updateConfig,
};
+8 -24
View File
@@ -346,10 +346,8 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
});
}
// Invalidate queries to refresh the data immediately
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
queryClient.invalidateQueries({ queryKey: ['showcase-moderation'] });
// If this is a Halloween app, also invalidate Halloween queries
if (isHalloweenSubmission) {
@@ -372,28 +370,14 @@ 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 */}
<Link
to={appNaddr ? `/showcase/${appNaddr}` : '#'}
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
>
{!imageError ? (
@@ -413,15 +397,15 @@ export function AppShowcaseCard({ app, onEdit, showModerationControls, hideAppro
</div>
</div>
)}
</Link>
</a>
{/* 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" disabled={isPending}>
<MoreVertical className={`w-4 h-4 ${isPending ? 'animate-spin' : ''}`} />
<Button variant="secondary" size="sm" className="h-8 w-8 p-0">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
+7
View File
@@ -124,6 +124,7 @@ 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>({
@@ -294,6 +295,10 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setShakespeareForm({ subdomain });
}, []);
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
setIsShakespeareFormValid(isValid);
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
@@ -317,6 +322,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
onValidationChange={handleShakespeareValidationChange}
/>
);
}
@@ -495,6 +501,7 @@ 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)
}
-112
View File
@@ -1,112 +0,0 @@
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>
);
}
+21 -6
View File
@@ -1,6 +1,7 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { ReactNode } from 'react';
import { cn } from '@/lib/utils';
import { ReactNode, useMemo } from 'react';
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
@@ -25,14 +26,28 @@ export function ExternalFavicon({
}: ExternalFaviconProps) {
const { config } = useAppContext();
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
// Generate the favicon URL using the configured template
const faviconSrc = faviconUrl(config.faviconUrl, normalizedUrl);
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]);
// 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>
)
}
return (
<span className={`inline-flex items-center justify-center ${className}`}>
<span className={cn('inline-flex items-center justify-center', className)}>
<img
src={faviconSrc}
alt=""
+54 -2
View File
@@ -25,6 +25,7 @@ const baseGitStatus = {
},
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
vi.mock('@/hooks/useGitStatus', () => ({
@@ -82,7 +83,16 @@ describe('GitDialog', () => {
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status', () => {
it('shows sync status when branch is published', () => {
// Mock git status with published branch
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -133,7 +143,17 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).not.toBeDisabled();
});
it('disables push button when no commits ahead', () => {
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,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -147,6 +167,38 @@ 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>
+107 -64
View File
@@ -243,13 +243,23 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
object: currentRef,
});
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
});
// 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) {
@@ -446,50 +456,7 @@ 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.');
}
// 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');
console.log('Repository has refs:', refTags);
// Set origin remote to Nostr URL
// Format: nostr://<npub>/<repo-id>
@@ -522,13 +489,54 @@ 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({
@@ -561,7 +569,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
return;
}
if (gitStatus.ahead === 0) {
// Allow push if there are commits ahead OR if the remote branch doesn't exist (publishing new branch)
if (gitStatus.ahead === 0 && gitStatus.remoteBranchExists) {
toast({
title: "Nothing to push",
description: "No commits ahead of remote. Commit your changes first.",
@@ -570,6 +579,16 @@ 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 {
@@ -583,11 +602,32 @@ 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}`,
});
}
toast({
title: "Push successful",
description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${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}`,
});
}
// Refresh git status after push
await refetchGitStatus();
@@ -683,8 +723,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
}
};
const getFileStatusIcon = (status: string) => {
switch (status) {
case 'added':
@@ -728,6 +766,11 @@ 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' };
}
@@ -1095,11 +1138,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
)}
</div>
{gitStatus.remotes.length > 0 && (
{originUrl.trim() && (
<div className="flex gap-2">
<Button
onClick={handlePull}
disabled={isPulling || isPushing || isPushingToNostr}
disabled={isPulling || isPushing || isPushingToNostr || !gitStatus.remoteBranchExists}
variant="outline"
size="sm"
className="flex-1"
@@ -1114,7 +1157,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
<Button
onClick={handlePush}
disabled={isPushing || isPulling || isPushingToNostr || gitStatus.ahead === 0}
disabled={isPushing || isPulling || isPushingToNostr || (gitStatus.ahead === 0 && gitStatus.remoteBranchExists)}
variant="outline"
size="sm"
className="flex-1"
@@ -1129,7 +1172,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
</div>
)}
{gitStatus.remotes.length === 0 && user && (
{!originUrl.trim() && user && (
<Button
onClick={handlePushToNostr}
disabled={isPushingToNostr || isPushing || isPulling}
@@ -1142,7 +1185,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
) : (
<Zap className="h-4 w-4 mr-2" />
)}
{isPushingToNostr ? 'Publishing to Nostr...' : 'Push to Nostr'}
{isPushingToNostr ? 'Loading...' : 'Push to Nostr'}
</Button>
)}
+30
View File
@@ -33,9 +33,11 @@ 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;
@@ -49,6 +51,7 @@ 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();
@@ -62,6 +65,24 @@ 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);
@@ -226,6 +247,15 @@ 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>
+68 -24
View File
@@ -11,6 +11,7 @@ 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;
@@ -30,23 +31,20 @@ interface ErrorBody {
}>;
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
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) {
const navigate = useNavigate();
const { settings } = useAISettings();
// 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 => {
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
// Handle Project Preview Console Errors
if (error instanceof ProjectPreviewConsoleError) {
return {
@@ -69,7 +67,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
onClick: onOpenModelSelector,
}],
};
}
}
if (error instanceof EmptyMessageError) {
return {
@@ -101,13 +99,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
};
case error.code === 'insufficient_quota': {
if (credits.data) {
// Only show credits dialog if we have a provider with nostr enabled
if (provider?.nostr) {
return {
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
actions: [{
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}],
message: 'Your account is low on credits. Please add credits to keep creating.',
showCreditsButton: true,
actions: [],
};
} else {
return {
@@ -204,7 +201,7 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
};
};
const { message, actions = [] } = renderBody(error);
const { message, actions = [], showCreditsButton } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
@@ -217,6 +214,12 @@ export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
</h4>
<p className="text-sm text-muted-foreground">
{message}
{showCreditsButton && provider && (
<>
{' '}
<QuillyCreditsButton provider={provider} />
</>
)}
{actions.length > 0 && (
<>
{' '}
@@ -242,12 +245,53 @@ export function Quilly({ 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}
/>
</div>
</>
);
}
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}
/>
);
}
-195
View File
@@ -1,195 +0,0 @@
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>
);
}
+4 -4
View File
@@ -42,7 +42,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -78,7 +78,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -115,7 +115,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
@@ -155,7 +155,7 @@ describe('SentryProvider', () => {
};
render(
<AppContext.Provider value={{ config, updateConfig: mockUpdateConfig }}>
<AppContext.Provider value={{ config, defaultConfig: config, updateConfig: mockUpdateConfig }}>
<SentryProvider>
<div>Test</div>
</SentryProvider>
+62 -12
View File
@@ -1,12 +1,12 @@
import { ReactNode, useMemo, useEffect } from 'react';
import { ReactNode, useEffect, useRef } 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,30 +17,80 @@ 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 } = useAppContext();
const { config, defaultConfig } = useAppContext();
const { nostr } = useNostr();
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]);
// 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,
);
}
// Cleanup on unmount
useEffect(() => {
return () => {
// Fire and forget cleanup - we don't need to await in useEffect cleanup
sessionManager.cleanup().catch(error => {
sessionManager.current?.cleanup().catch(error => {
console.warn('Failed to cleanup session manager:', error);
});
};
}, [sessionManager]);
}, []);
return (
<SessionManagerContext.Provider value={sessionManager}>
<SessionManagerContext.Provider value={sessionManager.current}>
{children}
</SessionManagerContext.Provider>
);
+2 -2
View File
@@ -166,7 +166,7 @@ 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, projectsPath, user?.signer),
shell: new ShellTool(fs, cwd, git, projectsPath, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath),
};
@@ -180,7 +180,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
}
return baseTools;
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, handleFileChanged]);
}, [fs, git, cwd, user, projectId, projectsPath, tmpPath, pluginsPath, config.corsProxy, handleFileChanged]);
// Convert tools to OpenAI format
const tools = useMemo(() => {
+271 -85
View File
@@ -1,16 +1,16 @@
import { encodeBase64 } from '@std/encoding/base64';
import { useState, useEffect, useCallback, useRef } from 'react';
import { useState, useEffect, useCallback, useRef, useMemo, memo } from 'react';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
import { addConsoleMessage, getConsoleMessages, addConsoleMessageListener, removeConsoleMessageListener, type ConsoleMessage } from '@/lib/consoleMessages';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useBuildProject } from '@/hooks/useBuildProject';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, X, Terminal } from 'lucide-react';
import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, Rocket, Terminal, Trash2, ChevronRight } from 'lucide-react';
import { useIsMobile } from '@/hooks/useIsMobile';
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
import { BrowserAddressBar } from '@/components/ui/browser-address-bar';
@@ -20,11 +20,6 @@ import {
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import {
Popover,
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -88,6 +83,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const [historyIndex, setHistoryIndex] = useState(0);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const [showConsoleView, setShowConsoleView] = useState(false);
const iframeRef = useRef<HTMLIFrameElement>(null);
const { fs } = useFS();
const { projectsPath } = useFSPaths();
@@ -465,6 +461,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
setFileContent('');
setMobileCodeView('explorer');
setDesktopCodeView('files');
setShowConsoleView(false);
// Reset navigation history and state
setCurrentPath('/');
@@ -521,102 +518,282 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
};
const ConsoleDropdown = () => {
const [isOpen, setIsOpen] = useState(false);
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
// Constants
const CONSOLE_SORT_ORDER_KEY = 'consoleSortOrder';
const COPY_FEEDBACK_DURATION = 2000;
const MAX_CONSOLE_MESSAGES = 500; // Limit displayed messages for performance
const messages = isOpen ? getConsoleMessages() : [];
// Helper function to get message level color
const getMessageLevelColor = (level: ConsoleMessage['level']): string => {
switch (level) {
case 'error': return 'text-destructive';
case 'warn': return 'text-warning';
case 'info': return 'text-primary';
default: return 'text-muted-foreground';
}
};
const ConsoleToggleButton = () => {
return (
<Button
variant={showConsoleView ? "secondary" : "ghost"}
size="sm"
className="h-8 w-8 p-0 relative"
onClick={() => setShowConsoleView(!showConsoleView)}
title={showConsoleView ? "Show preview" : "Show console"}
>
<Bug className="h-4 w-4" />
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
</Button>
);
};
// Individual console message component - memoized for performance
const ConsoleMessage = memo(({ msg, index, copiedMessageIndex, onCopy }: {
msg: ConsoleMessage;
index: number;
copiedMessageIndex: number | null;
onCopy: (msg: ConsoleMessage, index: number) => void;
}) => {
return (
<div
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
onClick={(e) => {
e.stopPropagation();
onCopy(msg, index);
}}
>
<div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
getMessageLevelColor(msg.level)
)}>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
onCopy(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
);
});
ConsoleMessage.displayName = 'ConsoleMessage';
const ConsoleView = () => {
const [copiedMessageIndex, setCopiedMessageIndex] = useState<number | null>(null);
const [isInitialLoad, setIsInitialLoad] = useState(true);
const [rawMessages, setRawMessages] = useState<ConsoleMessage[]>([]);
const [totalMessageCount, setTotalMessageCount] = useState(0);
// Load sort order from localStorage, default to 'newest-first'
const [sortOrder, setSortOrder] = useState<'newest-first' | 'oldest-first'>(() => {
const saved = localStorage.getItem(CONSOLE_SORT_ORDER_KEY);
return (saved === 'oldest-first' || saved === 'newest-first') ? saved : 'newest-first';
});
// Save sort order to localStorage whenever it changes
useEffect(() => {
localStorage.setItem(CONSOLE_SORT_ORDER_KEY, sortOrder);
}, [sortOrder]);
// Track rapid message bursts for intelligent batching
const lastMessageTimeRef = useRef<number>(0);
const pendingUpdateRef = useRef<number>();
const messageCountSinceUpdateRef = useRef<number>(0);
// Update messages from the global store - optimized for immediate updates
const updateMessages = useCallback(() => {
const allMessages = getConsoleMessages();
setTotalMessageCount(allMessages.length);
// Limit messages for performance (keep most recent)
const limitedMessages = allMessages.length > MAX_CONSOLE_MESSAGES
? allMessages.slice(-MAX_CONSOLE_MESSAGES)
: allMessages;
setRawMessages(limitedMessages);
setIsInitialLoad(false);
messageCountSinceUpdateRef.current = 0;
}, []);
// Smart update handler: immediate for single messages, batched for rapid bursts
const handleMessageUpdate = useCallback(() => {
const now = Date.now();
const timeSinceLastMessage = now - lastMessageTimeRef.current;
lastMessageTimeRef.current = now;
messageCountSinceUpdateRef.current += 1;
// Detect rapid bursts: if we get more than 3 messages within 50ms, batch them
const isRapidBurst = messageCountSinceUpdateRef.current > 3 && timeSinceLastMessage < 50;
// Clear any pending update
if (pendingUpdateRef.current) {
cancelAnimationFrame(pendingUpdateRef.current);
pendingUpdateRef.current = undefined;
}
if (isRapidBurst) {
// Batch rapid updates using requestAnimationFrame for smooth rendering
// This prevents UI blocking during loops that log many messages
pendingUpdateRef.current = requestAnimationFrame(() => {
updateMessages();
});
} else {
// Immediate update for normal console.log calls (like browser console)
// Single messages appear instantly, just like native browser console
updateMessages();
}
}, [updateMessages]);
// Initial load and listener setup
useEffect(() => {
// Initial load - check if we have many messages
const allMessages = getConsoleMessages();
if (allMessages.length > 500) {
setIsInitialLoad(true);
// Use requestIdleCallback for non-blocking initial render, fallback to setTimeout
const scheduleUpdate = () => {
if ('requestIdleCallback' in window) {
requestIdleCallback(() => {
updateMessages();
}, { timeout: 100 });
} else {
setTimeout(() => {
updateMessages();
}, 0);
}
};
scheduleUpdate();
} else {
updateMessages();
}
addConsoleMessageListener(handleMessageUpdate);
return () => {
removeConsoleMessageListener(handleMessageUpdate);
if (pendingUpdateRef.current) {
cancelAnimationFrame(pendingUpdateRef.current);
}
};
}, [handleMessageUpdate, updateMessages]);
// Memoize sorted messages to avoid recalculation on every render
const messages = useMemo(() => {
if (sortOrder === 'newest-first') {
// For newest-first, reverse the array (messages are stored oldest-first)
return [...rawMessages].reverse();
}
return rawMessages;
}, [rawMessages, sortOrder]);
const copyMessageToClipboard = async (msg: ConsoleMessage, index: number) => {
try {
await navigator.clipboard.writeText(msg.message);
setCopiedMessageIndex(index);
setTimeout(() => setCopiedMessageIndex(null), 2000);
setTimeout(() => setCopiedMessageIndex(null), COPY_FEEDBACK_DURATION);
} catch (error) {
console.error('Failed to copy message to clipboard:', error);
}
};
const handleClearMessages = () => {
clearErrors();
setCopiedMessageIndex(null);
};
const messageCount = messages.length;
const hasMoreMessages = rawMessages.length >= MAX_CONSOLE_MESSAGES;
return (
<Popover open={isOpen} onOpenChange={setIsOpen}>
<PopoverTrigger asChild>
<div className="h-full w-full flex flex-col bg-background">
{/* Header */}
<div className="h-12 flex-shrink-0 flex items-center justify-between px-4 border-b">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 relative"
onClick={() => setShowConsoleView(false)}
className="h-8 gap-2 text-muted-foreground hover:text-foreground"
>
<Bug className="h-4 w-4" />
{hasConsoleErrors && (
<span className="absolute -top-1 -right-1 h-3 w-3 rounded-full border-2 border-background bg-red-500" />
)}
<ArrowLeft className="h-4 w-4" />
Back
</Button>
</PopoverTrigger>
<PopoverContent
align="end"
className="w-[calc(100vw-1rem)] max-w-[480px] max-h-[512px] overflow-hidden shadow-lg border rounded-lg bg-background p-0"
sideOffset={4}
>
<div className="flex items-center gap-2">
{messageCount > 0 && (
<>
{hasMoreMessages && (
<span className="text-xs text-muted-foreground">
Showing last {MAX_CONSOLE_MESSAGES.toLocaleString()} of {totalMessageCount.toLocaleString()}
</span>
)}
<Button
variant="ghost"
size="sm"
onClick={() => setSortOrder(sortOrder === 'newest-first' ? 'oldest-first' : 'newest-first')}
className="h-8 text-muted-foreground hover:text-foreground"
>
{sortOrder === 'newest-first' ? t('latestFirst') : t('oldestFirst')}
</Button>
<Button
variant="ghost"
size="sm"
onClick={handleClearMessages}
className="h-8 w-8 p-0 text-destructive/80 hover:text-destructive"
>
<Trash2 className="h-4 w-4" />
</Button>
</>
)}
</div>
</div>
{/* Messages */}
<div className="h-[60vh] max-h-[512px] w-full bg-background text-foreground font-mono text-xs relative overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none]">
{/* Messages */}
<div className="flex-1 min-h-0 overflow-y-auto overflow-x-hidden [&::-webkit-scrollbar]:hidden [-ms-overflow-style:none] [scrollbar-width:none] bg-background text-foreground font-mono text-xs relative">
{isInitialLoad ? (
<div className="absolute inset-0 flex items-center justify-center z-10 bg-background">
<div className="flex flex-col items-center gap-2">
<Loader2 className="h-5 w-5 animate-spin text-primary" />
<span className="text-sm text-muted-foreground">Loading console messages...</span>
</div>
</div>
) : (
<div className="py-2 px-1 space-y-0">
{messageCount === 0 ? (
<div className="flex flex-col items-center justify-center py-12 text-center">
<p className="text-sm text-muted-foreground font-medium">No console messages</p>
<p className="text-xs text-muted-foreground mt-1">Messages from your project will appear here</p>
{/* Console prompt indicator - at top for newest-first, bottom for oldest-first */}
{sortOrder === 'newest-first' && (
<div className="py-0.5 px-1 flex items-center">
<ChevronRight className="h-3 w-3 text-muted-foreground" />
</div>
)}
{messages.map((msg, index) => (
<ConsoleMessage
key={`${index}-${msg.message.slice(0, 20)}`}
msg={msg}
index={index}
copiedMessageIndex={copiedMessageIndex}
onCopy={copyMessageToClipboard}
/>
))}
{sortOrder === 'oldest-first' && (
<div className="py-0.5 px-1 flex items-center">
<ChevronRight className="h-3 w-3 text-muted-foreground" />
</div>
) : (
messages.map((msg, index) => (
<div
key={index}
className="group relative py-0.5 px-1 hover:bg-muted/50 transition-colors duration-150 rounded cursor-pointer"
onClick={(e) => {
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
>
<div className={cn(
"text-xs font-mono leading-tight whitespace-pre-wrap break-words",
msg.level === 'error' ? "text-destructive" :
msg.level === 'warn' ? "text-warning" :
msg.level === 'info' ? "text-primary" :
"text-muted-foreground"
)}>
{msg.message}
</div>
<Button
variant="ghost"
size="sm"
onClick={(e) => {
e.preventDefault();
e.stopPropagation();
copyMessageToClipboard(msg, index);
}}
className="h-3 w-3 p-0 opacity-0 group-hover:opacity-100 transition-all duration-200 absolute right-1 top-1 hover:bg-muted/70 text-muted-foreground hover:text-foreground bg-background/80 rounded border"
>
{copiedMessageIndex === index ? (
<Check className="h-2 w-2 text-success" />
) : (
<Copy className="h-2 w-2" />
)}
</Button>
</div>
))
)}
</div>
</div>
{/* Close button */}
<button
onClick={() => setIsOpen(false)}
className="absolute top-2 right-2 h-8 w-8 p-0 bg-muted/50 hover:bg-muted/70 rounded-md z-10 flex items-center justify-center border"
>
<X className="h-5 w-5 text-muted-foreground" />
</button>
</PopoverContent>
</Popover>
)}
</div>
</div>
);
};
@@ -689,7 +866,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
<Code className="h-4 w-4" />
</Button>
)}
<ConsoleDropdown />
<ConsoleToggleButton />
<Menu />
</div>
)}
@@ -697,16 +874,25 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
</div>
{/* Content area */}
<div className="flex-1">
{hasBuiltProject ? (
<div className="flex-1 min-h-0 relative">
{/* Console View */}
<div className={cn("absolute inset-0", showConsoleView ? "block" : "hidden")}>
<ConsoleView />
</div>
{/* Preview iframe */}
{hasBuiltProject && (
<iframe
ref={iframeRef}
src={`https://${projectId}.${previewDomain}/`}
className="w-full h-full border-0"
className={cn("w-full h-full border-0", showConsoleView ? "hidden" : "block")}
title="Project Preview"
sandbox="allow-scripts allow-same-origin"
/>
) : (
)}
{/* Build prompt */}
{!hasBuiltProject && !showConsoleView && (
<div className="h-full flex items-center justify-center bg-muted">
<div className="text-center">
<h3 className="text-lg font-semibold mb-2">{t('projectPreview')}</h3>
+4 -2
View File
@@ -8,6 +8,7 @@ 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 {
@@ -37,10 +38,11 @@ export function Terminal({ projectId, className }: TerminalProps) {
const { projectsPath } = useFSPaths();
const { git } = useGit();
const { user } = useCurrentUser();
const { config } = useAppContext();
// Initialize ShellTool
useEffect(() => {
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, user?.signer);
shellToolRef.current = new ShellTool(fs, `${projectsPath}/${projectId}`, git, projectsPath, config.corsProxy, user?.signer);
// Add welcome message
setLines([{
@@ -49,7 +51,7 @@ export function Terminal({ projectId, className }: TerminalProps) {
content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`,
timestamp: new Date()
}]);
}, [projectId, fs, git, projectsPath, user?.signer]);
}, [projectId, fs, git, projectsPath, config.corsProxy, user?.signer]);
// Auto-scroll to bottom when new lines are added or execution state changes
useEffect(() => {
+4 -12
View File
@@ -5,7 +5,6 @@ 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';
@@ -27,10 +26,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 });
@@ -56,7 +55,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"
>
@@ -72,13 +71,6 @@ 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">
@@ -91,7 +83,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>
+6 -9
View File
@@ -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,13 +72,10 @@ export function CommentForm({
/>
<div className="flex justify-between items-center">
<span className="text-sm text-muted-foreground">
{isPending
? (reply ? 'Posting reply...' : 'Posting comment...')
: (reply ? 'Replying to comment' : 'Adding to the discussion')
}
{reply ? 'Replying to comment' : 'Adding to the discussion'}
</span>
<Button
type="submit"
<Button
type="submit"
disabled={!content.trim() || isPending}
size={compact ? "sm" : "default"}
>
-163
View File
@@ -1,163 +0,0 @@
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,24 +1,35 @@
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 (
@@ -30,7 +41,14 @@ 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>
+13 -3
View File
@@ -187,13 +187,23 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
object: currentRef,
});
toast({
title: 'Branch created',
description: `Created branch "${newBranchName}"`,
// Automatically check out the new branch
await git.checkout({
dir: projectPath,
ref: newBranchName.trim(),
force: true,
});
// 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) {
+4
View File
@@ -44,11 +44,15 @@ export interface AppConfig {
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;
}
+23 -21
View File
@@ -38,28 +38,30 @@ describe('useAIProjectId', () => {
});
// Mock useAppContext
mockUseAppContext.mockReturnValue({
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,
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',
sentryDsn: '',
sentryEnabled: false,
};
mockUseAppContext.mockReturnValue({
config,
defaultConfig: config,
updateConfig: vi.fn(),
});
+2 -2
View File
@@ -223,8 +223,8 @@ export function useAppSubmissions() {
return submissions;
},
staleTime: 10000, // 10 seconds
refetchInterval: 30000, // 30 seconds
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
-231
View File
@@ -1,231 +0,0 @@
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]
});
},
});
}
+1 -3
View File
@@ -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,7 +94,5 @@ export function useComments(root: NostrEvent | URL, limit?: number) {
};
},
enabled: !!root,
staleTime: 10000, // 10 seconds
refetchInterval: 30000, // 30 seconds
});
}
+648 -23
View File
@@ -1,32 +1,24 @@
import { describe, it, expect, vi } from 'vitest';
import { describe, it, expect, vi, beforeEach } 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: {
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),
},
git: mockGit,
}),
}));
@@ -44,7 +36,30 @@ 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,
@@ -57,7 +72,28 @@ describe('useGitFetch', () => {
expect(result.current.isSuccess).toBe(false);
});
it('fetches remote updates successfully', async () => {
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)
const { result } = renderHook(() => useGitFetch('test-project'), {
wrapper: TestApp,
});
@@ -72,9 +108,207 @@ 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,
});
@@ -85,11 +319,402 @@ 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);
});
});
});
+45 -18
View File
@@ -131,25 +131,31 @@ export function useGitFetch(projectId: string | null) {
let beforeDefaultOid: string | null = null;
let beforeCurrentOid: string | null = null;
// Get remote info to find default branch
// Get default branch from local symbolic ref
let defaultBranch: string | null = null;
try {
console.log('Fetching remote info...');
const remoteInfo = await git.getRemoteInfo({
url: remoteUrl,
...(credentials && {
onAuth: () => ({
username: credentials.username,
password: credentials.password,
}),
}),
});
console.log('Reading default branch from local symbolic ref...');
// 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);
// 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');
}
// If we have a default branch, try to get its OID before fetch
@@ -165,7 +171,7 @@ export function useGitFetch(projectId: string | null) {
}
}
} catch (error) {
console.warn('Could not get remote info:', error);
console.warn('Could not read default branch from local data:', error);
}
// Get current branch OID before fetch
@@ -204,6 +210,27 @@ 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({
@@ -319,7 +346,7 @@ export function useGitFetch(projectId: string | null) {
if (currentBranchChanged && query.data.currentBranch) {
toast({
title: 'Remote changes detected',
description: `The ${query.data.currentBranch} branch has new commits available.`,
description: `The ${query.data.currentBranch} branch has ${query.data.currentBranchOid === null ? 'been deleted' : 'new commits available'}.`,
variant: 'default',
});
+11 -5
View File
@@ -38,6 +38,7 @@ interface GitStatus {
branches: string[];
ahead: number;
behind: number;
remoteBranchExists: boolean;
}
export function useGitStatus(projectId: string | null) {
@@ -59,6 +60,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -80,6 +82,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
@@ -200,6 +203,7 @@ 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')
@@ -224,6 +228,9 @@ 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({
@@ -247,11 +254,8 @@ export function useGitStatus(projectId: string | null) {
behind = remoteOnlyCommits.length;
}
} catch {
// 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;
}
// Remote branch doesn't exist
remoteBranchExists = false;
}
}
} catch (err) {
@@ -269,6 +273,7 @@ export function useGitStatus(projectId: string | null) {
branches,
ahead,
behind,
remoteBranchExists,
};
} catch (error) {
console.error('Error checking git status:', error);
@@ -283,6 +288,7 @@ export function useGitStatus(projectId: string | null) {
branches: [],
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
}
},
+1 -48
View File
@@ -1,5 +1,5 @@
import { useNostr } from "@nostrify/react";
import { useMutation, useQueryClient, type UseMutationResult } from "@tanstack/react-query";
import { useMutation, type UseMutationResult } from "@tanstack/react-query";
import { useCurrentUser } from "./useCurrentUser";
@@ -8,7 +8,6 @@ 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'>) => {
@@ -38,52 +37,6 @@ 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'] });
}
},
});
}
+2 -55
View File
@@ -1,6 +1,5 @@
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 {
@@ -12,7 +11,6 @@ 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({
@@ -84,61 +82,10 @@ 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 to get the real data
// Invalidate and refetch comments
queryClient.invalidateQueries({
queryKey: ['nostr', 'comments', root instanceof URL ? root.toString() : root.id]
queryKey: ['comments', root instanceof URL ? root.toString() : root.id]
});
},
});
+63
View File
@@ -260,4 +260,67 @@ 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();
});
});
});
+34
View File
@@ -278,4 +278,38 @@ 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}`);
}
}
}
+39 -1
View File
@@ -1,6 +1,8 @@
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 = {
@@ -22,6 +24,39 @@ 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',
sentryDsn: '',
sentryEnabled: false,
};
describe('SessionManager', () => {
let sessionManager: SessionManager;
const mockAISettings = {
@@ -35,7 +70,10 @@ describe('SessionManager', () => {
};
beforeEach(() => {
sessionManager = new SessionManager(mockFS, mockAISettings);
const getSettings = () => mockAISettings;
const getConfig = () => testConfig;
const getDefaultConfig = () => testConfig;
sessionManager = new SessionManager(mockFS, mockNostr, getSettings, getConfig, getDefaultConfig);
});
it('should initialize streaming message with reasoning content', async () => {
+77 -24
View File
@@ -11,6 +11,9 @@ 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';
@@ -58,29 +61,34 @@ export class SessionManager {
private sessions = new Map<string, SessionState>();
private listeners: Partial<Record<keyof SessionManagerEvents, Set<(...args: unknown[]) => void>>> = {};
private fs: JSRuntimeFS;
private aiSettings: { providers: AIProvider[] };
private nostr: NPool;
private getSettings: () => { providers: AIProvider[] };
private getConfig: () => AppConfig;
private getDefaultConfig: () => AppConfig;
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,
aiSettings: { providers: AIProvider[] },
nostr: NPool,
getSettings: () => { providers: AIProvider[] },
getConfig: () => AppConfig,
getDefaultConfig: () => AppConfig,
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.aiSettings = aiSettings;
this.nostr = nostr;
this.getSettings = getSettings;
this.getConfig = getConfig;
this.getDefaultConfig = getDefaultConfig;
this.getProviderModels = getProviderModels;
this.getCurrentUser = getCurrentUser;
this.projectsPath = projectsPath;
this.pluginsPath = pluginsPath;
this.corsProxy = corsProxy;
}
private get git(): Git {
const config = this.getConfig();
return new Git({ fs: this.fs, nostr: this.nostr, corsProxy: config.corsProxy });
}
/**
@@ -97,7 +105,8 @@ export class SessionManager {
// Try to load existing history
try {
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${projectId}`);
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
const lastSession = await dotAI.readLastSessionHistory();
if (lastSession) {
messages = lastSession.messages;
@@ -154,7 +163,7 @@ export class SessionManager {
*/
async deleteSession(projectId: string): Promise<void> {
const session = this.sessions.get(projectId);
session?.abortController?.abort();
session?.abortController?.abort('Session deleted');
this.sessions.delete(projectId);
@@ -209,14 +218,19 @@ 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, this.aiSettings.providers);
const parsed = parseProviderModel(providerModel, settings.providers);
const provider = parsed.provider;
const model = parsed.model;
// Initialize OpenAI client
const { user, metadata } = this.getCurrentUser?.() ?? {};
const openai = createAIClient(provider, user, this.corsProxy);
const openai = createAIClient(provider, user, config.corsProxy);
let stepCount = 0;
const maxSteps = session.maxSteps || 50;
@@ -238,16 +252,26 @@ 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: `${this.projectsPath}/${projectId}`,
cwd: `${config.fsPathProjects}/${projectId}`,
fs: this.fs,
mode: "agent",
name: "Shakespeare",
profession: "software extraordinaire",
tools: Object.values(session.tools),
pluginsPath: this.pluginsPath,
config,
defaultConfig,
user,
metadata,
repositoryUrl,
template: config.systemPrompt,
});
// Prepare messages for AI
@@ -480,7 +504,7 @@ export class SessionManager {
const session = this.sessions.get(projectId);
if (!session) return;
session.abortController?.abort();
session.abortController?.abort('User stopped generation');
session.isLoading = false;
session.streamingMessage = undefined;
session.abortController = undefined;
@@ -524,7 +548,7 @@ export class SessionManager {
/**
* Update session cost and context usage based on usage data
*/
private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void {
private async updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): Promise<void> {
if (!this.getProviderModels) return;
const session = this.sessions.get(projectId);
@@ -534,12 +558,16 @@ 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 parsed = parseProviderModel(providerModel, this.aiSettings.providers);
const settings = this.getSettings();
const parsed = parseProviderModel(providerModel, settings.providers);
const modelName = parsed.model;
const provider = parsed.provider;
@@ -563,6 +591,9 @@ 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);
}
@@ -576,13 +607,35 @@ export class SessionManager {
if (!session) return;
try {
const dotAI = new DotAI(this.fs, `${this.projectsPath}/${session.projectId}`);
const config = this.getConfig();
const dotAI = new DotAI(this.fs, `${config.fsPathProjects}/${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
*/
+24 -8
View File
@@ -243,14 +243,12 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
// Handle bare imports like "react"
build.onResolve({ filter: /^[^./].*/ }, (args) => {
// 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 [path, query] = args.path.split("?");
const params = new URLSearchParams(query);
const packageName = args.path.startsWith("@")
? args.path.split("/").slice(0, 2).join("/")
: args.path.split("/")[0];
const packageName = path.startsWith("@")
? path.split("/").slice(0, 2).join("/")
: path.split("/")[0];
// If the importer is CSS, ignore (no JS deps)
try {
@@ -319,7 +317,7 @@ export function esmPlugin(options: EsmPluginOptions): Plugin {
}
}
const packagePath = args.path.slice(packageName.length);
const packagePath = path.slice(packageName.length);
const specifier = version
? `${cdnName}@${version}${packagePath}`
: `${cdnName}${packagePath}`;
@@ -339,6 +337,14 @@ 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",
@@ -426,6 +432,8 @@ 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";
}
@@ -438,6 +446,14 @@ 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",
};
});
},
};
}
+1 -1
View File
@@ -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(esmUrl);
const esbuild = await getEsbuild();
const indexHtmlText = await fs.readFile(
`${projectPath}/index.html`,
+2 -1
View File
@@ -23,9 +23,10 @@ const mockFS: JSRuntimeFS = {
describe('CurlCommand', () => {
let curlCommand: CurlCommand;
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
beforeEach(() => {
curlCommand = new CurlCommand(mockFS);
curlCommand = new CurlCommand(mockFS, testCorsProxy);
vi.clearAllMocks();
});
+7 -4
View File
@@ -3,6 +3,7 @@ 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
@@ -35,9 +36,11 @@ export class CurlCommand implements ShellCommand {
usage = 'curl [options] <url>';
private fs: JSRuntimeFS;
private corsProxy: string;
constructor(fs: JSRuntimeFS) {
constructor(fs: JSRuntimeFS, corsProxy: string) {
this.fs = fs;
this.corsProxy = corsProxy;
}
async execute(args: string[], cwd: string, _input?: string): Promise<ShellCommandResult> {
@@ -61,9 +64,9 @@ export class CurlCommand implements ShellCommand {
return createErrorResult(`${this.name}: unsupported protocol: ${url.protocol}`);
}
// Proxy the URL through CorsProxy
// Proxy the URL through configured CorsProxy
const originalUrl = url.toString();
const proxiedUrl = `https://proxy.shakespeare.diy/?url=${encodeURIComponent(originalUrl)}`;
const proxiedUrl = proxyUrl(this.corsProxy, originalUrl);
// Prepare request
const requestInit: RequestInit = {
@@ -93,7 +96,7 @@ export class CurlCommand implements ShellCommand {
let timeoutId: ReturnType<typeof setTimeout> | undefined;
if (options.timeout) {
timeoutId = setTimeout(() => controller.abort(), options.timeout * 1000);
timeoutId = setTimeout(() => controller.abort('Request timeout'), options.timeout * 1000);
requestInit.signal = controller.signal;
}
+6 -5
View File
@@ -1,22 +1,23 @@
import type _ESBuild from "esbuild-wasm";
import wasmUrl from "esbuild-wasm/esbuild.wasm?url";
type ESBuild = typeof _ESBuild;
let promise: Promise<ESBuild> | undefined;
export function getEsbuild(esmUrl: string): Promise<ESBuild> {
export function getEsbuild(): Promise<ESBuild> {
if (!promise) {
promise = loadEsbuild(esmUrl);
promise = loadEsbuild();
}
return promise;
}
async function loadEsbuild(esmUrl: string): Promise<ESBuild> {
async function loadEsbuild(): Promise<ESBuild> {
const { default: esbuild } = await import("esbuild-wasm");
await esbuild.initialize({
worker: false,
wasmURL: `${esmUrl}/[email protected]/esbuild.wasm`,
worker: true,
wasmURL: wasmUrl,
});
return esbuild;
+152 -33
View File
@@ -681,12 +681,14 @@ export class Git {
}
/**
* Get current repository state for creating a NIP-34 repository state event
* Create initial repository state from current local git repository
* This should only be used when no existing state event is found
*/
private async getCurrentRepositoryState(dir: string): Promise<{
refTags: string[][];
headRef?: string;
}> {
private async createInitialRepositoryState(
dir: string,
dTag: string,
signer: NostrSigner
): Promise<NostrEvent> {
const refTags: string[][] = [];
let headRef: string | undefined;
@@ -765,11 +767,70 @@ export class Git {
}
console.log(`Repository state: ${refTags.length} refs, HEAD=${headRef}`);
return { refTags, headRef };
} catch (error) {
console.error('Failed to get repository state:', error);
throw new Error(`Failed to get repository state: ${error}`);
}
// Create and sign the state event
return await signer.signEvent({
kind: 30618,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags: [
['d', dTag],
...refTags,
...(headRef ? [['HEAD', headRef]] : []),
],
});
}
/**
* Apply changes from a push operation to repository state and create updated event
* Mutates the state object directly and returns the signed event
*/
private async applyPushAndUpdateStateEvent(
state: RespositoryState,
remoteRef: string,
newCommit: string,
signer: NostrSigner
): Promise<NostrEvent> {
const remoteRefName = remoteRef.startsWith('refs/') ? remoteRef : `refs/heads/${remoteRef}`;
// Update the ref
state.refs[remoteRefName] = newCommit;
// Update head commit if this ref is HEAD
if (state.HEAD === `ref: ${remoteRefName}`) {
state.headCommit = newCommit;
}
// Extract d tag from original event
const dTag = state.event.tags.find(([name]) => name === 'd');
if (!dTag || !dTag[1]) {
throw new Error('Repository state event missing required d tag');
}
const tags: string[][] = [['d', dTag[1]]];
// Add HEAD if set
if (state.HEAD) {
tags.push(['HEAD', state.HEAD]);
}
// Add all refs
for (const [ref, commit] of Object.entries(state.refs)) {
tags.push([ref, commit]);
}
// Create and sign the updated event
state.event = await signer.signEvent({
kind: 30618,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags,
});
return state.event;
}
/**
@@ -1327,7 +1388,7 @@ export class Git {
/**
* Update remote tracking refs to match the Nostr state if git data present locally
* @returns refs with missing data including HEAD
* @returns refs with missing data including HEAD, updated refs, and deleted stale refs
*/
private async updateRemoteRefsToNostrState(
state: RespositoryState,
@@ -1335,18 +1396,22 @@ export class Git {
): Promise<{
updated?: Record<string, string>,
refsWithMissingData?: Record<string, string>,
deleted?: string[],
}> {
// Get the remote name from options (passed from the fetch call)
const remoteName = options.remote || 'origin';
const refsWithMissingData: Record<string, string> = {};
const updated: Record<string, string> = {};
for (const [refName, entry] of [
const entries = [
...Object.entries(state.refs),
...(state.HEAD ? [["HEAD", state.HEAD]] : [])
]) {
];
for (const [refName, entry] of entries) {
// update symbolic ref to use remote ref
const value = entry.startsWith("ref: ") ? `ref: ${this.localRefToRemoteRef(remoteName, entry.slice(5))}` : entry;
const isSymbolic = value.startsWith("ref: ");
const refValue = isSymbolic ? value.slice(5) : value; // Remove "ref: " prefix for symbolic refs
try {
// Check if we have this commit locally
try {
@@ -1356,27 +1421,32 @@ export class Git {
fs: this.fs,
dir: options.dir,
ref:remoteRefName,
depth: 1, // Don't resolve symbolic refs, just get the raw value
});
// update correct ref
if (existingValue === value) continue;
if (existingValue === refValue) continue;
} catch {
// ref doesnt exist yet
}
if (!value.startsWith("ref: ")) await git.readCommit({
fs: this.fs,
dir: options.dir,
// TODO handle and annotated tags
oid: value,
});
// We have the commit, update the remote tracking ref
if (!isSymbolic) {
// For non-symbolic refs, verify we have the commit locally
await git.readCommit({
fs: this.fs,
dir: options.dir,
// TODO handle annotated tags
oid: refValue,
});
}
// We have the commit (or it's a symbolic ref), update the remote tracking ref
await git.writeRef({
fs: this.fs,
dir: options.dir,
ref: remoteRefName,
force: true, // standard behaviour of git fetch
value: value,
value: refValue,
symbolic: isSymbolic, // Set symbolic flag for symbolic refs
});
console.log(`✓ Updated ${remoteRefName} to ${value}`);
console.log(`✓ Updated ${remoteRefName} to ${isSymbolic ? 'ref: ' : ''}${refValue}`);
updated[refName] = entry;
} catch (error) {
refsWithMissingData[refName] = value;
@@ -1388,9 +1458,48 @@ export class Git {
}
}
// Delete local remote refs that don't exist in Repository State
const deleted: string[] = [];
try {
// Get all local remote tracking refs for this remote
const localRemoteRefs = await git.listRefs({
fs: this.fs,
dir: options.dir,
filepath: `refs/remotes/${remoteName}`
});
// Build set of expected remote refs based on Repository State
// This should match the same set of refs we iterated over above
const expectedRemoteRefs = new Set<string>();
for (const [refName] of entries) {
expectedRemoteRefs.add(this.localRefToRemoteRef(remoteName, refName));
}
// Delete any local remote refs that don't exist in the Repository State
for (const localRemoteRef of localRemoteRefs) {
const fullRef = this.localRefToRemoteRef(remoteName, localRemoteRef);
if (!expectedRemoteRefs.has(fullRef)) {
try {
await git.deleteRef({
fs: this.fs,
dir: options.dir,
ref: fullRef,
});
console.log(`✓ Deleted stale remote ref ${localRemoteRef}`);
deleted.push(localRemoteRef);
} catch (error) {
console.warn(`Failed to delete stale remote ref ${localRemoteRef}:`, error);
}
}
}
} catch (error) {
console.warn('Failed to clean up stale remote refs:', error);
}
return {
refsWithMissingData: Object.keys(refsWithMissingData).length > 0 ? refsWithMissingData : undefined,
updated: Object.keys(updated).length > 0 ? updated : undefined,
deleted: deleted.length > 0 ? deleted : undefined,
}
}
@@ -1774,7 +1883,7 @@ export class Git {
}
// Extract relay URLs and clone URLs from the repository announcement
const relayUrls: string[] = [];
const relayUrls: string[] = [ ...(repo.relays) ?? []];
// If no relays specified in announcement, use default git-focused relays
if (relayUrls.length === 0) {
@@ -1813,20 +1922,30 @@ export class Git {
}
}
// Get current repository state
const repoState = await this.getCurrentRepositoryState(dir);
// Update or create repository state
let stateEvent: NostrEvent;
// Create repository state event (kind 30618)
const stateEvent = await signer.signEvent({
kind: 30618,
created_at: Math.floor(Date.now() / 1000),
content: '',
tags: [
['d', nostrURI.d], // Repository identifier
...repoState.refTags,
...(repoState.headRef ? [['HEAD', repoState.headRef]] : []),
],
});
if (state) {
// We have an existing state event - update it with the new ref
// Get the commit we're pushing
let localCommit: string;
try {
localCommit = await git.resolveRef({
fs: this.fs,
dir,
ref,
});
} catch (error) {
throw new Error(`Failed to resolve local ref ${ref}: ${error}`);
}
// Apply push changes and create updated event
stateEvent = await this.applyPushAndUpdateStateEvent(state, remoteRef, localCommit, signer);
} else {
// No existing state event - create initial state from repository
stateEvent = await this.createInitialRepositoryState(dir, nostrURI.d, signer);
}
// Publish the state event to Nostr relays
console.log(`Publishing repository state to ${relayUrls.length} relays`);
+1 -1
View File
@@ -50,7 +50,7 @@ export async function initializeSentry(dsn: string): Promise<void> {
// Environment
environment: import.meta.env.MODE,
// Release
release: import.meta.env.VERSION || 'development',
release: import.meta.env.VERSION,
// Censor sensitive data before sending to Sentry
beforeSend(event) {
// Regex to match Nostr nsec private keys
+522
View File
@@ -0,0 +1,522 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { makeSystemPrompt, MakeSystemPromptOpts } from './system';
import { JSRuntimeFS } from './JSRuntime';
import { NUser } from '@nostrify/react/login';
import { NostrMetadata } from '@nostrify/nostrify';
import { AppConfig } from '@/contexts/AppContext';
import OpenAI from 'openai';
// Mock the plugins module
vi.mock('./plugins', () => ({
getAllSkills: vi.fn(),
}));
// Mock path-browserify
vi.mock('path-browserify', () => ({
join: (...args: string[]) => args.join('/').replace(/\/+/g, '/'),
}));
import { getAllSkills } from './plugins';
// 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',
sentryDsn: '',
sentryEnabled: false,
};
describe('makeSystemPrompt', () => {
let mockFs: JSRuntimeFS;
let baseOpts: MakeSystemPromptOpts;
beforeEach(() => {
vi.clearAllMocks();
// Mock filesystem
mockFs = {
readFile: vi.fn(),
writeFile: vi.fn(),
readdir: vi.fn(),
stat: vi.fn(),
mkdir: vi.fn(),
rmdir: vi.fn(),
unlink: vi.fn(),
rename: vi.fn(),
exists: vi.fn(),
} as unknown as JSRuntimeFS;
// Base options for tests
baseOpts = {
tools: [],
mode: 'agent',
fs: mockFs,
cwd: '/projects/test-project',
config: testConfig,
defaultConfig: testConfig,
};
// Mock getAllSkills to return empty array by default
vi.mocked(getAllSkills).mockResolvedValue([]);
});
describe('basic system prompt generation', () => {
it('should generate a basic system prompt in agent mode', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
expect(result).toContain('Your goal is to work on the project in the current directory');
expect(result).toContain('explore and understand the project structure');
});
it('should generate a basic system prompt in init mode', async () => {
const result = await makeSystemPrompt({ ...baseOpts, mode: 'init' });
expect(result).toContain('You are Shakespeare, an expert software extraordinaire');
expect(result).toContain('The files in the current directory are a template');
expect(result).toContain('transform this template into a working project');
});
it('should include current date', async () => {
const result = await makeSystemPrompt(baseOpts);
const currentDate = new Date().toLocaleDateString('en-US', {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric',
});
expect(result).toContain(`**Current Date**: ${currentDate}`);
});
it('should include current working directory', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('**Current Working Directory**: /projects/test-project');
});
});
describe('user information', () => {
it('should include logged-out user message when no user is provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('The user is not logged in');
expect(result).toContain('can log into Nostr by clicking the "Login" button');
});
it('should include basic user information when user is provided', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const result = await makeSystemPrompt({ ...baseOpts, user });
expect(result).toContain('The user is logged into Nostr');
expect(result).toContain('**Nostr pubkey (hex)**: abc123def456');
expect(result).toContain('**Nostr npub**: npub1');
});
it('should include user metadata when provided', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const metadata: NostrMetadata = {
name: 'Alice',
about: 'A passionate developer',
website: 'https://alice.example.com',
picture: 'https://alice.example.com/avatar.jpg',
banner: 'https://alice.example.com/banner.jpg',
nip05: '[email protected]',
lud16: '[email protected]',
};
const result = await makeSystemPrompt({ ...baseOpts, user, metadata });
expect(result).toContain('**Name**: Alice');
expect(result).toContain('**About**: A passionate developer');
expect(result).toContain('**Website**: https://alice.example.com');
expect(result).toContain('**Avatar**: https://alice.example.com/avatar.jpg');
expect(result).toContain('**Banner**: https://alice.example.com/banner.jpg');
expect(result).toContain('**NIP-05**: [email protected]');
expect(result).toContain('**Lightning Address**: [email protected]');
});
it('should sanitize multiline about text', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const metadata: NostrMetadata = {
about: 'Line 1\nLine 2\r\nLine 3',
};
const result = await makeSystemPrompt({ ...baseOpts, user, metadata });
expect(result).toContain('**About**: Line 1 Line 2 Line 3');
expect(result).not.toContain('\n**About**');
});
});
describe('tools section', () => {
it('should not include tools section when no tools are provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).not.toContain('## Available Tools');
});
it('should list available tools with descriptions', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'read_file',
description: 'Read contents of a file',
parameters: {},
},
},
{
type: 'function',
function: {
name: 'write_file',
description: 'Write contents to a file',
parameters: {},
},
},
];
const result = await makeSystemPrompt({ ...baseOpts, tools });
expect(result).toContain('## Available Tools');
expect(result).toContain('**read_file**: Read contents of a file');
expect(result).toContain('**write_file**: Write contents to a file');
});
it('should handle tools without descriptions', async () => {
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'some_tool',
parameters: {},
},
},
];
const result = await makeSystemPrompt({ ...baseOpts, tools });
expect(result).toContain('**some_tool**: No description available');
});
});
describe('skills section', () => {
it('should show no skills message when pluginsPath is not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, fsPathPlugins: '' },
});
expect(result).toContain('## Skills');
expect(result).toContain('No skills are currently configured');
});
it('should show no skills message when getAllSkills returns empty array', async () => {
vi.mocked(getAllSkills).mockResolvedValue([]);
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins');
});
it('should list available skills when they exist', async () => {
vi.mocked(getAllSkills).mockResolvedValue([
{
name: 'create_component',
description: 'Create a new React component',
plugin: 'react-plugin',
path: '/plugins/react-plugin/skills/create_component.md',
},
{
name: 'setup_routing',
description: 'Setup React Router',
plugin: 'react-plugin',
path: '/plugins/react-plugin/skills/setup_routing.md',
},
]);
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Skills');
expect(result).toContain('**create_component**: Create a new React component');
expect(result).toContain('Plugin: react-plugin');
expect(result).toContain('**setup_routing**: Setup React Router');
expect(result).toContain('Skills MUST be used whenever applicable');
});
it('should handle getAllSkills errors gracefully', async () => {
vi.mocked(getAllSkills).mockRejectedValue(new Error('Plugin error'));
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
});
});
describe('CORS proxy section', () => {
it('should not include CORS proxy section when not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, corsProxy: '' },
});
expect(result).not.toContain('## Working Around CORS Issues');
});
it('should include CORS proxy information when provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('**CORS Proxy URL Template**: `https://proxy.shakespeare.diy/?url={href}`');
});
});
describe('Edit with Shakespeare section', () => {
it('should show message when no repository URL is configured', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Edit with Shakespeare');
expect(result).toContain('This project does not currently have a repository URL configured');
});
it('should include badge code snippets when repository URL is provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
repositoryUrl: 'https://github.com/user/repo.git',
});
expect(result).toContain('## Edit with Shakespeare');
expect(result).toContain('[![Edit with Shakespeare]');
expect(result).toContain('/badge.svg');
expect(result).toContain('/clone');
// URL is encoded, so check for the encoded version
expect(result).toContain('url=https%3A%2F%2Fgithub.com%2Fuser%2Frepo.git');
});
});
describe('README.md inclusion', () => {
it('should include README.md content when it exists', async () => {
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
if (path === '/projects/test-project/README.md') {
return '# My Project\n\nThis is a test project.';
}
throw new Error('File not found');
});
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('# My Project');
expect(result).toContain('This is a test project.');
});
it('should continue when README.md does not exist', async () => {
vi.mocked(mockFs.readFile).mockRejectedValue(new Error('File not found'));
const result = await makeSystemPrompt(baseOpts);
expect(result).toBeTruthy();
expect(result).not.toContain('# My Project');
});
});
describe('AGENTS.md and context files inclusion', () => {
it('should include AGENTS.md content when it exists', async () => {
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
if (path === '/projects/test-project/AGENTS.md') {
return '# Agent Instructions\n\nFollow these guidelines.';
}
throw new Error('File not found');
});
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('# Agent Instructions');
expect(result).toContain('Follow these guidelines.');
});
it('should try alternative context files in order', async () => {
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
if (path === '/projects/test-project/CONTEXT.md') {
return '# Context File\n\nProject context.';
}
throw new Error('File not found');
});
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('# Context File');
expect(result).toContain('Project context.');
});
it('should continue when no context files exist', async () => {
vi.mocked(mockFs.readFile).mockRejectedValue(new Error('File not found'));
const result = await makeSystemPrompt(baseOpts);
expect(result).toBeTruthy();
});
it('should try context files in correct order', async () => {
const readFileCalls: string[] = [];
vi.mocked(mockFs.readFile).mockImplementation(async (path: string) => {
readFileCalls.push(path);
throw new Error('File not found');
});
await makeSystemPrompt(baseOpts);
// Check that AGENTS.md is tried first
expect(readFileCalls).toContain('/projects/test-project/AGENTS.md');
});
});
describe('complete system prompt structure', () => {
it('should include all major sections', async () => {
// Use a valid hex pubkey (64 characters)
const validPubkey = '0'.repeat(64);
const user = new NUser('extension', validPubkey, {} as NUser['signer']);
const result = await makeSystemPrompt({
...baseOpts,
user,
repositoryUrl: 'https://github.com/test/repo.git',
});
expect(result).toContain('# Your Environment');
expect(result).toContain('## What Shakespeare Is');
expect(result).toContain('## The User');
expect(result).toContain('## User Interface');
expect(result).toContain('## User Actions');
expect(result).toContain('## Virtual Filesystem Structure');
expect(result).toContain('## Your Role');
expect(result).toContain('## Skills');
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('## Edit with Shakespeare');
});
it('should include Shakespeare architecture information', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('Browser-Based Storage');
expect(result).toContain('AI Provider Independence');
expect(result).toContain('Shakespeare AI Credits');
expect(result).toContain('Cross-Browser Access');
expect(result).toContain('No Central Shakespeare Server');
});
it('should include user interface description', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('**Homepage**');
expect(result).toContain('**Project View**');
expect(result).toContain('**Settings**');
expect(result).toContain('**Left Pane**: AI chat interface');
expect(result).toContain('**Right Pane**: Toggles between two views');
});
it('should include virtual filesystem structure', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('/projects/');
// The config/ and tmp/ paths are in a code block, so check for the exact format
expect(result).toContain('├── config/');
expect(result).toContain('└── tmp/');
expect(result).toContain('Project Isolation');
expect(result).toContain('Persistent Storage');
});
it('should include role description with commit reminder', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Your Role');
expect(result).toContain('Always commit your code changes');
});
});
describe('custom template support', () => {
it('should render a custom template when provided', async () => {
const customTemplate = `Hello Shakespeare! Current directory: {{ cwd }}`;
const result = await makeSystemPrompt({
...baseOpts,
template: customTemplate,
});
expect(result).toContain('Hello Shakespeare!');
expect(result).toContain('Current directory: /projects/test-project');
expect(result).not.toContain('# Your Environment'); // Should not include default template content
});
it('should support conditional logic in custom templates', async () => {
const customTemplate = `{% if mode === 'init' %}Initializing...{% else %}Working on project{% endif %}`;
const result = await makeSystemPrompt({
...baseOpts,
mode: 'agent',
template: customTemplate,
});
expect(result).toContain('Working on project');
expect(result).not.toContain('Initializing');
});
it('should provide access to all context variables in custom templates', async () => {
const user = new NUser(
'extension',
'abc123def456',
{} as NUser['signer']
);
const customTemplate = `User: {{ user.pubkey if user else 'none' }}
CWD: {{ cwd }}
Origin: {{ location.origin }}
Skills: {{ skills.length }}`;
const result = await makeSystemPrompt({
...baseOpts,
user,
template: customTemplate,
});
expect(result).toContain('User: abc123def456');
expect(result).toContain('CWD: /projects/test-project');
expect(result).toContain('Origin: http://localhost:3000');
expect(result).toContain('Skills: 0');
});
});
});
+164 -91
View File
@@ -3,64 +3,38 @@ import { NostrMetadata } from "@nostrify/nostrify";
import { join } from "path-browserify";
import OpenAI from "openai";
import { nip19 } from "nostr-tools";
import nunjucks from "nunjucks";
import { JSRuntimeFS } from "./JSRuntime";
import { getAllSkills } from "./plugins";
import type { AppConfig } from "@/contexts/AppContext";
export interface MakeSystemPromptOpts {
name: string;
profession: string;
tools: OpenAI.Chat.Completions.ChatCompletionTool[];
mode: "init" | "agent";
fs: JSRuntimeFS;
cwd: string;
pluginsPath?: string;
config: AppConfig;
defaultConfig: AppConfig;
user?: NUser;
metadata?: NostrMetadata;
repositoryUrl?: string;
template?: string;
}
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { name, profession, tools, mode, fs, cwd, pluginsPath, user, metadata } = opts;
/**
* Default system prompt template.
* This can be customized by users in Settings > System > System Prompt.
*/
export const defaultSystemPrompt = `{% if mode === "init" %}You are Shakespeare, an expert software extraordinaire. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.{% else %}You are Shakespeare, an expert software extraordinaire. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.{% endif %}
let system = mode === "init"
? `You are ${name}, an expert ${profession}. The files in the current directory are a template. Your goal is to transform this template into a working project according to the user's request.`
: `You are ${name}, an expert ${profession}. Your goal is to work on the project in the current directory according to the user's request. First, explore and understand the project structure, examine the existing files, and understand the context before making any assumptions about what the user is asking for.`;
// Add current date
const currentDate = new Date().toLocaleDateString("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
let userText: string;
if (user) {
userText = `The user is logged into Nostr with the following profile:
- **Nostr pubkey (hex)**: ${user.pubkey}
- **Nostr npub**: ${nip19.npubEncode(user.pubkey)}`;
if (metadata?.name) userText += `\n- **Name**: ${metadata.name}`;
if (metadata?.about) userText += `\n- **About**: ${metadata.about.replace(/[\r\n]+/g, ' ')}`;
if (metadata?.website) userText += `\n- **Website**: ${metadata.website}`;
if (metadata?.picture) userText += `\n- **Avatar**: ${metadata.picture}`;
if (metadata?.banner) userText += `\n- **Banner**: ${metadata.banner}`;
if (metadata?.nip05) userText += `\n- **NIP-05**: ${metadata.nip05}`;
if (metadata?.lud16) userText += `\n- **Lightning Address**: ${metadata.lud16}`;
userText += `\n\nSince the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.`;
} else {
userText = `The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.`;
}
// Add Your Environment section
system += `\n\n# Your Environment
# Your Environment
You are operating within **Shakespeare**, an AI-powered Nostr website builder that allows users to create custom Nostr applications through natural language conversation.
- **Current Date**: ${currentDate}
- **Current Page**: ${location.href}
- **Current Working Directory**: ${cwd}
- **Current Date**: {{ date }}
- **Current Page**: {{ location.href }}
- **Current Working Directory**: {{ cwd }}
- **Repository URL**: {{ repositoryUrl }}
## What Shakespeare Is
@@ -78,7 +52,19 @@ Shakespeare is a web-based development environment where users can build Nostr w
## The User
${userText}
{% if user %}The user is logged into Nostr with the following profile:
- **Nostr pubkey (hex)**: {{ user.pubkey }}
- **Nostr npub**: {{ user.npub }}{% if user.name %}
- **Name**: {{ user.name }}{% endif %}{% if user.about %}
- **About**: {{ user.about }}{% endif %}{% if user.website %}
- **Website**: {{ user.website }}{% endif %}{% if user.picture %}
- **Avatar**: {{ user.picture }}{% endif %}{% if user.banner %}
- **Banner**: {{ user.banner }}{% endif %}{% if user.nip05 %}
- **NIP-05**: {{ user.nip05 }}{% endif %}{% if user.lud16 %}
- **Lightning Address**: {{ user.lud16 }}{% endif %}
Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.{% else %}The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.{% endif %}
## User Interface
@@ -138,8 +124,8 @@ Shakespeare operates on a browser-based virtual filesystem (VFS) that persists a
├── config/ # Configuration files
│ ├── ai.json # AI provider settings and API keys
│ └── git.json # Git credentials and repository settings
└── tmp/ # Temporary files and scratch space
└── ... # Various temporary files and directories
└── tmp/ # Temporary files and scratch space
└── ... # Various temporary files and directories
\`\`\`
### Key VFS Features
@@ -163,73 +149,160 @@ As the AI assistant in Shakespeare, you help users by:
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.`;
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.{% if tools.length > 0 %}
// Add available tools to the system prompt
const toolNames = tools
.filter((tool) => tool.type === "function")
.map((tool) => tool.function.name);
## Available Tools
if (toolNames.length > 0) {
system +=
"\n\n## Available Tools\n\nYou have access to the following tools:\n";
for (const tool of tools) {
if (tool.type === "function") {
system += `\n- **${tool.function.name}**: ${
tool.function.description || "No description available"
}`;
}
}
}
You have access to the following tools:
{% for tool in tools %}{% if tool.type === 'function' %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% endif %}
// Add skills section
system += "\n\n## Skills\n\n";
## Skills
if (pluginsPath) {
{% if skills and skills.length > 0 %}You have access to the following skills. **Skills MUST be used whenever applicable** by calling the \`skill\` tool with the skill name.
Available skills:
{% for skill in skills %}
- **{{ skill.name }}**: {{ skill.description }}
- Plugin: {{ skill.plugin }}
- Path: {{ skill.path }}
{% endfor %}
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.{% else %}No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.{% endif %}
Users can configure skills in Settings > AI ({{ location.origin }}/settings/ai) by adding plugins that contain skills.{% if config.corsProxy %}
## Working Around CORS Issues
If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching external APIs, use the configured CORS proxy:
**CORS Proxy URL Template**: \`{{ config.corsProxy }}\`
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.{% endif %}
## Edit with Shakespeare
The "Edit with Shakespeare" button is a way that people can start editing any Shakespeare-compatible site with a single click. It can be added anywhere markdown or HTML is supported, including in READMEs, or within an app itself.{% if repositoryUrl %}
This project has a repository URL configured, so you can create an "Edit with Shakespeare" button using the following code snippets:
**Markdown:**
\`\`\`markdown
[![Edit with Shakespeare]({{ badgeUrl }})]({{ editUrl }})
\`\`\`
**HTML/JSX/TSX:**
\`\`\`jsx
<a href="{{ editUrl }}" target="_blank">
<img src="{{ badgeUrl }}" alt="Edit with Shakespeare" />
</a>
\`\`\`
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if readmeText %}
{{ readmeText }}{% endif %}{% if agentsText %}
{{ agentsText }}{% endif %}`;
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts;
// Add current date
const date = new Date().toLocaleDateString("en-US", {
weekday: "long",
year: "numeric",
month: "long",
day: "numeric",
});
// Get skills
let skills: Array<{ name: string; description: string; plugin: string; path: string }> = [];
if (config.fsPathPlugins) {
try {
const skills = await getAllSkills(fs, pluginsPath);
if (skills.length > 0) {
system += "You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.\n\n";
system += "Available skills:\n\n";
for (const skill of skills) {
system += `- **${skill.name}**: ${skill.description}\n - Plugin: ${skill.plugin}\n - Path: ${skill.path}\n`;
}
system += `\n**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.\n`;
} else {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
skills = await getAllSkills(fs, config.fsPathPlugins);
} catch {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
// Skills not available, use empty array
skills = [];
}
} else {
system += "No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.\n";
}
system += `\nUsers can configure skills in Settings > AI (${location.origin}/settings/ai) by adding plugins that contain skills.`;
// Add README.md if it exists
// Get README.md if it exists
let readmeText: string | undefined;
try {
const readmePath = join(cwd, "README.md");
const readmeText = await fs.readFile(readmePath, "utf8");
if (readmeText) {
system += "\n\n" + readmeText;
}
readmeText = await fs.readFile(readmePath, "utf8");
} catch {
// README.md not found, continue
}
// Add context from AGENTS.md if it exists
// Get agent context if it exists
let agentsText: string | undefined;
try {
const { text } = await getAgentContext(fs, cwd);
system += "\n\n" + text;
agentsText = text;
} catch {
// AGENTS.md not found, continue
}
return system;
// Build URLs for Edit with Shakespeare
let badgeUrl: string | undefined;
let editUrl: string | undefined;
if (repositoryUrl) {
badgeUrl = new URL('/badge.svg', location.origin).toString();
const editUrlObj = new URL('/clone', location.origin);
editUrlObj.searchParams.set('url', repositoryUrl);
editUrl = editUrlObj.toString();
}
// Build context object for template
const context = {
mode,
date,
cwd,
repositoryUrl,
config,
defaultConfig,
user: user
? {
...metadata,
pubkey: user.pubkey,
npub: nip19.npubEncode(user.pubkey),
about: metadata?.about?.replace(/[\r\n]+/g, ' '),
}
: undefined,
tools,
skills,
location: {
href: location.href,
origin: location.origin,
pathname: location.pathname,
port: location.port,
hostname: location.hostname,
protocol: location.protocol,
search: location.search,
hash: location.hash,
},
badgeUrl,
editUrl,
readmeText,
agentsText,
};
// Render the template with the context
// Use the provided template, or fall back to the default
const templateToRender = template || defaultSystemPrompt;
try {
// Configure nunjucks environment
const env = new nunjucks.Environment(null, { autoescape: false });
return env.renderString(templateToRender, context);
} catch (error) {
console.error("Error rendering system prompt template:", error);
// Return the template as-is if rendering fails
return templateToRender;
}
}
async function getAgentContext(
+2 -1
View File
@@ -35,12 +35,13 @@ describe('ShellTool', () => {
let mockNostr: NPool;
let shellTool: ShellTool;
const testCwd = '/test/dir';
const testCorsProxy = 'https://proxy.shakespeare.diy/?url={href}';
beforeEach(() => {
mockFS = createMockFS();
mockNostr = createMockNostr();
mockGit = new Git({ fs: mockFS, nostr: mockNostr });
shellTool = new ShellTool(mockFS, testCwd, mockGit);
shellTool = new ShellTool(mockFS, testCwd, mockGit, '/projects', testCorsProxy);
});
it('should have correct tool properties', () => {
+4 -2
View File
@@ -53,6 +53,7 @@ export class ShellTool implements Tool<ShellToolParams> {
private commands: Map<string, ShellCommand>;
private projectsPath: string;
private signer?: NostrSigner;
private corsProxy: string;
readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection with > and >> operators";
@@ -62,11 +63,12 @@ export class ShellTool implements Tool<ShellToolParams> {
),
});
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', signer?: NostrSigner) {
constructor(fs: JSRuntimeFS, cwd: string, git: Git, projectsPath: string = '/projects', corsProxy: string, signer?: NostrSigner) {
this.fs = fs;
this.cwd = cwd;
this.git = git;
this.projectsPath = projectsPath;
this.corsProxy = corsProxy;
this.signer = signer;
this.commands = new Map();
@@ -75,7 +77,7 @@ export class ShellTool implements Tool<ShellToolParams> {
this.registerCommand(new CdCommand(fs));
this.registerCommand(new ClearCommand());
this.registerCommand(new CpCommand(fs));
this.registerCommand(new CurlCommand(fs));
this.registerCommand(new CurlCommand(fs, this.corsProxy));
this.registerCommand(new CutCommand(fs));
this.registerCommand(new DateCommand());
this.registerCommand(new DiffCommand(fs));
+8 -1
View File
@@ -59,6 +59,8 @@
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
"shareErrorReports": "Share error reports",
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
"systemPrompt": "System Prompt",
"systemPromptDescription": "Customize the AI assistant's system prompt using Jinja-like template syntax. This controls the assistant's behavior and knowledge.",
"english": "English",
"portuguese": "Portuguese",
"chinese": "Chinese",
@@ -85,6 +87,8 @@
"add": "Add",
"remove": "Remove",
"retry": "Retry",
"latestFirst": "Latest First",
"oldestFirst": "Oldest First",
"name": "Name",
"email": "Email",
"buildNostrApps": "Build apps with AI",
@@ -483,5 +487,8 @@
"configDirectoryDescription": "Directory where configuration files are stored in the virtual filesystem.",
"temporaryDirectory": "Temporary Directory",
"temporaryDirectoryDescription": "Directory for temporary files in the virtual filesystem.",
"deleting": "Deleting..."
"deleting": "Deleting...",
"modified": "Modified",
"restoreToDefault": "Restore to default",
"restoredToDefault": "Restored to Default"
}
+8 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Hanyar tsarin fayil inda ake adana fayilolin saiti",
"temporaryDirectory": "Kundin Wucin Gadi",
"temporaryDirectoryDescription": "Hanyar tsarin fayil don fayilolin wucin gadi",
"systemPrompt": "Tambarin Tsarin",
"systemPromptDescription": "Keɓanta tambarin tsarin mataimaki na AI ta amfani da tsarin samfuri mai kama da Jinja. Wannan yana sarrafa ɗabi'a da ilimi na mataimaki.",
"english": "Turanci",
"portuguese": "Fotigis",
"chinese": "Sinanci",
@@ -81,6 +83,8 @@
"add": "Ƙara",
"remove": "Cire",
"retry": "Sake gwadawa",
"latestFirst": "Na Baya-bayan nan Da farko",
"oldestFirst": "Na Dā Da farko",
"name": "Suna",
"email": "Imel",
"buildNostrApps": "Gina aikace-aikace da AI",
@@ -422,5 +426,8 @@
"invalidGiftCard": "Katin Kyauta Ba Daidai Ba",
"giftCardNotFound": "Ba a iya samun wannan katin kyauta.",
"alreadyRedeemed": "An riga an Fanshi",
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta."
"giftCardAlreadyRedeemed": "An riga an fanshi wannan katin kyauta.",
"modified": "An Canza",
"restoreToDefault": "Mayar da asali",
"restoredToDefault": "An Mayar da Asali"
}
+8 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Ụzọ sistemu faịlụ ebe echekwara faịlụ nhazi",
"temporaryDirectory": "Ndekọ Nwa Oge",
"temporaryDirectoryDescription": "Ụzọ sistemu faịlụ maka faịlụ nwa oge",
"systemPrompt": "Ajụjụ Sistemu",
"systemPromptDescription": "Hazie ajụjụ sistemu nke enyemaka AI site na iji syntax template yiri Jinja. Nke a na-achịkwa omume na ihe ọmụma nke enyemaka ahụ.",
"english": "Bekee",
"portuguese": "Portuguese",
"chinese": "Chinese",
@@ -81,6 +83,8 @@
"add": "Tinye",
"remove": "Wepụ",
"retry": "Nwaa ọzọ",
"latestFirst": "Nke Ọhụrụ Mbụ",
"oldestFirst": "Nke Ochie Mbụ",
"name": "Aha",
"email": "Ozi-eletrọniki",
"buildNostrApps": "Wuo ngwa na AI",
@@ -419,5 +423,8 @@
"invalidGiftCard": "Kaadị Onyinye Na-ezighị Ezi",
"giftCardNotFound": "Achọtaghị kaadị onyinye a.",
"alreadyRedeemed": "Egbapụtalarị",
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a."
"giftCardAlreadyRedeemed": "Egbapụtalarị kaadị onyinye a.",
"modified": "Gbanwere",
"restoreToDefault": "Weghachi na nke mbụ",
"restoredToDefault": "Weghachiri na Nke Mbụ"
}
+8 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Caminho do sistema de arquivos onde os arquivos de configuração são armazenados",
"temporaryDirectory": "Diretório Temporário",
"temporaryDirectoryDescription": "Caminho do sistema de arquivos para arquivos temporários",
"systemPrompt": "Prompt do Sistema",
"systemPromptDescription": "Personalize o prompt do sistema do assistente de IA usando sintaxe de template semelhante a Jinja. Isso controla o comportamento e conhecimento do assistente.",
"english": "Inglês",
"portuguese": "Português",
"chinese": "Chinês",
@@ -81,6 +83,8 @@
"add": "Adicionar",
"remove": "Remover",
"retry": "Tentar novamente",
"latestFirst": "Mais Recentes Primeiro",
"oldestFirst": "Mais Antigos Primeiro",
"name": "Nome",
"email": "Email",
"buildNostrApps": "Construa aplicativos com IA",
@@ -432,5 +436,8 @@
"invalidGiftCard": "Cartão Presente Inválido",
"giftCardNotFound": "Este cartão presente não pôde ser encontrado.",
"alreadyRedeemed": "Já Resgatado",
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado."
"giftCardAlreadyRedeemed": "Este cartão presente já foi resgatado.",
"modified": "Modificado",
"restoreToDefault": "Restaurar para padrão",
"restoredToDefault": "Restaurado para Padrão"
}
+8 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "Ọna eto faili nibiti a tọju awọn faili iṣeto",
"temporaryDirectory": "Itọsọna Igba diẹ",
"temporaryDirectoryDescription": "Ọna eto faili fun awọn faili igba diẹ",
"systemPrompt": "Ibeere Eto",
"systemPromptDescription": "Ṣe adani ibeere eto oluranlọwọ AI nipa lilo sintasi awoṣe ti o jọ Jinja. Eyi n ṣakoso ihuwasi ati imọ oluranlọwọ naa.",
"english": "Gẹẹsi",
"portuguese": "Potogisi",
"chinese": "Kannada",
@@ -81,6 +83,8 @@
"add": "Fi kun",
"remove": "Yọ kuro",
"retry": "Tun gbiyanju",
"latestFirst": "Tuntun Akọkọ",
"oldestFirst": "Atijọ Akọkọ",
"name": "Orukọ",
"email": "Imeeli",
"buildNostrApps": "Kọ awọn ohun elo pẹlu AI",
@@ -419,5 +423,8 @@
"invalidGiftCard": "Kaadi Ẹbun Ti ko Tọ",
"giftCardNotFound": "A ko le ri kaadi ẹbun yii.",
"alreadyRedeemed": "Ti ra Tẹlẹ",
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ."
"giftCardAlreadyRedeemed": "A ti ra kaadi ẹbun yii tẹlẹ.",
"modified": "Ti Yipada",
"restoreToDefault": "Pada si atilẹwa",
"restoredToDefault": "Ti Pada si Atilẹwa"
}
+8 -1
View File
@@ -55,6 +55,8 @@
"configDirectoryDescription": "存储配置文件的文件系统路径",
"temporaryDirectory": "临时目录",
"temporaryDirectoryDescription": "临时文件的文件系统路径",
"systemPrompt": "系统提示",
"systemPromptDescription": "使用类似Jinja的模板语法自定义AI助手的系统提示。这控制助手的行为和知识。",
"english": "English",
"portuguese": "Português",
"chinese": "中文",
@@ -81,6 +83,8 @@
"add": "添加",
"remove": "移除",
"retry": "重试",
"latestFirst": "最新优先",
"oldestFirst": "最旧优先",
"name": "名称",
"email": "邮箱",
"buildNostrApps": "使用AI构建应用",
@@ -432,5 +436,8 @@
"invalidGiftCard": "无效的礼品卡",
"giftCardNotFound": "找不到此礼品卡。",
"alreadyRedeemed": "已兑换",
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。"
"giftCardAlreadyRedeemed": "此礼品卡已被兑换。",
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值"
}
-10
View File
@@ -105,16 +105,6 @@ export function AboutSettings() {
<ExternalLink className="ml-auto h-4 w-4" />
</a>
</Button>
<Button
variant="outline"
className="w-full h-10 flex items-center gap-2 justify-start"
asChild
>
<a href="https://shakespeare.soapbox.dev" target="_blank" rel="noopener noreferrer">
<span className="font-mono text-sm">shakespeare.soapbox.dev</span>
<ExternalLink className="ml-auto h-4 w-4" />
</a>
</Button>
<Button
variant="outline"
className="w-full h-10 flex items-center gap-2 justify-start"
-986
View File
@@ -1,986 +0,0 @@
import React, { useState } from 'react';
import { useParams, Link, useNavigate } from 'react-router-dom';
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader } from '@/components/ui/card';
import { Skeleton } from '@/components/ui/skeleton';
import { Badge } from '@/components/ui/badge';
import { CommentsSection } from '@/components/comments/CommentsSection';
import { useAuthor } from '@/hooks/useAuthor';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useToast } from '@/hooks/useToast';
import {
ExternalLink,
User,
Star,
ArrowLeft,
Edit,
MoreVertical,
StarOff,
Eye,
EyeOff,
CheckCircle,
XCircle,
Home,
} from 'lucide-react';
import { nip19 } from 'nostr-tools';
import type { NostrEvent } from '@nostrify/nostrify';
import { AppLayout } from '@/components/AppLayout';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import { useQueryClient } from '@tanstack/react-query';
// Kind 31733 for app submissions
const APP_SUBMISSION_KIND = 31733;
// The moderator npub and hex
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
const MODERATOR_HEX = (() => {
try {
const decoded = nip19.decode(MODERATOR_NPUB);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
})();
export default function ShowcasePage() {
const { id } = useParams<{ id: string }>();
const navigate = useNavigate();
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { toast } = useToast();
const { mutate: publishEvent, isPending } = useNostrPublish();
const queryClient = useQueryClient();
const [imageError, setImageError] = useState(false);
// Decode the naddr to get the app submission
const appData = React.useMemo(() => {
if (!id) return null;
try {
const decoded = nip19.decode(id);
if (decoded.type === 'naddr') {
return decoded.data;
}
} catch (error) {
console.error('Failed to decode naddr:', error);
}
return null;
}, [id]);
// Fetch the app submission event
const { data: appEvent, isLoading } = useQuery({
queryKey: ['showcase-app', id],
queryFn: async () => {
if (!appData) return null;
const events = await nostr.query(
[
{
kinds: [appData.kind],
authors: [appData.pubkey],
'#d': [appData.identifier],
limit: 1,
},
],
{ signal: AbortSignal.timeout(3000) }
);
return events[0] || null;
},
enabled: !!appData,
});
// Fetch moderation lists
const { data: moderationData } = useQuery({
queryKey: ['showcase-moderation', id],
queryFn: async () => {
if (!appEvent) return null;
const [moderatorListEvents, reportEvents] = await Promise.all([
nostr.query(
[
{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': [
'soapbox-featured-apps',
'soapbox-approved-apps',
'soapbox-homepage-apps',
],
limit: 3,
},
],
{ signal: AbortSignal.timeout(1000) }
),
nostr.query(
[
{
kinds: [1984],
authors: [MODERATOR_HEX],
limit: 1000,
},
],
{ signal: AbortSignal.timeout(1000) }
),
]);
// Process moderation lists
const featuredList = moderatorListEvents.find((e) =>
e.tags.find((tag) => tag[0] === 'd' && tag[1] === 'soapbox-featured-apps')
);
const approvedList = moderatorListEvents.find((e) =>
e.tags.find((tag) => tag[0] === 'd' && tag[1] === 'soapbox-approved-apps')
);
const homepageList = moderatorListEvents.find((e) =>
e.tags.find((tag) => tag[0] === 'd' && tag[1] === 'soapbox-homepage-apps')
);
const dTag = appEvent.tags.find((tag) => tag[0] === 'd')?.[1];
const appCoordinate = `${APP_SUBMISSION_KIND}:${appEvent.pubkey}:${dTag}`;
const isFeatured = featuredList?.tags.some(
(tag) => tag[0] === 'a' && tag[1] === appCoordinate
);
const isApproved = approvedList?.tags.some(
(tag) => tag[0] === 'a' && tag[1] === appCoordinate
);
const isHomepage = homepageList?.tags.some(
(tag) => tag[0] === 'a' && tag[1] === appCoordinate
);
// Check if hidden
const appReports = new Map<string, { hidden: number; unhidden: number }>();
for (const report of reportEvents) {
const aTag = report.tags.find((tag) => tag[0] === 'a');
if (!aTag || !aTag[1]) continue;
const reportCoord = aTag[1];
if (reportCoord !== appCoordinate) continue;
const reportType = aTag[2];
const moderationLabel = report.tags.find(
(tag) => tag[0] === 'l' && tag[2] === 'soapbox.moderation'
)?.[1];
if (moderationLabel === 'hidden' && (reportType === 'spam' || reportType === 'other')) {
if (!appReports.has(reportCoord)) {
appReports.set(reportCoord, { hidden: 0, unhidden: 0 });
}
appReports.get(reportCoord)!.hidden = Math.max(
appReports.get(reportCoord)!.hidden,
report.created_at
);
} else if (moderationLabel === 'unhidden' && reportType === 'other') {
if (!appReports.has(reportCoord)) {
appReports.set(reportCoord, { hidden: 0, unhidden: 0 });
}
appReports.get(reportCoord)!.unhidden = Math.max(
appReports.get(reportCoord)!.unhidden,
report.created_at
);
}
}
const reports = appReports.get(appCoordinate);
const isHidden = reports && reports.hidden > reports.unhidden;
return { isFeatured, isApproved, isHomepage, isHidden };
},
enabled: !!appEvent,
staleTime: 5000, // 5 seconds
refetchInterval: 15000, // 15 seconds
});
// Parse app data from event
const app = React.useMemo(() => {
if (!appEvent) return null;
const appName = appEvent.tags.find((tag) => tag[0] === 'title')?.[1] || '';
const websiteUrl = appEvent.tags.find((tag) => tag[0] === 'website')?.[1] || '';
const repositoryUrl = appEvent.tags.find((tag) => tag[0] === 'repository')?.[1] || '';
const appIconUrl = appEvent.tags.find((tag) => tag[0] === 'icon')?.[1] || '';
const screenshotUrl = appEvent.tags.find((tag) => tag[0] === 'screenshot')?.[1] || '';
const authorNpub = appEvent.tags.find((tag) => tag[0] === 'author')?.[1] || appEvent.pubkey;
const appTags = appEvent.tags.filter((tag) => tag[0] === 'app-tag').map((tag) => tag[1]);
return {
appName,
websiteUrl,
repositoryUrl,
description: appEvent.content,
appIconUrl,
screenshotUrl,
authorNpub,
appTags,
};
}, [appEvent]);
// Get author pubkey
const authorPubkey = React.useMemo(() => {
if (!app?.authorNpub) return appEvent?.pubkey || '';
try {
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
return app.authorNpub;
}
const decoded = nip19.decode(app.authorNpub);
return decoded.type === 'npub' ? decoded.data : appEvent?.pubkey || '';
} catch {
return appEvent?.pubkey || '';
}
}, [app?.authorNpub, appEvent?.pubkey]);
const { data: authorData } = useAuthor(authorPubkey);
const isOwner = user?.pubkey === appEvent?.pubkey;
const isModerator = user?.pubkey === MODERATOR_HEX;
// Moderation actions
const handleModerationAction = async (
action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage'
) => {
if (!isModerator || !user || !appEvent) return;
const dTag = appEvent.tags.find((tag) => tag[0] === 'd')?.[1];
if (!dTag) {
toast({
title: 'Error',
description: 'Cannot perform moderation action: missing app identifier',
variant: 'destructive',
});
return;
}
const appCoordinate = `${APP_SUBMISSION_KIND}:${appEvent.pubkey}:${dTag}`;
try {
if (action === 'homepage' || action === 'unhomepage') {
const currentHomepageLists = await nostr.query(
[
{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-homepage-apps'],
limit: 1,
},
],
{ signal: AbortSignal.timeout(3000) }
);
const currentHomepageList = currentHomepageLists.reduce(
(latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
const currentHomepageApps = new Set<string>();
if (currentHomepageList) {
currentHomepageList.tags
.filter((tag) => tag[0] === 'a')
.forEach((tag) => currentHomepageApps.add(tag[1]));
}
if (action === 'homepage') {
currentHomepageApps.add(appCoordinate);
} else {
currentHomepageApps.delete(appCoordinate);
}
publishEvent({
kind: 30267,
content: 'Soapbox homepage apps curated by moderators',
tags: [
['d', 'soapbox-homepage-apps'],
['title', 'Soapbox Homepage Apps'],
['description', 'Apps displayed on the Soapbox homepage'],
...Array.from(currentHomepageApps).map((coord) => ['a', coord]),
],
created_at: Math.floor(Date.now() / 1000),
});
if (action === 'homepage') {
const currentApprovedLists = await nostr.query(
[
{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1,
},
],
{ signal: AbortSignal.timeout(3000) }
);
const currentApprovedList = currentApprovedLists.reduce(
(latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter((tag) => tag[0] === 'a')
.forEach((tag) => currentApprovedApps.add(tag[1]));
}
currentApprovedApps.add(appCoordinate);
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map((coord) => ['a', coord]),
],
created_at: Math.floor(Date.now() / 1000),
});
}
} else if (action === 'feature' || action === 'unfeature') {
const currentFeaturedLists = await nostr.query(
[
{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-featured-apps'],
limit: 1,
},
],
{ signal: AbortSignal.timeout(3000) }
);
const currentFeaturedList = currentFeaturedLists.reduce(
(latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
const currentFeaturedApps = new Set<string>();
if (currentFeaturedList) {
currentFeaturedList.tags
.filter((tag) => tag[0] === 'a')
.forEach((tag) => currentFeaturedApps.add(tag[1]));
}
if (action === 'feature') {
currentFeaturedApps.add(appCoordinate);
} else {
currentFeaturedApps.delete(appCoordinate);
}
publishEvent({
kind: 30267,
content: 'Soapbox featured apps curated by moderators',
tags: [
['d', 'soapbox-featured-apps'],
['title', 'Soapbox Featured Apps'],
['description', 'Apps featured in the Soapbox showcase'],
...Array.from(currentFeaturedApps).map((coord) => ['a', coord]),
],
created_at: Math.floor(Date.now() / 1000),
});
if (action === 'feature') {
const currentApprovedLists = await nostr.query(
[
{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1,
},
],
{ signal: AbortSignal.timeout(3000) }
);
const currentApprovedList = currentApprovedLists.reduce(
(latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter((tag) => tag[0] === 'a')
.forEach((tag) => currentApprovedApps.add(tag[1]));
}
currentApprovedApps.add(appCoordinate);
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map((coord) => ['a', coord]),
],
created_at: Math.floor(Date.now() / 1000),
});
}
} else if (action === 'approve' || action === 'unapprove') {
const currentApprovedLists = await nostr.query(
[
{
kinds: [30267],
authors: [MODERATOR_HEX],
'#d': ['soapbox-approved-apps'],
limit: 1,
},
],
{ signal: AbortSignal.timeout(3000) }
);
const currentApprovedList = currentApprovedLists.reduce(
(latest: NostrEvent | null, current: NostrEvent) =>
!latest || current.created_at > latest.created_at ? current : latest,
null as NostrEvent | null
);
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter((tag) => tag[0] === 'a')
.forEach((tag) => currentApprovedApps.add(tag[1]));
}
if (action === 'approve') {
currentApprovedApps.add(appCoordinate);
} else {
currentApprovedApps.delete(appCoordinate);
}
publishEvent({
kind: 30267,
content: 'Soapbox approved apps curated by moderators',
tags: [
['d', 'soapbox-approved-apps'],
['title', 'Soapbox Approved Apps'],
['description', 'Apps approved for the Soapbox showcase'],
...Array.from(currentApprovedApps).map((coord) => ['a', coord]),
],
created_at: Math.floor(Date.now() / 1000),
});
} else if (action === 'hide' || action === 'unhide') {
publishEvent({
kind: 1984,
content: `App ${action}den by moderator: "${app?.appName}"`,
tags: [
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
['p', appEvent.pubkey],
['L', 'soapbox.moderation'],
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation'],
],
created_at: Math.floor(Date.now() / 1000),
});
}
// Invalidate queries immediately for real-time updates
queryClient.invalidateQueries({ queryKey: ['showcase-moderation', id] });
queryClient.invalidateQueries({ queryKey: ['nostr', 'app-submissions'] });
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
toast({
title: 'Success!',
description: `App "${app?.appName}" ${action}d successfully`,
});
} catch (error) {
console.error('Moderation action failed:', error);
toast({
title: 'Error',
description: `Failed to ${action} app "${app?.appName}"`,
variant: 'destructive',
});
}
};
if (!id || !appData) {
return (
<AppLayout>
<div className="container mx-auto px-4 py-8 max-w-5xl">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<p className="text-muted-foreground">Invalid showcase app identifier</p>
<Button asChild variant="outline" className="mt-4">
<Link to="/">
<ArrowLeft className="h-4 w-4 mr-2" />
Back to Home
</Link>
</Button>
</CardContent>
</Card>
</div>
</AppLayout>
);
}
if (isLoading || !appEvent || !app) {
return (
<AppLayout>
<div className="container mx-auto px-4 py-8 max-w-5xl">
<div className="mb-6">
<Skeleton className="h-10 w-32" />
</div>
<Card className="mb-8">
<Skeleton className="aspect-video rounded-t-lg" />
<CardContent className="p-6">
<div className="flex items-start gap-4 mb-4">
<Skeleton className="w-16 h-16 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-8 w-64" />
<Skeleton className="h-4 w-32" />
</div>
</div>
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
<Skeleton className="h-4 w-3/4" />
</div>
<div className="flex gap-2 mb-4">
<Skeleton className="h-6 w-20" />
<Skeleton className="h-6 w-24" />
</div>
<div className="flex gap-2">
<Skeleton className="h-10 flex-1" />
<Skeleton className="h-10 w-32" />
</div>
</CardContent>
</Card>
<Skeleton className="h-64 w-full" />
</div>
</AppLayout>
);
}
return (
<AppLayout>
<div className="container mx-auto px-4 py-8 max-w-5xl">
{/* Back button */}
<div className="mb-6">
<Button variant="ghost" onClick={() => navigate(-1)}>
<ArrowLeft className="h-4 w-4 mr-2" />
Back
</Button>
</div>
{/* App Details Card */}
<Card className="mb-8">
<div className="relative">
{/* Screenshot */}
<div className="aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden">
{!imageError ? (
<img
src={app.screenshotUrl}
alt={`${app.appName} screenshot`}
className="w-full h-full object-cover"
onError={() => setImageError(true)}
/>
) : (
<div className="w-full h-full flex items-center justify-center text-muted-foreground">
<div className="text-center">
<div className="w-16 h-16 mx-auto mb-2 bg-muted rounded-lg flex items-center justify-center">
<ExternalLink className="w-8 h-8" />
</div>
<p className="text-sm">Screenshot unavailable</p>
</div>
</div>
)}
</div>
{/* Actions Menu */}
{(isOwner || isModerator) && (
<div className="absolute top-4 right-4">
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button variant="secondary" size="sm" className="h-9 w-9 p-0">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isOwner && (
<DropdownMenuItem>
<Edit className="w-4 h-4 mr-2" />
Edit App
</DropdownMenuItem>
)}
{isModerator && moderationData && (
<>
{!moderationData.isApproved && (
<DropdownMenuItem
onClick={() => handleModerationAction('approve')}
disabled={isPending}
>
<CheckCircle className="w-4 h-4 mr-2" />
Approve
</DropdownMenuItem>
)}
{moderationData.isApproved && !moderationData.isFeatured && (
<DropdownMenuItem
onClick={() => handleModerationAction('unapprove')}
disabled={isPending}
>
<XCircle className="w-4 h-4 mr-2" />
Unapprove
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={() =>
handleModerationAction(moderationData.isFeatured ? 'unfeature' : 'feature')
}
disabled={isPending}
>
{moderationData.isFeatured ? (
<>
<StarOff className="w-4 h-4 mr-2" />
Un-feature
</>
) : (
<>
<Star className="w-4 h-4 mr-2" />
Feature
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
handleModerationAction(moderationData.isHomepage ? 'unhomepage' : 'homepage')
}
disabled={isPending}
>
{moderationData.isHomepage ? (
<>
<Home className="w-4 h-4 mr-2" />
Remove from Homepage
</>
) : (
<>
<Home className="w-4 h-4 mr-2" />
Add to Homepage
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() =>
handleModerationAction(moderationData.isHidden ? 'unhide' : 'hide')
}
disabled={isPending}
>
{moderationData.isHidden ? (
<>
<Eye className="w-4 h-4 mr-2" />
Unhide
</>
) : (
<>
<EyeOff className="w-4 h-4 mr-2" />
Hide
</>
)}
</DropdownMenuItem>
</>
)}
</DropdownMenuContent>
</DropdownMenu>
</div>
)}
</div>
<CardContent className="p-6">
{/* App Header */}
<div className="flex items-start gap-4 mb-4">
<div className="w-16 h-16 rounded-lg overflow-hidden bg-muted flex-shrink-0">
<img
src={app.appIconUrl}
alt={`${app.appName} icon`}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
}}
/>
</div>
<div className="flex-1">
<h1 className="text-3xl font-bold text-foreground mb-2">{app.appName}</h1>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<div className="w-6 h-6 rounded-full overflow-hidden bg-muted flex-shrink-0">
{authorData?.metadata?.picture ? (
<img
src={authorData.metadata.picture}
alt={`${authorData.metadata.name || 'Author'} avatar`}
className="w-full h-full object-cover"
onError={(e) => {
const target = e.target as HTMLImageElement;
target.style.display = 'none';
target.parentElement!.innerHTML =
'<div class="w-full h-full flex items-center justify-center"><svg class="w-3 h-3 text-gray-400" fill="currentColor" viewBox="0 0 20 20"><path fill-rule="evenodd" d="M10 9a3 3 0 100-6 3 3 0 000 6zm-7 9a7 7 0 1114 0H3z" clip-rule="evenodd"></path></svg></div>';
}}
/>
) : (
<div className="w-full h-full flex items-center justify-center">
<User className="w-3 h-3 text-muted-foreground" />
</div>
)}
</div>
<span>
by{' '}
<a
href={`https://ditto.pub/${app.authorNpub || nip19.npubEncode(authorPubkey)}`}
target="_blank"
rel="noopener noreferrer"
className="text-primary hover:text-primary/80 transition-colors hover:underline"
>
{authorData?.metadata?.name ||
authorData?.metadata?.display_name ||
'Anonymous'}
</a>
</span>
</div>
</div>
</div>
{/* Description */}
<p className="text-muted-foreground mb-4 whitespace-pre-wrap">{app.description}</p>
{/* Tags */}
{app.appTags.length > 0 && (
<div className="flex flex-wrap gap-2 mb-6">
{app.appTags.map((tag, index) => (
<Badge key={index} variant="secondary">
{tag}
</Badge>
))}
</div>
)}
{/* Action Buttons */}
<div className="flex flex-wrap gap-3">
<Link
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
className="flex-1 min-w-[200px]"
>
<img
src="/badge.svg"
alt="Edit with Shakespeare"
className="h-10 hover:opacity-80 transition-opacity"
/>
</Link>
<Button variant="default" size="lg" asChild>
<a href={app.websiteUrl} target="_blank" rel="noopener noreferrer">
<ExternalLink className="w-4 h-4 mr-2" />
Visit Website
</a>
</Button>
</div>
</CardContent>
</Card>
{/* Ratings Section */}
<Card className="mb-8">
<CardHeader>
<h2 className="text-2xl font-bold flex items-center gap-2">
<Star className="w-6 h-6 text-yellow-500" />
Ratings
</h2>
</CardHeader>
<CardContent>
<RatingsSection appEvent={appEvent} />
</CardContent>
</Card>
{/* Comments Section */}
<CommentsSection
root={appEvent}
title="Comments"
emptyStateMessage="No comments yet"
emptyStateSubtitle="Be the first to share your thoughts about this app!"
/>
</div>
</AppLayout>
);
}
// Ratings Section Component
function RatingsSection({ appEvent }: { appEvent: NostrEvent }) {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { mutate: publishEvent, isPending } = useNostrPublish();
const { toast } = useToast();
const queryClient = useQueryClient();
// Fetch ratings (kind 7 reactions with rating content)
const { data: ratings = [], isLoading } = useQuery({
queryKey: ['ratings', appEvent.id],
queryFn: async () => {
const events = await nostr.query(
[
{
kinds: [7],
'#e': [appEvent.id],
limit: 500,
},
],
{ signal: AbortSignal.timeout(3000) }
);
// Filter for numeric ratings (1-5)
return events.filter((e) => {
const rating = parseInt(e.content);
return !isNaN(rating) && rating >= 1 && rating <= 5;
});
},
staleTime: 10000, // 10 seconds
refetchInterval: 30000, // 30 seconds
});
// Calculate average rating
const averageRating = React.useMemo(() => {
if (ratings.length === 0) return 0;
const sum = ratings.reduce((acc, r) => acc + parseInt(r.content), 0);
return sum / ratings.length;
}, [ratings]);
// Check if user has already rated
const userRating = React.useMemo(() => {
if (!user) return null;
const userRatingEvent = ratings.find((r) => r.pubkey === user.pubkey);
return userRatingEvent ? parseInt(userRatingEvent.content) : null;
}, [ratings, user]);
const handleRate = (rating: number) => {
if (!user) {
toast({
title: 'Login Required',
description: 'Please log in to rate this app',
variant: 'destructive',
});
return;
}
// Optimistic update
const optimisticRating = {
id: `temp-${Date.now()}`,
pubkey: user.pubkey,
content: rating.toString(),
created_at: Math.floor(Date.now() / 1000),
kind: 7,
tags: [['e', appEvent.id], ['p', appEvent.pubkey]],
sig: ''
};
// Update cache optimistically
queryClient.setQueryData(['ratings', appEvent.id], (oldRatings: NostrEvent[] = []) => {
// Remove any existing rating from this user
const filteredRatings = oldRatings.filter(r => r.pubkey !== user.pubkey);
// Add the new rating
return [...filteredRatings, optimisticRating];
});
publishEvent({
kind: 7,
content: rating.toString(),
tags: [
['e', appEvent.id],
['p', appEvent.pubkey],
],
created_at: Math.floor(Date.now() / 1000),
}, {
onSuccess: () => {
toast({
title: 'Rating Submitted!',
description: `You rated this app ${rating} star${rating > 1 ? 's' : ''}`,
});
},
onError: () => {
// Revert optimistic update on error
queryClient.invalidateQueries({ queryKey: ['ratings', appEvent.id] });
toast({
title: 'Error',
description: 'Failed to submit rating. Please try again.',
variant: 'destructive',
});
}
});
};
if (isLoading) {
return (
<div className="space-y-4">
<Skeleton className="h-8 w-48" />
<Skeleton className="h-12 w-full" />
</div>
);
}
return (
<div className="space-y-6">
{/* Average Rating Display */}
<div className="text-center">
<div className="text-5xl font-bold mb-2">
{averageRating > 0 ? averageRating.toFixed(1) : 'No ratings yet'}
</div>
{averageRating > 0 && (
<div className="flex items-center justify-center gap-1 mb-2">
{Array.from({ length: 5 }).map((_, i) => (
<Star
key={i}
className={`w-6 h-6 ${
i < Math.round(averageRating)
? 'fill-yellow-500 text-yellow-500'
: 'text-gray-300'
}`}
/>
))}
</div>
)}
<p className="text-sm text-muted-foreground">
{ratings.length} {ratings.length === 1 ? 'rating' : 'ratings'}
</p>
</div>
{/* User Rating Input */}
<div className="border-t pt-6">
<p className="text-sm font-medium mb-3">
{userRating ? 'Your rating:' : 'Rate this app:'}
</p>
<div className="flex items-center gap-2">
{Array.from({ length: 5 }).map((_, i) => {
const starValue = i + 1;
return (
<button
key={i}
onClick={() => handleRate(starValue)}
className="transition-transform hover:scale-110 disabled:opacity-50 disabled:cursor-not-allowed"
disabled={!user || isPending}
>
<Star
className={`w-10 h-10 ${
userRating && starValue <= userRating
? 'fill-yellow-500 text-yellow-500'
: 'text-gray-300 hover:text-yellow-500'
} ${isPending ? 'animate-pulse' : ''}`}
/>
</button>
);
})}
</div>
{!user && (
<p className="text-xs text-muted-foreground mt-2">Log in to rate this app</p>
)}
</div>
</div>
);
}
+564 -194
View File
@@ -1,22 +1,24 @@
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2 } from "lucide-react";
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { useState, useEffect } from "react";
import { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
import { useAppContext } from "@/hooks/useAppContext";
import { useOffline } from "@/hooks/useOffline";
import { useToast } from "@/hooks/useToast";
import { defaultSystemPrompt } from "@/lib/system";
export function SystemSettings() {
const { t } = useTranslation();
const isMobile = useIsMobile();
const navigate = useNavigate();
const { config, updateConfig } = useAppContext();
const { config, defaultConfig, updateConfig } = useAppContext();
const { toast } = useToast();
const { serviceWorkerRegistration, updateServiceWorker, clearCache } = useOffline();
@@ -31,6 +33,102 @@ export function SystemSettings() {
const [fsPathTmpInput, setFsPathTmpInput] = useState(config.fsPathTmp);
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
// Check which settings differ from defaults
const isModified = useMemo(() => ({
projectTemplate: config.projectTemplate !== defaultConfig.projectTemplate,
esmUrl: config.esmUrl !== defaultConfig.esmUrl,
corsProxy: config.corsProxy !== defaultConfig.corsProxy,
faviconUrl: config.faviconUrl !== defaultConfig.faviconUrl,
previewDomain: config.previewDomain !== defaultConfig.previewDomain,
showcaseEnabled: config.showcaseEnabled !== defaultConfig.showcaseEnabled,
showcaseModerator: config.showcaseModerator !== defaultConfig.showcaseModerator,
fsPathProjects: config.fsPathProjects !== defaultConfig.fsPathProjects,
fsPathConfig: config.fsPathConfig !== defaultConfig.fsPathConfig,
fsPathTmp: config.fsPathTmp !== defaultConfig.fsPathTmp,
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
}), [config, defaultConfig]);
// Restore functions
const restoreProjectTemplate = () => {
const defaultValue = defaultConfig.projectTemplate;
setProjectTemplateInput(defaultValue);
updateConfig((current) => ({ ...current, projectTemplate: defaultValue }));
};
const restoreEsmUrl = () => {
const defaultValue = defaultConfig.esmUrl;
setEsmUrlInput(defaultValue);
updateConfig((current) => ({ ...current, esmUrl: defaultValue }));
};
const restoreCorsProxy = () => {
const defaultValue = defaultConfig.corsProxy;
setCorsProxyInput(defaultValue);
updateConfig((current) => ({ ...current, corsProxy: defaultValue }));
};
const restoreFaviconUrl = () => {
const defaultValue = defaultConfig.faviconUrl;
setFaviconUrlInput(defaultValue);
updateConfig((current) => ({ ...current, faviconUrl: defaultValue }));
};
const restorePreviewDomain = () => {
const defaultValue = defaultConfig.previewDomain;
setPreviewDomainInput(defaultValue);
updateConfig((current) => ({ ...current, previewDomain: defaultValue }));
};
const restoreShowcaseEnabled = () => {
const defaultValue = defaultConfig.showcaseEnabled;
updateConfig((current) => ({ ...current, showcaseEnabled: defaultValue }));
};
const restoreShowcaseModerator = () => {
const defaultValue = defaultConfig.showcaseModerator;
setShowcaseModeratorInput(defaultValue);
updateConfig((current) => ({ ...current, showcaseModerator: defaultValue }));
};
const restoreFsPathProjects = () => {
const defaultValue = defaultConfig.fsPathProjects;
setFsPathProjectsInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathProjects: defaultValue }));
};
const restoreFsPathConfig = () => {
const defaultValue = defaultConfig.fsPathConfig;
setFsPathConfigInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathConfig: defaultValue }));
};
const restoreFsPathTmp = () => {
const defaultValue = defaultConfig.fsPathTmp;
setFsPathTmpInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathTmp: defaultValue }));
};
const restoreFsPathPlugins = () => {
const defaultValue = defaultConfig.fsPathPlugins;
setFsPathPluginsInput(defaultValue);
updateConfig((current) => ({ ...current, fsPathPlugins: defaultValue }));
};
const restoreSentryDsn = () => {
const defaultValue = defaultConfig.sentryDsn;
setSentryDsnInput(defaultValue);
updateConfig((current) => ({ ...current, sentryDsn: defaultValue }));
};
const restoreSystemPrompt = () => {
const defaultValue = defaultSystemPrompt;
setSystemPromptInput(defaultValue);
updateConfig((current) => ({ ...current, systemPrompt: defaultValue }));
};
// Service Worker state
const [swState, setSwState] = useState<string>('');
@@ -265,24 +363,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="project-template" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
{isModified.projectTemplate && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="project-template"
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={projectTemplateInput}
onChange={(e) => {
const value = e.target.value;
setProjectTemplateInput(value);
updateConfig((current) => ({
...current,
projectTemplate: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="project-template"
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={projectTemplateInput}
onChange={(e) => {
const value = e.target.value;
setProjectTemplateInput(value);
updateConfig((current) => ({
...current,
projectTemplate: value,
}));
}}
className="flex-1"
/>
{isModified.projectTemplate && (
<Button
variant="outline"
size="icon"
onClick={restoreProjectTemplate}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('projectTemplateDescription')}
</p>
@@ -295,24 +411,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="cors-proxy" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
{isModified.corsProxy && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="cors-proxy"
type="url"
placeholder="https://proxy.shakespeare.diy/?url={href}"
value={corsProxyInput}
onChange={(e) => {
const value = e.target.value;
setCorsProxyInput(value);
updateConfig((current) => ({
...current,
corsProxy: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="cors-proxy"
type="url"
placeholder="https://proxy.shakespeare.diy/?url={href}"
value={corsProxyInput}
onChange={(e) => {
const value = e.target.value;
setCorsProxyInput(value);
updateConfig((current) => ({
...current,
corsProxy: value,
}));
}}
className="flex-1"
/>
{isModified.corsProxy && (
<Button
variant="outline"
size="icon"
onClick={restoreCorsProxy}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('corsProxyDescription')}
</p>
@@ -325,24 +459,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="favicon-url" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
{isModified.faviconUrl && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="favicon-url"
type="url"
placeholder="https://favicon.shakespeare.diy/?url={href}"
value={faviconUrlInput}
onChange={(e) => {
const value = e.target.value;
setFaviconUrlInput(value);
updateConfig((current) => ({
...current,
faviconUrl: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="favicon-url"
type="url"
placeholder="https://favicon.shakespeare.diy/?url={href}"
value={faviconUrlInput}
onChange={(e) => {
const value = e.target.value;
setFaviconUrlInput(value);
updateConfig((current) => ({
...current,
faviconUrl: value,
}));
}}
className="flex-1"
/>
{isModified.faviconUrl && (
<Button
variant="outline"
size="icon"
onClick={restoreFaviconUrl}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('faviconUrlDescription')}
</p>
@@ -355,25 +507,43 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="esm-url" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
{isModified.esmUrl && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="esm-url"
type="url"
placeholder="https://esm.sh"
value={esmUrlInput}
onChange={(e) => {
// Strip trailing slash on save.
const value = e.target.value;
setEsmUrlInput(value);
updateConfig((current) => ({
...current,
esmUrl: value.replace(/\/+$/, ''),
}));
}}
/>
<div className="flex gap-2">
<Input
id="esm-url"
type="url"
placeholder="https://esm.sh"
value={esmUrlInput}
onChange={(e) => {
// Strip trailing slash on save.
const value = e.target.value;
setEsmUrlInput(value);
updateConfig((current) => ({
...current,
esmUrl: value.replace(/\/+$/, ''),
}));
}}
className="flex-1"
/>
{isModified.esmUrl && (
<Button
variant="outline"
size="icon"
onClick={restoreEsmUrl}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('esmUrlDescription')}
</p>
@@ -386,24 +556,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="preview-domain" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
{isModified.previewDomain && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="preview-domain"
type="text"
placeholder="local-shakespeare.dev"
value={previewDomainInput}
onChange={(e) => {
const value = e.target.value;
setPreviewDomainInput(value);
updateConfig((current) => ({
...current,
previewDomain: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="preview-domain"
type="text"
placeholder="local-shakespeare.dev"
value={previewDomainInput}
onChange={(e) => {
const value = e.target.value;
setPreviewDomainInput(value);
updateConfig((current) => ({
...current,
previewDomain: value,
}));
}}
className="flex-1"
/>
{isModified.previewDomain && (
<Button
variant="outline"
size="icon"
onClick={restorePreviewDomain}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('previewDomainDescription')}
</p>
@@ -416,47 +604,87 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="showcase" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('showcase')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('showcase')}</h4>
{(isModified.showcaseEnabled || isModified.showcaseModerator) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="flex items-center justify-between">
<Label htmlFor="showcase-enabled" className="text-sm font-medium">
{t('showcaseEnabled')}
</Label>
<Switch
id="showcase-enabled"
checked={config.showcaseEnabled}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
showcaseEnabled: checked,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="showcase-enabled" className="text-sm font-medium">
{t('showcaseEnabled')}
</Label>
{isModified.showcaseEnabled && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex items-center gap-2">
<Switch
id="showcase-enabled"
checked={config.showcaseEnabled}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
showcaseEnabled: checked,
}));
}}
/>
{isModified.showcaseEnabled && (
<Button
variant="outline"
size="icon"
onClick={restoreShowcaseEnabled}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
</div>
<p className="text-xs text-muted-foreground">
{t('showcaseEnabledDescription')}
</p>
<div className="space-y-2">
<Label htmlFor="showcase-moderator" className="text-sm font-medium">
{t('showcaseModerator')}
</Label>
<Input
id="showcase-moderator"
type="text"
placeholder="npub1..."
value={showcaseModeratorInput}
onChange={(e) => {
const value = e.target.value;
setShowcaseModeratorInput(value);
updateConfig((current) => ({
...current,
showcaseModerator: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="showcase-moderator" className="text-sm font-medium">
{t('showcaseModerator')}
</Label>
{isModified.showcaseModerator && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="showcase-moderator"
type="text"
placeholder="npub1..."
value={showcaseModeratorInput}
onChange={(e) => {
const value = e.target.value;
setShowcaseModeratorInput(value);
updateConfig((current) => ({
...current,
showcaseModerator: value,
}));
}}
className="flex-1"
/>
{isModified.showcaseModerator && (
<Button
variant="outline"
size="icon"
onClick={restoreShowcaseModerator}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('showcaseModeratorDescription')}
</p>
@@ -470,24 +698,42 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="sentry-dsn" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
{isModified.sentryDsn && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<Input
id="sentry-dsn"
type="text"
placeholder="https://..."
value={sentryDsnInput}
onChange={(e) => {
const value = e.target.value;
setSentryDsnInput(value);
updateConfig((current) => ({
...current,
sentryDsn: value,
}));
}}
/>
<div className="flex gap-2">
<Input
id="sentry-dsn"
type="text"
placeholder="https://..."
value={sentryDsnInput}
onChange={(e) => {
const value = e.target.value;
setSentryDsnInput(value);
updateConfig((current) => ({
...current,
sentryDsn: value,
}));
}}
className="flex-1"
/>
{isModified.sentryDsn && (
<Button
variant="outline"
size="icon"
onClick={restoreSentryDsn}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('sentryDsnDescription')}
</p>
@@ -500,97 +746,174 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="filesystem-paths" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
<div className="space-y-2">
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
{t('projectsDirectory')}
</Label>
<Input
id="fs-path-projects"
type="text"
placeholder="/projects"
value={fsPathProjectsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathProjectsInput(value);
updateConfig((current) => ({
...current,
fsPathProjects: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-projects" className="text-sm font-medium">
{t('projectsDirectory')}
</Label>
{isModified.fsPathProjects && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-projects"
type="text"
placeholder="/projects"
value={fsPathProjectsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathProjectsInput(value);
updateConfig((current) => ({
...current,
fsPathProjects: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathProjects && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathProjects}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('projectsDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="fs-path-config" className="text-sm font-medium">
{t('configDirectory')}
</Label>
<Input
id="fs-path-config"
type="text"
placeholder="/config"
value={fsPathConfigInput}
onChange={(e) => {
const value = e.target.value;
setFsPathConfigInput(value);
updateConfig((current) => ({
...current,
fsPathConfig: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-config" className="text-sm font-medium">
{t('configDirectory')}
</Label>
{isModified.fsPathConfig && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-config"
type="text"
placeholder="/config"
value={fsPathConfigInput}
onChange={(e) => {
const value = e.target.value;
setFsPathConfigInput(value);
updateConfig((current) => ({
...current,
fsPathConfig: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathConfig && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathConfig}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('configDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="fs-path-tmp" className="text-sm font-medium">
{t('temporaryDirectory')}
</Label>
<Input
id="fs-path-tmp"
type="text"
placeholder="/tmp"
value={fsPathTmpInput}
onChange={(e) => {
const value = e.target.value;
setFsPathTmpInput(value);
updateConfig((current) => ({
...current,
fsPathTmp: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-tmp" className="text-sm font-medium">
{t('temporaryDirectory')}
</Label>
{isModified.fsPathTmp && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-tmp"
type="text"
placeholder="/tmp"
value={fsPathTmpInput}
onChange={(e) => {
const value = e.target.value;
setFsPathTmpInput(value);
updateConfig((current) => ({
...current,
fsPathTmp: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathTmp && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathTmp}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('temporaryDirectoryDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="fs-path-plugins" className="text-sm font-medium">
{t('pluginsDirectory')}
</Label>
<Input
id="fs-path-plugins"
type="text"
placeholder="/plugins"
value={fsPathPluginsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathPluginsInput(value);
updateConfig((current) => ({
...current,
fsPathPlugins: value,
}));
}}
/>
<div className="flex items-center gap-2">
<Label htmlFor="fs-path-plugins" className="text-sm font-medium">
{t('pluginsDirectory')}
</Label>
{isModified.fsPathPlugins && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<div className="flex gap-2">
<Input
id="fs-path-plugins"
type="text"
placeholder="/plugins"
value={fsPathPluginsInput}
onChange={(e) => {
const value = e.target.value;
setFsPathPluginsInput(value);
updateConfig((current) => ({
...current,
fsPathPlugins: value,
}));
}}
className="flex-1"
/>
{isModified.fsPathPlugins && (
<Button
variant="outline"
size="icon"
onClick={restoreFsPathPlugins}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('pluginsDirectoryDescription')}
</p>
@@ -599,6 +922,53 @@ export function SystemSettings() {
</AccordionContent>
</AccordionItem>
</Accordion>
{/* System Prompt Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('systemPrompt')}</h4>
{isModified.systemPrompt && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<div className="flex gap-2 flex-col">
<Textarea
id="system-prompt"
placeholder="Enter EJS template..."
value={systemPromptInput}
onChange={(e) => {
const value = e.target.value;
setSystemPromptInput(value);
updateConfig((current) => ({
...current,
systemPrompt: value,
}));
}}
className="flex-1 font-mono text-xs min-h-[400px]"
/>
{isModified.systemPrompt && (
<Button
variant="outline"
onClick={restoreSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('systemPromptDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
);
+1 -1
View File
@@ -33,7 +33,7 @@ export default defineConfig(() => ({
manifest: false, // Use existing manifest.webmanifest from public folder
workbox: {
globPatterns: ['**/*.{js,css,html,ico,png,svg,woff2,wasm,mp3}'],
maximumFileSizeToCacheInBytes: 10 * 1024 * 1024, // 10 MB
maximumFileSizeToCacheInBytes: 15 * 1024 * 1024, // 15 MB (to accommodate esbuild.wasm at ~12 MB)
cleanupOutdatedCaches: true,
},
devOptions: {