Compare commits

..
Author SHA1 Message Date
Chad Curtis f09f1436ae further changes 2025-09-25 19:28:38 +00:00
385 changed files with 9651 additions and 57499 deletions

No files matched your search

-147
View File
@@ -1,147 +0,0 @@
<!DOCTYPE html><html lang="en" class="light"><head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="content-security-policy" content="default-src 'self'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:">
<title>Shakespeare Resources - FAQ &amp; Guides | Soapbox</title>
<meta name="description" content="Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.">
<!-- Open Graph / Facebook -->
<meta property="og:type" content="website">
<meta property="og:title" content="Shakespeare Resources - FAQ &amp; Guides | Soapbox">
<meta property="og:description" content="Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.">
<meta property="og:image" content="https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png">
<meta property="og:url" content="https://soapbox.pub/shakespeare-resources">
<meta property="og:site_name" content="Soapbox">
<!-- Twitter -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="Shakespeare Resources - FAQ &amp; Guides | Soapbox">
<meta name="twitter:description" content="Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.">
<meta name="twitter:image" content="https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png">
<!-- Additional meta tags -->
<meta name="image" content="https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png">
<meta name="author" content="Soapbox Technology">
<meta name="keywords" content="shakespeare resources, shakespeare faq, shakespeare blog, ai website builder help, shakespeare tutorials">
<meta name="robots" content="index, follow">
<meta name="language" content="English">
<meta name="revisit-after" content="7 days">
<!-- Additional Open Graph tags -->
<meta property="og:locale" content="en_US">
<meta property="og:image:width" content="1200">
<meta property="og:image:height" content="630">
<meta property="og:image:type" content="image/jpeg">
<!-- Twitter specific -->
<meta name="twitter:site" content="@soapbox_pub">
<meta name="twitter:creator" content="@soapbox_pub">
<!-- Canonical URL -->
<link rel="canonical" href="https://soapbox.pub/shakespeare-resources">
<!-- Favicon -->
<link rel="apple-touch-icon" sizes="180x180" href="/favicon/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/favicon/safari-pinned-tab.svg" color="#0482d8">
<link rel="shortcut icon" href="/favicon/favicon.ico">
<meta name="msapplication-TileColor" content="#0482d8">
<meta name="msapplication-config" content="/favicon/browserconfig.xml">
<meta name="theme-color" content="#0482d8">
<script type="module" crossorigin="" src="/assets/index-SKr11h0N.js"></script>
<link rel="stylesheet" crossorigin="" href="/assets/index-Ck_Ce8d7.css">
<script id="structured-data" type="application/ld+json">{
"@context": "https://schema.org",
"@type": "WebPage",
"name": "Shakespeare Resources - FAQ & Guides | Soapbox",
"description": "Complete resource hub for Shakespeare AI website builder. Find answers to frequently asked questions and explore tutorials on how to make the most of Shakespeare.",
"url": "https://soapbox.pub/shakespeare-resources",
"image": "https://soapbox.pub/assets/images/shakespeare-screenshots/resrouce-center.png",
"isPartOf": {
"@type": "WebSite",
"name": "Soapbox",
"url": "https://soapbox.pub"
}
}</script></head>
<body>
<div id="root"><div role="region" aria-label="Notifications (F8)" tabindex="-1" style="pointer-events: none;"><ol tabindex="-1" class="fixed top-0 z-[100] flex max-h-screen w-full flex-col-reverse p-4 sm:bottom-0 sm:right-0 sm:top-auto sm:flex-col md:max-w-[420px]"></ol></div><div class="min-h-screen bg-gradient-to-br from-blue-50 via-white to-purple-50"><nav class="border-b bg-white/80 backdrop-blur-sm sticky top-0 z-50"><div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8"><div class="flex justify-between items-center h-16"><a class="flex items-center space-x-2" href="/"><img src="/logo.svg" alt="Soapbox Logo" width="32" height="32"><span class="font-display font-bold text-xl text-gray-900">Soapbox</span></a><div class="hidden md:flex items-center space-x-8"><a class="transition-colors text-gray-600 hover:text-azure" href="/">Home</a><a class="transition-colors text-gray-600 hover:text-azure" href="/tools">Tools</a><a class="transition-colors text-gray-600 hover:text-azure" href="/showcase">Showcase</a><a class="transition-colors text-gray-600 hover:text-azure" href="/about">About</a><a class="transition-colors text-gray-600 hover:text-azure" href="/blog">Blog</a><a class="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 h-9 rounded-md px-3 bg-blue-100 hover:bg-blue-200 text-blue-700 border border-blue-200 hover:border-blue-300 transition-all duration-200 flex items-center space-x-2" href="/tools/shakespeare"><span class="text-sm">🎭</span><span>Shakespeare</span></a></div><div class="md:hidden"><button class="inline-flex items-center justify-center gap-2 whitespace-nowrap text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 hover:bg-accent hover:text-accent-foreground h-9 rounded-md p-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-menu h-6 w-6"><line x1="4" x2="20" y1="12" y2="12"></line><line x1="4" x2="20" y1="6" y2="6"></line><line x1="4" x2="20" y1="18" y2="18"></line></svg></button></div></div></div></nav><section class="pt-20 pb-16 px-4 sm:px-6 lg:px-8"><div class="max-w-7xl mx-auto text-center"><div class="space-y-6"><div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 hover:bg-secondary/80 bg-purple-100 text-purple-700 border-purple-200">📚 Resource Hub</div><h1 class="text-5xl md:text-6xl font-display font-bold text-gray-900"><span class="text-purple-600">🎭 Shakespeare</span> Resources</h1><p class="text-xl text-gray-600 max-w-3xl mx-auto">Find answers to common questions and explore our latest guides.</p></div></div></section><section class="py-16 px-4 sm:px-6 lg:px-8 bg-gradient-to-br from-purple-50 to-blue-50"><div class="max-w-6xl mx-auto"><div class="text-center mb-12"><div class="flex items-center justify-center mb-4"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-play h-8 w-8 text-purple-600 mr-3"><polygon points="6 3 20 12 6 21 6 3"></polygon></svg><h2 class="text-4xl font-display font-bold text-gray-900">Video Tutorial Playlist</h2></div><p class="text-lg text-gray-600">Watch our complete video guide series to master Shakespeare</p></div><div class="mb-8"><div class="relative w-full aspect-video mb-8 max-w-5xl mx-auto"><iframe src="https://www.youtube.com/embed/videoseries?si=NoONPhl3VGl5cEOX&amp;list=PLPVwsk16NNURX_8MJxm5luRZpGVoZ7Qba" title="Shakespeare Tutorial Playlist - Complete Guide Series" class="absolute inset-0 w-full h-full rounded-lg" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen=""></iframe></div></div><div class="text-center"><p class="text-gray-600 mb-4">This playlist includes step-by-step tutorials covering all major Shakespeare features</p><div class="flex flex-wrap justify-center gap-2"><div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 border-purple-200 text-purple-700">🔄 Import Projects</div><div class="inline-flex items-center rounded-full border px-2.5 py-0.5 text-xs font-semibold transition-colors focus:outline-none focus:ring-2 foLine truncated
#mc_embed_signup {
background: transparent !important;
clear: left;
font: 14px Helvetica, Arial, sans-serif;
width: 100% !important;
}
#mc_embed_signup h2 {
display: none;
}
#mc_embed_signup .mc-field-group {
margin-bottom: 1rem;
}
#mc_embed_signup label {
font-weight: 600;
margin-bottom: 0.5rem;
display: block;
color: inherit;
}
#mc_embed_signup input[type="text"],
#mc_embed_signup input[type="email"] {
width: 100%;
padding: 0.75rem;
border: 1px solid #d1d5db;
border-radius: 0.5rem;
font-size: 14px;
background: white;
}
#mc_embed_signup input.error {
border-color: #ef4444 !important;
}
#mc_embed_signup .button {
background: linear-gradient(to right, #8B5CF6, #3B82F6) !important;
border: none !important;
border-radius: 0.5rem !important;
color: white !important;
padding: 0.75rem 2rem !important;
font-weight: 600 !important;
cursor: pointer !important;
width: 100% !important;
margin-top: 1rem !important;
}
#mc_embed_signup .button:hover {
background: linear-gradient(to right, #7C3AED, #2563EB) !important;
}
#mc_embed_signup .indicates-required {
font-size: 12px;
color: #6b7280;
margin-bottom: 1rem;
}
#mc_embed_signup .asterisk {
color: #ef4444;
}
.dark #mc_embed_signup input[type="text"],
.dark #mc_embed_signup input[type="email"] {
background: #374151;
border-color: #4b5563;
color: white;
}
.dark #mc_embed_signup label {
color: #f9fafb;
}
.dark #mc_embed_signup input.error {
border-color: #ef4444 !important;
}
</style><div id="mc_embed_signup"><form action="https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&amp;id=f7271442a0&amp;f_id=00ffa3e4f0" method="post" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" class="validate" target="_blank"><div id="mc_embed_signup_scroll"><div class="indicates-required"><span class="asterisk">*</span> indicates required</div><div class="mc-field-group"><label for="mce-NPUB">Nostr Public Key (npub) <span style="color: rgb(107, 114, 128); font-weight: normal;">(optional)</span></label><input type="text" name="NPUB" class="text " id="mce-NPUB" placeholder="npub1..." value=""></div><div class="mc-field-group"><label for="mce-EMAIL">Email Address <span class="asterisk">*</span></label><input type="email" name="EMAIL" class="required email" id="mce-EMAIL" required="" placeholder="[email protected]"></div><div hidden=""><input type="hidden" name="tags" value="8982394"></div><div id="mce-responses" class="clear"><div class="response" id="mce-error-response" style="display: none;"></div><div class="response" id="mce-success-response" style="display: none;"></div></div><div aria-hidden="true" style="position: absolute; left: -5000px;"><input type="text" name="b_f1f718a93795f42a604d558d8_f7271442a0" tabindex="-1"></div><div class="clear"><input type="submit" name="subscribe" id="mc-embedded-subscribe" class="button" value="Sign Up"></div></div></form></div><script type="text/javascript" src="//s3.amazonaws.com/downloads.mailchimp.com/js/mc-validate.js"></script><script type="text/javascript">(function($) {
window.fnames = new Array();
window.ftypes = new Array();
fnames[6]='NPUB';ftypes[6]='text';
fnames[0]='EMAIL';ftypes[0]='email';
fnames[1]='FNAME';ftypes[1]='text';
fnames[2]='LNAME';ftypes[2]='text';
fnames[3]='ADDRESS';ftypes[3]='address';
fnames[4]='PHONE';ftypes[4]='phone';
fnames[5]='BIRTHDAY';ftypes[5]='birthday';
}(jQuery));
var $mcj = jQuery.noConflict(true);</script></div></div></div></div></section><footer class="bg-gray-900 text-white py-16 px-4 sm:px-6 lg:px-8"><div class="max-w-7xl mx-auto"><div class="grid md:grid-cols-6 gap-8"><div class="md:col-span-2 space-y-6"><div class="space-y-4"><div class="flex items-center space-x-2"><img src="/logo.svg" alt="Soapbox Logo" width="32" height="32"><span class="font-display font-bold text-xl">Soapbox</span></div><p class="text-gray-400 max-w-md">Software for the next generation of social media.</p></div><div class="space-y-3"><h4 class="font-semibold text-sm uppercase tracking-wide">Stay Updated</h4><form class="space-y-2"><div class="flex gap-2"><div class="relative flex-1"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-mail absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-500 h-4 w-4"><rect width="20" height="16" x="2" y="4" rx="2"></rect><path d="m22 7-8.97 5.7a1.94 1.94 0 0 1-2.06 0L2 7"></path></svg><input type="email" class="flex h-10 w-full rounded-md border px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm pl-10 text-gray-900 placeholder:text-gray-500 bg-white border-gray-300" placeholder="Your email address" required="" value=""></div><button class="inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 bg-primary text-primary-foreground hover:bg-primary/90 h-10 py-2 px-6" type="submit">Sign up</button></div></form><div class="pt-2"><button class="inline-flex items-center gap-2 whitespace-nowrap rounded-md text-sm font-medium ring-offset-background transition-colors focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none disabled:opacity-50 [&amp;_svg]:pointer-events-none [&amp;_svg]:size-4 [&amp;_svg]:shrink-0 border border-input bg-transparent hover:bg-accent hover:text-accent-foreground h-10 px-4 py-2 justify-between w-full" role="combobox" aria-expanded="false" type="button" aria-haspopup="dialog" aria-controls="radix-:rk:" data-state="closed"><div class="flex items-center gap-2"><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-wifi h-4 w-4"><path d="M12 20h.01"></path><path d="M2 8.82a15 15 0 0 1 20 0"></path><path d="M5 12.859a10 10 0 0 1 14 0"></path><path d="M8.5 16.429a5 5 0 0 1 7 0"></path></svg><span class="truncate">Ditto</span></div><svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" class="lucide lucide-chevrons-up-down ml-2 h-4 w-4 shrink-0 opacity-50"><path d="m7 15 5 5 5-5"></path><path d="m7 9 5-5 5 5"></path></svg></button></div></div></div><div><h4 class="font-semibold mb-4">Tools</h4><ul class="space-y-2 text-gray-400"><li><a href="https://ditto.pub" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Ditto</a></li><li><a href="https://mkstack.xyz" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">MKStack</a></li><li><a href="https://getstacks.dev" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Stacks</a></li><li><a href="https://nostrbook.dev" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Nostrbook</a></li><li><a href="https://nostrhub.io" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">NostrHub</a></li><li><a href="https://nostrify.dev" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Nostrify</a></li></ul></div><div><h4 class="font-semibold mb-4">Communities</h4><ul class="space-y-2 text-gray-400"><li><a href="https://ditto.pub" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Ditto.pub</a></li><li><a href="https://treasures.to" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Treasures</a></li><li><a href="https://blobbi.pet" class="hover:text-white transition-colors" target="_blank" rel="noopener noreferrer">Blobbi</a></li><li><a href="https://bookstr.xyz" class="hover:text-white transition-colors" target="_bLine truncated
</body></html>
+1 -13
View File
@@ -1,14 +1,2 @@
# Sentry
VITE_SENTRY_DSN="https://********************************@*****************.example.com/****************"
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="********************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
# Netlify OAuth Configuration
VITE_NETLIFY_OAUTH_CLIENT_ID="********************"
VITE_NETLIFY_OAUTH_CLIENT_SECRET="****************************************"
# Vercel OAuth Configuration
VITE_VERCEL_OAUTH_CLIENT_ID="********************"
VITE_VERCEL_OAUTH_CLIENT_SECRET="****************************************"
VITE_GITHUB_OAUTH_CLIENT_SECRET="****************************************"
-7
View File
@@ -7,17 +7,11 @@ yarn-error.log*
pnpm-debug.log*
lerna-debug.log*
deploy.sh
node_modules
dist
dist-ssr
*.local
.ai-history/
*.apk
*.aab
# Electron build output
electron-dist
# Editor directories and files
.idea
@@ -36,4 +30,3 @@ electron-dist
.env.*
!.env.example
.ai/
*.keystore
+2 -3
View File
@@ -1,4 +1,3 @@
{
"editor.tabSize": 2,
"editor.insertSpaces": true
}
"editor.tabSize": 2
}
+17 -102
View File
@@ -1,6 +1,6 @@
# Shakespeare - AI-Powered App Builder
# Shakespeare - AI-Powered Nostr Website Builder
Shakespeare is a browser-based AI chat application that allows users to build custom web applications through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
Shakespeare is a browser-based AI chat application that allows users to build custom Nostr websites through natural language conversation. All operations including AI chat and Git operations are executed in client-side JavaScript, with API keys stored in browser storage. Simply describe what you want to build, and AI will help you create it.
### Virtual Filesystem Layout
@@ -33,7 +33,7 @@ This architecture allows Shakespeare to provide a full development environment e
Shakespeare provides AI agents with specialized tools for project development (note: these are different from the tools available during Shakespeare's own development). These tools are defined in `src/lib/tools/`:
- **ShellTool**: Execute shell commands (virtual in browser, real OS shell in Electron)
- **ShellTool**: Execute shell commands in the virtual filesystem environment
- **TextEditorViewTool**: Read file contents and view directory structures
- **TextEditorWriteTool**: Create or overwrite files with new content
- **TextEditorStrReplaceTool**: Replace strings in files
@@ -55,7 +55,6 @@ Shakespeare provides AI agents with specialized tools for project development (n
#### Shell Commands
**In Browser Mode:**
Shakespeare provides a comprehensive set of shell commands that are JavaScript reimplementations of common Unix commands. These commands operate on the virtual filesystem (VFS) and are accessible through the ShellTool. The shell commands are implemented in `src/lib/commands/` and provide familiar Unix-like functionality for file and directory operations.
**Available Commands:**
@@ -64,16 +63,6 @@ Shakespeare provides a comprehensive set of shell commands that are JavaScript r
- **System Commands**: `echo`, `which`, `wc`, `head`, `tail`
- **Git Commands**: `git add`, `git commit`, `git push`, `git pull`, `git status`, `git log`, etc.
**In Electron Mode:**
When running in Electron, the ShellTool automatically uses the **real OS terminal** instead of the virtual terminal. This means:
- **All OS commands available**: Not limited to built-in commands
- **Native shell features**: Pipes, redirection, environment variables work natively
- **Package managers**: `npm`, `yarn`, `pnpm` work directly
- **Build tools**: `vite`, `webpack`, `tsc`, etc. available
- **System utilities**: Full access to OS commands
The ShellTool detects the environment automatically and uses the appropriate execution method.
#### Security
AI filesystem access through tools (including shell commands via ShellTool) has path restrictions to ensure safe operation:
@@ -91,7 +80,6 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
- **GitCommitTool**: AI tool for automated commits with staging and validation
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
- **useGitFetch Hook**: Automatic remote fetch with change detection (updates every 60 seconds, shows toast notifications)
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
#### Core Features
@@ -120,30 +108,6 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
Git operations happen transparently in the background, providing professional version control without requiring Git knowledge from users.
### Gift Card Redemption
Shakespeare supports automatic gift card redemption via URL parameters. Users can click shareable gift card links to instantly redeem AI credits.
**URL Format:**
```
/giftcard#baseURL=<providerBaseURL>&code=<giftcardCode>
```
**Flow:**
1. User clicks gift card link (e.g., from email or social media)
2. Shakespeare displays a dialog showing the credit amount
3. URL is rewritten to `/` for privacy (removes gift card code from history)
4. If user is not logged in or provider is not configured, a multi-step wizard guides them through setup
5. User can switch between Nostr accounts before redeeming
6. Credits are added to the user's account via NIP-98 authenticated API call
**Components:**
- `GiftCardRedeemDialog`: Main dialog handling the entire redemption flow
- Integrates with existing login/signup dialogs and provider configuration
- Automatically matches provider baseURL against configured providers and presets
See `GIFTCARD_REDEMPTION.md` for detailed documentation.
## AI Message Format
Shakespeare uses OpenAI-compatible messages for communication between users and AI assistants. The message format follows these conventions:
@@ -220,7 +184,6 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
- `useGitSettings`: Manage Git credentials and repository settings
- `useSessionManager`: Access session management for AI chat sessions
- `useGitStatus`: Real-time Git repository status monitoring
- `useGitFetch`: Automatic remote fetch with change detection and toast notifications
- `useProjects`: Project management and CRUD operations
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
- `useTheme`: Theme management
@@ -1100,19 +1063,12 @@ The project includes an `AppProvider` that manages global application state incl
```typescript
const defaultConfig: AppConfig = {
theme: "system",
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
],
updatedAt: 0,
},
// ... other config options
theme: "light",
relayUrl: "wss://relay.nostr.band",
};
```
The app uses NIP-65 relay lists for managing multiple relays with read/write permissions. Configuration is persisted in local storage.
Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences.
## Routing
@@ -1166,12 +1122,11 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag
### Empty States and No Content Found
When no content is found (empty search results, no data available, etc.), display a minimalist empty state that guides users to take action or provides helpful context.
When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources.
```tsx
import { RelaySelector } from '@/components/RelaySelector';
import { Card, CardContent } from '@/components/ui/card';
import { Button } from '@/components/ui/button';
import { Link } from 'react-router-dom';
// Empty state example
<div className="col-span-full">
@@ -1179,64 +1134,24 @@ import { Link } from 'react-router-dom';
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
No results found. Configure your relays to discover more content.
No results found. Try another relay?
</p>
<Button asChild variant="outline">
<Link to="/settings/nostr">Manage Relays</Link>
</Button>
<RelaySelector className="w-full" />
</div>
</CardContent>
</Card>
</div>
```
## CRITICAL Design Standards
## Design Customization
- Create breathtaking, immersive designs that feel like bespoke masterpieces, rivaling the polish of Apple, Stripe, or luxury brands
- Designs must be production-ready, fully featured, with no placeholders unless explicitly requested, ensuring every element serves a functional and aesthetic purpose
- Avoid generic or templated aesthetics at all costs; every design must have a unique, brand-specific visual signature that feels custom-crafted
- Headers must be dynamic, immersive, and storytelling-driven, using layered visuals, motion, and symbolic elements to reflect the brand’s identity—never use simple “icon and text” combos
- Incorporate purposeful, lightweight animations for scroll reveals, micro-interactions (e.g., hover, click, transitions), and section transitions to create a sense of delight and fluidity
**Tailor the site's look and feel based on the user's specific request.** This includes:
### Design Principles
- Achieve Apple-level refinement with meticulous attention to detail, ensuring designs evoke strong emotions (e.g., wonder, inspiration, energy) through color, motion, and composition
- Deliver fully functional interactive components with intuitive feedback states, ensuring every element has a clear purpose and enhances user engagement
- Use custom illustrations, 3D elements, or symbolic visuals instead of generic stock imagery to create a unique brand narrative; stock imagery, when required, must be sourced exclusively from Pexels (NEVER Unsplash) and align with the design’s emotional tone
- Ensure designs feel alive and modern with dynamic elements like gradients, glows, or parallax effects, avoiding static or flat aesthetics
- Before finalizing, ask: "Would this design make Apple or Stripe designers pause and take notice?" If not, iterate until it does
### Avoid Generic Design
- No basic layouts (e.g., text-on-left, image-on-right) without significant custom polish, such as dynamic backgrounds, layered visuals, or interactive elements
- No simplistic headers; they must be immersive, animated, and reflective of the brand’s core identity and mission
- No designs that could be mistaken for free templates or overused patterns; every element must feel intentional and tailored
### Interaction Patterns
- Use progressive disclosure for complex forms or content to guide users intuitively and reduce cognitive load
- Incorporate contextual menus, smart tooltips, and visual cues to enhance navigation and usability
- Implement drag-and-drop, hover effects, and transitions with clear, dynamic visual feedback to elevate the user experience
- Support power users with keyboard shortcuts, ARIA labels, and focus states for accessibility and efficiency
- Add subtle parallax effects or scroll-triggered animations to create depth and engagement without overwhelming the user
### Technical Requirements
- Curated color FRpalette (3-5 evocative colors + neutrals) that aligns with the brand’s emotional tone and creates a memorable impact
- Ensure a minimum 4.5:1 contrast ratio for all text and interactive elements to meet accessibility standards
- Use expressive, readable fonts (18px+ for body text, 40px+ for headlines) with a clear hierarchy; pair a modern sans-serif (e.g., Inter) with an elegant serif (e.g., Playfair Display) for personality
- Design for full responsiveness, ensuring flawless performance and aesthetics across all screen sizes (mobile, tablet, desktop)
- Adhere to WCAG 2.1 AA guidelines, including keyboard navigation, screen reader support, and reduced motion options
- Follow an 8px grid system for consistent spacing, padding, and alignment to ensure visual harmony
- Add depth with subtle shadows, gradients, glows, and rounded corners (e.g., 16px radius) to create a polished, modern aesthetic
- Optimize animations and interactions to be lightweight and performant, ensuring smooth experiences across devices
### Components
- Design reusable, modular components with consistent styling, behavior, and feedback states (e.g., hover, active, focus, error)
- Include purposeful animations (e.g., scale-up on hover, fade-in on scroll) to guide attention and enhance interactivity without distraction
- Ensure full accessibility support with keyboard navigation, ARIA labels, and visible focus states (e.g., a glowing outline in an accent color)
- Use custom icons or illustrations for components to reinforce the brand’s visual identity
- **Color schemes**: Incorporate the user's color preferences when specified, and choose an appropriate scheme that matches the application's purpose and aesthetic
- **Typography**: Choose fonts that match the requested aesthetic (modern, elegant, playful, etc.)
- **Layout**: Follow the requested structure (3-column, sidebar, grid, etc.)
- **Component styling**: Use appropriate border radius, shadows, and spacing for the desired feel
- **Interactive elements**: Style buttons, forms, and hover states to match the theme
### Adding Fonts
+68 -26
View File
@@ -1,43 +1,85 @@
# Shakespeare 🎭
# Shakespeare - AI-Powered Nostr Website Builder
[![Edit with Shakespeare](https://shakespeare.diy/badge.svg)](https://shakespeare.diy/clone?url=https://gitlab.com/soapbox-pub/shakespeare.git)
Shakespeare is an open-source AI app builder that runs entirely in your browser.
https://shakespeare.diy
Shakespeare is an AI chat application that allows users to build custom Nostr websites through natural language conversation. Simply describe what you want to build, and AI will help you create it.
## Features
- **Use any AI provider** OpenAI, Anthropic, OpenRouter, xAI, ZAI, Deepseek, and more
- **Buy credits anonymously** with Nostr and Lightning ⚡
- **Redeem gift cards** with shareable links for instant credits
- **Runs entirely in the browser** No backend required
- **AI-Powered Development**: Chat with an AI assistant to build your Nostr website
- **File Attachments**: Attach files directly to chat messages with structured text parts, visual badges, and deduplication. Supports both file selection and clipboard image pasting
- **Project Management**: Create and manage multiple projects with sidebar navigation
- **Real-time Editing**: Edit files directly in the browser with syntax highlighting
- **File Explorer**: Browse and manage your project files
- **Project Preview**: Preview your website as you build it
- **Template Cloning**: Start from a pre-configured Nostr template
## How it Works
## Getting Started
Shakespeare is a React PWA that stores files in IndexedDB with [LightningFS](https://github.com/isomorphic-git/lightning-fs). Your browser connects directly to AI providers and git services (through [isomorphic-git](https://github.com/isomorphic-git/isomorphic-git)) to enable you to build and deploy AI apps entirely from your device.
1. **Create a Project**: Enter a description of what you want to build in the prompt textarea
2. **Chat with AI**: Use the AI assistant to add features, edit files, and build your website
3. **Attach Files**: Click the paperclip icon to attach files or paste images directly from your clipboard - they'll show as "Added file: /path/filename"
4. **Edit Code**: Switch to the code view to manually edit files if needed
5. **Preview**: View your website in the preview pane
Shakespeare hosts no backend (except for a couple microservices in the `services/` directory; these are fully configurable within Shakespeare's settings). All your code and configuration is stored in your browser.
## Project Structure
Configure any AI providers and git services you want. Configuration is stored entirely in the browser in localStorage.
Each project includes:
- React 18 with TypeScript
- Vite for building
- TailwindCSS for styling
- Nostrify for Nostr integration
- shadcn/ui components
You can then push and pull code to syncronize your work across devices.
## AI Capabilities
Shakespeare can work on any type of project. But it is specialized to build React applications in TypeScript, which it compiles in the browser with [esbuild-wasm](https://www.npmjs.com/package/esbuild-wasm) and custom plugins. Any codebase can be worked on, but only compatible projects can be previewed directly in Shakespeare.
The AI assistant can:
- Read and write project files
- Add new components and pages
- Configure Nostr functionality
- Build the project
- Search through files
- Provide project structure overview
- Add and remove npm packages
- Install dependencies and dev dependencies
## Open Source
## Usage
Shakespeare is proudly Open Source software licensed under the GNU AGPLv3. The purpose of Shakespeare is to provide a free and open platform for building AI applications that respects user privacy and freedom.
1. **Homepage**: Enter a project description in the textarea to create new projects, with existing projects listed in the sidebar
2. **Project View**: Split-pane interface with AI chat on the left and preview/code on the right
3. **File Explorer**: Navigate your project files in the code view
4. **File Editor**: Edit files with syntax highlighting and save changes
## Mirrors
## Git Integration
Shakespeare is available on the following URLs:
Shakespeare includes full Git functionality with credential management:
- [shakespeare.diy](https://shakespeare.diy)
- [shakespeare-diy.github.io](https://shakespeare-diy.github.io)
- [shakespeare-b0b9c8.gitlab.io](https://shakespeare-b0b9c8.gitlab.io)
### Features
- **Version Control**: Full Git repository support with commit history and branch management
- **Global Credentials**: Configure Git credentials once and use them across all projects
- **Automatic Matching**: Credentials are automatically matched to repository origins
- **Popular Providers**: Built-in support for GitHub, GitLab, and custom Git providers
- **Secure Storage**: Credentials are stored locally in your browser using IndexedDB
## Alternatives
### Setting Up Git Credentials
- [goose](https://github.com/block/goose) - open-source desktop app and cli utilizing your full computer for AI tasks
- [bolt.diy](https://github.com/stackblitz-labs/bolt.diy) - similar to Shakespeare, but built on closed-source WebContainers technology
1. **Access Git Settings**: Click the gear icon in any Git dialog or use the Git Settings option
2. **Add Provider**: Choose from GitHub, GitLab, or add a custom Git provider
3. **Enter Token**: Use your username and personal access token for authentication
4. **Automatic Usage**: Credentials are automatically used for push/pull operations in matching repositories
### Repository Operations
- **Push/Pull**: Sync changes with remote repositories using configured credentials
- **Status Monitoring**: Real-time Git status with file changes and sync information
- **Commit History**: View commit history and repository information
- **Branch Management**: Work with different branches and track remote changes
## Development
Built with:
- React 18
- TypeScript
- Vite
- TailwindCSS
- shadcn/ui
- LightningFS for filesystem
- isomorphic-git for template cloning
-544
View File
@@ -1,544 +0,0 @@
# Unified OAuth System
Shakespeare implements a unified OAuth 2.0 authentication system that supports multiple providers with a consistent API. This document explains how the system works and how to add new OAuth providers.
## Architecture
The OAuth system consists of three main components:
1. **Generic OAuth Hook** (`useOAuth`) - Core OAuth logic that works with any provider
2. **Provider-Specific Hooks** - Thin wrappers that configure the generic hook for specific providers
3. **OAuth Callback Pages** - React components that handle the OAuth redirect flow
### Current Supported Providers
- **GitHub** - Git repository hosting (with PKCE support)
- **Netlify** - Static site deployment
- **Vercel** - Static site deployment
## File Structure
```
src/
├── hooks/
│ ├── useOAuth.ts # Generic OAuth hook (core logic)
│ ├── useGitHubOAuth.ts # GitHub-specific configuration
│ ├── useNetlifyOAuth.ts # Netlify-specific configuration
│ └── useVercelOAuth.ts # Vercel-specific configuration
├── pages/
│ ├── GitHubOAuth.tsx # GitHub OAuth callback page
│ ├── NetlifyOAuth.tsx # Netlify OAuth callback page
│ └── VercelOAuth.tsx # Vercel OAuth callback page
└── AppRouter.tsx # Routes for OAuth callbacks
```
## Environment Variables
OAuth credentials are stored in environment variables and loaded from `process.env`:
```bash
# GitHub OAuth Configuration
VITE_GITHUB_OAUTH_CLIENT_ID="your_github_client_id"
VITE_GITHUB_OAUTH_CLIENT_SECRET="your_github_client_secret"
# Netlify OAuth Configuration
VITE_NETLIFY_OAUTH_CLIENT_ID="your_netlify_client_id"
VITE_NETLIFY_OAUTH_CLIENT_SECRET="your_netlify_client_secret"
# Vercel OAuth Configuration
VITE_VERCEL_OAUTH_CLIENT_ID="your_vercel_client_id"
VITE_VERCEL_OAUTH_CLIENT_SECRET="your_vercel_client_secret"
```
### Security Note
**Client secrets are stored in environment variables** and bundled into the client-side JavaScript. This is necessary because the OAuth flow runs entirely in the browser. While this approach is less secure than a traditional server-side OAuth flow, it's acceptable for this use case because:
1. Shakespeare is a client-side application with no backend
2. The OAuth tokens are scoped to specific permissions
3. Users can revoke tokens at any time from the provider's settings
4. The redirect URIs are validated by the OAuth provider
For production deployments, consider using a serverless function or backend service to handle the token exchange step, keeping client secrets secure.
## How It Works
### 1. Generic OAuth Hook (`useOAuth`)
The `useOAuth` hook implements the OAuth 2.0 authorization code flow with optional PKCE (Proof Key for Code Exchange) support. It accepts a configuration object and returns methods to initiate and handle the OAuth flow.
**Configuration Interface:**
```typescript
interface OAuthConfig {
provider: 'github' | 'netlify' | 'vercel'; // Provider identifier
clientId: string; // OAuth client ID
clientSecret: string; // OAuth client secret
authorizeUrl: string; // Provider's authorization endpoint
tokenUrl: string; // Provider's token exchange endpoint
scope?: string; // Requested OAuth scopes (optional)
redirectUri: string; // Callback URL after authorization
usePKCE?: boolean; // Enable PKCE (default: false)
getUserInfo?: ( // Optional function to fetch user info
accessToken: string,
corsProxy: string
) => Promise<{
username: string;
[key: string]: unknown;
}>;
}
```
**Returned API:**
```typescript
{
isLoading: boolean; // True during token exchange
error: string | null; // Error message if OAuth fails
isOAuthConfigured: boolean; // True if client ID and secret are set
initiateOAuth: () => void; // Start the OAuth flow
handleCallback: ( // Handle the OAuth callback
code: string,
state: string
) => Promise<OAuthResult | null>;
}
```
### 2. OAuth Flow Steps
#### Step 1: Initiate OAuth
When the user clicks "Connect to [Provider]", the `initiateOAuth()` function:
1. Generates a random `state` parameter for CSRF protection
2. Optionally generates PKCE parameters (code verifier and challenge)
3. Stores the state and code verifier in localStorage
4. Redirects to the provider's authorization page
```typescript
const { initiateOAuth } = useGitHubOAuth();
// User clicks button
<Button onClick={initiateOAuth}>Connect to GitHub</Button>
```
#### Step 2: User Authorizes
The user is redirected to the provider's authorization page where they:
1. Log in to their account (if not already logged in)
2. Review the requested permissions
3. Approve or deny the authorization request
#### Step 3: OAuth Callback
After authorization, the provider redirects back to the callback URL with:
- `code` - Authorization code
- `state` - The state parameter we sent
- `error` (optional) - Error code if authorization failed
- `error_description` (optional) - Human-readable error description
The callback page (e.g., `GitHubOAuth.tsx`) extracts these parameters and calls `handleCallback()`.
#### Step 4: Token Exchange
The `handleCallback()` function:
1. Verifies the `state` parameter matches what we stored
2. Retrieves the PKCE code verifier (if PKCE is enabled)
3. Exchanges the authorization code for an access token
4. Optionally fetches user information using the access token
5. Returns an `OAuthResult` object with the token and user data
```typescript
interface OAuthResult {
accessToken: string; // OAuth access token
username?: string; // User's username/email
scopes?: string[]; // Granted OAuth scopes
userData?: Record<string, unknown>; // Additional user data
}
```
#### Step 5: Store Credentials
Provider-specific hooks override `handleCallback` to store the credentials appropriately:
- **GitHub**: Stores in Git settings (for push/pull operations)
- **Netlify/Vercel**: Stores in Deploy settings (for deployment operations)
### 3. PKCE Support
PKCE (Proof Key for Code Exchange) adds an extra layer of security to the OAuth flow by preventing authorization code interception attacks. It's recommended for public clients like browser-based apps.
**How PKCE works:**
1. Generate a random `code_verifier` (cryptographically random string)
2. Create a `code_challenge` by hashing the verifier with SHA-256
3. Send the `code_challenge` during authorization
4. Send the `code_verifier` during token exchange
5. The server verifies that the verifier matches the challenge
**Enabling PKCE:**
```typescript
const config: OAuthConfig = {
// ... other config
usePKCE: true, // Enable PKCE
};
```
**Provider Support:**
- ✅ GitHub - Supports PKCE (enabled)
- ❌ Netlify - Doesn't support PKCE (disabled)
- ❌ Vercel - Doesn't support PKCE (disabled)
### Scope Parameter
The `scope` parameter is optional in the OAuth configuration. Some providers (like Netlify) don't use scopes in the authorization request - instead, permissions are configured when you create the OAuth application in the provider's settings.
**Provider Scope Usage:**
- ✅ GitHub - Uses scopes (e.g., `repo workflow`)
- ❌ Netlify - No scope parameter (permissions set in app settings)
- ✅ Vercel - Uses scopes (e.g., `deployments:write projects:read`)
## Adding a New OAuth Provider
To add a new OAuth provider, follow these steps:
### 1. Add Environment Variables
Add the client ID and secret to `.env.example`:
```bash
# NewProvider OAuth Configuration
VITE_NEWPROVIDER_OAUTH_CLIENT_ID="********************"
VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET="****************************************"
```
### 2. Create Provider-Specific Hook
Create a new file `src/hooks/useNewProviderOAuth.ts`:
```typescript
import { useCallback } from 'react';
import { useOAuth, type OAuthConfig, type OAuthResult } from './useOAuth';
import { proxyUrl } from '@/lib/proxyUrl';
interface NewProviderUserInfo {
id: string;
email: string;
// ... other user fields
}
export function useNewProviderOAuth() {
// Get the context where you want to store credentials
// e.g., useDeploySettings() or useGitSettings()
const { setProviders, settings } = useDeploySettings();
const config: OAuthConfig = {
provider: 'newprovider',
clientId: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_ID || '',
clientSecret: import.meta.env.VITE_NEWPROVIDER_OAUTH_CLIENT_SECRET || '',
authorizeUrl: 'https://provider.com/oauth/authorize',
tokenUrl: 'https://provider.com/oauth/token',
scope: 'read write', // Optional - omit if provider doesn't use scopes
redirectUri: window.location.origin + '/oauth/newprovider',
usePKCE: false, // Set to true if provider supports PKCE
getUserInfo: async (accessToken: string, corsProxy: string) => {
const userUrl = proxyUrl(corsProxy, 'https://api.provider.com/user');
const userResponse = await fetch(userUrl, {
headers: {
'Authorization': `Bearer ${accessToken}`,
},
});
if (!userResponse.ok) {
throw new Error(`Failed to verify token: ${userResponse.statusText}`);
}
const userData: NewProviderUserInfo = await userResponse.json();
return {
username: userData.email,
...userData,
};
},
};
const oauth = useOAuth(config);
const handleCallbackAndStore = useCallback(async (
code: string,
state: string
): Promise<boolean> => {
const result: OAuthResult | null = await oauth.handleCallback(code, state);
if (!result) {
return false;
}
// Store the credentials in the appropriate context
// This will vary based on what the provider is used for
const newProvider = {
id: crypto.randomUUID(),
name: result.username ? `NewProvider (${result.username})` : 'NewProvider',
type: 'newprovider',
apiKey: result.accessToken,
proxy: true,
};
setProviders([...settings.providers, newProvider]);
return true;
}, [oauth, setProviders, settings.providers]);
return {
...oauth,
handleCallback: handleCallbackAndStore,
};
}
```
### 3. Create OAuth Callback Page
Create a new file `src/pages/NewProviderOAuth.tsx`:
```typescript
import { useEffect } from 'react';
import { useSearchParams, useNavigate } from 'react-router-dom';
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
import { useToast } from '@/hooks/useToast';
import { Card, CardContent } from '@/components/ui/card';
export default function NewProviderOAuth() {
const [searchParams] = useSearchParams();
const navigate = useNavigate();
const { handleCallback } = useNewProviderOAuth();
const { toast } = useToast();
useEffect(() => {
const code = searchParams.get('code');
const state = searchParams.get('state');
const error = searchParams.get('error');
const errorDescription = searchParams.get('error_description');
const storedState = localStorage.getItem('newprovider_oauth_state');
if (error) {
toast({
title: "NewProvider OAuth Error",
description: errorDescription || error,
variant: "destructive",
});
navigate('/settings/deploy'); // or appropriate settings page
return;
}
if (code && state && storedState) {
handleCallback(code, state).then((success) => {
if (success) {
toast({
title: "NewProvider Connected",
description: "Successfully connected to NewProvider.",
});
} else {
toast({
title: "Connection Failed",
description: "Failed to connect to NewProvider. Please try again.",
variant: "destructive",
});
}
navigate('/settings/deploy'); // or appropriate settings page
});
} else {
navigate('/settings/deploy');
}
}, [searchParams, handleCallback, toast, navigate]);
return (
<div className="min-h-screen flex items-center justify-center p-4">
<Card className="w-full max-w-md">
<CardContent className="py-12 px-8 text-center">
<div className="space-y-6">
{/* Provider logo/icon */}
<div className="flex justify-center">
<svg className="h-12 w-12 text-primary" viewBox="0 0 24 24">
{/* Provider icon SVG */}
</svg>
</div>
<div className="space-y-2">
<h1 className="text-xl font-semibold">Connecting to NewProvider</h1>
<p className="text-muted-foreground">
Processing your NewProvider authentication...
</p>
</div>
<div className="flex justify-center">
<div className="animate-spin rounded-full h-6 w-6 border-b-2 border-primary"></div>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
```
### 4. Add Route
Add the OAuth callback route to `src/AppRouter.tsx`:
```typescript
import NewProviderOAuth from "./pages/NewProviderOAuth";
// ...
<Route path="/oauth/newprovider" element={<NewProviderOAuth />} />
```
### 5. Add to UI
Add the provider to the appropriate settings page (e.g., `DeploySettings.tsx`):
```typescript
import { useNewProviderOAuth } from '@/hooks/useNewProviderOAuth';
// In component:
const newProviderOAuth = useNewProviderOAuth();
// In PRESET_PROVIDERS array:
{
id: 'newprovider',
type: 'newprovider',
name: 'NewProvider',
description: 'Deploy to NewProvider',
apiKeyLabel: 'Access Token',
apiKeyURL: 'https://provider.com/settings/tokens',
proxy: true,
}
// In the render logic, add the OAuth hook to the switch:
const oauthHook = preset.type === 'netlify' ? netlifyOAuth :
preset.type === 'vercel' ? vercelOAuth :
preset.type === 'newprovider' ? newProviderOAuth : null;
```
### 6. Register OAuth Application
Register your OAuth application with the provider:
1. Go to the provider's developer settings
2. Create a new OAuth application
3. Set the **redirect URI** to: `https://yourdomain.com/oauth/newprovider`
4. Note the **client ID** and **client secret**
5. Add them to your `.env` file
## Testing OAuth Flow
To test the OAuth flow locally:
1. **Set up a tunnel** (e.g., ngrok, cloudflared) to expose localhost:
```bash
npx cloudflared tunnel --url http://localhost:5173
```
2. **Register OAuth app** with the tunnel URL as the redirect URI:
```
https://your-tunnel-url.trycloudflare.com/oauth/provider
```
3. **Add credentials** to `.env`:
```bash
VITE_PROVIDER_OAUTH_CLIENT_ID="your_client_id"
VITE_PROVIDER_OAUTH_CLIENT_SECRET="your_client_secret"
```
4. **Start the dev server**:
```bash
npm run dev
```
5. **Test the flow** by clicking the "Connect to Provider" button
## Error Handling
The OAuth system handles several types of errors:
### User Denies Authorization
If the user denies authorization, the provider redirects with an `error` parameter:
```
/oauth/provider?error=access_denied&error_description=User+denied+access
```
The callback page displays an error toast and redirects to settings.
### Invalid State Parameter
If the `state` parameter doesn't match what we stored (CSRF attack), the flow is aborted and an error is shown.
### Token Exchange Failure
If the token exchange fails (invalid code, expired, etc.), an error is logged and shown to the user.
### Missing PKCE Verifier
If PKCE is enabled but the code verifier is missing from localStorage, the flow is aborted.
## Security Considerations
1. **State Parameter**: Always used for CSRF protection
2. **PKCE**: Used when supported by the provider for additional security
3. **HTTPS Only**: OAuth should only be used over HTTPS in production
4. **Token Storage**: Tokens are stored in browser storage (localStorage/IndexedDB)
5. **Token Revocation**: Users can revoke tokens from the provider's settings
6. **Scope Limitation**: Request only the minimum required scopes
## Troubleshooting
### "OAuth client ID not configured"
The environment variables are not set. Check your `.env` file and ensure the variables are prefixed with `VITE_`.
### "Invalid OAuth state parameter"
The state parameter doesn't match. This could be caused by:
- Multiple OAuth flows running simultaneously
- Browser localStorage being cleared mid-flow
- CSRF attack attempt
### "Failed to verify token"
The provider's API rejected the access token. This could be caused by:
- Incorrect API endpoint URL
- Token doesn't have required scopes
- Provider API is down
### Redirect URI Mismatch
The redirect URI in your OAuth app registration must exactly match the URI in your code:
```typescript
redirectUri: window.location.origin + '/oauth/provider'
```
For local development with a tunnel, this would be:
```
https://your-tunnel-url.trycloudflare.com/oauth/provider
```
## Best Practices
1. **Always use PKCE** when the provider supports it
2. **Request minimal scopes** - only what you need
3. **Handle errors gracefully** - show user-friendly error messages
4. **Clear localStorage** on errors to prevent stuck states
5. **Validate tokens** by fetching user info after exchange
6. **Store tokens securely** - use appropriate browser storage APIs
7. **Provide token revocation** - link to provider's token management page
8. **Test error cases** - user denial, network failures, etc.
## Future Improvements
Potential enhancements to the OAuth system:
1. **Token Refresh**: Implement refresh token flow for long-lived sessions
2. **Token Expiry**: Track token expiration and prompt for re-authentication
3. **Multiple Accounts**: Support multiple accounts per provider
4. **Backend Proxy**: Optional backend service for secure token exchange
5. **Device Flow**: Support OAuth device flow for CLI tools
6. **Biometric Auth**: Integrate with WebAuthn for passwordless OAuth
-278
View File
@@ -1,278 +0,0 @@
# Shakespeare Plugins System
Shakespeare now includes a comprehensive plugins system that allows you to extend the AI's capabilities with reusable skills.
## Overview
Plugins are Git repositories that can contain **skills** - specialized AI workflows that help the AI assistant perform specific tasks more effectively. Skills are automatically discovered and made available to the AI through the `skill` tool.
## Features
- **Git-based plugins**: Clone plugins from any Git repository (GitHub, GitLab, etc.)
- **Automatic skill discovery**: Skills are automatically found and registered from all installed plugins
- **Configurable storage**: Plugin directory is configurable in System Settings
- **Sync support**: Pull latest changes from plugin repositories
- **Delete support**: Remove plugins when no longer needed
- **AI integration**: Skills are automatically included in the system prompt and accessible via the `skill` tool
## User Interface
### AI Settings Page (`/settings/ai`)
The AI Settings page now includes a **Plugins** section with:
1. **Add Plugin**: Clone a new plugin by entering its Git URL
2. **Plugin List**: View all installed plugins with their skills
3. **Sync**: Pull latest changes from a plugin's Git repository
4. **Delete**: Remove a plugin and all its skills
### System Settings Page (`/settings/system`)
The System Settings page includes a **Filesystem Paths** section where you can configure:
- **Plugins Directory**: Path where plugins are stored (default: `/plugins`)
## Plugin Structure
A plugin is a Git repository with the following structure:
```
my-plugin/
├── skills/
│ ├── skill1/
│ │ └── SKILL.md
│ ├── skill2/
│ │ └── SKILL.md
│ └── ...
└── README.md (optional)
```
### Skill Format
Each skill is defined by a `SKILL.md` file with YAML frontmatter:
```markdown
---
name: skillname
description: A brief description of what this skill does
---
# Skill Content
The rest of the file contains instructions, examples, and context
that will be provided to the AI when this skill is invoked.
This can include:
- Step-by-step workflows
- Code examples
- Best practices
- Domain-specific knowledge
```
#### Required Frontmatter Fields
- **`name`**: Skill identifier (must be lowercase alphanumeric with hyphens, e.g., `myskill`, `skill-123`, `condition-based-waiting`)
- **`description`**: Human-readable description of what the skill does
#### Skill Name Validation
Skill names must:
- Contain only lowercase letters (a-z), numbers (0-9), and hyphens (-)
- No spaces, underscores, uppercase letters, or other special characters
- Examples: ✅ `myskill`, `skill-123`, `condition-based-waiting` | ❌ `My-Skill`, `skill_name`, `SKILL`
## How It Works
### For Users
1. **Add a Plugin**:
- Go to Settings > AI
- Scroll to the Plugins section
- Click "Add Plugin"
- Enter the Git URL (e.g., `https://github.com/user/shakespeare-skills.git`)
- Click "Add Plugin"
2. **View Skills**:
- Installed plugins show the number of skills they contain
- Expand a plugin to see all its skills with descriptions
3. **Sync a Plugin**:
- Click the "Sync" button next to a plugin to pull latest changes
- Useful when the plugin repository is updated with new skills
4. **Delete a Plugin**:
- Click the "Delete" button next to a plugin to remove it
- All skills from that plugin will no longer be available
### For the AI
The AI assistant automatically:
1. **Discovers Skills**: All skills from installed plugins are scanned on startup
2. **Includes in System Prompt**: Skills are listed in the system prompt with their names, descriptions, and paths
3. **Enforces Usage**: The system prompt instructs the AI to use skills whenever applicable
4. **Accesses via Tool**: The AI calls the `skill` tool with a skill name to load its content
Example AI workflow:
```
User: "Help me build a Nostr marketplace"
AI: [Sees "nostrmarket" skill in system prompt]
[Calls skill tool with name="nostrmarket"]
[Receives SKILL.md content with marketplace implementation guide]
[Follows the skill's instructions to build the marketplace]
```
## Technical Implementation
### Key Files
- **`src/lib/plugins.ts`**: Core plugin and skill management functions
- **`src/lib/tools/SkillTool.ts`**: AI tool for loading skill content
- **`src/hooks/usePlugins.ts`**: React hook for plugin CRUD operations
- **`src/components/PluginsSection.tsx`**: UI component for managing plugins
- **`src/lib/system.ts`**: Updated to include skills in system prompt
### API
#### `getPlugins(fs, pluginsPath)`
Returns array of plugin names (directory basenames).
#### `getAllSkills(fs, pluginsPath)`
Returns array of all skills from all plugins.
#### `findSkill(fs, pluginsPath, skillName)`
Finds a skill by name across all plugins.
#### `readSkillContent(fs, skill)`
Reads the SKILL.md content for a skill.
#### `deletePlugin(fs, pluginsPath, pluginName)`
Recursively deletes a plugin directory.
### Skill Tool
The `SkillTool` is exposed to the AI as the `skill` function:
```typescript
{
name: "skill",
description: "Load and execute a skill from the configured plugins",
parameters: {
name: "The name of the skill to execute"
}
}
```
When called, it:
1. Searches all plugins for a skill with the matching name
2. Returns the full SKILL.md content
3. Includes metadata (plugin name, description, path)
### Storage
Plugins are stored in the configured plugins directory:
- **Browser**: `/plugins` (IndexedDB via LightningFS)
- **Electron (Windows)**: `~/AppData/Local/shakespeare/plugins`
- **Electron (macOS)**: `~/Library/Application Support/shakespeare/plugins`
- **Electron (Linux)**: `~/.config/shakespeare/plugins`
## System Prompt Integration
The system prompt now includes a **Skills** section that:
1. Lists all available skills with their names, descriptions, plugins, and paths
2. Instructs the AI to use skills whenever applicable
3. Provides the Settings > AI URL for users to configure skills
4. Includes this section even when no skills are configured (to inform users about the feature)
Example system prompt section:
```
## Skills
You have access to the following skills. **Skills MUST be used whenever applicable** by calling the `skill` tool with the skill name.
Available skills:
- **nostrmarket**: Build a Nostr marketplace application
- Plugin: nostr-skills
- Path: /plugins/nostr-skills/skills/nostrmarket
**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.
Users can configure skills in Settings > AI (https://shakespeare.diy/settings/ai) by adding plugins that contain skills.
```
## Creating Your Own Plugin
1. **Create a Git repository** with the plugin structure
2. **Add skills** in the `skills/` directory
3. **Write SKILL.md files** with frontmatter and content
4. **Push to GitHub/GitLab** or any Git hosting service
5. **Share the Git URL** with others to install your plugin
### Example Plugin Repository
```
my-shakespeare-skills/
├── README.md
└── skills/
├── webdesign/
│ └── SKILL.md
└── database/
└── SKILL.md
```
**skills/webdesign/SKILL.md**:
```markdown
---
name: webdesign
description: Create beautiful, modern web designs with best practices
---
# Web Design Skill
When designing web interfaces, follow these principles:
1. **Use a consistent color palette** (3-5 colors + neutrals)
2. **Implement proper spacing** (8px grid system)
3. **Choose readable fonts** (18px+ for body text)
4. **Ensure accessibility** (WCAG 2.1 AA compliance)
[... detailed instructions ...]
```
## Configuration
### Plugins Directory Path
Configure in **Settings > System > Filesystem Paths**:
- Default browser: `/plugins`
- Default Electron: OS-specific (see Storage section)
- Custom: Any absolute path
Changes take effect immediately.
## Limitations
- Plugins must be Git repositories (no ZIP uploads)
- Skills must be in `skills/` subdirectory
- Skill names must be alphanumeric lowercase only
- Each skill must have a `SKILL.md` file with required frontmatter
- No automatic skill updates (users must manually sync)
## Future Enhancements
Potential future features:
- Plugin marketplace/registry
- Automatic skill updates
- Skill versioning
- Skill dependencies
- Plugin configuration files
- Skill categories/tags
- Skill search functionality
- Plugin publishing workflow
-5
View File
@@ -1,5 +0,0 @@
package.json
package-lock.json
README.md
node_modules/
dist/
-582
View File
@@ -1,582 +0,0 @@
# Shakespeare Electron - Complete Guide
This guide provides comprehensive documentation for developing, building, and troubleshooting the Shakespeare Electron desktop application.
## Table of Contents
1. [Filesystem Architecture](#filesystem-architecture)
2. [Terminal Integration](#terminal-integration)
3. [Development Workflow](#development-workflow)
4. [Building for Distribution](#building-for-distribution)
5. [Troubleshooting](#troubleshooting)
---
## Filesystem Architecture
### Overview
The Electron version uses your local OS filesystem at `~/shakespeare` instead of IndexedDB, providing direct file access and unlimited storage.
### Path Resolution
All paths are relative to `~/shakespeare`:
- `/projects/my-app/` → `~/shakespeare/projects/my-app/`
- `/tmp/upload.txt` → `~/shakespeare/tmp/upload.txt`
- `/config/ai.json` → `~/shakespeare/config/ai.json`
### Implementation
**Automatic Adapter Selection** (`src/App.tsx`):
```typescript
const fs = window.electron?.isElectron
? new NodeFSAdapter() // Real filesystem
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
```
**IPC Communication Flow:**
1. **Renderer** (`NodeFSAdapter.ts`) - Calls `window.electron.fs.*` methods
2. **Preload** (`preload.js`) - Exposes API via `contextBridge`
3. **Main** (`main.js`) - Handles IPC with `ipcMain.handle()`, performs filesystem operations
### Supported Operations
All standard filesystem operations are supported:
- **Files**: `readFile`, `writeFile`, `unlink`, `rename`
- **Directories**: `readdir`, `mkdir`, `rmdir`
- **Metadata**: `stat`, `lstat`
- **Symlinks**: `readlink`, `symlink`
### Benefits
✅ **No storage limits** - Only limited by disk space
✅ **Direct access** - Use any editor, file manager, or Git client
✅ **Easy backup** - Standard backup tools work
✅ **Better performance** - Faster for large projects
✅ **Data portability** - Copy projects between machines
### Data Migration
**Browser to Electron:**
1. Export project as ZIP from browser
2. Import ZIP in Electron version
**Electron to Browser:**
1. Export project as ZIP from Electron
2. Import ZIP in browser version
---
## Terminal Integration
### Overview
The Electron version uses the **real OS terminal** instead of the virtual terminal, providing access to all system commands.
### Architecture
**ShellTool Detection** (`src/lib/tools/ShellTool.ts`):
```typescript
if (window.electron?.shell) {
// Use real OS shell
const result = await window.electron.shell.exec(command, workingDir);
} else {
// Use virtual command system
const result = await executeCommand(command, workingDir, fs);
}
```
**Shell Execution** (`electron/main.js`):
- Uses `child_process.spawn()` to execute commands
- Windows: Uses `cmd.exe`
- macOS/Linux: Uses `/bin/sh`
- Executes in project directory: `~/shakespeare/projects/{projectId}`
### Features
**All OS Commands Available:**
```bash
# Package managers
$ npm install
$ yarn add lodash
$ pnpm update
# Build tools
$ vite build
$ webpack --config webpack.config.js
$ tsc --noEmit
# Git operations
$ git commit -m "Update"
$ git push origin main
# System utilities
$ grep -r "TODO" src/
$ curl https://api.example.com
$ python script.py
```
**Native Shell Features:**
- Pipes: `ls | grep ".ts$"`
- Redirection: `echo "test" > file.txt`
- Environment variables: `$PATH`, `$HOME`
- Command chaining: `npm install && npm run build`
### ANSI Code Stripping
Output from shell commands is cleaned for AI consumption:
- Color codes removed (e.g., `\u001b[31m`)
- Cursor control sequences stripped
- Text formatting removed (bold, italic)
- Newlines preserved
**Example:**
```
Input: \u001b[1m\u001b[32madded 142 packages\u001b[39m\u001b[22m in 3s
Output: added 142 packages in 3s
```
Terminal UI still shows colored output for users.
### Platform Support
| Platform | Shell | Notes |
|----------|-------|-------|
| macOS | `/bin/sh` | All Unix commands available |
| Linux | `/bin/sh` | Standard Linux utilities |
| Windows | `cmd.exe` | Windows commands, consider Git Bash for Unix tools |
### Security
- Commands run with user permissions (no sudo/elevation)
- Working directory sandboxed to `~/shakespeare`
- Environment variables inherited from Electron process
---
## Development Workflow
### Running in Development Mode
```bash
npm run electron:dev
```
This will:
1. Start Vite dev server on http://localhost:5173
2. Wait for server to be ready
3. Launch Electron with hot reload
4. Open DevTools automatically
### Testing Shell Execution
Use the provided test script to verify shell functionality:
```bash
# Start Electron in dev mode
npm run electron:dev
# Open DevTools (View > Toggle Developer Tools)
# Paste contents of electron/test-terminal.js into console
```
The test script verifies:
- Basic command execution
- File listing
- Node.js version check
- Error handling
- Working directory
### Debugging
**Renderer Process:**
- DevTools open automatically in dev mode
- Or press `Cmd+Option+I` (macOS) / `Ctrl+Shift+I` (Windows/Linux)
**Main Process:**
```bash
# Enable verbose logging
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
```
**Check Configuration:**
```bash
node electron/test-config.js
```
### File Watching
In development mode:
- Vite provides hot module replacement
- Changes to React components reload instantly
- Electron process restarts on main.js changes (via `nodemon` in the script)
---
## Building for Distribution
### Prerequisites
- Node.js 18+ installed
- All dependencies installed: `npm install`
- Web build completed: `npm run build`
### Build Commands
**Current Platform:**
```bash
npm run electron:build
```
**Specific Platforms:**
```bash
npm run electron:build:mac # macOS (DMG + ZIP)
npm run electron:build:win # Windows (NSIS + Portable)
npm run electron:build:linux # Linux (AppImage, DEB, RPM)
npm run electron:build:all # All platforms
```
### Build Output
```
electron-dist/
├── mac/
│ ├── Shakespeare.app # macOS application bundle
│ ├── Shakespeare.dmg # DMG installer
│ └── Shakespeare-mac.zip # ZIP archive
├── win-unpacked/
│ └── Shakespeare.exe # Windows executable
├── Shakespeare Setup.exe # NSIS installer
├── Shakespeare Portable.exe # Portable executable
├── shakespeare-*.AppImage # Linux AppImage
├── shakespeare_*.deb # Debian package
└── shakespeare-*.rpm # RPM package
```
### Platform-Specific Notes
**macOS:**
- Builds for Intel (x64) and Apple Silicon (arm64)
- Code signing optional for development
- For distribution: Requires Apple Developer account
**Windows:**
- Builds for x64 and ARM64
- No code signing required for development
- For distribution: EV certificate recommended for SmartScreen
**Linux:**
- Builds for x64 and ARM64
- AppImage requires FUSE: `sudo apt-get install fuse`
- DEB/RPM packages can be installed with package managers
### Cross-Platform Limitations
- **macOS builds require macOS** (for code signing)
- Windows/Linux can be built from any platform
- Use GitHub Actions or CI/CD for multi-platform builds
### Code Signing
**Development (Disable Signing):**
Edit `electron/builder.config.js`:
```javascript
mac: {
identity: null, // Disable code signing
}
```
**Production (macOS):**
1. Obtain Apple Developer account
2. Create certificates in Xcode
3. Configure signing in builder.config.js
4. See: https://www.electron.build/code-signing
**Production (Windows):**
1. Obtain EV code signing certificate
2. Configure in builder.config.js
3. Builds reputation with SmartScreen over time
---
## Troubleshooting
### Development Issues
#### Port 5173 Already in Use
**Solution:**
```bash
# Find and kill the process
lsof -i :5173 # macOS/Linux
netstat -ano | findstr :5173 # Windows
# Or change the port in vite.config.ts
export default defineConfig({
server: { port: 5174 },
});
```
#### Blank Screen on Launch
**Browser Mode:**
1. Check Vite server is running: http://localhost:5173
2. Check Electron console for errors
3. Verify URL in `electron/main.js` matches Vite server
4. Clear cache: Delete `node_modules/.vite`
**Production Build:**
1. Ensure `base: './'` is set in `vite.config.ts`
2. Check `dist/` directory contains all files
3. Look for "Failed to load resource" errors in console
4. Verify file:// protocol is used in loadURL
#### Assets Fail to Load: "net::ERR_FILE_NOT_FOUND"
**Problem:** CSS/JS fail to load with `file:///assets/npm/...` errors
**Solution:** Add to `vite.config.ts`:
```typescript
export default defineConfig(() => ({
base: './', // Required for Electron
// ... rest of config
}))
```
Then rebuild: `npm run build`
#### 404 Error: Page Not Found
**Problem:** App shows "404: Oops! Page not found" on launch
**Solution:** Verify `HashRouter` is used in Electron.
Check `src/AppRouter.tsx`:
```typescript
const Router = window.electron?.isElectron ? HashRouter : BrowserRouter;
```
Rebuild: `npm run build && npm run electron:build`
#### Service Worker Errors
**Solution:** Service workers don't work with `file://` protocol.
Check `src/main.tsx`:
```typescript
if ('serviceWorker' in navigator && !window.electron?.isElectron) {
// Only register in web environment
}
```
#### CSP Font Errors
**Solution:** Update CSP in `index.html`:
```html
<meta http-equiv="content-security-policy"
content="... font-src 'self' data:; ...">
```
#### Broken SVG Images
**Problem:** Logo/SVG files show as broken
**Solution:** Import SVG files properly:
```typescript
// ❌ Wrong
<img src="/shakespeare.svg" alt="Logo" />
// ✅ Correct
import logo from '/shakespeare.svg?url';
<img src={logo} alt="Logo" />
```
#### Preload Script ESM Errors
**Solution:** Requires `sandbox: false` in webPreferences.
Check `electron/main.js`:
```javascript
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true, // Still enabled
sandbox: false, // Disabled for ESM
webSecurity: true,
}
```
### Build Issues
#### Build Fails with "Cannot find module"
**Solutions:**
1. Install dependencies: `npm install`
2. Clear and reinstall: `rm -rf node_modules package-lock.json && npm install`
3. Build web first: `npm run build`
4. Verify `dist/` exists
5. Check config: `node electron/test-config.js`
#### Icons Not Appearing
**Solution:** Should work automatically with `public/shakespeare-512x512.png`.
If not:
1. Verify PNG exists
2. Check build output for icon errors
3. Try: `npm run electron:icons` (requires ImageMagick)
4. Check paths in `electron/builder.config.js`
#### Code Signing Errors (macOS)
**Development:** Disable signing:
```javascript
mac: {
identity: null,
}
```
**Production:** Requires Apple Developer account and certificates.
#### App Won't Launch After Build
**Solutions:**
1. Check console/terminal for errors
2. Try unpacked version first
3. macOS: Check Security & Privacy settings
4. Windows: Check Windows Defender logs
5. Verify `dist/` contains valid files
### Runtime Issues
#### App Crashes on Startup
**Solutions:**
1. Check crash logs:
- macOS: `~/Library/Logs/Shakespeare/`
- Windows: `%APPDATA%\Shakespeare\logs\`
- Linux: `~/.config/Shakespeare/logs/`
2. Run from terminal to see errors
3. Test web build in browser first
#### Shell Execution Error: "spawn /bin/sh ENOENT"
**Problem:** Terminal commands fail with spawn error
**Root Cause:** Working directory doesn't exist
**Solution:** Should be fixed - main.js creates directories automatically.
**Debug:**
1. Open DevTools
2. Check console for "Shell exec in directory: ..."
3. Verify directory exists: `ls -la ~/shakespeare/projects/`
4. Manually create if needed: `mkdir -p ~/shakespeare/projects`
#### External Links Not Opening
**Solution:** Should open in default browser automatically.
Check `electron/main.js` has:
```javascript
mainWindow.webContents.setWindowOpenHandler(({ url }) => {
shell.openExternal(url);
return { action: 'deny' };
});
```
### Platform-Specific Issues
#### macOS: "App is damaged and can't be opened"
**Solutions:**
1. Development: `xattr -cr /path/to/Shakespeare.app`
2. Distribution: Requires code signing
3. Users: Right-click → Open (instead of double-click)
#### Windows: "Windows protected your PC"
**Solutions:**
1. Testing: Click "More info" → "Run anyway"
2. Distribution: Requires EV code signing
3. Build reputation over time
#### Linux: "Permission denied"
**Solutions:**
1. Make executable: `chmod +x Shakespeare*.AppImage`
2. Install FUSE: `sudo apt-get install fuse`
3. Try DEB/RPM package instead
### Performance Issues
#### App Feels Slow
**Solutions:**
1. Close DevTools
2. Check system resources
3. Use production build
4. Disable hardware acceleration in `main.js`:
```javascript
app.disableHardwareAcceleration();
```
#### High Memory Usage
**Solutions:**
1. Normal for Chromium-based apps
2. Close unused projects
3. Restart app periodically
4. Check for memory leaks in web code
---
## Getting Help
If issues persist:
1. **Check existing issues:** https://gitlab.com/soapbox-pub/shakespeare/-/issues
2. **Create new issue** with:
- OS and version
- Electron version: `npm list electron`
- Steps to reproduce
- Error messages/logs
- Screenshots
3. **Community support:** Check project README for links
## Useful Commands
**Complete rebuild:**
```bash
rm -rf node_modules dist electron-dist package-lock.json
npm install
npm run build
npm run electron:build
```
**Check versions:**
```bash
npm list electron
node --version
npm --version
```
**Verbose logging:**
```bash
ELECTRON_ENABLE_LOGGING=1 npm run electron:dev
```
**Check build contents:**
```bash
npm run electron:build -- --dir
ls -la electron-dist/[platform]-unpacked/
```
## Additional Resources
- [Electron Documentation](https://www.electronjs.org/docs)
- [electron-builder Documentation](https://www.electron.build/)
- [Electron Security](https://www.electronjs.org/docs/latest/tutorial/security)
- [Debugging Electron](https://www.electronjs.org/docs/latest/tutorial/debugging-main-process)
- [Shakespeare Main Docs](../README.md)
-22
View File
@@ -1,22 +0,0 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
import electron from 'electron';
const __dirname = dirname(fileURLToPath(import.meta.url));
const appPath = join(__dirname, '..');
const child = spawn(electron, [appPath], {
stdio: 'inherit',
windowsHide: false,
});
child.on('close', code => process.exit(code ?? 0));
child.on('error', err => {
console.error('Failed to launch Electron:', err);
process.exit(1);
});
process.on('SIGINT', () => child.kill('SIGINT'));
process.on('SIGTERM', () => child.kill('SIGTERM'));
-99
View File
@@ -1,99 +0,0 @@
/**
* TypeScript definitions for the Electron API exposed to the renderer process.
*
* Add this to your tsconfig.json include array to use these types:
* "include": ["src", "electron/electron.d.ts"]
*/
interface DirectoryEntry {
name: string;
isDirectory: boolean;
isFile: boolean;
}
interface StatResult {
isDirectory: boolean;
isFile: boolean;
isBlockDevice: boolean;
isCharacterDevice: boolean;
isSymbolicLink: boolean;
isFIFO: boolean;
isSocket: boolean;
size: number;
mtimeMs: number;
ctimeMs: number;
atimeMs: number;
// Timestamps (serialized as numbers for IPC)
mtime: number;
ctime: number;
atime: number;
}
interface ElectronFSAPI {
readFile(path: string, encoding?: string): Promise<string | number[]>;
writeFile(path: string, data: string | number[], encoding?: string): Promise<void>;
readdir(path: string, withFileTypes?: boolean): Promise<string[] | DirectoryEntry[]>;
mkdir(path: string, recursive?: boolean): Promise<void>;
stat(path: string): Promise<StatResult>;
lstat(path: string): Promise<StatResult>;
unlink(path: string): Promise<void>;
rmdir(path: string): Promise<void>;
rename(oldPath: string, newPath: string): Promise<void>;
readlink(path: string): Promise<string>;
symlink(target: string, path: string): Promise<void>;
}
interface ShellExecResult {
stdout: string;
stderr: string;
exitCode: number;
}
interface ElectronShellAPI {
/**
* Execute a shell command on the host OS.
* @param command - The command to execute
* @param cwd - Working directory (relative to ~/shakespeare)
* @returns Promise with stdout, stderr, and exit code
*/
exec(command: string, cwd?: string): Promise<ShellExecResult>;
}
interface ElectronAPI {
/**
* Get the user's home directory path.
*/
homedir: string;
/**
* Get the current platform.
* @returns 'darwin' | 'win32' | 'linux'
*/
platform(): Promise<string>;
/**
* Get the application version from package.json.
* @returns Version string (e.g., "1.0.0")
*/
version(): Promise<string>;
/**
* Filesystem API for accessing the local OS filesystem.
* All paths are relative to ~/shakespeare directory.
*/
fs: ElectronFSAPI;
/**
* Shell API for executing real shell commands on the host OS.
* All paths in commands are relative to ~/shakespeare directory.
*/
shell: ElectronShellAPI;
}
interface Window {
/**
* Electron API exposed via preload script.
* Only available when running in Electron.
*/
electron?: ElectronAPI;
}
-532
View File
@@ -1,532 +0,0 @@
import { app, BrowserWindow, ipcMain, shell, Menu, protocol } from 'electron';
import { spawn } from 'child_process';
import path from 'path';
import { fileURLToPath } from 'url';
import fs from 'fs/promises';
import os from 'os';
// ESM equivalent of __dirname
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
let mainWindow;
function createWindow() {
// Remove the default menu (File, Edit, View, etc.)
Menu.setApplicationMenu(null);
// Create the browser window.
mainWindow = new BrowserWindow({
width: 1400,
height: 900,
minWidth: 800,
minHeight: 600,
webPreferences: {
preload: path.join(__dirname, 'preload.js'),
nodeIntegration: false,
contextIsolation: true,
sandbox: false, // Disabled to support ESM in preload
webSecurity: true,
},
icon: path.join(__dirname, 'dist/shakespeare-512x512.png'),
title: 'Shakespeare',
backgroundColor: '#ffffff',
});
// Enable DevTools keyboard shortcut (Ctrl+Shift+I / Cmd+Option+I)
mainWindow.webContents.on('before-input-event', (event, input) => {
// Check for Ctrl+Shift+I (Windows/Linux) or Cmd+Option+I (Mac)
if (input.control && input.shift && input.key.toLowerCase() === 'i') {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
// Also support F12
if (input.key === 'F12') {
mainWindow.webContents.toggleDevTools();
event.preventDefault();
}
});
// Load the app
if (process.env.ELECTRON_DEV) {
// Development mode - load from Vite dev server
console.log('Loading from Vite dev server: http://localhost:5173');
mainWindow.loadURL('http://localhost:5173');
mainWindow.webContents.openDevTools();
} else {
// Production mode - load from custom protocol
// This allows absolute paths like /shakespeare.svg to work naturally
console.log('Loading from app:// protocol: app://./index.html');
mainWindow.loadURL('app://./index.html');
}
// Log any load errors
mainWindow.webContents.on('did-fail-load', (event, errorCode, errorDescription, validatedURL) => {
console.error('Failed to load:', validatedURL, errorCode, errorDescription);
});
// Log successful load
mainWindow.webContents.on('did-finish-load', () => {
console.log('Successfully loaded app');
});
// Handle window close
mainWindow.on('closed', () => {
mainWindow = null;
});
}
// Register custom protocol scheme before app is ready (required for privileges)
if (!process.env.ELECTRON_DEV) {
protocol.registerSchemesAsPrivileged([
{
scheme: 'app',
privileges: {
standard: true,
secure: true,
supportFetchAPI: true,
corsEnabled: false,
},
},
]);
}
// This method will be called when Electron has finished
// initialization and is ready to create browser windows.
app.whenReady().then(async () => {
// Register the app:// protocol to serve files from dist/
// This allows absolute paths (/) to work naturally without base: './'
if (!process.env.ELECTRON_DEV) {
protocol.registerFileProtocol('app', (request, callback) => {
// Remove 'app://' prefix and normalize path
let filePath = request.url.replace('app://', '');
// Remove trailing slashes
filePath = filePath.replace(/\/+$/, '');
// Handle root path
if (filePath === '' || filePath === '/') {
filePath = 'index.html';
}
// Remove leading slash if present
if (filePath.startsWith('/')) {
filePath = filePath.substring(1);
}
// Resolve to dist directory
const fullPath = path.join(__dirname, 'dist', filePath);
console.log('Protocol handler:', request.url, '->', fullPath);
callback({ path: fullPath });
});
}
createWindow();
app.on('activate', () => {
// On macOS it's common to re-create a window in the app when the
// dock icon is clicked and there are no other windows open.
if (BrowserWindow.getAllWindows().length === 0) {
createWindow();
}
});
});
// Quit when all windows are closed, except on macOS.
app.on('window-all-closed', () => {
if (process.platform !== 'darwin') {
app.quit();
}
});
// Handle app-level events
app.on('web-contents-created', (event, contents) => {
// Security: Prevent navigation to external sites
contents.on('will-navigate', (event, navigationUrl) => {
const parsedUrl = new URL(navigationUrl);
// Allow navigation within the app
if (parsedUrl.origin === 'http://localhost:5173' ||
parsedUrl.protocol === 'file:') {
return;
}
// Block all other navigation
event.preventDefault();
});
// Security: Prevent opening new windows
contents.setWindowOpenHandler(({ url }) => {
// Open external links in the default browser
shell.openExternal(url);
return { action: 'deny' };
});
});
// IPC handlers can be added here if needed for future Electron-specific features
// For example: file system access, native dialogs, etc.
// Example: Handle getting app version
ipcMain.handle('get-app-version', () => {
return app.getVersion();
});
// Example: Handle getting platform
ipcMain.handle('get-platform', () => {
return process.platform;
});
// Helper function to expand tilde (~) in paths
function expandTilde(filepath) {
if (filepath.startsWith('~/') || filepath === '~') {
return path.join(os.homedir(), filepath.slice(1));
}
return filepath;
}
// Filesystem IPC handlers
ipcMain.handle('fs:readFile', async (event, filePath, encoding) => {
if (!filePath) {
const err = new Error('Failed to read file: path is required');
err.code = 'EINVAL';
// Don't log - empty paths are expected from isomorphic-git's ref resolution
throw err;
}
try {
const fullPath = expandTilde(filePath);
const data = await fs.readFile(fullPath, encoding ? { encoding } : undefined);
// If no encoding, convert Buffer to array for IPC serialization
return encoding ? data : Array.from(data);
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
// Serialize the error code as a regular property so it survives IPC
const err = new Error(`Failed to read file ${filePath}: ${error.message}`);
// Copy enumerable properties including code
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
// Don't log ENOENT errors - these are expected for git packed objects and missing refs
// Only log unexpected errors
if (error.code !== 'ENOENT' && error.code !== 'EINVAL') {
console.error(err);
}
throw err;
}
});
ipcMain.handle('fs:writeFile', async (event, filePath, data, encoding) => {
if (!filePath) {
const err = new Error('Failed to write file: path is required');
err.code = 'EINVAL';
throw err;
}
try {
const fullPath = expandTilde(filePath);
// Ensure parent directory exists
await fs.mkdir(path.dirname(fullPath), { recursive: true });
// Convert array back to Buffer if needed
const dataToWrite = Array.isArray(data) ? Buffer.from(data) : data;
await fs.writeFile(fullPath, dataToWrite, encoding ? { encoding } : undefined);
} catch (error) {
const err = new Error(`Failed to write file ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:readdir', async (event, dirPath, withFileTypes) => {
try {
const fullPath = expandTilde(dirPath);
const entries = await fs.readdir(fullPath, { withFileTypes: !!withFileTypes });
if (withFileTypes) {
// Convert Dirent objects to plain objects for IPC
return entries.map(entry => ({
name: entry.name,
isDirectory: entry.isDirectory(),
isFile: entry.isFile(),
}));
}
return entries;
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to read directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
// Only log non-ENOTDIR errors (ENOTDIR is expected when checking if a file is a directory)
if (error.code !== 'ENOTDIR') {
console.error(err);
}
throw err;
}
});
ipcMain.handle('fs:mkdir', async (event, dirPath, recursive) => {
try {
const fullPath = expandTilde(dirPath);
await fs.mkdir(fullPath, { recursive: !!recursive });
} catch (error) {
const err = new Error(`Failed to create directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:stat', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
const stats = await fs.stat(fullPath);
const now = Date.now();
return {
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
isBlockDevice: stats.isBlockDevice(),
isCharacterDevice: stats.isCharacterDevice(),
isSymbolicLink: stats.isSymbolicLink(),
isFIFO: stats.isFIFO(),
isSocket: stats.isSocket(),
size: stats.size,
mtimeMs: stats.mtimeMs ?? now,
ctimeMs: stats.ctimeMs ?? now,
atimeMs: stats.atimeMs ?? now,
// Date objects need to be serialized as timestamps for IPC
// Use optional chaining and fallback to now to prevent valueOf errors
mtime: stats.mtime?.getTime() ?? now,
ctime: stats.ctime?.getTime() ?? now,
atime: stats.atime?.getTime() ?? now,
};
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to stat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:lstat', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
const stats = await fs.lstat(fullPath);
const now = Date.now();
return {
isDirectory: stats.isDirectory(),
isFile: stats.isFile(),
isBlockDevice: stats.isBlockDevice(),
isCharacterDevice: stats.isCharacterDevice(),
isSymbolicLink: stats.isSymbolicLink(),
isFIFO: stats.isFIFO(),
isSocket: stats.isSocket(),
size: stats.size,
mtimeMs: stats.mtimeMs ?? now,
ctimeMs: stats.ctimeMs ?? now,
atimeMs: stats.atimeMs ?? now,
// Date objects need to be serialized as timestamps for IPC
// Use optional chaining and fallback to now to prevent valueOf errors
mtime: stats.mtime?.getTime() ?? now,
ctime: stats.ctime?.getTime() ?? now,
atime: stats.atime?.getTime() ?? now,
};
} catch (error) {
const err = new Error(`Failed to lstat ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:unlink', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
await fs.unlink(fullPath);
} catch (error) {
const err = new Error(`Failed to unlink ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:rmdir', async (event, dirPath) => {
try {
const fullPath = expandTilde(dirPath);
await fs.rmdir(fullPath);
} catch (error) {
// Re-throw with original error code preserved for ENOENT handling
const err = new Error(`Failed to remove directory ${dirPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:rename', async (event, oldPath, newPath) => {
try {
const fullOldPath = expandTilde(oldPath);
const fullNewPath = expandTilde(newPath);
// Ensure parent directory of new path exists
await fs.mkdir(path.dirname(fullNewPath), { recursive: true });
await fs.rename(fullOldPath, fullNewPath);
} catch (error) {
const err = new Error(`Failed to rename ${oldPath} to ${newPath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:readlink', async (event, filePath) => {
try {
const fullPath = expandTilde(filePath);
return await fs.readlink(fullPath);
} catch (error) {
const err = new Error(`Failed to read link ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
ipcMain.handle('fs:symlink', async (event, target, filePath) => {
try {
const fullPath = expandTilde(filePath);
// Ensure parent directory exists
await fs.mkdir(path.dirname(fullPath), { recursive: true });
await fs.symlink(target, fullPath);
} catch (error) {
const err = new Error(`Failed to create symlink ${filePath}: ${error.message}`);
if (error.code) {
Object.defineProperty(err, 'code', {
value: error.code,
enumerable: true,
writable: true,
configurable: true,
});
}
throw err;
}
});
// Shell execution handler
ipcMain.handle('shell:exec', async (event, command, cwd) => {
return new Promise(async (resolve, reject) => {
try {
// Determine the shell and command execution method based on platform
const isWindows = process.platform === 'win32';
const shellCmd = isWindows ? 'cmd.exe' : '/bin/sh';
const shellArgs = isWindows ? ['/c', command] : ['-c', command];
// Expand tilde in working directory if provided, otherwise use home directory
const workingDir = cwd ? expandTilde(cwd) : os.homedir();
// Ensure the working directory exists before spawning
try {
await fs.mkdir(workingDir, { recursive: true });
console.log(`Shell exec in directory: ${workingDir}`);
console.log(`Command: ${command}`);
} catch (mkdirError) {
console.warn(`Failed to create directory ${workingDir}:`, mkdirError.message);
// Continue anyway - directory might already exist
}
const child = spawn(shellCmd, shellArgs, {
cwd: workingDir,
env: { ...process.env },
shell: false, // We're already using the shell
});
let stdout = '';
let stderr = '';
child.stdout?.on('data', (data) => {
stdout += data.toString();
});
child.stderr?.on('data', (data) => {
stderr += data.toString();
});
child.on('error', (error) => {
console.error('Shell execution error:', error);
console.error('Working directory:', workingDir);
console.error('Shell command:', shellCmd);
console.error('Shell args:', shellArgs);
reject(new Error(`Failed to execute command: ${error.message} (cwd: ${workingDir})`));
});
child.on('close', (code) => {
resolve({
stdout,
stderr,
exitCode: code ?? 0,
});
});
} catch (error) {
console.error('Shell setup error:', error);
reject(new Error(`Failed to setup shell execution: ${error.message}`));
}
});
});
-35
View File
@@ -1,35 +0,0 @@
import { contextBridge, ipcRenderer } from 'electron';
import os from 'node:os';
// Expose protected methods that allow the renderer process to use
// ipcRenderer without exposing the entire object
contextBridge.exposeInMainWorld('electron', {
// Get the home directory
homedir: os.homedir(),
// Platform information
platform: () => ipcRenderer.invoke('get-platform'),
// App version
version: () => ipcRenderer.invoke('get-app-version'),
// Filesystem API - paths support tilde (~) expansion for home directory
fs: {
readFile: (path, encoding) => ipcRenderer.invoke('fs:readFile', path, encoding),
writeFile: (path, data, encoding) => ipcRenderer.invoke('fs:writeFile', path, data, encoding),
readdir: (path, withFileTypes) => ipcRenderer.invoke('fs:readdir', path, withFileTypes),
mkdir: (path, recursive) => ipcRenderer.invoke('fs:mkdir', path, recursive),
stat: (path) => ipcRenderer.invoke('fs:stat', path),
lstat: (path) => ipcRenderer.invoke('fs:lstat', path),
unlink: (path) => ipcRenderer.invoke('fs:unlink', path),
rmdir: (path) => ipcRenderer.invoke('fs:rmdir', path),
rename: (oldPath, newPath) => ipcRenderer.invoke('fs:rename', oldPath, newPath),
readlink: (path) => ipcRenderer.invoke('fs:readlink', path),
symlink: (target, path) => ipcRenderer.invoke('fs:symlink', target, path),
},
// Shell API - execute real shell commands
shell: {
exec: (command, cwd) => ipcRenderer.invoke('shell:exec', command, cwd),
},
});
+1 -8
View File
@@ -8,7 +8,7 @@ import htmlParser from "@html-eslint/parser";
import customRules from "./eslint-rules/index.js";
export default tseslint.config(
{ ignores: ["dist", "electron/dist"] },
{ ignores: ["dist"] },
{
extends: [js.configs.recommended, ...tseslint.configs.recommended],
files: ["**/*.{ts,tsx}"],
@@ -40,18 +40,11 @@ export default tseslint.config(
"ignoreRestSiblings": true,
},
],
"indent": [
"warn",
2,
{ SwitchCase: 1 },
],
"no-tabs": "warn",
"custom/no-placeholder-comments": "error",
"no-warning-comments": [
"error",
{ terms: ["fixme"] },
],
"no-control-regex": "off", // Allow ANSI escape sequences in regex
},
},
{
File renamed without changes.
File renamed without changes.
File renamed without changes.
+7 -12
View File
@@ -2,19 +2,14 @@
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover" />
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">
<title>Shakespeare - Open Source AI Builder</title>
<meta name="description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Shakespeare - AI-Powered Nostr Development</title>
<meta name="description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<meta property="og:type" content="website">
<meta property="og:title" content="Shakespeare - Open Source AI Builder">
<meta property="og:description" content="Build custom apps with AI assistance using Shakespeare, an open-source development environment">
<meta property="og:image" content="https://shakespeare.diy/og-image.png">
<meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self' 'unsafe-eval' 'wasm-unsafe-eval'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; worker-src 'self' blob:; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: http: wss: ws:; img-src 'self' data: blob: https:; media-src 'self' https:">
<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">
<meta property="og:title" content="Shakespeare - AI-Powered Nostr Development">
<meta property="og:description" content="Build custom Nostr websites with AI assistance using Shakespeare, an AI-powered development environment">
<!-- <meta http-equiv="content-security-policy" content="default-src 'none'; script-src 'self'; style-src 'self' 'unsafe-inline'; frame-src 'self' https:; font-src 'self'; base-uri 'self'; manifest-src 'self'; connect-src 'self' blob: https: wss:; img-src 'self' data: blob: https:; media-src 'self' https:"> -->
<link rel="icon" type="image/png" href="/favicon.png">
<link rel="manifest" href="/manifest.webmanifest">
</head>
<body>
+108 -5662
View File
File diff suppressed because it is too large. Load diff
+5 -30
View File
@@ -1,25 +1,14 @@
{
"name": "shakespeare.diy",
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"homepage": "https://shakespeare.diy",
"license": "AGPL-3.0-or-later",
"name": "mkstack",
"private": true,
"version": "0.0.0",
"type": "module",
"author": {
"name": "shakespeare.diy",
"email": "[email protected]"
},
"repository": {
"type": "git",
"url": "https://gitlab.com/soapbox-pub/shakespeare.git"
},
"scripts": {
"dev": "npm i --silent && vite",
"build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'",
"typecheck": "npm i --silent && tsc --noEmit",
"test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'",
"electron": "npm run build && rm -rf electron/dist && cp -r dist electron/dist && node scripts/prepare-electron-publish.js && electron electron",
"electron:publish": "npm run build && node scripts/prepare-electron-publish.js && cd electron && npm publish"
"deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup"
},
"dependencies": {
"@dnd-kit/core": "^6.3.1",
@@ -29,10 +18,9 @@
"@getalby/sdk": "^6.0.1",
"@hookform/resolvers": "^3.9.0",
"@isomorphic-git/lightning-fs": "^4.6.2",
"@modelcontextprotocol/sdk": "^1.22.0",
"@mozilla/readability": "^0.6.0",
"@nostrify/nostrify": "^0.47.1",
"@nostrify/react": "^0.2.17",
"@nostrify/nostrify": "npm:@jsr/nostrify__nostrify@^0.46.5",
"@nostrify/react": "npm:@jsr/nostrify__react@^0.2.9",
"@radix-ui/react-accordion": "^1.2.0",
"@radix-ui/react-alert-dialog": "^1.1.1",
"@radix-ui/react-aspect-ratio": "^1.1.0",
@@ -60,7 +48,6 @@
"@radix-ui/react-toggle": "^1.1.0",
"@radix-ui/react-toggle-group": "^1.1.0",
"@radix-ui/react-tooltip": "^1.1.4",
"@sentry/react": "^10.22.0",
"@std/encoding": "npm:@jsr/std__encoding@^1.0.10",
"@tanstack/react-query": "^5.56.2",
"@unhead/addons": "^2.0.10",
@@ -72,25 +59,19 @@
"decimal.js": "^10.6.0",
"embla-carousel-react": "^8.3.0",
"esbuild-wasm": "^0.25.8",
"gray-matter": "^4.0.3",
"i18next": "^25.5.2",
"ignore": "^7.0.5",
"input-otp": "^1.2.4",
"isomorphic-git": "^1.32.1",
"jsonc-parser": "^3.3.1",
"jszip": "^3.10.1",
"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",
"qrcode": "^1.5.4",
"react": "^18.3.1",
"react-day-picker": "^8.10.1",
"react-dom": "^18.3.1",
"react-error-boundary": "^6.0.0",
"react-hook-form": "^7.53.0",
"react-i18next": "^15.7.3",
"react-markdown": "^10.1.0",
@@ -101,13 +82,11 @@
"streamdown": "~1.0.0",
"tailwind-merge": "^2.5.2",
"tailwindcss-animate": "^1.0.7",
"tailwindcss-safe-area": "^0.8.0",
"turndown": "^7.2.1",
"uri-templates": "^0.2.0",
"use-stick-to-bottom": "^1.1.1",
"vaul": "^0.9.3",
"webln": "^0.3.2",
"workbox-window": "^7.3.0",
"zod": "^3.25.76"
},
"devDependencies": {
@@ -120,9 +99,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",
"@types/react": "^18.3.1",
"@types/react-dom": "^18.3.1",
@@ -130,7 +107,6 @@
"@types/uri-templates": "^0.1.34",
"@vitejs/plugin-react-swc": "^3.5.0",
"autoprefixer": "^10.4.20",
"electron": "^39.0.0",
"eslint": "^9.9.0",
"eslint-plugin-react-hooks": "^5.1.0-rc.0",
"eslint-plugin-react-refresh": "^0.4.9",
@@ -141,7 +117,6 @@
"typescript": "^5.5.3",
"typescript-eslint": "^8.0.1",
"vite": "^6.3.5",
"vite-plugin-pwa": "^1.1.0",
"vitest": "^3.1.4"
}
}
+2 -2
View File
@@ -13,7 +13,7 @@ export default {
status: 200,
headers: {
"Access-Control-Allow-Origin": "*",
"Access-Control-Allow-Methods": "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS",
"Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS",
"Access-Control-Allow-Headers": "*", // Or specify specific headers
"Access-Control-Max-Age": "86400", // Cache preflight for 24 hours
}
@@ -32,7 +32,7 @@ export default {
const response = new Response(targetResponse.body, targetResponse);
response.headers.set("Access-Control-Allow-Origin", "*");
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS");
response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS");
response.headers.set("Access-Control-Allow-Headers", "*");
return response;
+234 -261
View File
@@ -1,45 +1,35 @@
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<!-- saved from url=(0053)https://www.gnu.org/licenses/agpl-3.0-standalone.html -->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>GNU Affero General Public License - GNU Project - Free Software Foundation (FSF)</title>
<link rel="alternate" type="application/rdf+xml" href="http://www.gnu.org/licenses/agpl-3.0.rdf">
</head>
<body>
<h3 style="text-align: center;">GNU AFFERO GENERAL PUBLIC LICENSE</h3>
<p style="text-align: center;">Version 3, 19 November 2007</p>
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
<p>Copyright © 2007 Free Software Foundation,
Inc. &lt;<a href="https://fsf.org/">https://fsf.org/</a>&gt;
<br>
Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.</p>
of this license document, but changing it is not allowed.
<h4 id="preamble">Preamble</h4>
Preamble
<p>The GNU Affero General Public License is a free, copyleft license
for software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.</p>
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
<p>The licenses for most software and other practical works are
designed to take away your freedom to share and change the works. By
contrast, our General Public Licenses are intended to guarantee your
freedom to share and change all versions of a program--to make sure it
remains free software for all its users.</p>
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
<p>When we speak of free software, we are referring to freedom, not
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.</p>
free programs, and that you know you can do these things.
<p>Developers that use our General Public Licenses protect your rights
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.</p>
and/or modify the software.
<p>A secondary benefit of defending all users' freedom is that
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
@@ -47,79 +37,78 @@ encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.</p>
source code to the public.
<p>The GNU Affero General Public License is designed specifically to
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.</p>
code of the modified version.
<p>An older license, called the Affero General Public License and
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.</p>
this license.
<p>The precise terms and conditions for copying, distribution and
modification follow.</p>
The precise terms and conditions for copying, distribution and
modification follow.
<h4 id="terms">TERMS AND CONDITIONS</h4>
TERMS AND CONDITIONS
<h4 id="section0">0. Definitions.</h4>
0. Definitions.
<p>"This License" refers to version 3 of the GNU Affero General Public
License.</p>
"This License" refers to version 3 of the GNU Affero General Public License.
<p>"Copyright" also means copyright-like laws that apply to other kinds
of works, such as semiconductor masks.</p>
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
<p>"The Program" refers to any copyrightable work licensed under this
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.</p>
"recipients" may be individuals or organizations.
<p>To "modify" a work means to copy from or adapt all or part of the work
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.</p>
earlier work or a work "based on" the earlier work.
<p>A "covered work" means either the unmodified Program or a work based
on the Program.</p>
A "covered work" means either the unmodified Program or a work based
on the Program.
<p>To "propagate" a work means to do anything with it that, without
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.</p>
public, and in some countries other activities as well.
<p>To "convey" a work means any kind of propagation that enables other
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.</p>
a computer network, with no transfer of a copy, is not conveying.
<p>An interactive user interface displays "Appropriate Legal Notices"
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.</p>
menu, a prominent item in the list meets this criterion.
<h4 id="section1">1. Source Code.</h4>
1. Source Code.
<p>The "source code" for a work means the preferred form of the work
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.</p>
form of a work.
<p>A "Standard Interface" means an interface that either is an official
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.</p>
is widely used among developers working in that language.
<p>The "System Libraries" of an executable work include anything, other
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
@@ -128,9 +117,9 @@ implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.</p>
produce the work, or an object code interpreter used to run it.
<p>The "Corresponding Source" for a work in object code form means all
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
@@ -141,26 +130,26 @@ includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.</p>
subprograms and other parts of the work.
<p>The Corresponding Source need not include anything that users
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.</p>
Source.
<p>The Corresponding Source for a work in source code form is that
same work.</p>
The Corresponding Source for a work in source code form is that
same work.
<h4 id="section2">2. Basic Permissions.</h4>
2. Basic Permissions.
<p>All rights granted under this License are granted for the term of
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.</p>
rights of fair use or other equivalent, as provided by copyright law.
<p>You may make, run and propagate covered works that you do not
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
@@ -169,73 +158,69 @@ the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.</p>
your copyrighted material outside their relationship with you.
<p>Conveying under any other circumstances is permitted solely under
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.</p>
makes it unnecessary.
<h4 id="section3">3. Protecting Users' Legal Rights From Anti-Circumvention Law.</h4>
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
<p>No covered work shall be deemed part of an effective technological
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.</p>
measures.
<p>When you convey a covered work, you waive any legal power to forbid
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.</p>
technological measures.
<h4 id="section4">4. Conveying Verbatim Copies.</h4>
4. Conveying Verbatim Copies.
<p>You may convey verbatim copies of the Program's source code as you
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.</p>
recipients a copy of this License along with the Program.
<p>You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.</p>
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
<h4 id="section5">5. Conveying Modified Source Versions.</h4>
5. Conveying Modified Source Versions.
<p>You may convey a work based on the Program, or the modifications to
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:</p>
terms of section 4, provided that you also meet all of these conditions:
<ul>
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
<li>a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.</li>
<li>b) The work must carry prominent notices stating that it is
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".</li>
"keep intact all notices".
<li>c) You must license the entire work, as a whole, under this
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.</li>
invalidate such permission if you have separately received it.
<li>d) If the work has interactive user interfaces, each must display
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.</li>
work need not make them do so.
</ul>
<p>A compilation of a covered work with other separate and independent
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
@@ -243,23 +228,21 @@ in or on a volume of a storage or distribution medium, is called an
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.</p>
parts of the aggregate.
<h4 id="section6">6. Conveying Non-Source Forms.</h4>
6. Conveying Non-Source Forms.
<p>You may convey a covered work in object code form under the terms
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:</p>
in one of these ways:
<ul>
<li>a) Convey the object code in, or embodied in, a physical product
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.</li>
customarily used for software interchange.
<li>b) Convey the object code in, or embodied in, a physical product
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
@@ -269,15 +252,15 @@ in one of these ways:</p>
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.</li>
Corresponding Source from a network server at no charge.
<li>c) Convey individual copies of the object code with a copy of the
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.</li>
with subsection 6b.
<li>d) Convey the object code by offering access from a designated
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
@@ -288,20 +271,18 @@ in one of these ways:</p>
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.</li>
available for as long as needed to satisfy these requirements.
<li>e) Convey the object code using peer-to-peer transmission, provided
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.</li>
charge under subsection 6d.
</ul>
<p>A separable portion of the object code, whose source code is excluded
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.</p>
included in conveying the object code work.
<p>A "User Product" is either (1) a "consumer product", which means any
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
@@ -312,17 +293,17 @@ of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.</p>
the only significant mode of use of the product.
<p>"Installation Information" for a User Product means any methods,
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.</p>
modification has been made.
<p>If you convey an object code work under this section in, or with, or
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
@@ -331,137 +312,133 @@ Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).</p>
been installed in ROM).
<p>The requirement to provide Installation Information does not include a
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.</p>
protocols for communication across the network.
<p>Corresponding Source conveyed, and Installation Information provided,
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.</p>
unpacking, reading or copying.
<h4 id="section7">7. Additional Terms.</h4>
7. Additional Terms.
<p>"Additional permissions" are terms that supplement the terms of this
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.</p>
this License without regard to the additional permissions.
<p>When you convey a copy of a covered work, you may at your option
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.</p>
for which you have or can give appropriate copyright permission.
<p>Notwithstanding any other provision of this License, for material you
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:</p>
that material) supplement the terms of this License with terms:
<ul>
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
<li>a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or</li>
<li>b) Requiring preservation of specified reasonable legal notices or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or</li>
Notices displayed by works containing it; or
<li>c) Prohibiting misrepresentation of the origin of that material, or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or</li>
reasonable ways as different from the original version; or
<li>d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or</li>
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
<li>e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or</li>
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
<li>f) Requiring indemnification of licensors and authors of that
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.</li>
those licensors and authors.
</ul>
<p>All other non-permissive additional terms are considered "further
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further restriction,
you may remove that term. If a license document contains a further
restriction but permits relicensing or conveying under this License, you
may add to a covered work material governed by the terms of that license
document, provided that the further restriction does not survive such
relicensing or conveying.</p>
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
<p>If you add terms to a covered work in accord with this section, you
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.</p>
where to find the applicable terms.
<p>Additional terms, permissive or non-permissive, may be stated in the
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.</p>
the above requirements apply either way.
<h4 id="section8">8. Termination.</h4>
8. Termination.
<p>You may not propagate or modify a covered work except as expressly
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).</p>
paragraph of section 11).
<p>However, if you cease all violation of this License, then your
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.</p>
prior to 60 days after the cessation.
<p>Moreover, your license from a particular copyright holder is
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.</p>
your receipt of the notice.
<p>Termination of your rights under this section does not terminate the
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.</p>
material under section 10.
<h4 id="section9">9. Acceptance Not Required for Having Copies.</h4>
9. Acceptance Not Required for Having Copies.
<p>You are not required to accept this License in order to receive or
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.</p>
covered work, you indicate your acceptance of this License to do so.
<h4 id="section10">10. Automatic Licensing of Downstream Recipients.</h4>
10. Automatic Licensing of Downstream Recipients.
<p>Each time you convey a covered work, the recipient automatically
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.</p>
for enforcing compliance by third parties with this License.
<p>An "entity transaction" is a transaction transferring control of an
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
@@ -469,23 +446,23 @@ transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.</p>
the predecessor has it or can get it with reasonable efforts.
<p>You may not impose any further restrictions on the exercise of the
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.</p>
sale, or importing the Program or any portion of it.
<h4 id="section11">11. Patents.</h4>
11. Patents.
<p>A "contributor" is a copyright holder who authorizes use under this
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".</p>
work thus licensed is called the contributor's "contributor version".
<p>A contributor's "essential patent claims" are all patent claims
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
@@ -493,21 +470,21 @@ but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.</p>
this License.
<p>Each contributor grants you a non-exclusive, worldwide, royalty-free
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.</p>
propagate the contents of its contributor version.
<p>In the following three paragraphs, a "patent license" is any express
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.</p>
patent against the party.
<p>If you convey a covered work, knowingly relying on a patent license,
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
@@ -519,17 +496,17 @@ license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.</p>
country that you have reason to believe are valid.
<p>If, pursuant to or in connection with a single transaction or
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.</p>
work and works based on it.
<p>A patent license is "discriminatory" if it does not include within
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
@@ -542,15 +519,15 @@ patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.</p>
or that patent license was granted, prior to 28 March 2007.
<p>Nothing in this License shall be construed as excluding or limiting
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.</p>
otherwise be available to you under applicable patent law.
<h4 id="section12">12. No Surrender of Others' Freedom.</h4>
12. No Surrender of Others' Freedom.
<p>If conditions are imposed on you (whether by court order, agreement or
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
@@ -558,11 +535,11 @@ License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.</p>
License would be to refrain entirely from conveying the Program.
<h4 id="section13">13. Remote Network Interaction; Use with the GNU General Public License.</h4>
13. Remote Network Interaction; Use with the GNU General Public License.
<p>Notwithstanding any other provision of this License, if you modify the
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
@@ -571,56 +548,56 @@ from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.</p>
following paragraph.
<p>Notwithstanding any other provision of this License, you have permission
to link or combine any covered work with a work licensed under version 3
of the GNU General Public License into a single combined work, and to
convey the resulting work. The terms of this License will continue to
apply to the part which is the covered work, but the work with which it is
combined will remain governed by version 3 of the GNU General Public
License.</p>
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
<h4 id="section14">14. Revised Versions of this License.</h4>
14. Revised Versions of this License.
<p>The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may differ
in detail to address new problems or concerns.</p>
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
<p>Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero
General Public License "or any later version" applies to it, you have
the option of following the terms and conditions either of that
numbered version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number
of the GNU Affero General Public License, you may choose any version
ever published by the Free Software Foundation.</p>
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
<p>If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that
proxy's public statement of acceptance of a version permanently
authorizes you to choose that version for the Program.</p>
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
<p>Later license versions may give you additional or different
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.</p>
later version.
<h4 id="section15">15. Disclaimer of Warranty.</h4>
15. Disclaimer of Warranty.
<p>THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.</p>
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
<h4 id="section16">16. Limitation of Liability.</h4>
16. Limitation of Liability.
<p>IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
@@ -628,37 +605,37 @@ USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.</p>
SUCH DAMAGES.
<h4 id="section17">17. Interpretation of Sections 15 and 16.</h4>
17. Interpretation of Sections 15 and 16.
<p>If the disclaimer of warranty and limitation of liability provided
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.</p>
copy of the Program in return for a fee.
<p>END OF TERMS AND CONDITIONS</p>
END OF TERMS AND CONDITIONS
<h4 id="howto">How to Apply These Terms to Your New Programs</h4>
How to Apply These Terms to Your New Programs
<p>If you develop a new program, and you want it to be of the greatest
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.</p>
free software which everyone can redistribute and change under these terms.
<p>To do so, attach the following notices to the program. It is safest
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.</p>
the "copyright" line and a pointer to where the full notice is found.
<pre> &lt;one line to give the program's name and a brief idea of what it does.&gt;
Copyright (C) &lt;year&gt; &lt;name of author&gt;
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
@@ -666,23 +643,19 @@ the "copyright" line and a pointer to where the full notice is found.</p>
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see &lt;https://www.gnu.org/licenses/&gt;.
</pre>
along with this program. If not, see <https://www.gnu.org/licenses/>.
<p>Also add information on how to contact you by electronic and paper mail.</p>
Also add information on how to contact you by electronic and paper mail.
<p>If your software can interact with users remotely through a computer
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.</p>
specific requirements.
<p>You should also get your employer (if you work as a programmer) or school,
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
&lt;<a href="https://www.gnu.org/licenses/">https://www.gnu.org/licenses/</a>&gt;.</p>
</body></html>
<https://www.gnu.org/licenses/>.
+1 -2
View File
@@ -1,2 +1 @@
/assets/* /assets/:splat 200
/* /index.html 200
/* /index.html 200
Binary file not shown.

After

Width:  |  Height:  |  Size: 18 KiB

+8 -57
View File
@@ -1,70 +1,21 @@
{
"$schema": "https://json.schemastore.org/web-manifest-combined.json",
"name": "Shakespeare - Open Source AI Builder",
"name": "Shakespeare - AI-Powered Nostr Development",
"short_name": "Shakespeare",
"description": "Build custom apps with AI assistance using Shakespeare, an open-source development environment",
"categories": ["productivity", "devtools"],
"id": "/",
"scope": "/",
"description": "Build custom Nostr websites with AI assistance",
"start_url": "/",
"display": "standalone",
"orientation": "any",
"background_color": "#2b0037",
"theme_color": "#2b0037",
"background_color": "#ffffff",
"theme_color": "#000000",
"icons": [
{
"src": "/shakespeare-192x192.png",
"src": "/favicon.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "any"
"type": "image/png"
},
{
"src": "/shakespeare-512x512.png",
"src": "/favicon.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "any"
},
{
"src": "/shakespeare-maskable-192x192.png",
"sizes": "192x192",
"type": "image/png",
"purpose": "maskable"
},
{
"src": "/shakespeare-maskable-512x512.png",
"sizes": "512x512",
"type": "image/png",
"purpose": "maskable"
}
],
"screenshots": [
{
"label": "Home",
"src": "/screenshot-mobile-home.png",
"sizes": "1179x2556",
"type": "image/png",
"form_factor": "narrow"
},
{
"label": "Project",
"src": "/screenshot-mobile-project.png",
"sizes": "1179x2556",
"type": "image/png",
"form_factor": "narrow"
},
{
"label": "Preview",
"src": "/screenshot-mobile-preview.png",
"sizes": "1179x2556",
"type": "image/png",
"form_factor": "narrow"
},
{
"label": "Desktop",
"src": "/screenshot-desktop.png",
"sizes": "1920x1080",
"type": "image/png",
"form_factor": "wide"
"type": "image/png"
}
]
}
Binary file not shown.

Before

Width:  |  Height:  |  Size: 70 KiB

-2
View File
@@ -1,2 +0,0 @@
User-agent: *
Allow: /
Binary file not shown.

Before

Width:  |  Height:  |  Size: 219 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 266 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 321 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 167 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 7.9 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 8.6 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 4.8 KiB

Binary file not shown.

Before

Width:  |  Height:  |  Size: 14 KiB

-63
View File
@@ -1,63 +0,0 @@
<?xml version="1.0" encoding="utf-8"?>
<!-- Generator: Adobe Illustrator 25.2.3, SVG Export Plug-In . SVG Version: 6.00 Build 0) -->
<svg version="1.1" id="レイヤー_1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px"
y="0px" viewBox="0 0 128 128" style="enable-background:new 0 0 128 128;" xml:space="preserve">
<g>
<g>
<path style="fill:#F45125;" d="M110.28,61.32l2.63,8.84c0,0,7.24-1.6,7.62,3.2c0.38,4.8-6.77,8-6.77,8l2.26,10.63
c0,0,7.9-6.4,8-15.61c0,0,0.66-11.29-6.11-13.92C113.67,60.85,110.28,61.32,110.28,61.32z"/>
<path style="fill:#F45125;" d="M68.71,94.99c0,0-11.1-4.7-16.46,1.98c-0.75,0.94-1.41,1.88-2.16,2.82
c-0.56,0.75-1.13,1.5-1.69,2.16c-0.47,0.56-1.03,1.13-1.69,1.5c-0.66,0.38-1.32,0.66-2.07,0.85c-0.94,0.19-1.88,0.19-2.82,0.09
c-1.32-0.09-2.63-0.38-3.95-0.66c-0.47-0.09-0.85-0.19-1.22-0.28c-0.09,0-0.19-0.09-0.28-0.09s-0.19-0.09-0.28-0.09
c-0.38,0.09,0.19,0.75,0.38,0.94c0.28,0.28,0.56,0.66,0.85,0.94c0.85,0.75,1.69,1.5,2.73,1.98c1.32,0.66,2.73,1.03,4.14,1.13
c0.09,0,0.38,0,0.47,0.09c0.19,0.19-0.28,0.47-0.47,0.56c-0.28,0.19-0.47,0.28-0.75,0.38c-0.85,0.38-1.79,0.56-2.63,0.75
c-0.85,0.19-1.69,0.28-2.45,0.28c-0.47,0-0.85,0.09-1.22,0.09c-0.28,0-0.56-0.09-0.85,0s0.09,0.47,0.28,0.56
c0.38,0.19,0.75,0.47,1.13,0.66c1.13,0.56,2.26,1.03,3.39,1.32c1.5,0.38,3.1,0.56,4.61,0.38c1.32-0.19,2.63-0.56,3.86-1.03
c6.77-3.1,6.21-9.59,12.42-10.16c4.61-0.38,11.1,2.07,11.1,2.07L68.71,94.99z"/>
<path style="fill:#F45125;" d="M19.79,38.28c0,0-12.13,1.98-15.24,12.79C0.61,64.9,20.26,69.5,20.26,69.5l1.22-9.41
c0,0-13.07-1.32-12.32-6.3c0.94-6.21,11.85-5.64,11.85-5.64L19.79,38.28z"/>
<path style="fill:#F45125;" d="M20.73,70.92c0,0-1.88,0.56-4.61,2.54c-1.88,1.32-4.42,3.01-6.87,5.93
c-1.22,1.41-2.16,3.1-2.82,4.89c-0.47,1.22-0.66,2.45-0.66,3.76c0,0.28,0,0.56,0,0.85c0,0.09,0,0.85,0.28,0.66
c0.09-0.09,0.19-0.38,0.28-0.47c0.19-0.47,0.47-0.85,0.75-1.22c0.85-1.13,1.88-2.16,3.01-3.01c0.38-0.28,0.75-0.47,1.13-0.66
c0.28-0.28,0.75-0.66,0.94-0.28c0.09,0.19-0.09,0.47-0.19,0.66c-0.09,0.28-0.19,0.66-0.19,0.94c-0.38,1.5-0.56,3.01-0.75,4.51
c-0.09,0.85-0.09,1.69,0,2.45c0,0.38,0.09,0.85,0.09,1.22c0,0.19,0.09,0.38,0.09,0.56c0,0.19,0.19,0.47,0.38,0.19
c0.09-0.09,0.09-0.19,0.19-0.38c0.19-0.28,0.28-0.66,0.47-0.94c0.47-0.85,0.94-1.69,1.5-2.63c0.66-1.13,1.41-2.16,2.16-3.1
c0.85-1.13,1.88-2.26,2.92-3.2c1.13-1.03,2.35-2.07,3.67-2.92c0.75-0.47,1.6-0.94,2.45-1.32L20.73,70.92z"/>
<g>
<path style="fill:#FCC21B;" d="M116.4,79.29c-1.13-5.55-2.73-11.01-4.51-16.46c-1.5-4.61-3.1-9.31-5.83-13.36
c-1.22-1.79-3.01-3.01-5.27-3.86c-4.33-1.69-9.97-1.98-13.73-1.98c-5.64,0-11.48,1.22-16.74,3.67
c-1.88,5.64-7.05,19.94-14.86,26.34c0.47,2.63,1.03,5.36,1.79,8c1.32,4.61,3.01,9.22,4.61,13.83c1.5,4.42,3.29,8.84,6.58,12.23
c0.85,0.94,1.88,1.69,2.82,2.45c2.26,1.88,4.99,3.01,7.71,3.95c2.54,0.85,5.17,1.5,7.81,2.07c4.7,1.03,11.48,2.82,16.08,0.66
c2.54-1.13,4.61-2.92,6.3-5.08c1.79-2.26,3.2-4.8,4.42-7.43c1.88-3.95,3.86-8.37,4.14-12.89
C117.99,87.38,117.24,83.24,116.4,79.29z"/>
<path style="fill:#429ADF;" d="M77.64,33.57c-0.28-1.03-1.03-2.07-1.6-3.01c-6.3-11.01-20.04-16.27-32.26-15.52
c-3.76,0.28-9.31,0.85-13.54,2.73c-2.07,0.94-3.86,2.35-4.99,4.14c-2.54,4.23-3.76,8.94-5.08,13.64
C18.67,41,17.35,46.55,16.5,52.2c-0.75,4.89-1.41,10.25-0.09,15.14c1.03,3.86,3.29,9.22,5.74,12.32
c2.73,3.39,6.58,7.34,10.72,8.84c0.75,0.28,1.6,0.47,2.45,0.66c1.6,0.28,3.29,0.47,4.89,0.19c0.94-0.19,1.98-0.28,2.92-0.56
c1.88-0.47,3.67-1.13,5.46-1.79c7.52-3.01,13.64-7.43,17.68-14.58c1.69-3.1,3.1-6.4,4.42-9.69c0.09-0.19,0.19-0.38,0.19-0.56
c1.98-5.46,3.29-11.19,4.61-16.84c0.66-2.73,1.41-5.55,1.79-8.37C77.55,35.92,77.92,34.7,77.64,33.57z"/>
</g>
</g>
<path style="fill:#193D51;" d="M23.09,40.53c1.69-3.1,5.74-5.55,9.31-5.08c0.56,0.09,1.22,0.19,1.79,0.47
c3.57,1.5,5.74,4.99,4.89,8.56c-0.19,0.75-0.66,0.85-1.22,0.38c-1.98-1.69-3.57-3.01-6.21-3.67c-2.16-0.56-4.61-0.28-6.68,0.28
c-0.47,0.09-1.22,0.56-1.69,0.38C22.61,41.57,22.9,40.91,23.09,40.53z"/>
<path style="fill:#193D51;" d="M62.21,64.9c-1.03,1.6-2.45,3.01-3.86,4.33c-0.38,0.28-0.66,0.66-1.03,0.94
c-5.64,4.7-13.26,7.05-20.51,5.27c-1.98-0.47-4.14-1.5-5.74-2.73c-1.22-0.94-2.45-2.16-3.48-3.39c-1.88-2.26-3.29-4.89-4.23-7.62
c-0.47-1.41-0.75-2.73-0.94-4.23c0-0.47-0.66-5.46,0.85-4.8c0.38,0.19,0.66,0.47,0.94,0.75c0.28,0.38,0.47,0.75,0.75,1.03
c0.66,0.85,1.32,1.69,2.07,2.45c2.35,2.73,5.27,4.89,8.56,6.4c2.26,1.03,4.7,1.6,7.15,1.79c1.41,0.09,2.73,0.19,4.14,0.09
c5.08-0.28,10.25-1.79,14.86-3.76c0.38-0.19,0.85-0.47,1.32-0.47C64.66,61.04,62.5,64.52,62.21,64.9z"/>
<path style="fill:#193D51;" d="M67.58,51.16c0,0.47-0.19,1.13-0.75,1.03c-0.47-0.09-0.85-0.94-1.13-1.22
c-1.32-1.69-3.86-3.57-6.4-4.14c-3.01-0.75-5.27,0.56-8.28,0.85c-0.85,0.09-1.32-0.28-0.94-1.03c1.6-3.48,5.83-6.21,10.25-5.46
c0.75,0.09,1.41,0.28,2.07,0.56C66.26,43.36,67.86,47.59,67.58,51.16z"/>
<path style="fill:#9B7515;" d="M91.84,63.86c4.23,2.73,9.69,3.48,14.58,3.2c1.41-0.09,2.26,0.09,1.88,1.69
c-0.75,3.29-3.86,5.17-6.87,5.83c-0.75,0.19-1.5,0.19-2.26,0.19c-1.41-0.09-2.82-0.66-4.04-1.5c-2.63-1.79-4.61-4.89-5.17-8
C89.68,63.67,90.25,62.83,91.84,63.86z"/>
<path style="fill:#9B7515;" d="M65.22,80.79C64,79.57,64.66,79,65.98,78.25c4.51-2.35,9.03-5.93,11.38-10.63
c0.85-1.79,1.79-1.41,2.45,0.28c1.13,3.1,1.03,6.87-0.38,9.88c-0.66,1.41-1.6,2.63-2.82,3.57c-0.66,0.47-1.32,0.75-2.07,1.03
C71.43,83.33,67.58,83.24,65.22,80.79z"/>
<path style="fill:#9B7515;" d="M110,96.41c-0.38,0-0.94-0.38-1.41-0.66c-0.47-0.28-0.94-0.66-1.22-0.85
c-1.13-0.56-2.45-1.13-3.67-1.5c-3.76-1.22-7.9-1.22-11.57,0c-2.63,0.85-5.17,2.45-7.24,4.33c-2.26,2.16-3.95,4.8-6.11,7.05
c-0.28,0.28-0.56,0.56-0.85,0.75c-0.56,0.28-1.13-0.09-1.32-0.66c-0.94-3.95,1.69-9.5,3.67-12.89c2.26-3.76,5.55-6.77,9.78-8
c2.07-0.66,4.33-0.66,6.49-0.38c6.3,0.94,12.79,5.93,14.02,11.66C110.56,95.75,110.47,96.5,110,96.41z"/>
</g>
</svg>

Before

Width:  |  Height:  |  Size: 5.8 KiB

-78
View File
@@ -1,78 +0,0 @@
#!/usr/bin/env node
import { readFileSync, writeFileSync, copyFileSync, rmSync, cpSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, join } from 'node:path';
const __filename = fileURLToPath(import.meta.url);
const __dirname = dirname(__filename);
const rootDir = join(__dirname, '..');
const electronDir = join(rootDir, 'electron');
const distDir = join(rootDir, 'dist');
const electronDistDir = join(electronDir, 'dist');
// Read root package.json
const rootPackage = JSON.parse(readFileSync(join(rootDir, 'package.json'), 'utf-8'));
// Generate CalVer version (YYYY.MM.DDHHMM) in UTC
const now = new Date();
const year = now.getUTCFullYear();
const month = String(now.getUTCMonth() + 1).padStart(2, '0');
const day = String(now.getUTCDate()).padStart(2, '0');
const hour = String(now.getUTCHours()).padStart(2, '0');
const minute = String(now.getUTCMinutes()).padStart(2, '0');
const version = `${year}.${month}.${day}${hour}${minute}`;
// Get electron version from root devDependencies
const electronVersion = rootPackage.devDependencies.electron;
// Remove old electron/dist and copy new one
console.log('Removing old electron/dist...');
rmSync(electronDistDir, { recursive: true, force: true });
console.log('Copying dist to electron/dist...');
cpSync(distDir, electronDistDir, { recursive: true });
// Create electron package.json
const electronPackage = {
name: rootPackage.name,
description: rootPackage.description,
homepage: rootPackage.homepage,
license: rootPackage.license,
version: version,
type: "module",
main: "main.js",
bin: {
shakespeare: "./bin/shakespeare.js"
},
files: [
"bin/",
"dist/",
"main.js",
"package.json",
"preload.js",
"LICENSE",
"README.md"
],
author: rootPackage.author,
repository: rootPackage.repository,
dependencies: {
electron: electronVersion
}
};
// Write electron package.json
writeFileSync(
join(electronDir, 'package.json'),
JSON.stringify(electronPackage, null, 2) + '\n',
'utf-8'
);
// Copy README.md to electron directory
copyFileSync(
join(rootDir, 'README.md'),
join(electronDir, 'README.md')
);
console.log(`✓ Generated electron/package.json with version ${version}`);
console.log('✓ Copied README.md to electron/');
-3
View File
@@ -1,3 +0,0 @@
# Shakespeare Services
This directory contains additional microservices that can be optionally deployed alongside Shakespeare to host a complete Shakespeare instance.
-26
View File
@@ -1,26 +0,0 @@
export default {
async fetch(request) {
const url = new URL(request.url);
if (url.pathname === "/") {
return Response.redirect("https://shakespeare.diy", 302);
}
url.hostname = "esm.sh";
// Cache response via Cloudflare
const response = await fetch(url, {
cf: { cacheEverything: true }
});
const headers = new Headers(response.headers);
headers.set("Cache-Control", "public, max-age=86400, immutable");
headers.set("Access-Control-Allow-Origin", "*");
return new Response(response.body, {
status: response.status,
statusText: response.statusText,
headers
});
}
};
-46
View File
@@ -1,46 +0,0 @@
/**
* Favicon Proxy Service
*
* Proxies favicon requests to DuckDuckGo's favicon service.
* This allows fetching favicons for any domain without CORS issues.
*
* Usage: GET /favicon?url=https://example.com
* Returns: The favicon image for the specified domain
*/
export default {
async fetch(request: Request): Promise<Response> {
const requestUrl = new URL(request.url);
const targetUrl = requestUrl.searchParams.get('url');
if (!targetUrl) {
return new Response('Missing url parameter', { status: 400 });
}
let url: URL;
try {
url = new URL(targetUrl);
} catch {
return new Response('Invalid url parameter', { status: 400 });
}
// AI-provider-specific hacks
let hostname = url.hostname;
if (url.host === 'localhost:11434' || url.origin === '127.0.0.1:11434') {
hostname = 'ollama.com';
} else if (url.host === 'generativelanguage.googleapis.com') {
hostname = 'gemini.google.com';
} else if (url.host === 'api.z.ai') {
hostname = 'docs.z.ai';
}
// Strip `ai.` and `api.` subdomains for a better chance at finding a favicon
hostname = hostname.replace(/^(ai\.|api\.)/, '');
return fetchFavicon(hostname);
},
};
function fetchFavicon(hostname: string): Promise<Response> {
return fetch(`https://external-content.duckduckgo.com/ip3/${hostname}.ico`);
}
+2 -5
View File
@@ -1,11 +1,8 @@
import { render } from '@testing-library/react';
import { test, expect } from 'vitest';
import { test } from 'vitest';
import App from './App';
test('App', () => {
const { container } = render(<App />);
// Basic smoke test to ensure App renders without crashing
expect(container).toBeInTheDocument();
render(<App />);
})
+44 -150
View File
@@ -7,28 +7,18 @@ import { InferSeoMetaPlugin } from '@unhead/addons';
import { Suspense, useEffect } from 'react';
import LightningFS from '@isomorphic-git/lightning-fs';
import NostrProvider from '@/components/NostrProvider';
import { NostrSync } from '@/components/NostrSync';
import { Toaster } from "@/components/ui/toaster";
import { TooltipProvider } from "@/components/ui/tooltip";
import { NostrLoginProvider } from '@nostrify/react/login';
import { AppProvider } from '@/components/AppProvider';
import { AppConfig } from '@/contexts/AppContext';
import { useAppContext } from '@/hooks/useAppContext';
import { SentryProvider } from '@/components/SentryProvider';
import { AISettingsProvider } from '@/components/AISettingsProvider';
import { GitSettingsProvider } from '@/components/GitSettingsProvider';
import { DeploySettingsProvider } from '@/components/DeploySettingsProvider';
import { SessionManagerProvider } from '@/components/SessionManagerProvider';
import { FSProvider } from '@/components/FSProvider';
import { ConsoleErrorProvider } from '@/components/ConsoleErrorProvider';
import { ConsoleProvider } from '@/contexts/ConsoleContext';
import { LightningFSAdapter } from '@/lib/LightningFSAdapter';
import { ElectronFSAdapter } from '@/lib/ElectronFSAdapter';
import { cleanupTmpDirectory } from '@/lib/tmpCleanup';
import { DynamicFavicon } from '@/components/DynamicFavicon';
import { OfflineIndicator } from '@/components/OfflineIndicator';
import { PWAUpdatePrompt } from '@/components/PWAUpdatePrompt';
import { ErrorBoundary } from '@/components/ErrorBoundary';
import { GlobalChatProvider } from '@/components/GlobalChatProvider';
import AppRouter from './AppRouter';
@@ -48,160 +38,64 @@ const queryClient = new QueryClient({
},
});
// Get OS-specific default paths for Electron
function getElectronDefaultPaths(): { fsPathProjects: string; fsPathConfig: string; fsPathTmp: string; fsPathPlugins: string; fsPathTemplates: string } {
if (!globalThis.electron) {
// Browser defaults - use virtual filesystem paths
return {
fsPathProjects: "/projects",
fsPathConfig: "/config",
fsPathTmp: "/tmp",
fsPathPlugins: "/plugins",
fsPathTemplates: "/templates",
};
}
// Electron defaults - use OS-specific paths
// Note: The ~ will be expanded by the Electron main process
const platform = navigator.platform.toLowerCase();
if (platform.includes('win')) {
// Windows
return {
fsPathProjects: "~/Documents/Projects",
fsPathConfig: "~/AppData/Local/shakespeare",
fsPathTmp: "~/AppData/Local/Temp/shakespeare",
fsPathPlugins: "~/AppData/Local/shakespeare/plugins",
fsPathTemplates: "~/AppData/Local/shakespeare/templates",
};
} else if (platform.includes('mac')) {
// macOS
return {
fsPathProjects: "~/Projects",
fsPathConfig: "~/Library/Application Support/shakespeare",
fsPathTmp: "/tmp/shakespeare",
fsPathPlugins: "~/Library/Application Support/shakespeare/plugins",
fsPathTemplates: "~/Library/Application Support/shakespeare/templates",
};
} else {
// Linux and other Unix-like systems
return {
fsPathProjects: "~/Projects",
fsPathConfig: "~/.config/shakespeare",
fsPathTmp: "/tmp/shakespeare",
fsPathPlugins: "~/.config/shakespeare/plugins",
fsPathTemplates: "~/.config/shakespeare/templates",
};
}
}
const electronPaths = getElectronDefaultPaths();
const defaultConfig: AppConfig = {
theme: "system",
relayMetadata: {
relays: [
{ url: 'wss://relay.ditto.pub', read: true, write: true },
{ url: 'wss://relay.nostr.band', read: true, write: true },
{ url: 'wss://relay.primal.net', read: true, write: true },
],
updatedAt: 0,
},
templates: [
{
name: "MKStack",
description: "Build Nostr clients with React. This is the default template that you should choose in the majority of cases. It ships with complete Nostr integration out of the box, enabling a variety of use-cases from social media to blogging to AI-powered apps. If you're not sure which template to choose, choose this one.",
url: "https://gitlab.com/soapbox-pub/mkstack.git",
},
{
name: "Nutstack",
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
url: "https://gitlab.com/lemonknowsall/nutstack.git",
},
{
name: "Luvstack",
description: "Barebones React template. Choose this to build mockups or demo sites that don't require Nostr functionality. Only choose this if the user has indicated they want to create a demo or mockup site, as it cannot support any sort of backend functionality or remote storage. It might also work for simple PWAs.",
url: "https://gitlab.com/soapbox-pub/luvstack.git",
}
],
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
previewDomain: "local-shakespeare.dev",
showcaseEnabled: true,
showcaseModerator: "npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc",
ngitServers: ["git.shakespeare.diy", "relay.ngit.dev"],
fsPathProjects: electronPaths.fsPathProjects,
fsPathConfig: electronPaths.fsPathConfig,
fsPathTmp: electronPaths.fsPathTmp,
fsPathPlugins: electronPaths.fsPathPlugins,
fsPathTemplates: electronPaths.fsPathTemplates,
sentryDsn: import.meta.env.VITE_SENTRY_DSN || "",
sentryEnabled: true,
theme: "light",
relayUrl: "wss://relay.primal.net",
deployServer: "shakespeare.wtf",
};
// Initialize filesystem adapter based on environment
// In Electron, use Electron filesystem at ~/shakespeare
// In browser, use LightningFS (IndexedDB-backed virtual filesystem)
const fs = globalThis.electron
? new ElectronFSAdapter()
: new LightningFSAdapter(new LightningFS('shakespeare-fs').promises);
const presetRelays = [
{ url: 'wss://ditto.pub/relay', name: 'Ditto' },
{ url: 'wss://relay.nostr.band', name: 'Nostr.Band' },
{ url: 'wss://relay.damus.io', name: 'Damus' },
{ url: 'wss://relay.primal.net', name: 'Primal' },
];
// Initialize LightningFS
const lightningFS = new LightningFS('shakespeare-fs');
const fs = new LightningFSAdapter(lightningFS.promises);
// Component to handle filesystem cleanup on startup
// Automatically removes files older than 1 hour from tmp directory
// Automatically removes files older than 1 hour from /tmp directory
function FSCleanupHandler() {
const { config } = useAppContext();
useEffect(() => {
// Run cleanup on application startup to remove stale temporary files
// This helps prevent the VFS from accumulating old files over time
cleanupTmpDirectory(fs, config.fsPathTmp).catch(console.error);
}, [config.fsPathTmp]);
cleanupTmpDirectory(fs).catch(console.error);
}, []);
return null;
}
export function App() {
return (
<ErrorBoundary>
<UnheadProvider head={head}>
<QueryClientProvider client={queryClient}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig}>
<SentryProvider>
<FSProvider fs={fs}>
<ConsoleErrorProvider>
<FSCleanupHandler />
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<NostrSync />
<AISettingsProvider>
<GitSettingsProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<GlobalChatProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</GlobalChatProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleErrorProvider>
</FSProvider>
</SentryProvider>
</AppProvider>
</QueryClientProvider>
</UnheadProvider>
</ErrorBoundary>
<UnheadProvider head={head}>
<QueryClientProvider client={queryClient}>
<AppProvider storageKey="nostr:app-config" defaultConfig={defaultConfig} presetRelays={presetRelays}>
<FSProvider fs={fs}>
<FSCleanupHandler />
<ConsoleProvider>
<NostrLoginProvider storageKey='nostr:login'>
<NostrProvider>
<AISettingsProvider>
<GitSettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</GitSettingsProvider>
</AISettingsProvider>
</NostrProvider>
</NostrLoginProvider>
</ConsoleProvider>
</FSProvider>
</AppProvider>
</QueryClientProvider>
</UnheadProvider>
);
}
+7 -25
View File
@@ -1,9 +1,6 @@
import { BrowserRouter, HashRouter, Route, Routes } from "react-router-dom";
import { BrowserRouter, Route, Routes } from "react-router-dom";
import { ScrollToTop } from "./components/ScrollToTop";
import { SessionMonitor } from "./components/SessionMonitor";
import { URLFragmentHandler } from "./components/URLFragmentHandler";
import { FloatingChatButton } from "./components/FloatingChatButton";
import { GlobalChatPane } from "./components/GlobalChatPane";
import Index from "./pages/Index";
import Clone from "./pages/Clone";
@@ -12,44 +9,32 @@ import Preferences from "./pages/Preferences";
import NostrSettings from "./pages/NostrSettings";
import AISettings from "./pages/AISettings";
import GitSettings from "./pages/GitSettings";
import DeploySettings from "./pages/DeploySettings";
import SystemSettings from "./pages/SystemSettings";
import StorageSettings from "./pages/StorageSettings";
import DataSettings from "./pages/DataSettings";
import AboutSettings from "./pages/AboutSettings";
import EmailSettings from "./pages/EmailSettings";
import GitHubOAuth from "./pages/GitHubOAuth";
import NetlifyOAuth from "./pages/NetlifyOAuth";
import VercelOAuth from "./pages/VercelOAuth";
import { NIP19Page } from "./pages/NIP19Page";
import NotFound from "./pages/NotFound";
import { ProjectView } from "./pages/ProjectView";
import { SettingsLayout } from "./components/SettingsLayout";
export function AppRouter() {
// Use HashRouter in Electron, BrowserRouter in web
const Router = globalThis.electron ? HashRouter : BrowserRouter;
return (
<Router>
<BrowserRouter>
<ScrollToTop />
<SessionMonitor />
<URLFragmentHandler />
<Routes>
<Route path="/" element={<Index />} />
<Route path="/giftcard" element={<Index />} />
<Route path="/clone" element={<Clone />} />
<Route path="/oauth/github" element={<GitHubOAuth />} />
<Route path="/oauth/netlify" element={<NetlifyOAuth />} />
<Route path="/oauth/vercel" element={<VercelOAuth />} />
<Route path="/settings" element={<SettingsLayout />}>
<Route index element={<Settings />} />
<Route path="preferences" element={<Preferences />} />
<Route path="nostr" element={<NostrSettings />} />
<Route path="ai" element={<AISettings />} />
<Route path="git" element={<GitSettings />} />
<Route path="deploy" element={<DeploySettings />} />
<Route path="system" element={<SystemSettings />} />
<Route path="storage" element={<StorageSettings />} />
<Route path="data" element={<DataSettings />} />
<Route path="email" element={<EmailSettings />} />
<Route path="about" element={<AboutSettings />} />
</Route>
<Route path="/project/:projectId" element={<ProjectView />} />
@@ -58,10 +43,7 @@ export function AppRouter() {
{/* ADD ALL CUSTOM ROUTES ABOVE THE CATCH-ALL "*" ROUTE */}
<Route path="*" element={<NotFound />} />
</Routes>
{/* Global floating chat - available on all pages */}
<FloatingChatButton />
<GlobalChatPane />
</Router>
</BrowserRouter>
);
}
export default AppRouter;
+12 -107
View File
@@ -1,14 +1,11 @@
import { memo, useState } from 'react';
import { Streamdown } from 'streamdown';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs, Send, Puzzle } from 'lucide-react';
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react';
import type { AIMessage } from '@/lib/SessionManager';
import { cn } from '@/lib/utils';
import { UserMessage } from '@/components/UserMessage';
import OpenAI from 'openai';
import { useTheme } from '@/hooks/useTheme';
import { isEmptyMessage } from '@/lib/isEmptyMessage';
import { Dialog, DialogPortal, DialogOverlay } from '@/components/ui/dialog';
import * as DialogPrimitive from '@radix-ui/react-dialog';
// Type guard to check if message has reasoning content
function hasReasoningContent(message: AIMessage): message is AIMessage & { reasoning_content: string } {
@@ -28,7 +25,6 @@ export const AIMessageItem = memo(({
}: AIMessageItemProps) => {
const [isToolExpanded, setIsToolExpanded] = useState(false);
const [isReasoningExpanded, setIsReasoningExpanded] = useState(false);
const [expandedImageUrl, setExpandedImageUrl] = useState<string | null>(null);
const { displayTheme } = useTheme();
// Get content to display
@@ -73,8 +69,8 @@ export const AIMessageItem = memo(({
case 'text_editor_view': {
const title = args.path
? (args.start_line || args.end_line
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`)
? `Viewed ${args.path} (lines ${args.start_line || 1}-${args.end_line || 'end'})`
: `Viewed ${args.path}`)
: 'Viewed File';
return { icon: Eye, title };
}
@@ -144,13 +140,6 @@ export const AIMessageItem = memo(({
icon: Plus,
title: args.range ? `Generated ${args.range} kind` : 'Generated Kind'
};
case 'nostr_publish_events': {
const eventCount = args.events?.length || 0;
return {
icon: Send,
title: eventCount > 1 ? `Published ${eventCount} Nostr events` : 'Published Nostr event'
};
}
case 'deploy_project':
return {
icon: Globe,
@@ -161,16 +150,6 @@ export const AIMessageItem = memo(({
icon: CheckCircle,
title: 'TypeScript'
};
case 'read_console_messages':
return {
icon: Logs,
title: 'Read Console'
};
case 'skill':
return {
icon: Puzzle,
title: args.name ? `Skill: ${args.name}` : 'Skill'
};
default:
return {
icon: Wrench,
@@ -298,99 +277,25 @@ export const AIMessageItem = memo(({
// Regular rendering for non-tool messages
if (message.role === 'user') {
// User messages: right-aligned bubble without avatar/name
// Extract text and image parts from message content
const contentArray = Array.isArray(message.content) ? message.content : null;
const textParts = contentArray
? contentArray.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: [];
const userContent = typeof message.content === 'string'
? message.content
: textParts.length > 0
? textParts.map(part => part.text).join('\n')
: Array.isArray(message.content)
? message.content.filter(part => part.type === 'text') as OpenAI.Chat.Completions.ChatCompletionContentPartText[]
: '';
// Extract image URLs from content array
const imageUrls = contentArray
? contentArray
.filter(part => part.type === 'image_url')
.map(part => (part as OpenAI.Chat.Completions.ChatCompletionContentPartImage).image_url.url)
: [];
return (
<>
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words space-y-2">
{/* Render text content and attachments first */}
{userContent && <UserMessage content={userContent} />}
{/* Render images after text and attachments */}
{imageUrls.length > 0 && (
<div className="space-y-2">
{imageUrls.map((url, index) => (
<div
key={index}
className="rounded-lg overflow-hidden border border-border cursor-pointer hover:opacity-90 transition-opacity"
onClick={() => setExpandedImageUrl(url)}
>
<img
src={url}
alt={`User uploaded image ${index + 1}`}
className="max-w-full h-auto max-h-96 object-contain"
loading="lazy"
onError={(e) => {
// Fallback if image fails to load
const target = e.target as HTMLImageElement;
target.style.display = 'none';
const fallback = document.createElement('div');
fallback.className = 'p-2 text-xs text-muted-foreground bg-muted rounded';
fallback.textContent = `Image failed to load: ${url}`;
target.parentElement?.appendChild(fallback);
}}
/>
</div>
))}
</div>
)}
</div>
<div className="flex justify-end py-6">
<div className="max-w-[80%] bg-secondary rounded-2xl rounded-br-md px-4 py-3">
<div className="text-sm break-words">
<UserMessage content={userContent} />
</div>
</div>
{/* Image expansion dialog */}
<Dialog open={!!expandedImageUrl} onOpenChange={(open) => !open && setExpandedImageUrl(null)}>
<DialogPortal>
<DialogOverlay className="bg-black/95" />
<DialogPrimitive.Content
className={cn(
"fixed left-[50%] top-[50%] z-50 max-w-[95vw] max-h-[95vh] translate-x-[-50%] translate-y-[-50%] p-0 bg-transparent border-0 shadow-none",
"data-[state=open]:animate-in data-[state=closed]:animate-out",
"data-[state=closed]:fade-out-0 data-[state=open]:fade-in-0",
"data-[state=closed]:zoom-out-95 data-[state=open]:zoom-in-95"
)}
onPointerDownOutside={() => setExpandedImageUrl(null)}
onEscapeKeyDown={() => setExpandedImageUrl(null)}
>
{expandedImageUrl && (
<div className="relative flex items-center justify-center">
<img
src={expandedImageUrl}
alt="Expanded image"
className="max-w-full max-h-[95vh] w-auto h-auto object-contain rounded-lg"
/>
</div>
)}
</DialogPrimitive.Content>
</DialogPortal>
</Dialog>
</>
</div>
);
}
if (message.role !== 'assistant') {
return null; // Only render assistant and user messages
}
// If the message is empty (no content or reasoning), render nothing
if (isEmptyMessage({ ...message, tool_calls: [] })) {
// If there's no reasoning content and the main content is empty, render nothing
if (!hasReasoningContent(message) && !getContent().trim()) {
return null;
}
+32 -2
View File
@@ -125,7 +125,6 @@ describe('AISettingsProvider', () => {
providers: [
{
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'test-key'
}
@@ -174,7 +173,6 @@ describe('AISettingsProvider', () => {
providers: [
{
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key'
}
@@ -184,4 +182,36 @@ describe('AISettingsProvider', () => {
expect(mockInvalidateQueries).toHaveBeenCalledWith({ queryKey: ['provider-models'] });
});
it('should not invalidate provider-models query when updateSettings is called without providers', async () => {
// Mock the QueryClient.invalidateQueries method
const mockInvalidateQueries = vi.fn();
// Create a custom TestApp that mocks the query client
const MockedTestApp = ({ children }: { children: React.ReactNode }) => {
const queryClient = useQueryClient();
vi.spyOn(queryClient, 'invalidateQueries').mockImplementation(mockInvalidateQueries);
return <>{children}</>;
};
const { result } = renderHook(() => useAISettings(), {
wrapper: ({ children }) => (
<TestApp>
<MockedTestApp>{children}</MockedTestApp>
</TestApp>
),
});
await waitFor(() => {
expect(result.current.settings.recentlyUsedModels).toEqual([]);
});
act(() => {
result.current.updateSettings({
recentlyUsedModels: ['test-model']
});
});
expect(mockInvalidateQueries).not.toHaveBeenCalled();
});
});
+5 -35
View File
@@ -1,8 +1,7 @@
import { useQueryClient } from '@tanstack/react-query';
import { ReactNode, useState, useEffect } from 'react';
import { AISettingsContext, type AISettings, type AIProvider, type MCPServer, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readAISettings, writeAISettings } from '@/lib/configUtils';
interface AISettingsProviderProps {
@@ -12,13 +11,11 @@ interface AISettingsProviderProps {
const DEFAULT_SETTINGS: AISettings = {
providers: [],
recentlyUsedModels: [],
mcpServers: {},
};
export function AISettingsProvider({ children }: AISettingsProviderProps) {
const queryClient = useQueryClient();
const { fs } = useFS();
const { configPath } = useFSPaths();
const [settings, setSettings] = useState<AISettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
@@ -26,7 +23,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readAISettings(fs, configPath);
const settings = await readAISettings(fs);
setSettings(settings);
} catch (error) {
console.error('Failed to initialize AI settings:', error);
@@ -37,7 +34,7 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
};
initializeSettings();
}, [fs, configPath]);
}, [fs]);
// Save settings to VFS whenever they change (but not during initialization)
useEffect(() => {
@@ -45,14 +42,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
const saveSettings = async () => {
try {
await writeAISettings(fs, settings, configPath);
await writeAISettings(fs, settings);
} catch (error) {
console.error('Failed to save AI settings:', error);
}
};
saveSettings();
}, [fs, settings, isInitialized, configPath]);
}, [fs, settings, isInitialized]);
const updateSettings = (newSettings: Partial<AISettings>) => {
setSettings(prev => ({ ...prev, ...newSettings }));
@@ -60,7 +57,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
// If providers are being updated, invalidate the provider-models query
if ('providers' in newSettings) {
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
}
};
@@ -84,7 +80,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
}
});
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const removeProvider = (id: string) => {
@@ -93,7 +88,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
providers: prev.providers.filter(provider => provider.id !== id),
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const setProviders = (providers: AIProvider[]) => {
@@ -102,7 +96,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
providers,
}));
queryClient.invalidateQueries({ queryKey: ['provider-models'] });
queryClient.invalidateQueries({ queryKey: ['ai-credits'] });
};
const addRecentlyUsedModel = (modelId: string) => {
@@ -129,27 +122,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
});
};
const setMCPServer = (name: string, server: MCPServer) => {
setSettings(prev => ({
...prev,
mcpServers: {
...(prev.mcpServers || {}),
[name]: server,
},
}));
};
const removeMCPServer = (name: string) => {
setSettings(prev => {
const newMCPServers = { ...(prev.mcpServers || {}) };
delete newMCPServers[name];
return {
...prev,
mcpServers: newMCPServers,
};
});
};
const isConfigured = settings.providers.length > 0;
const contextValue: AISettingsContextType = {
@@ -159,8 +131,6 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) {
removeProvider,
setProviders,
addRecentlyUsedModel,
setMCPServer,
removeMCPServer,
isConfigured,
};
-312
View File
@@ -1,312 +0,0 @@
import { useState, useEffect } from 'react';
import { ArrowRight, ArrowLeft, Download, Upload, ExternalLink, Sparkles } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { useAICredits } from '@/hooks/useAICredits';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
interface Act1DialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type DialogStep = 'welcome' | 'migration' | 'credits' | 'conclusion';
// Helper function to get the Shakespeare provider preset
function getShakespeareProvider(): PresetProvider {
const shakespeare = AI_PROVIDER_PRESETS.find(preset => preset.id === "shakespeare");
if (!shakespeare) {
throw new Error("Shakespeare provider preset not found");
}
return shakespeare;
}
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
const [step, setStep] = useState<DialogStep>('welcome');
const { data: creditsData } = useAICredits(getShakespeareProvider());
const handleGetStarted = async () => {
try {
setStep('migration');
} catch (error) {
console.error('Failed to configure Shakespeare provider:', error);
}
};
const handleContinue = () => {
setStep('credits');
};
const handleCreditsNext = () => {
setStep('conclusion');
};
const handleFinish = () => {
// Mark that the user is a previous Act 1 user
localStorage.setItem('act1', 'true');
// Remove the selectedNSPAddr from localStorage
localStorage.removeItem('selectedNSPAddr');
onOpenChange(false);
};
const handleVisitAct1 = () => {
window.open('https://act1.shakespeare.diy', '_blank');
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
}
}, [open]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[90vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{step === 'migration' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('welcome')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'credits' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('migration')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('credits')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
</DialogTitle>
</DialogHeader>
<div className="overflow-y-auto max-h-[calc(90vh-120px)] pr-2">
<div className="space-y-6 py-4">
{step === 'welcome' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">🎭✨</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Welcome to Act 2!
</h2>
<p className="text-lg text-muted-foreground max-w-lg mx-auto">
We're excited to see you again! Shakespeare has been completely rebuilt
with new features, improved performance, and a better development experience.
</p>
</div>
<Card className="max-w-lg mx-auto text-left">
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<span className="text-2xl">🔄</span>
What's Changed
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Use any AI Provider</p>
<p className="text-sm text-muted-foreground">Your browser connects to AI providers directly</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Git Integration</p>
<p className="text-sm text-muted-foreground">Push to GitHub, Nostr relays, and more</p>
</div>
</div>
<div className="flex items-start gap-3">
<Badge variant="secondary" className="mt-0.5">New</Badge>
<div>
<p className="font-medium">Your Files</p>
<p className="text-sm text-muted-foreground">Files are stored on your device directly in your browser</p>
</div>
</div>
</CardContent>
</Card>
<div className="bg-amber-50 dark:bg-amber-950/20 border border-amber-200 dark:border-amber-800 rounded-lg p-4 max-w-lg mx-auto">
<div className="flex items-start gap-3">
<span className="text-amber-600 dark:text-amber-400 text-lg">⚠️</span>
<div className="text-left">
<p className="font-medium text-amber-800 dark:text-amber-200">Act 2 is in Development</p>
<p className="text-sm text-amber-700 dark:text-amber-300">
While we're working hard to make Act 2 stable, you may encounter bugs.
Your Act 1 projects remain safe and accessible.
</p>
</div>
</div>
</div>
<Button
onClick={handleGetStarted}
size="lg"
className="gap-2"
>
Next
</Button>
</div>
)}
{step === 'migration' && (
<div className="space-y-6">
<div className="text-center space-y-3">
<h2 className="text-xl font-bold">Your Act 1 Projects & Credits</h2>
<p className="text-muted-foreground max-w-lg mx-auto">
All your Act 1 projects and credits are safe and still accessible.
Here's how to work with them in Act 2.
</p>
</div>
<div className="text-center">
<Button
variant="outline"
onClick={handleVisitAct1}
className="gap-2"
>
<ExternalLink className="h-4 w-4" />
Visit Act 1
</Button>
</div>
<div className="grid gap-4">
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Download className="h-5 w-5 text-green-500" />
Export from Act 1
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 1, you can export your projects as ZIP files using the project menu.
</p>
</CardContent>
</Card>
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Upload className="h-5 w-5 text-purple-500" />
Import to Act 2
</CardTitle>
</CardHeader>
<CardContent className="space-y-3">
<p className="text-sm text-muted-foreground">
In Act 2, use the "Import Project" option in the sidebar to upload your exported ZIP files.
</p>
</CardContent>
</Card>
</div>
<div className="flex justify-end pt-4">
<Button
onClick={handleContinue}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'credits' && (
<div className="text-center space-y-6">
<div className="text-6xl mb-4">💳</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Your Credits</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
Your Act 1 credits are still available through the Shakespeare AI provider.
</p>
</div>
<Card className="max-w-md mx-auto">
<CardContent className="pt-6">
<div className="text-center space-y-4">
<div className="space-y-2">
<div className="text-3xl font-bold text-green-600 dark:text-green-400">
${(creditsData?.amount ?? 0).toFixed(2)}
</div>
<p className="text-sm text-muted-foreground">
Available credits
</p>
</div>
<div className="bg-green-50 dark:bg-green-950/20 border border-green-200 dark:border-green-800 rounded-lg p-3">
<p className="text-sm text-green-800 dark:text-green-200">
✅ You're all set! We've configured the premium Shakespeare model for you.
</p>
</div>
</div>
</CardContent>
</Card>
<div className="flex justify-end pt-4">
<Button
onClick={handleCreditsNext}
className="gap-2"
>
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'conclusion' && (
<div className="text-center space-y-6">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
</p>
</div>
<div className="space-y-3">
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
Start Building in Act 2
</Button>
<div className="text-xs text-muted-foreground">
Remember: You can always access Act 1 at{' '}
<button
onClick={handleVisitAct1}
className="text-primary hover:underline"
>
act1.shakespeare.diy
</button>
</div>
</div>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
+1 -19
View File
@@ -12,11 +12,9 @@ import {
MessageSquarePlus,
History,
Folder,
Rocket,
} from 'lucide-react';
import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog';
import { GitDialog } from '@/components/GitDialog';
import { DeployDialog } from '@/components/DeployDialog';
interface ActionsMenuProps {
projectId: string;
@@ -31,7 +29,7 @@ interface ActionsMenuProps {
export function ActionsMenu({
projectId,
projectName,
projectName: _projectName,
onNewChat,
onProjectDetails,
isLoading = false,
@@ -41,7 +39,6 @@ export function ActionsMenu({
}: ActionsMenuProps) {
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
const [gitDialogOpen, setGitDialogOpen] = useState(false);
const [deployDialogOpen, setDeployDialogOpen] = useState(false);
const isAnyLoading = isLoading || isBuildLoading;
@@ -89,15 +86,6 @@ export function ActionsMenu({
Repository
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setDeployDialogOpen(true)}
disabled={isAnyLoading}
className="gap-2"
>
<Rocket className="h-4 w-4" />
Deploy
</DropdownMenuItem>
<DropdownMenuItem
onClick={onProjectDetails}
disabled={isAnyLoading}
@@ -124,12 +112,6 @@ export function ActionsMenu({
onOpenChange={setGitHistoryOpen}
/>
<DeployDialog
projectId={projectId}
projectName={projectName}
open={deployDialogOpen}
onOpenChange={setDeployDialogOpen}
/>
</>
);
-136
View File
@@ -1,136 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TestApp } from '@/test/TestApp';
import { AddProviderDialog } from './AddProviderDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
describe('AddProviderDialog', () => {
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'sk-test-key-123',
};
it('renders new provider dialog', () => {
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</TestApp>
);
// Provider name is used as the heading (fallback to id since it's not in presets)
expect(screen.getByRole('heading', { name: 'test-provider' })).toBeInTheDocument();
expect(screen.getByText(/Add test-provider to your configuration/i)).toBeInTheDocument();
});
it('shows add provider button for new provider', () => {
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</TestApp>
);
// No cancel button, only add provider button
expect(screen.queryByRole('button', { name: /cancel/i })).not.toBeInTheDocument();
expect(screen.getByRole('button', { name: /add provider/i })).toBeInTheDocument();
});
it('calls onOpenChange when add provider is clicked', async () => {
const user = userEvent.setup();
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</TestApp>
);
const addButton = screen.getByRole('button', { name: /add provider/i });
await user.click(addButton);
expect(onOpenChange).toHaveBeenCalledWith(false);
});
it('does not display provider details for new provider', () => {
const onOpenChange = vi.fn();
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={mockProvider}
/>
</TestApp>
);
// Provider details (API key, base URL, etc.) are not displayed for new providers
expect(screen.queryByText('••••••••')).not.toBeInTheDocument();
expect(screen.queryByText('sk-test-key-123')).not.toBeInTheDocument();
expect(screen.queryByText('https://api.test.com/v1')).not.toBeInTheDocument();
});
it('displays provider name from presets when available', () => {
const onOpenChange = vi.fn();
// Use a provider that exists in presets
const openrouterProvider: AIProvider = {
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'sk-test-123',
};
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={openrouterProvider}
/>
</TestApp>
);
// Should show the preset name "OpenRouter" instead of the id
expect(screen.getByText(/Add OpenRouter to your configuration/i)).toBeInTheDocument();
});
it('uses provider id as fallback name when not in presets', () => {
const onOpenChange = vi.fn();
const customProvider: AIProvider = {
id: 'my-custom-provider',
name: 'My Custom Provider',
baseURL: 'https://api.custom.com/v1',
};
render(
<TestApp>
<AddProviderDialog
open={true}
onOpenChange={onOpenChange}
provider={customProvider}
/>
</TestApp>
);
// Should use the id as the name since it's not in presets
expect(screen.getByText(/Add my-custom-provider to your configuration/i)).toBeInTheDocument();
});
});
-217
View File
@@ -1,217 +0,0 @@
import { useEffect, useRef, useState } from 'react';
import { Check, Sparkles, ArrowRight, AlertCircle, ExternalLink } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Checkbox } from '@/components/ui/checkbox';
import { useAISettings } from '@/hooks/useAISettings';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import type { AIProvider } from '@/contexts/AISettingsContext';
interface AddProviderDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
provider: AIProvider;
}
export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderDialogProps) {
const scrollableContentRef = useRef<HTMLDivElement>(null);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const { settings, setProvider } = useAISettings();
// Check if provider already exists and if it's identical
const existingProvider = settings.providers.find(p => p.id === provider.id);
const isIdentical = existingProvider &&
existingProvider.baseURL === provider.baseURL &&
existingProvider.apiKey === provider.apiKey &&
existingProvider.nostr === provider.nostr &&
existingProvider.proxy === provider.proxy;
// Get provider preset if available
const preset = AI_PROVIDER_PRESETS.find(
p => p.id === provider.id && p.baseURL === provider.baseURL
);
const providerName = preset?.name || provider.id;
const handleAddProvider = () => {
setProvider(provider);
onOpenChange(false);
};
// Reset agreed to terms when dialog opens or provider changes
useEffect(() => {
if (open) {
setAgreedToTerms(false);
if (scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
}
}
}, [open, provider.id]);
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
<DialogHeader className="flex-shrink-0">
<DialogTitle className="flex items-center gap-2">
<span className="text-xl">Add Provider</span>
</DialogTitle>
</DialogHeader>
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
<div className="space-y-6 py-4">
{isIdentical ? (
// Provider already exists with identical configuration
<div className="text-center space-y-6">
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
<Check className="h-8 w-8 text-primary" />
</div>
<div className="space-y-2">
<h2 className="text-2xl font-bold">Already Configured</h2>
<p className="text-muted-foreground max-w-md mx-auto">
You already have {providerName} configured with the same settings.
</p>
</div>
<Button onClick={() => onOpenChange(false)} className="gap-2">
Close
</Button>
</div>
) : existingProvider ? (
// Provider exists but with different configuration
<div className="space-y-6">
<div className="mx-auto w-16 h-16 rounded-full bg-yellow-500/10 flex items-center justify-center">
<AlertCircle className="h-8 w-8 text-yellow-500" />
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold">Provider Already Exists</h2>
<p className="text-muted-foreground max-w-md mx-auto">
A provider with this ID already exists but with different settings. Would you like to overwrite it?
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 gap-4 max-w-2xl mx-auto">
<div className="space-y-2 p-4 rounded-lg border">
<h3 className="font-semibold text-sm">Current Settings</h3>
<div className="text-xs text-muted-foreground space-y-1">
<div>
<span className="font-medium">Base URL:</span>
<div className="font-mono break-all">{existingProvider.baseURL}</div>
</div>
{existingProvider.apiKey && (
<div>
<span className="font-medium">API Key:</span>
<div className="font-mono">••••••••</div>
</div>
)}
{existingProvider.nostr && (
<div>
<span className="font-medium">Nostr Auth:</span> Enabled
</div>
)}
{existingProvider.proxy && (
<div>
<span className="font-medium">Proxy:</span> Enabled
</div>
)}
</div>
</div>
<div className="space-y-2 p-4 rounded-lg border border-primary">
<h3 className="font-semibold text-sm">New Settings</h3>
<div className="text-xs text-muted-foreground space-y-1">
<div>
<span className="font-medium">Base URL:</span>
<div className="font-mono break-all">{provider.baseURL}</div>
</div>
{provider.apiKey && (
<div>
<span className="font-medium">API Key:</span>
<div className="font-mono">••••••••</div>
</div>
)}
{provider.nostr && (
<div>
<span className="font-medium">Nostr Auth:</span> Enabled
</div>
)}
{provider.proxy && (
<div>
<span className="font-medium">Proxy:</span> Enabled
</div>
)}
</div>
</div>
</div>
<div className="flex justify-center gap-3">
<Button variant="outline" onClick={() => onOpenChange(false)}>
Cancel
</Button>
<Button onClick={handleAddProvider} className="gap-2">
Overwrite Provider
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
) : (
// New provider
<div className="space-y-6">
<div className="mx-auto w-16 h-16 rounded-full bg-primary/10 flex items-center justify-center">
<ExternalFavicon
url={provider.baseURL}
size={32}
fallback={<Sparkles className="h-8 w-8 text-primary" />}
/>
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold">{providerName}</h2>
<p className="text-muted-foreground max-w-md mx-auto">
Add {providerName} to your configuration?
</p>
</div>
{/* Terms of Service Agreement */}
{preset?.tosURL && (
<div className="space-y-3 max-w-md mx-auto">
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-provider-terms"
checked={agreedToTerms}
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
/>
<label
htmlFor="agree-provider-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
I agree to {providerName}'s{' '}
<a
href={preset.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:no-underline inline-flex items-center gap-1"
onClick={(e) => e.stopPropagation()}
>
Terms of Service
<ExternalLink className="h-3 w-3" />
</a>
</label>
</div>
</div>
)}
<div className="flex justify-center">
<Button
onClick={handleAddProvider}
disabled={preset?.tosURL ? !agreedToTerms : false}
>
Add Provider
</Button>
</div>
</div>
)}
</div>
</div>
</DialogContent>
</Dialog>
);
}
+19 -17
View File
@@ -18,6 +18,7 @@ interface AppLayoutProps {
export function AppLayout({
children,
selectedProject = null,
title = "Shakespeare",
showSidebar = true,
headerContent
}: AppLayoutProps) {
@@ -72,22 +73,23 @@ export function AppLayout({
return (
<div className="min-h-dvh bg-gradient-to-br from-primary/5 to-accent/5">
{/* Mobile Header */}
<header className="bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur pt-safe">
<div className="h-12 px-4 py-3 flex items-center justify-between border-b">
<div className="flex items-center space-x-2">
{showSidebar && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
</div>
{headerContent}
<header className="h-12 border-b bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10 backdrop-blur px-4 py-3 flex items-center justify-between">
<div className="flex items-center space-x-2">
{showSidebar && (
<Button
variant="ghost"
size="sm"
onClick={() => setIsSidebarVisible(!isSidebarVisible)}
aria-label="Toggle sidebar"
>
<Menu className="h-4 w-4" />
</Button>
)}
<h1 className="text-lg font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{title}
</h1>
</div>
{headerContent}
</header>
{/* Mobile Sidebar Overlay - show if showSidebar is true and sidebar is visible */}
@@ -99,7 +101,7 @@ export function AppLayout({
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={(project) => {
@@ -123,7 +125,7 @@ export function AppLayout({
<div className="min-h-screen flex bg-background">
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="w-72 border-r bg-sidebar transition-all duration-300">
<div className="w-80 border-r bg-sidebar transition-all duration-300">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
+14 -66
View File
@@ -1,7 +1,7 @@
import { ReactNode, useEffect } from 'react';
import { z } from 'zod';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext';
import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext';
import i18n from '@/lib/i18n';
interface AppProviderProps {
@@ -10,86 +10,48 @@ interface AppProviderProps {
storageKey: string;
/** Default app configuration */
defaultConfig: AppConfig;
/** Optional list of preset relays to display in the RelaySelector */
presetRelays?: { name: string; url: string }[];
}
// Zod schema for RelayMetadata
const RelayMetadataSchema = z.object({
relays: z.array(z.object({
url: z.string().url(),
read: z.boolean(),
write: z.boolean(),
})),
updatedAt: z.number(),
}) satisfies z.ZodType<RelayMetadata>;
// Zod schema for ProjectTemplate
const ProjectTemplateSchema = z.object({
name: z.string().min(1),
description: z.string().min(1),
url: z.string().url(),
});
// Zod schema for AppConfig validation
const AppConfigSchema = z.object({
const AppConfigSchema: z.ZodType<AppConfig, z.ZodTypeDef, unknown> = z.object({
theme: z.enum(['dark', 'light', 'system']),
relayMetadata: RelayMetadataSchema,
templates: z.array(ProjectTemplateSchema),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
faviconUrl: z.string().url(),
previewDomain: z.string().min(1),
language: z.string(),
showcaseEnabled: z.boolean(),
showcaseModerator: z.string(),
ngitServers: z.array(z.string()),
fsPathProjects: z.string().min(1),
fsPathConfig: z.string().min(1),
fsPathTmp: z.string().min(1),
fsPathPlugins: z.string().min(1),
fsPathTemplates: z.string().min(1),
sentryDsn: z.string(),
sentryEnabled: z.boolean(),
}) satisfies z.ZodType<AppConfig>;
relayUrl: z.string().url(),
deployServer: z.string().min(1),
language: z.string().optional(),
});
export function AppProvider(props: AppProviderProps) {
const {
children,
storageKey,
defaultConfig,
presetRelays,
} = props;
// App configuration state with localStorage persistence
const [rawConfig, setConfig] = useLocalStorage<Partial<AppConfig>>(
const [config, setConfig] = useLocalStorage<AppConfig>(
storageKey,
{},
defaultConfig,
{
serialize: JSON.stringify,
deserialize: (value: string) => {
const parsed = JSON.parse(value);
return AppConfigSchema.partial().parse(parsed);
return AppConfigSchema.parse(parsed);
}
}
);
// Generic config updater with callback pattern
const updateConfig = (updater: (currentConfig: Partial<AppConfig>) => Partial<AppConfig>) => {
const updateConfig = (updater: (currentConfig: AppConfig) => AppConfig) => {
setConfig(updater);
};
// Merge default config with stored config
const config = { ...defaultConfig, ...rawConfig };
// Expand filesystem paths
config.fsPathConfig = expandPath(config.fsPathConfig);
config.fsPathProjects = expandPath(config.fsPathProjects);
config.fsPathTmp = expandPath(config.fsPathTmp);
config.fsPathPlugins = expandPath(config.fsPathPlugins);
config.fsPathTemplates = expandPath(config.fsPathTemplates);
const appContextValue: AppContextType = {
config,
defaultConfig,
updateConfig,
presetRelays,
};
// Apply theme effects to document
@@ -153,18 +115,4 @@ function useApplyLanguage(language?: string): void {
useEffect(() => {
i18n.changeLanguage(language ?? navigator.language);
}, [language]);
}
/** Expand FS paths with the user's home directory, if available. */
function expandPath(path: string): string {
const homedir = window.electron?.homedir;
if (!homedir) {
return path;
} else if (path.startsWith('~/')) {
return homedir + path.slice(1);
} else if (path === '~') {
return homedir;
} else {
return path;
}
}
-215
View File
@@ -1,215 +0,0 @@
import React, { useState, useMemo } from "react";
import { Button } from "@/components/ui/button";
import { useCurrentUser } from "@/hooks/useCurrentUser";
import { useAppSubmissions } from "@/hooks/useAppSubmissions";
import { AppShowcaseCard } from "@/components/AppShowcaseCard";
import {
Collapsible,
CollapsibleContent,
CollapsibleTrigger,
} from "@/components/ui/collapsible";
import { nip19 } from 'nostr-tools';
import { shuffleArray } from "@/lib/utils";
import { Skeleton } from "@/components/ui/skeleton";
import { Card, CardContent } from "@/components/ui/card";
import { useAppContext } from "@/hooks/useAppContext";
import { useTranslation } from 'react-i18next';
import { Link } from 'react-router-dom';
import { Settings } from 'lucide-react';
export function AppShowcase() {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const { data: submissions = [], isLoading } = useAppSubmissions();
const [showAllApps, setShowAllApps] = useState(false);
// Get moderator hex from config
const MODERATOR_HEX = useMemo(() => {
try {
const decoded = nip19.decode(config.showcaseModerator);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
}, [config.showcaseModerator]);
const isModerator = user?.pubkey === MODERATOR_HEX;
// Filter and shuffle submissions - memoized with stable dependency
const { templateApps, featuredApps, approvedApps } = useMemo(() => {
// Filter visible submissions
const visibleSubmissions = submissions.filter(app => !app.isHidden);
// Separate template apps from other apps
const templates = shuffleArray(visibleSubmissions.filter(app => app.appTags.includes('Template')));
const nonTemplateSubmissions = visibleSubmissions.filter(app => !app.appTags.includes('Template'));
// Shuffle featured and approved apps for random display order
const featured = shuffleArray(nonTemplateSubmissions.filter(app => app.isFeatured));
const approved = shuffleArray(nonTemplateSubmissions.filter(app => app.isApproved && !app.isFeatured));
return {
templateApps: templates,
featuredApps: featured,
approvedApps: approved,
};
}, [submissions]); // Only depend on submissions, not intermediate filtered arrays
// Don't show showcase if disabled in settings
if (!config.showcaseEnabled) {
return null;
}
// Don't show showcase if no apps exist
if (isLoading) {
return (
<div className="mt-16 max-w-7xl mx-auto">
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 6 }).map((_, i) => (
<Card key={i} className="h-full flex flex-col">
<Skeleton className="aspect-video rounded-t-lg" />
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-center gap-3 mb-3">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="space-y-2">
<Skeleton className="h-4 w-32" />
<Skeleton className="h-3 w-24" />
</div>
</div>
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-6 flex-1" />
<Skeleton className="h-8 w-8" />
<Skeleton className="h-8 w-8" />
</div>
</CardContent>
</Card>
))}
</div>
</div>
);
}
if (!submissions.length) {
return (
<div className="mt-16 max-w-7xl mx-auto">
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-6">
<p className="text-muted-foreground">
{t('noAppsFound')}
</p>
<Button asChild variant="outline" className="w-full">
<Link to="/settings/nostr">
<Settings className="h-4 w-4 mr-2" />
{t('relayConfiguration')}
</Link>
</Button>
</div>
</CardContent>
</Card>
</div>
);
}
return (
<div className="mt-16 max-w-7xl mx-auto">
{/* Apps Grid */}
<div className="space-y-12">
{/* Featured Apps */}
{featuredApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-yellow-100 dark:bg-yellow-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">⭐</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('featuredApps')}</h3>
<p className="text-sm text-muted-foreground">{t('featuredAppsDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{featuredApps.slice(0, 6).map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* Templates Section */}
{templateApps.length > 0 && (
<div>
<div className="flex items-start gap-3 mb-6">
<div className="flex-none w-8 h-8 bg-purple-100 dark:bg-purple-900/30 rounded-lg flex items-center justify-center">
<span className="text-sm">📋</span>
</div>
<div>
<h3 className="text-xl font-bold text-foreground">{t('templates')}</h3>
<p className="text-sm text-muted-foreground">{t('templatesDescription')}</p>
</div>
</div>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{templateApps.slice(0, 6).map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</div>
)}
{/* More Apps (Approved) - Collapsible */}
{approvedApps.length > 0 && (
<div>
<Collapsible open={showAllApps} onOpenChange={setShowAllApps}>
<CollapsibleTrigger asChild>
<Button variant="ghost" className="p-0 h-auto mb-6 hover:bg-transparent">
<div className="flex items-start gap-3">
<div className="flex-none w-8 h-8 bg-blue-100 dark:bg-blue-900/50 rounded-lg flex items-center justify-center">
<span className="text-sm">📱</span>
</div>
<div className="text-left">
<h3 className="text-xl font-bold text-foreground">
{t('moreAppsCount', { count: approvedApps.length })}
</h3>
<p className="text-sm text-muted-foreground">
{showAllApps ? t('clickToCollapse') : t('clickToViewMore')}
</p>
</div>
</div>
</Button>
</CollapsibleTrigger>
<CollapsibleContent>
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{approvedApps.map((app) => (
<AppShowcaseCard
key={app.id}
app={app}
showModerationControls={isModerator}
hideApprovalStatus={true}
/>
))}
</div>
</CollapsibleContent>
</Collapsible>
</div>
)}
</div>
</div>
);
}
-589
View File
@@ -1,589 +0,0 @@
import React, { useState } from 'react';
import { Link } from 'react-router-dom';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import {
ExternalLink,
Edit,
Star,
StarOff,
Eye,
EyeOff,
MoreVertical,
CheckCircle,
XCircle,
User,
Home,
Contact
} from 'lucide-react';
import {
DropdownMenu,
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
} from '@/components/ui/dropdown-menu';
import type { AppSubmission } from '@/hooks/useAppSubmissions';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { useNostr } from '@nostrify/react';
import { useAuthor } from '@/hooks/useAuthor';
import { nip19 } from 'nostr-tools';
import { useToast } from '@/hooks/useToast';
import { useQueryClient } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
interface AppShowcaseCardProps {
app: AppSubmission;
onEdit?: (app: AppSubmission) => void;
showModerationControls?: boolean;
hideApprovalStatus?: boolean; // Hide pending/approval badges
}
export function AppShowcaseCard({ app, onEdit, showModerationControls, hideApprovalStatus: _hideApprovalStatus }: AppShowcaseCardProps) {
const { user } = useCurrentUser();
const { nostr } = useNostr();
const { mutate: publishEvent, isPending } = useNostrPublish();
const queryClient = useQueryClient();
const [imageError, setImageError] = useState(false);
const { toast } = useToast();
// Get author pubkey from authorNpub field
const authorPubkey = React.useMemo(() => {
if (!app.authorNpub) return app.pubkey; // Fallback to event pubkey
try {
// If it's already a hex key, use it directly
if (app.authorNpub.length === 64 && /^[0-9a-f]+$/i.test(app.authorNpub)) {
return app.authorNpub;
}
// Otherwise try to decode as npub
const decoded = nip19.decode(app.authorNpub);
return decoded.type === 'npub' ? decoded.data : app.pubkey;
} catch {
return app.pubkey; // Fallback to event pubkey if decode fails
}
}, [app.authorNpub, app.pubkey]);
const { data: authorData } = useAuthor(authorPubkey);
const isOwner = user?.pubkey === app.pubkey;
const MODERATOR_NPUB = 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc';
const MODERATOR_HEX = (() => {
try {
const decoded = nip19.decode(MODERATOR_NPUB);
return decoded.type === 'npub' ? decoded.data : '';
} catch {
return '';
}
})();
const isModerator = user?.pubkey === MODERATOR_HEX;
// Check if this is a Halloween submission by looking for Halloween tags
const isHalloweenSubmission = app.appTags.includes('Halloween Hackathon 2025');
// Get contact info from Halloween submissions (these have lightning/email tags)
const getContactInfo = () => {
if (!isHalloweenSubmission) return null;
// Look for lightning and email tags in the event tags
const lightningTag = app.tags?.find((tag: string[]) => tag[0] === 'lightning')?.[1];
const emailTag = app.tags?.find((tag: string[]) => tag[0] === 'email')?.[1];
return { lightning: lightningTag, email: emailTag };
};
const handleCopyContactInfo = () => {
const contactInfo = getContactInfo();
if (!contactInfo) return;
const info: string[] = [];
if (contactInfo.lightning) info.push(`Lightning: ${contactInfo.lightning}`);
if (contactInfo.email) info.push(`Email: ${contactInfo.email}`);
const textToCopy = info.join('\n');
navigator.clipboard.writeText(textToCopy);
toast({
title: 'Contact Info Copied!',
description: `Copied ${info.length} contact method(s) to clipboard`
});
};
const handleModerationAction = async (action: 'feature' | 'unfeature' | 'approve' | 'unapprove' | 'hide' | 'unhide' | 'homepage' | 'unhomepage') => {
if (!isModerator || !user) return;
const dTag = app.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.kind}:${app.pubkey}:${dTag}`;
try {
if (action === 'homepage' || action === 'unhomepage') {
// Get current homepage apps list
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
);
// Get current homepage app coordinates
const currentHomepageApps = new Set<string>();
if (currentHomepageList) {
currentHomepageList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentHomepageApps.add(tag[1]));
}
// Update the homepage set
if (action === 'homepage') {
currentHomepageApps.add(appCoordinate);
} else {
currentHomepageApps.delete(appCoordinate);
}
// Publish updated homepage apps list
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 adding to homepage, also ensure it's approved
if (action === 'homepage') {
// Get current approved apps list
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
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
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') {
// Get current featured apps list
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
);
// Get current featured app coordinates
const currentFeaturedApps = new Set<string>();
if (currentFeaturedList) {
currentFeaturedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentFeaturedApps.add(tag[1]));
}
// Update the featured set
if (action === 'feature') {
currentFeaturedApps.add(appCoordinate);
} else {
currentFeaturedApps.delete(appCoordinate);
}
// Publish updated featured apps list
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 featuring an app, also ensure it's approved
if (action === 'feature') {
// Get current approved apps list
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
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Add to approved list if not already there
currentApprovedApps.add(appCoordinate);
// Publish updated approved apps list
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') {
// Get current approved apps list
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
);
// Get current approved app coordinates
const currentApprovedApps = new Set<string>();
if (currentApprovedList) {
currentApprovedList.tags
.filter(tag => tag[0] === 'a')
.forEach(tag => currentApprovedApps.add(tag[1]));
}
// Update the approved set
if (action === 'approve') {
currentApprovedApps.add(appCoordinate);
} else {
currentApprovedApps.delete(appCoordinate);
}
// Publish updated approved apps list
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') {
// Create NIP-56 report event
publishEvent({
kind: 1984,
content: `App ${action}den by moderator: "${app.appName}"`,
tags: [
['a', appCoordinate, action === 'hide' ? 'spam' : 'other'],
['p', app.pubkey],
['L', 'soapbox.moderation'],
['l', action === 'hide' ? 'hidden' : 'unhidden', 'soapbox.moderation']
],
created_at: Math.floor(Date.now() / 1000)
});
}
// Invalidate queries to refresh the data
queryClient.invalidateQueries({ queryKey: ['app-submissions'] });
// If this is a Halloween app, also invalidate Halloween queries
if (isHalloweenSubmission) {
queryClient.invalidateQueries({ queryKey: ['halloween-submissions'] });
queryClient.invalidateQueries({ queryKey: ['halloween-submissions-with-contacts'] });
}
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'
});
}
};
return (
<Card className="group hover:shadow-lg transition-all duration-300 hover:border-primary/20 h-full flex flex-col">
<div className="relative">
{/* App Screenshot */}
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
className="block aspect-video bg-gradient-to-br from-muted/50 to-muted rounded-t-lg overflow-hidden cursor-pointer"
>
{!imageError ? (
<img
src={app.screenshotUrl}
alt={`${app.appName} screenshot`}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
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>
)}
</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">
<MoreVertical className="w-4 h-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
{isOwner && (
<DropdownMenuItem onClick={() => onEdit?.(app)}>
<Edit className="w-4 h-4 mr-2" />
Edit App
</DropdownMenuItem>
)}
{showModerationControls && isModerator && (
<>
{isHalloweenSubmission && getContactInfo() && (getContactInfo()?.lightning || getContactInfo()?.email) && (
<DropdownMenuItem
onClick={handleCopyContactInfo}
>
<Contact className="w-4 h-4 mr-2" />
View Contact Info
</DropdownMenuItem>
)}
{!app.isApproved && (
<DropdownMenuItem
onClick={() => handleModerationAction('approve')}
disabled={isPending}
>
<CheckCircle className="w-4 h-4 mr-2" />
Approve
</DropdownMenuItem>
)}
{app.isApproved && !app.isFeatured && (
<DropdownMenuItem
onClick={() => handleModerationAction('unapprove')}
disabled={isPending}
>
<XCircle className="w-4 h-4 mr-2" />
Unapprove
</DropdownMenuItem>
)}
<DropdownMenuItem
onClick={() => handleModerationAction(app.isFeatured ? 'unfeature' : 'feature')}
disabled={isPending}
>
{app.isFeatured ? (
<>
<StarOff className="w-4 h-4 mr-2" />
Un-feature
</>
) : (
<>
<Star className="w-4 h-4 mr-2" />
Feature
</>
)}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => handleModerationAction(app.isHomepage ? 'unhomepage' : 'homepage')}
disabled={isPending}
>
{app.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(app.isHidden ? 'unhide' : 'hide')}
disabled={isPending}
>
{app.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 flex flex-col flex-1">
<div className="flex items-start justify-between mb-3">
<div className="flex items-center gap-3">
{/* App Icon */}
<div className="w-12 h-12 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>
<h3 className="text-xl font-semibold text-foreground mb-1" title={app.appName}>
{app.appName.length > 50 ? `${app.appName.slice(0, 50)}...` : app.appName}
</h3>
</div>
</div>
</div>
<p className="text-muted-foreground mb-3 line-clamp-3">{app.description}</p>
{/* Author Information */}
<div className="flex items-center gap-2 mb-4">
<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 className="text-sm text-muted-foreground">
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>
{/* Spacer to push action links to bottom */}
<div className="flex-1"></div>
{/* Action Links */}
<div className="flex items-center gap-2 mt-auto">
<Link
to={`/clone?url=${encodeURIComponent(app.repositoryUrl)}`}
className="flex-1"
>
<img
src="/badge.svg"
alt="Edit with Shakespeare"
className="h-6 hover:opacity-80 transition-opacity"
/>
</Link>
<Button variant="outline" size="sm" asChild>
<a
href={app.websiteUrl}
target="_blank"
rel="noopener noreferrer"
title="Visit app"
>
<ExternalLink className="w-4 h-4" />
</a>
</Button>
</div>
</CardContent>
</Card>
);
}
@@ -1,152 +0,0 @@
import { describe, it, expect, beforeEach } from 'vitest';
import { renderHook, act } from '@testing-library/react';
import { ReactNode } from 'react';
import { ConsoleErrorProvider } from './ConsoleErrorProvider';
import { useConsoleError } from '@/hooks/useConsoleError';
import { addConsoleMessage, clearConsoleMessages, ProjectPreviewConsoleError } from '@/lib/consoleMessages';
// Wrapper component for testing
function TestWrapper({ children }: { children: ReactNode }) {
return (
<ConsoleErrorProvider>
{children}
</ConsoleErrorProvider>
);
}
describe('ConsoleErrorProvider', () => {
beforeEach(() => {
clearConsoleMessages();
});
it('should provide initial state with no errors', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should update hasErrors when console error is added', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
expect(result.current.hasErrors).toBe(false);
// Add an error message
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.hasErrors).toBe(true);
expect(result.current.consoleError).toBeInstanceOf(ProjectPreviewConsoleError);
expect(result.current.consoleError?.message).toBe('Console error detected: Test error message');
});
it('should not update hasErrors for non-error messages', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add non-error messages
act(() => {
addConsoleMessage('log', 'Test log message');
addConsoleMessage('warn', 'Test warning message');
addConsoleMessage('info', 'Test info message');
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should update consoleError with latest error message', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add first error
act(() => {
addConsoleMessage('error', 'First error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: First error');
// Add second error - should update to show latest error
act(() => {
addConsoleMessage('error', 'Second error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: Second error');
expect(result.current.consoleError?.logs).toHaveLength(2);
});
it('should clear errors when clearErrors is called', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add error to set state
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.hasErrors).toBe(true);
expect(result.current.consoleError).not.toBeNull();
// Clear errors
act(() => {
result.current.clearErrors();
});
expect(result.current.hasErrors).toBe(false);
expect(result.current.consoleError).toBeNull();
});
it('should dismiss console error when dismissConsoleError is called', async () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add error to create console error
act(() => {
addConsoleMessage('error', 'Test error message');
});
expect(result.current.consoleError).not.toBeNull();
// Dismiss console error (this only clears the Quilly error, not the global state)
act(() => {
result.current.dismissConsoleError();
});
expect(result.current.consoleError).toBeNull();
// hasErrors should still be true since we only dismissed the Quilly display
expect(result.current.hasErrors).toBe(true);
});
it('should include all error messages in console error logs', () => {
const { result } = renderHook(() => useConsoleError(), {
wrapper: TestWrapper,
});
// Add multiple errors and non-errors
act(() => {
addConsoleMessage('log', 'Log message');
addConsoleMessage('error', 'First error');
addConsoleMessage('warn', 'Warning message');
addConsoleMessage('error', 'Second error');
addConsoleMessage('info', 'Info message');
addConsoleMessage('error', 'Third error');
});
expect(result.current.consoleError?.message).toBe('Console error detected: Third error');
expect(result.current.consoleError?.logs).toHaveLength(3);
expect(result.current.consoleError?.logs.map(log => log.message)).toEqual([
'First error',
'Second error',
'Third error'
]);
});
});
-63
View File
@@ -1,63 +0,0 @@
import { useState, useEffect, useCallback, ReactNode } from 'react';
import {
addConsoleMessageListener,
removeConsoleMessageListener,
getHasConsoleErrors,
getConsoleMessages,
clearConsoleMessages,
ProjectPreviewConsoleError
} from '@/lib/consoleMessages';
import { ConsoleErrorContext } from '@/contexts/ConsoleErrorContext';
interface ConsoleErrorProviderProps {
children: ReactNode;
}
export function ConsoleErrorProvider({ children }: ConsoleErrorProviderProps) {
const [hasErrors, setHasErrors] = useState(() => getHasConsoleErrors());
const [consoleError, setConsoleError] = useState<ProjectPreviewConsoleError | null>(null);
const updateState = useCallback(() => {
const hasConsoleErrors = getHasConsoleErrors();
setHasErrors(hasConsoleErrors);
if (hasConsoleErrors) {
const errorMessages = getConsoleMessages().filter(msg => msg.level === 'error');
const latestError = errorMessages[errorMessages.length - 1];
setConsoleError(new ProjectPreviewConsoleError(
`Console error detected: ${latestError.message}`,
errorMessages
));
} else {
setConsoleError(null);
}
}, []);
useEffect(() => {
addConsoleMessageListener(updateState);
updateState(); // Initial sync
return () => removeConsoleMessageListener(updateState);
}, [updateState]);
const clearErrors = useCallback(() => {
clearConsoleMessages();
}, []);
const dismissConsoleError = useCallback(() => {
setConsoleError(null);
}, []);
const value = {
hasErrors,
consoleError,
clearErrors,
dismissConsoleError,
};
return (
<ConsoleErrorContext.Provider value={value}>
{children}
</ConsoleErrorContext.Provider>
);
}
-1
View File
@@ -17,7 +17,6 @@ global.fetch = vi.fn();
const mockProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
};
-1
View File
@@ -9,7 +9,6 @@ global.fetch = vi.fn();
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
File diff suppressed because it is too large. Load diff
+131 -608
View File
@@ -1,659 +1,182 @@
import { useState, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ExternalLink, AlertCircle } from 'lucide-react';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { useState, useEffect } from 'react';
import {
Dialog,
DialogContent,
DialogDescription,
DialogHeader,
DialogTitle,
DialogFooter,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Alert, AlertDescription } from '@/components/ui/alert';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DenoDeployAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider, DenoDeployProvider } from '@/contexts/DeploySettingsContext';
import { ShakespeareDeployForm } from '@/components/deploy/ShakespeareDeployForm';
import { NetlifyDeployForm } from '@/components/deploy/NetlifyDeployForm';
import { VercelDeployForm } from '@/components/deploy/VercelDeployForm';
import { NsiteDeployForm } from '@/components/deploy/NsiteDeployForm';
import { CloudflareDeployForm } from '@/components/deploy/CloudflareDeployForm';
import { DenoDeployForm } from '@/components/deploy/DenoDeployForm';
/**
* Helper function to get provider URL for favicon
*/
function getProviderUrl(provider: DeployProvider): string | null {
switch (provider.type) {
case 'shakespeare':
if (provider.host) {
return `https://${provider.host}`;
}
return 'https://shakespeare.diy';
case 'netlify':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://netlify.com';
case 'vercel':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://vercel.com';
case 'cloudflare':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://cloudflare.com';
case 'deno':
if (provider.baseURL) {
return provider.baseURL;
}
return 'https://deno.com';
case 'nsite':
return null;
default:
return null;
}
}
/**
* Render provider icon using favicon or fallback
*/
function renderProviderIcon(provider: DeployProvider, size = 14) {
const url = getProviderUrl(provider);
if (url) {
return (
<ExternalFavicon
url={url}
size={size}
fallback={<Rocket size={size} />}
/>
);
}
return <Rocket size={size} />;
}
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useMutation } from '@tanstack/react-query';
import { deployProject } from '@/lib/deploy';
import { useFS } from '@/hooks/useFS';
import {
CloudUpload,
Loader2,
} from 'lucide-react';
interface DeployDialogProps {
projectId: string;
projectName: string;
open: boolean;
onOpenChange: (open: boolean) => void;
onFirstInteraction?: () => void;
}
interface ShakespeareFormData {
subdomain: string;
}
interface NsiteFormData {
nsec: string;
}
interface NetlifyFormData {
siteId: string;
siteName: string;
}
interface VercelFormData {
projectName: string;
teamId: string;
}
interface CloudflareFormData {
projectName: string;
}
interface DenoDeployFormData {
projectName: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
const { settings: projectSettings, updateSettings: updateProjectSettings } = useProjectDeploySettings(projectId);
export function DeployDialog({
projectId,
projectName,
open,
onOpenChange,
onFirstInteraction
}: DeployDialogProps) {
const { config } = useAppContext();
const { user } = useCurrentUser();
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const { config } = useAppContext();
const { nostr } = useNostr();
const { toast } = useToast();
const [selectedProviderId, setSelectedProviderId] = useState<string>('');
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);
// State for the deploy URL input
const [deployUrl, setDeployUrl] = useState('');
// Provider-specific form data
const [shakespeareForm, setShakespeareForm] = useState<ShakespeareFormData>({
subdomain: projectId,
});
const [nsiteForm, setNsiteForm] = useState<NsiteFormData>({
nsec: '',
});
const [netlifyForm, setNetlifyForm] = useState<NetlifyFormData>({
siteId: '',
siteName: '',
});
const [vercelForm, setVercelForm] = useState<VercelFormData>({
projectName: projectName || projectId,
teamId: '',
});
const [cloudflareForm, setCloudflareForm] = useState<CloudflareFormData>({
projectName: projectName || projectId,
});
const [denoDeployForm, setDenoDeployForm] = useState<DenoDeployFormData>({
projectName: projectName || projectId,
});
// Load project settings when dialog opens
// Initialize deploy URL when dialog opens
useEffect(() => {
if (open) {
// First, try to use the currentProvider from project settings
if (projectSettings.currentProvider && settings.providers.some(p => p.id === projectSettings.currentProvider)) {
setSelectedProviderId(projectSettings.currentProvider);
} else {
// Otherwise, find the first configured provider in project settings
const providerIds = Object.keys(projectSettings.providers);
if (providerIds.length > 0) {
setSelectedProviderId(providerIds[0]);
}
}
setDeployUrl(`${projectId}.${config.deployServer}`);
}
}, [open, projectSettings, settings.providers]);
}, [open, projectId, config.deployServer]);
const selectedProvider = settings.providers.find(p => p.id === selectedProviderId);
const handleDeploy = async () => {
if (!selectedProvider) return;
setIsDeploying(true);
setError(null);
setDeployResult(null);
try {
const projectPath = `${projectsPath}/${projectId}`;
let adapter: DeployAdapter;
if (selectedProvider.type === 'shakespeare') {
if (!user) {
throw new Error('You must be logged in with Nostr to use Shakespeare Deploy');
}
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
adapter = new ShakespeareAdapter({
fs,
signer: user.signer,
host: shakespeareProvider.host,
subdomain: shakespeareForm.subdomain || undefined,
corsProxy: shakespeareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'nsite') {
const nsiteProvider = selectedProvider as import('@/contexts/DeploySettingsContext').NsiteProvider;
if (!nsiteForm.nsec) {
throw new Error('Site private key (nsec) is required');
}
adapter = new NsiteAdapter({
fs,
nostr,
nsec: nsiteForm.nsec,
gateway: nsiteProvider.gateway,
relayUrls: nsiteProvider.relayUrls,
blossomServers: nsiteProvider.blossomServers,
});
} else if (selectedProvider.type === 'netlify') {
const netlifyProvider = selectedProvider as NetlifyProvider;
if (!netlifyProvider.apiKey) {
throw new Error('Netlify API key is required');
}
// If siteId is empty, we're creating a new site, so only pass siteName
// If siteId is set, we're updating an existing site
adapter = new NetlifyAdapter({
fs,
apiKey: netlifyProvider.apiKey,
baseURL: netlifyProvider.baseURL,
siteName: netlifyForm.siteId ? undefined : (netlifyForm.siteName || undefined),
siteId: netlifyForm.siteId || undefined,
corsProxy: netlifyProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'vercel') {
const vercelProvider = selectedProvider as VercelProvider;
if (!vercelProvider.apiKey) {
throw new Error('Vercel API key is required');
}
adapter = new VercelAdapter({
fs,
apiKey: vercelProvider.apiKey,
baseURL: vercelProvider.baseURL,
teamId: vercelForm.teamId || undefined,
projectName: vercelForm.projectName || undefined,
corsProxy: vercelProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'cloudflare') {
const cloudflareProvider = selectedProvider as CloudflareProvider;
if (!cloudflareProvider.apiKey) {
throw new Error('Cloudflare API key is required');
}
if (!cloudflareProvider.accountId) {
throw new Error('Cloudflare account ID is required');
}
adapter = new CloudflareAdapter({
fs,
apiKey: cloudflareProvider.apiKey,
accountId: cloudflareProvider.accountId,
baseURL: cloudflareProvider.baseURL,
baseDomain: cloudflareProvider.baseDomain,
projectName: cloudflareForm.projectName || undefined,
corsProxy: cloudflareProvider.proxy ? config.corsProxy : undefined,
});
} else if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider as DenoDeployProvider;
if (!denoProvider.apiKey) {
throw new Error('Deno Deploy access token is required');
}
if (!denoProvider.organizationId) {
throw new Error('Deno Deploy organization ID is required');
}
adapter = new DenoDeployAdapter({
fs,
apiKey: denoProvider.apiKey,
organizationId: denoProvider.organizationId,
baseDomain: denoProvider.baseDomain,
baseURL: denoProvider.baseURL,
projectName: denoDeployForm.projectName || undefined,
corsProxy: denoProvider.proxy ? config.corsProxy : undefined,
});
} else {
throw new Error('Unknown provider type');
const deployMutation = useMutation({
mutationFn: async () => {
if (!user) {
throw new Error("You must be logged into Nostr to deploy a project");
}
const result = await adapter.deploy({
projectId,
projectPath,
// Parse the deploy URL to extract hostname and server
const hostname = deployUrl.trim();
const parts = hostname.split('.');
if (parts.length < 2) {
throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com");
}
// Extract the deploy server (everything after the first dot)
const deployServer = parts.slice(1).join('.');
return await deployProject({
fs,
projectId, // Keep the original projectId for file path
deployServer,
projectPath: `/projects/${projectId}`,
signer: user.signer,
customHostname: hostname, // Pass the custom hostname
});
},
onSuccess: (result) => {
toast({
title: "Deployment successful!",
description: `Your project is now live at ${result.hostname}`,
});
// Save project-specific settings (updateSettings now automatically sets currentProvider)
if (selectedProvider.type === 'shakespeare') {
await updateProjectSettings(selectedProviderId, {
type: 'shakespeare',
data: {
subdomain: shakespeareForm.subdomain || undefined,
},
});
} else if (selectedProvider.type === 'nsite') {
await updateProjectSettings(selectedProviderId, {
type: 'nsite',
data: {
nsec: nsiteForm.nsec,
},
});
} else if (selectedProvider.type === 'netlify') {
await updateProjectSettings(selectedProviderId, {
type: 'netlify',
data: {
siteId: result.metadata?.siteId as string | undefined,
},
});
} else if (selectedProvider.type === 'vercel') {
await updateProjectSettings(selectedProviderId, {
type: 'vercel',
data: {
teamId: vercelForm.teamId || undefined,
projectId: vercelForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'cloudflare') {
await updateProjectSettings(selectedProviderId, {
type: 'cloudflare',
data: {
projectName: cloudflareForm.projectName || undefined,
},
});
} else if (selectedProvider.type === 'deno') {
await updateProjectSettings(selectedProviderId, {
type: 'deno',
data: {
projectName: denoDeployForm.projectName || undefined,
},
});
}
// Open the deployed site in a new tab
window.open(result.url, '_blank');
setDeployResult(result);
} catch (err) {
setError(err instanceof Error ? err.message : 'Deployment failed');
} finally {
setIsDeploying(false);
// Close the dialog
onOpenChange(false);
},
onError: (error) => {
toast({
title: "Deployment failed",
description: error instanceof Error ? error.message : "An unexpected error occurred",
variant: "destructive",
});
},
});
const handleDeploy = () => {
if (onFirstInteraction) {
onFirstInteraction();
}
deployMutation.mutate();
};
const handleClose = () => {
setSelectedProviderId('');
setDeployResult(null);
setError(null);
// Reset forms
setShakespeareForm({ subdomain: projectId });
setNsiteForm({ nsec: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
onOpenChange(false);
const handleUrlChange = (value: string) => {
// Remove protocol if user enters it
const cleanValue = value.replace(/^https?:\/\//, '');
setDeployUrl(cleanValue);
};
const handleShakespeareSubdomainChange = useCallback((subdomain: string) => {
setShakespeareForm({ subdomain });
}, []);
const handleShakespeareValidationChange = useCallback((isValid: boolean) => {
setIsShakespeareFormValid(isValid);
}, []);
const handleNsiteNsecChange = useCallback((nsec: string) => {
setNsiteForm({ nsec });
}, []);
const handleNetlifySiteChange = useCallback((siteId: string, siteName: string) => {
setNetlifyForm({ siteId, siteName });
}, []);
const handleVercelConfigChange = useCallback((projectName: string, teamId: string) => {
setVercelForm({ projectName, teamId });
}, []);
const handleCloudflareProjectChange = useCallback((projectName: string) => {
setCloudflareForm({ projectName });
}, []);
const handleDenoDeployProjectChange = useCallback((projectName: string) => {
setDenoDeployForm({ projectName });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
if (selectedProvider.type === 'shakespeare') {
const shakespeareProvider = selectedProvider as ShakespeareDeployProvider;
return (
<ShakespeareDeployForm
host={shakespeareProvider.host}
projectId={projectId}
onSubdomainChange={handleShakespeareSubdomainChange}
onValidationChange={handleShakespeareValidationChange}
/>
);
}
if (selectedProvider.type === 'nsite') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedNsec = savedConfig?.type === 'nsite' ? savedConfig.data.nsec : undefined;
return (
<NsiteDeployForm
gateway={selectedProvider.gateway}
savedNsec={savedNsec}
onNsecChange={handleNsiteNsecChange}
/>
);
}
if (selectedProvider.type === 'netlify') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedSiteId = savedConfig?.type === 'netlify' ? savedConfig.data.siteId : undefined;
return (
<NetlifyDeployForm
apiKey={selectedProvider.apiKey}
baseURL={selectedProvider.baseURL}
projectId={projectId}
projectName={projectName}
savedSiteId={savedSiteId}
onSiteChange={handleNetlifySiteChange}
corsProxy={selectedProvider.proxy ? config.corsProxy : undefined}
/>
);
}
if (selectedProvider.type === 'vercel') {
const savedConfig = projectSettings.providers[selectedProviderId];
const savedTeamId = savedConfig?.type === 'vercel' ? savedConfig.data.teamId : undefined;
const savedProjectName = savedConfig?.type === 'vercel' ? savedConfig.data.projectId : undefined;
return (
<VercelDeployForm
projectId={projectId}
projectName={projectName}
savedTeamId={savedTeamId}
savedProjectName={savedProjectName}
onConfigChange={handleVercelConfigChange}
/>
);
}
if (selectedProvider.type === 'cloudflare') {
const cloudflareProvider = selectedProvider as CloudflareProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedProjectName = savedConfig?.type === 'cloudflare' ? savedConfig.data.projectName : undefined;
return (
<CloudflareDeployForm
apiKey={cloudflareProvider.apiKey}
accountId={cloudflareProvider.accountId}
baseURL={cloudflareProvider.baseURL}
baseDomain={cloudflareProvider.baseDomain}
projectId={projectId}
projectName={projectName}
savedProjectName={savedProjectName}
onProjectChange={handleCloudflareProjectChange}
corsProxy={cloudflareProvider.proxy ? config.corsProxy : undefined}
/>
);
}
if (selectedProvider.type === 'deno') {
const denoProvider = selectedProvider as DenoDeployProvider;
const savedConfig = projectSettings.providers[selectedProviderId];
const savedProjectName = savedConfig?.type === 'deno' ? savedConfig.data.projectName : undefined;
return (
<DenoDeployForm
apiKey={denoProvider.apiKey}
organizationId={denoProvider.organizationId}
baseURL={denoProvider.baseURL}
baseDomain={denoProvider.baseDomain}
projectId={projectId}
projectName={projectName}
savedProjectName={savedProjectName}
onProjectChange={handleDenoDeployProjectChange}
corsProxy={denoProvider.proxy ? config.corsProxy : undefined}
/>
);
}
return null;
const isValidUrl = () => {
const trimmed = deployUrl.trim();
return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.');
};
return (
<Dialog open={open} onOpenChange={handleClose}>
<DialogContent className="sm:max-w-[500px]">
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Rocket className="h-5 w-5" />
Deploy Project
<CloudUpload className="h-5 w-5" />
Deploy "{projectName}"
</DialogTitle>
<DialogDescription>
Deploy your project to a hosting platform
</DialogDescription>
</DialogHeader>
{deployResult ? (
<div className="space-y-4">
<Alert>
<Rocket className="h-4 w-4" />
<AlertDescription>
Your project has been successfully deployed!
</AlertDescription>
</Alert>
<div className="space-y-2">
<Label>Deployed URL</Label>
<div className="flex gap-2">
<Input
value={deployResult.url}
readOnly
className="flex-1"
/>
<Button
size="sm"
variant="outline"
onClick={() => window.open(deployResult.url, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<div className="flex justify-end gap-2">
<Button onClick={handleClose}>
{t('close')}
</Button>
<div className="space-y-4">
<div className="space-y-2">
<Label htmlFor="deploy-url">Deploy URL</Label>
<div className="relative">
<span className="absolute left-3 top-1/2 -translate-y-1/2 text-sm text-muted-foreground">
https://
</span>
<Input
id="deploy-url"
value={deployUrl}
onChange={(e) => handleUrlChange(e.target.value)}
placeholder={`${projectId}.${config.deployServer}`}
className="pl-16"
disabled={deployMutation.isPending}
/>
</div>
<p className="text-xs text-muted-foreground">
Your project will be deployed to this URL. You can customize the subdomain.
</p>
</div>
) : (
<div className="space-y-4">
{settings.providers.length === 0 ? (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
No deployment providers configured.{' '}
<Link
to="/settings/deploy"
className="underline hover:no-underline"
onClick={handleClose}
>
Configure deployment settings
</Link>
</AlertDescription>
</Alert>
{!user && (
<div className="p-3 bg-muted rounded-lg">
<p className="text-sm text-muted-foreground">
You must be logged into Nostr to deploy projects.
</p>
</div>
)}
</div>
<DialogFooter>
<Button
variant="outline"
onClick={() => onOpenChange(false)}
disabled={deployMutation.isPending}
>
Cancel
</Button>
<Button
onClick={handleDeploy}
disabled={!user || !isValidUrl() || deployMutation.isPending}
className="gap-2"
>
{deployMutation.isPending ? (
<Loader2 className="h-4 w-4 animate-spin" />
) : (
<>
<div className="space-y-2">
<Label htmlFor="provider">Select Provider</Label>
<Select value={selectedProviderId} onValueChange={setSelectedProviderId}>
<SelectTrigger id="provider">
{selectedProvider ? (
<div className="flex items-center gap-2">
{renderProviderIcon(selectedProvider, 14)}
<span>{selectedProvider.name}</span>
</div>
) : (
<SelectValue placeholder="Choose a deployment provider..." />
)}
</SelectTrigger>
<SelectContent>
{settings.providers.map((provider) => (
<SelectItem key={provider.id} value={provider.id}>
<div className="flex items-center gap-2">
{renderProviderIcon(provider, 14)}
<span>{provider.name}</span>
</div>
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProvider && renderProviderFields()}
{selectedProvider?.type === 'shakespeare' && !user && (
<Alert>
<AlertCircle className="h-4 w-4" />
<AlertDescription>
You must be logged in with Nostr to use Shakespeare Deploy.{' '}
<Link
to="/settings/nostr"
className="underline hover:no-underline"
onClick={handleClose}
>
Go to Nostr Settings
</Link>
</AlertDescription>
</Alert>
)}
{error && (
<Alert variant="destructive">
<AlertCircle className="h-4 w-4" />
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="flex justify-end gap-2">
<Button variant="outline" onClick={handleClose}>
{t('cancel')}
</Button>
<Button
onClick={handleDeploy}
disabled={
!selectedProvider ||
isDeploying ||
(selectedProvider.type === 'shakespeare' && !user) ||
(selectedProvider.type === 'shakespeare' && !isShakespeareFormValid) ||
(selectedProvider.type === 'nsite' && !nsiteForm.nsec) ||
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName) ||
(selectedProvider.type === 'cloudflare' && !cloudflareForm.projectName) ||
(selectedProvider.type === 'deno' && !denoDeployForm.projectName)
}
>
{isDeploying ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white mr-2"></div>
Deploying...
</>
) : (
<>
<Rocket className="h-4 w-4 mr-2" />
Deploy
</>
)}
</Button>
</div>
</>
<CloudUpload className="h-4 w-4" />
)}
</div>
)}
{deployMutation.isPending ? 'Deploying...' : 'Deploy'}
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
}
-82
View File
@@ -1,82 +0,0 @@
import { useState, useEffect, useMemo, type ReactNode } from 'react';
import { DeploySettingsContext, type DeploySettings, type DeployProvider } from '@/contexts/DeploySettingsContext';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readDeploySettings, writeDeploySettings } from '@/lib/configUtils';
const DEFAULT_SETTINGS: DeploySettings = {
providers: [],
};
export function DeploySettingsProvider({ children }: { children: ReactNode }) {
const { fs } = useFS();
const { configPath } = useFSPaths();
const [settings, setSettings] = useState<DeploySettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
// Initialize settings from VFS on mount
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readDeploySettings(fs, configPath);
setSettings(settings);
} catch (error) {
console.error('Failed to initialize deploy settings:', error);
setSettings(DEFAULT_SETTINGS);
} finally {
setIsInitialized(true);
}
};
initializeSettings();
}, [fs, configPath]);
// Save settings to VFS whenever they change (but not during initialization)
useEffect(() => {
if (!isInitialized) return;
const saveSettings = async () => {
try {
await writeDeploySettings(fs, settings, configPath);
} catch (error) {
console.error('Failed to save deploy settings:', error);
}
};
saveSettings();
}, [fs, settings, isInitialized, configPath]);
const updateSettings = (updates: Partial<DeploySettings>) => {
setSettings(prev => ({ ...prev, ...updates }));
};
const removeProvider = (index: number) => {
setSettings(prev => ({
...prev,
providers: prev.providers.filter((_, i) => i !== index),
}));
};
const setProviders = (providers: DeployProvider[]) => {
setSettings(prev => ({ ...prev, providers }));
};
const isConfigured = useMemo(() => {
return settings.providers.length > 0;
}, [settings.providers]);
const value = {
settings,
updateSettings,
removeProvider,
setProviders,
isConfigured,
isInitialized,
};
return (
<DeploySettingsContext.Provider value={value}>
{children}
</DeploySettingsContext.Provider>
);
}
-151
View File
@@ -1,151 +0,0 @@
import { useEffect, useRef } from 'react';
import { useAnyProjectBusy } from '@/hooks/useAnyProjectBusy';
/**
* Component that dynamically updates the favicon when any project is busy with AI
* Rotates the favicon counter-clockwise when busy
*/
export function DynamicFavicon() {
const isBusy = useAnyProjectBusy();
const canvasRef = useRef<HTMLCanvasElement | null>(null);
const animationRef = useRef<number | null>(null);
const rotationRef = useRef(0);
const originalFaviconRef = useRef<string | null>(null);
const originalImageRef = useRef<HTMLImageElement | null>(null);
// Initialize canvas and save original favicon
useEffect(() => {
// Create canvas element for drawing the favicon
if (!canvasRef.current) {
canvasRef.current = document.createElement('canvas');
canvasRef.current.width = 32;
canvasRef.current.height = 32;
}
// Store the original favicon URL
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement && !originalFaviconRef.current) {
originalFaviconRef.current = faviconElement.getAttribute('href');
}
// Preload the favicon image
if (!originalImageRef.current) {
const img = new Image();
img.crossOrigin = 'anonymous';
img.src = originalFaviconRef.current || '/shakespeare-192x192.png';
img.onload = () => {
originalImageRef.current = img;
};
}
return () => {
// Restore original favicon on unmount
if (originalFaviconRef.current) {
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', originalFaviconRef.current);
}
}
// Cancel any ongoing animation
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
}
};
}, []);
// Handle busy state changes
useEffect(() => {
if (!canvasRef.current) return;
// If busy, start rotation animation
if (isBusy) {
const startRotationAnimation = () => {
if (!canvasRef.current || !originalImageRef.current) {
// If image isn't loaded yet, try again in a moment
setTimeout(startRotationAnimation, 100);
return;
}
const canvas = canvasRef.current;
const ctx = canvas.getContext('2d');
if (!ctx) return;
const img = originalImageRef.current;
const animate = () => {
if (!ctx || !canvas) return;
// Clear canvas
ctx.clearRect(0, 0, canvas.width, canvas.height);
// Save context state
ctx.save();
// Translate to center for rotation
ctx.translate(canvas.width / 2, canvas.height / 2);
// Rotate counter-clockwise
ctx.rotate(-rotationRef.current);
// Draw the image centered
ctx.drawImage(
img,
-canvas.width / 2,
-canvas.height / 2,
canvas.width,
canvas.height
);
// Restore context state
ctx.restore();
// Update rotation for next frame (slower rotation)
rotationRef.current += 0.05;
// Update favicon
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', canvas.toDataURL('image/png'));
}
// Continue animation
animationRef.current = requestAnimationFrame(animate);
};
// Start animation loop
animate();
};
startRotationAnimation();
} else {
// If not busy, restore original favicon and stop animation
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
// Reset rotation
rotationRef.current = 0;
// Restore original favicon
if (originalFaviconRef.current) {
const faviconElement = document.querySelector('link[rel="icon"]');
if (faviconElement) {
faviconElement.setAttribute('href', originalFaviconRef.current);
}
}
}
return () => {
// Cancel animation on effect cleanup
if (animationRef.current !== null) {
cancelAnimationFrame(animationRef.current);
animationRef.current = null;
}
};
}, [isBusy]);
// This component doesn't render anything visible
return null;
}
-204
View File
@@ -1,204 +0,0 @@
import { useState, useEffect } from 'react';
import { Mail, CheckCircle } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useToast } from '@/hooks/useToast';
import { nip19 } from 'nostr-tools';
export function EmailSubscription() {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { toast } = useToast();
const [email, setEmail] = useState('');
const [isSubmitting, setIsSubmitting] = useState(false);
const [isSubmitted, setIsSubmitted] = useState(false);
const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0');
const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`;
const tag = '8982396';
// Check localStorage on component mount
useEffect(() => {
const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed');
if (hasSubscribed === 'true') {
setIsSubmitted(true);
}
}, []);
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault();
if (!email.trim()) {
toast({
title: "Email required",
description: "Please enter your email address",
variant: "destructive",
});
return;
}
// Basic email validation
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
if (!emailRegex.test(email)) {
toast({
title: "Invalid email",
description: "Please enter a valid email address",
variant: "destructive",
});
return;
}
setIsSubmitting(true);
try {
// Submit to Mailchimp
const form = document.createElement('form');
form.method = 'POST';
form.action = url.href;
form.target = '_blank'; // Open in new tab
form.style.display = 'none';
// Add email field
const emailInput = document.createElement('input');
emailInput.type = 'email';
emailInput.name = 'EMAIL';
emailInput.value = email.trim();
form.appendChild(emailInput);
// Add tag field with the new Shakespeare tag ID
const tagInput = document.createElement('input');
tagInput.type = 'hidden';
tagInput.name = 'tags';
tagInput.value = tag;
form.appendChild(tagInput);
// Add npub if available
if (user?.pubkey) {
const npubInput = document.createElement('input');
npubInput.type = 'text';
npubInput.name = 'NPUB';
npubInput.value = nip19.npubEncode(user.pubkey);
npubInput.style.display = 'none';
form.appendChild(npubInput);
}
// Add honeypot field
const honeypotInput = document.createElement('input');
honeypotInput.type = 'text';
honeypotInput.name = honeypot;
honeypotInput.tabIndex = -1;
honeypotInput.style.position = 'absolute';
honeypotInput.style.left = '-5000px';
form.appendChild(honeypotInput);
// Add form to document and submit
document.body.appendChild(form);
form.submit();
// Clean up after a short delay
setTimeout(() => {
document.body.removeChild(form);
}, 1000);
// Save subscription status to localStorage
localStorage.setItem('shakespeare-email-subscribed', 'true');
setIsSubmitted(true);
toast({
title: "Successfully subscribed!",
description: "You'll receive Shakespeare updates and resources occasionally.",
});
} catch (error) {
console.error('Email signup error:', error);
toast({
title: "Subscription failed",
description: "There was an error subscribing you to updates. Please try again.",
variant: "destructive",
});
} finally {
setIsSubmitting(false);
}
};
if (isSubmitted) {
return (
<Card>
<CardContent className="pt-6">
<div className="text-center space-y-4">
<CheckCircle className="h-12 w-12 mx-auto text-green-500" />
<div className="space-y-2">
<h3 className="text-lg font-semibold">
Thanks for subscribing!
</h3>
<p className="text-muted-foreground text-sm">
You can opt out at any time using the unsubscribe link in our emails.
</p>
</div>
<Button
onClick={() => {
localStorage.removeItem('shakespeare-email-subscribed');
setIsSubmitted(false);
setEmail('');
}}
variant="outline"
className="w-full text-xs"
>
Subscribe with different email
</Button>
</div>
</CardContent>
</Card>
);
}
return (
<Card>
<CardHeader>
<CardTitle className="text-lg flex items-center gap-2">
<Mail className="h-5 w-5 text-primary" />
{t('emailUpdates')}
</CardTitle>
<CardDescription>
{t('emailUpdatesDescription')}
</CardDescription>
</CardHeader>
<CardContent>
<form onSubmit={handleSubmit} className="space-y-4">
<div className="space-y-2">
<Label htmlFor="email">
Email Address
</Label>
<Input
id="email"
type="email"
placeholder="[email protected]"
value={email}
onChange={(e) => setEmail(e.target.value)}
disabled={isSubmitting}
required
/>
</div>
<div className="space-y-3">
<Button
type="submit"
className="w-full"
disabled={isSubmitting}
>
{isSubmitting ? 'Subscribing...' : 'Subscribe to Updates'}
</Button>
<p className="text-xs text-muted-foreground text-center">
You can opt out at any time using the unsubscribe link in our emails.
</p>
</div>
</form>
</CardContent>
</Card>
);
}
-113
View File
@@ -1,113 +0,0 @@
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen } from '@testing-library/react';
import { ErrorBoundary } from './ErrorBoundary';
// Component that throws an error
function ThrowError({ shouldThrow }: { shouldThrow: boolean }) {
if (shouldThrow) {
throw new Error('Test error message');
}
return <div>No error</div>;
}
describe('ErrorBoundary', () => {
// Suppress console.error during tests to avoid noise
const originalError = console.error;
beforeEach(() => {
console.error = vi.fn();
});
afterEach(() => {
console.error = originalError;
});
it('renders children when there is no error', () => {
render(
<ErrorBoundary>
<div>Test content</div>
</ErrorBoundary>
);
expect(screen.getByText('Test content')).toBeInTheDocument();
});
it('renders error UI when child component throws', () => {
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Something went wrong')).toBeInTheDocument();
expect(screen.getByText('Test error message')).toBeInTheDocument();
});
it('renders custom fallback when provided as ReactNode', () => {
const customFallback = <div>Custom error UI</div>;
render(
<ErrorBoundary fallback={customFallback}>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Custom error UI')).toBeInTheDocument();
});
it('renders custom fallback when provided as function', () => {
const customFallback = ({ error }: { error: Error }) => (
<div>Error: {error.message}</div>
);
render(
<ErrorBoundary fallback={customFallback}>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Error: Test error message')).toBeInTheDocument();
});
it('calls onError callback when error occurs', () => {
const onError = vi.fn();
render(
<ErrorBoundary onError={onError}>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(onError).toHaveBeenCalledWith(
expect.any(Error),
expect.objectContaining({
componentStack: expect.any(String),
})
);
});
it('shows action buttons in error state', () => {
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByRole('button', { name: /reload page/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /go home/i })).toBeInTheDocument();
});
it('shows stack trace in development mode', () => {
const originalEnv = process.env.NODE_ENV;
process.env.NODE_ENV = 'development';
render(
<ErrorBoundary>
<ThrowError shouldThrow={true} />
</ErrorBoundary>
);
expect(screen.getByText('Stack Trace')).toBeInTheDocument();
process.env.NODE_ENV = originalEnv;
});
});
-131
View File
@@ -1,131 +0,0 @@
import { ReactNode } from 'react';
import { ErrorBoundary as ReactErrorBoundary, FallbackProps } from 'react-error-boundary';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardFooter, CardHeader, CardTitle } from '@/components/ui/card';
import { Alert, AlertDescription, AlertTitle } from '@/components/ui/alert';
import { AlertTriangle, RefreshCw, Home } from 'lucide-react';
import { getSentryInstance } from '@/lib/sentry';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: ReactNode | ((props: FallbackProps) => ReactNode);
onError?: (error: Error, info: { componentStack: string | null }) => void;
/** Whether to report errors to Sentry (default: true) */
reportToSentry?: boolean;
}
/**
* Default error fallback component
*/
function ErrorFallback({ error }: FallbackProps) {
const handleReload = () => {
window.location.reload();
};
const handleGoHome = () => {
window.location.href = '/';
};
return (
<div className="min-h-screen flex items-center justify-center p-4 bg-background">
<Card className="max-w-2xl w-full">
<CardHeader>
<div className="flex items-center gap-3">
<div className="p-2 bg-destructive/10 rounded-full">
<AlertTriangle className="h-6 w-6 text-destructive" />
</div>
<div>
<CardTitle className="text-2xl">Something went wrong</CardTitle>
<CardDescription className="mt-1">
We encountered an unexpected error. Don't worry, your data is safe.
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent className="space-y-4">
<Alert variant="destructive">
<AlertTriangle className="h-4 w-4" />
<AlertTitle>Error Details</AlertTitle>
<AlertDescription className="mt-2 font-mono text-xs break-all">
{error.message}
</AlertDescription>
</Alert>
{process.env.NODE_ENV === 'development' && error.stack && (
<details className="mt-4">
<summary className="cursor-pointer text-sm font-medium mb-2">
Stack Trace
</summary>
<pre className="text-xs bg-muted p-4 rounded-md overflow-auto max-h-64">
{error.stack}
</pre>
</details>
)}
</CardContent>
<CardFooter className="flex flex-wrap gap-2">
<Button onClick={handleReload} variant="outline" className="gap-2">
<RefreshCw className="h-4 w-4" />
Reload Page
</Button>
<Button onClick={handleGoHome} variant="outline" className="gap-2">
<Home className="h-4 w-4" />
Go Home
</Button>
</CardFooter>
</Card>
</div>
);
}
/**
* Error Boundary component that catches React rendering errors and displays a fallback UI.
* Prevents the entire app from crashing when a component throws an error.
*
* Built on top of react-error-boundary for robust error handling.
*/
export function ErrorBoundary({
children,
fallback,
onError,
reportToSentry = true,
}: ErrorBoundaryProps) {
const handleError = (error: Error, info: { componentStack: string | null }) => {
// Log error details for debugging
console.error('ErrorBoundary caught an error:', error, info);
// Report to Sentry if enabled
if (reportToSentry) {
const Sentry = getSentryInstance();
if (Sentry) {
Sentry.captureException(error, {
contexts: {
react: {
componentStack: info.componentStack,
},
},
});
}
}
// Call optional error handler
onError?.(error, info);
};
// Determine fallback render
const fallbackRender = typeof fallback === 'function'
? fallback
: fallback
? () => fallback
: ErrorFallback;
return (
<ReactErrorBoundary
fallbackRender={fallbackRender}
onError={handleError}
>
{children}
</ReactErrorBoundary>
);
}
-72
View File
@@ -1,72 +0,0 @@
import { useAppContext } from '@/hooks/useAppContext';
import { faviconUrl, normalizeUrl } from '@/lib/faviconUrl';
import { cn } from '@/lib/utils';
import { ReactNode, useMemo } from 'react';
interface ExternalFaviconProps {
/** The URL to fetch the favicon for */
url: string;
/** Size of the favicon in pixels */
size?: number;
/** Fallback element to display if favicon fails to load */
fallback?: ReactNode;
/** Additional CSS classes */
className?: string;
}
/**
* ExternalFavicon component that fetches and displays a favicon for a given URL
* using the configurable favicon service from app settings.
*/
export function ExternalFavicon({
url,
size = 16,
fallback,
className = '',
}: ExternalFaviconProps) {
const { config } = useAppContext();
// Generate the favicon URL using the configured template
const faviconSrc = useMemo(() => {
try {
// Normalize the URL to ensure it has a protocol
const normalizedUrl = normalizeUrl(url);
return faviconUrl(config.faviconUrl, normalizedUrl);
} catch {
return;
}
}, [url, config.faviconUrl]);
// 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={cn('inline-flex items-center justify-center', className)}>
<img
src={faviconSrc}
alt=""
className="object-contain"
style={{ width: size, height: size }}
onError={(e) => {
// Hide the image and show the fallback on error
e.currentTarget.style.display = 'none';
const fallbackElement = e.currentTarget.nextElementSibling as HTMLElement;
if (fallbackElement) {
fallbackElement.style.display = 'inline-block';
}
}}
/>
{fallback && (
<span style={{ display: 'none' }}>
{fallback}
</span>
)}
</span>
);
}
-91
View File
@@ -1,91 +0,0 @@
import { useState, useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { MessageCircle, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext';
import { useIsMobile } from '@/hooks/useIsMobile';
import { cn } from '@/lib/utils';
export function FloatingChatButton() {
const { isOpen, setIsOpen, hasUnread } = useGlobalChat();
const { config } = useAppContext();
const location = useLocation();
const isMobile = useIsMobile();
const [isHovered, setIsHovered] = useState(false);
const [isHiddenTemporarily, setIsHiddenTemporarily] = useState(false);
// Reset hidden state when navigating to a different page
useEffect(() => {
setIsHiddenTemporarily(false);
}, [location.pathname]);
// Don't render if disabled in settings
if (config.globalChatEnabled === false) {
return null;
}
// Don't render on settings pages
if (location.pathname.startsWith('/settings')) {
return null;
}
// On mobile, only show on home screen (/ or /giftcard)
const isHomePage = location.pathname === '/' || location.pathname === '/giftcard';
if (isMobile && !isHomePage) {
return null;
}
// Don't render if temporarily hidden
if (isHiddenTemporarily) {
return null;
}
const handleClose = (e: React.MouseEvent) => {
e.stopPropagation();
setIsHiddenTemporarily(true);
};
return (
<div
className="fixed bottom-6 right-6 z-40"
onMouseEnter={() => setIsHovered(true)}
onMouseLeave={() => setIsHovered(false)}
>
{/* Main chat button */}
<Button
onClick={() => setIsOpen(!isOpen)}
size="lg"
className={cn(
'h-14 w-14 rounded-full shadow-lg',
'bg-primary hover:bg-primary/90 text-primary-foreground',
'transition-all duration-200 hover:scale-105',
'flex items-center justify-center p-0',
isOpen && 'ring-2 ring-ring ring-offset-2'
)}
aria-label={isOpen ? 'Close chat' : 'Open chat'}
>
<MessageCircle className="h-6 w-6" />
{/* Unread indicator - small dot when there are unread messages */}
{!isOpen && hasUnread && (
<span className="absolute top-0 right-0 h-3 w-3 rounded-full bg-destructive ring-2 ring-background" />
)}
</Button>
{/* Close button - appears on hover, rendered last to be on top */}
<Button
onClick={handleClose}
size="icon"
variant="secondary"
className={cn(
'absolute -top-2 -right-2 h-6 w-6 rounded-full shadow-md border',
'transition-all duration-200',
isHovered ? 'opacity-100 scale-100' : 'opacity-0 scale-75 pointer-events-none'
)}
aria-label="Hide chat button"
>
<X className="h-3 w-3" />
</Button>
</div>
);
}
@@ -1,155 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, waitFor } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { GiftCardRedeemDialog } from './GiftCardRedeemDialog';
// Mock fetch
global.fetch = vi.fn();
describe('GiftCardRedeemDialog', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('renders loading state initially', async () => {
// Mock the gift card check endpoint
(global.fetch as ReturnType<typeof vi.fn>).mockImplementation(() =>
new Promise(() => {}) // Never resolves to keep it loading
);
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Should show loading skeleton
expect(screen.getByRole('dialog')).toBeInTheDocument();
});
it('shows error for invalid gift card', async () => {
// Mock the gift card check endpoint to return an error
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: false,
json: async () => ({
error: {
message: 'No giftcard found with code "INVALID-CODE"',
},
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="INVALID-CODE"
/>
</TestApp>
);
// Wait for error message to appear
await waitFor(() => {
expect(screen.getByText('Invalid Gift Card')).toBeInTheDocument();
});
});
it('shows already redeemed message for redeemed gift card', async () => {
// Mock the gift card check endpoint to return a redeemed gift card
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => ({
object: 'giftcard',
id: 'gc_123',
code: 'TEST-CODE-1234-5678',
amount: 25.0,
redeemed: true,
created_at: 1640995200,
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Wait for redeemed message to appear
await waitFor(() => {
expect(screen.getByText('Already Redeemed')).toBeInTheDocument();
});
});
it('shows gift card amount for valid unredeemed gift card', async () => {
// Mock the gift card check endpoint to return a valid gift card
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => ({
object: 'giftcard',
id: 'gc_123',
code: 'TEST-CODE-1234-5678',
amount: 25.0,
redeemed: false,
created_at: 1640995200,
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Wait for gift card amount to appear
await waitFor(() => {
expect(screen.getByText(/You've got \$25\.00!/)).toBeInTheDocument();
});
});
it('shows provider name when matching preset is found', async () => {
// Mock the gift card check endpoint
(global.fetch as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
ok: true,
json: async () => ({
object: 'giftcard',
id: 'gc_123',
code: 'TEST-CODE-1234-5678',
amount: 10.0,
redeemed: false,
created_at: 1640995200,
}),
});
render(
<TestApp>
<GiftCardRedeemDialog
open={true}
onOpenChange={() => {}}
baseURL="https://ai.shakespeare.diy/v1"
code="TEST-CODE-1234-5678"
/>
</TestApp>
);
// Wait for provider name to appear
await waitFor(() => {
expect(screen.getByText('Shakespeare AI')).toBeInTheDocument();
});
});
});
-358
View File
@@ -1,358 +0,0 @@
import { useState, useEffect, useRef } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { Gift, Check } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { generateSecretKey, nip19 } from 'nostr-tools';
import { Dialog, DialogContent } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Checkbox } from '@/components/ui/checkbox';
import { useToast } from '@/hooks/useToast';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAISettings } from '@/hooks/useAISettings';
import { useLoginActions } from '@/hooks/useLoginActions';
import { createAIClient } from '@/lib/ai-client';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import { LoginArea } from '@/components/auth/LoginArea';
import { useAppContext } from '@/hooks/useAppContext';
interface GiftCardRedeemDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
baseURL: string;
code: string;
}
interface Giftcard {
object: 'giftcard';
id: string;
code: string;
amount: number;
redeemed: boolean;
created_at?: number;
}
interface GiftcardRedemption {
object: 'giftcard_redemption';
amount: number;
}
// No steps needed - everything on one screen!
/**
* Gift Card Redemption Dialog
*
* This component handles the complete gift card redemption flow, including:
* - Fetching gift card details from the provider API
* - Multi-step wizard for login and provider setup
* - Account switching before redemption
* - Automatic provider matching against presets
*
* Flow:
* 1. Check if gift card is valid (unauthenticated API call)
* 2. Determine required steps based on user state:
* - Not logged in? → Show login step
* - Provider not configured? → Show provider setup step
* - Ready to redeem? → Show preview with account switcher
* 3. Redeem gift card and add credits to user's account
* 4. Navigate to AI Settings to show new balance
*
* @param open - Whether the dialog is open
* @param onOpenChange - Callback when dialog open state changes
* @param baseURL - Provider base URL (e.g., https://ai.shakespeare.diy/v1)
* @param code - Gift card code to redeem (e.g., XXXX-XXXX-XXXX-XXXX)
*/
export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: GiftCardRedeemDialogProps) {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { settings, setProvider } = useAISettings();
const { config } = useAppContext();
const { toast } = useToast();
const login = useLoginActions();
const queryClient = useQueryClient();
const [generatedNsec, setGeneratedNsec] = useState<string>('');
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
const hasInitialized = useRef(false);
// Find matching provider by baseURL
const matchingProvider = settings.providers.find(p => p.baseURL === baseURL);
const matchingPreset = AI_PROVIDER_PRESETS.find(p => p.baseURL === baseURL);
// Query gift card details without authentication
const { data: giftcard, isLoading: isLoadingGiftcard, error: giftcardError } = useQuery({
queryKey: ['giftcard-check', baseURL, code],
queryFn: async (): Promise<Giftcard> => {
const response = await fetch(`${baseURL}/credits/giftcards/check/${code}`);
if (!response.ok) {
const error = await response.json();
throw new Error(error.error?.message || 'Failed to fetch gift card details');
}
return response.json();
},
enabled: open && !!baseURL && !!code,
retry: false,
});
// Mutation for redeeming gift card
const redeemMutation = useMutation({
mutationFn: async (): Promise<GiftcardRedemption> => {
if (!matchingProvider) {
throw new Error('Provider not configured');
}
const ai = createAIClient(matchingProvider, user, config.corsProxy);
return await ai.post('/credits/giftcards/redeem', {
body: { code },
}) as GiftcardRedemption;
},
onSuccess: (redemption) => {
toast({
title: '🎉 ' + t('giftCardRedeemed'),
description: t('creditsAddedToAccount', { amount: formatCurrency(redemption.amount) }),
});
onOpenChange(false);
},
onError: (error: Error) => {
toast({
title: t('redemptionFailed'),
description: error.message || t('failedToRedeemGiftCard'),
variant: 'destructive',
});
},
});
// Reset state and initialize when dialog opens
useEffect(() => {
if (!open) {
// Clear state when closing
setGeneratedNsec('');
setAgreedToProviderTerms(false);
hasInitialized.current = false;
return;
}
// Only initialize once when dialog opens
if (!hasInitialized.current) {
hasInitialized.current = true;
// Auto-generate account if needed
if (!user && !generatedNsec) {
const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey);
setGeneratedNsec(nsec);
login.nsec(nsec);
}
}
}, [open, user, generatedNsec, login]);
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
const handleRedeem = () => {
// Check prerequisites
if (!user) return;
// If provider not configured, add it first
if (!matchingProvider && matchingPreset) {
if (!agreedToProviderTerms) return;
const providerConfig = {
id: matchingPreset.id,
name: matchingPreset.name,
baseURL: matchingPreset.baseURL,
nostr: matchingPreset.nostr || undefined,
};
setProvider(providerConfig);
}
// Redeem the gift card
redeemMutation.mutate(undefined, {
onSuccess() {
// Invalidate AI credits query for this provider and user
const providerId = matchingProvider?.id || matchingPreset?.id;
if (providerId) {
queryClient.invalidateQueries({ queryKey: ['ai-credits', user.pubkey, providerId] });
}
}
});
};
// Error state
if (giftcardError) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8">
<div className="mb-4">
<Gift className="h-16 w-16 mx-auto text-muted-foreground opacity-50" />
</div>
<h2 className="text-2xl font-bold mb-2">{t('invalidGiftCard')}</h2>
<p className="text-muted-foreground">
{giftcardError instanceof Error ? giftcardError.message : t('giftCardNotFound')}
</p>
<Button onClick={() => onOpenChange(false)} className="mt-6">
{t('close')}
</Button>
</div>
</DialogContent>
</Dialog>
);
}
// Loading state
if (isLoadingGiftcard) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8 space-y-4">
<Skeleton className="h-16 w-16 rounded-full mx-auto" />
<Skeleton className="h-8 w-48 mx-auto" />
<Skeleton className="h-4 w-64 mx-auto" />
<Skeleton className="h-12 w-full" />
</div>
</DialogContent>
</Dialog>
);
}
// Already redeemed
if (giftcard?.redeemed) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8">
<div className="mb-4">
<Check className="h-16 w-16 mx-auto text-green-500" />
</div>
<h2 className="text-2xl font-bold mb-2">{t('alreadyRedeemed')}</h2>
<p className="text-muted-foreground">
{t('giftCardAlreadyRedeemed')}
</p>
<Button onClick={() => onOpenChange(false)} className="mt-6">
{t('close')}
</Button>
</div>
</DialogContent>
</Dialog>
);
}
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md">
<div className="text-center py-8 space-y-6">
{/* Animated gift icon */}
<div className="relative">
<div className="absolute inset-0 flex items-center justify-center">
<div className="h-24 w-24 rounded-full bg-primary/10 animate-pulse" />
</div>
<div className="relative flex items-center justify-center">
<Gift className="h-16 w-16 text-primary animate-bounce" style={{ animationDuration: '2s' }} />
</div>
</div>
{/* Title and amount */}
<div>
<h2 className="text-3xl font-bold mb-2 bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{t('youveGotCredits', { amount: giftcard && formatCurrency(giftcard.amount) })}
</h2>
<p className="text-muted-foreground">
{t('readyToAddCredits')}
</p>
</div>
{/* Provider info */}
{matchingPreset && (
<div className="bg-muted/50 rounded-lg p-4 text-sm">
<div className="flex items-center justify-center gap-2">
<span className="text-muted-foreground">{t('provider')}:</span>
<span className="font-medium">{matchingPreset.name}</span>
</div>
</div>
)}
{/* Account selector - always show */}
<div className="border rounded-lg p-4">
<p className="text-xs text-muted-foreground mb-3 text-left">
{t('redeemingToAccount')}
</p>
<LoginArea className="w-full" />
</div>
{/* Provider ToS - only show if provider not configured */}
{!matchingProvider && matchingPreset && (
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-provider-terms"
checked={agreedToProviderTerms}
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
/>
<label
htmlFor="agree-provider-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('agreeToTermsOfService', { providerName: matchingPreset.name })}{' '}
{matchingPreset.tosURL ? (
<a
href={matchingPreset.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
{t('termsOfService')}
</a>
) : (
t('termsOfService')
)}
</label>
</div>
)}
{/* Action buttons */}
<div className="space-y-3">
<Button
onClick={handleRedeem}
disabled={
!user ||
redeemMutation.isPending ||
(!matchingProvider && !agreedToProviderTerms)
}
size="lg"
className="w-full text-lg h-14 font-semibold"
>
{redeemMutation.isPending ? (
<>
<div className="animate-spin rounded-full h-5 w-5 border-b-2 border-white mr-2" />
{t('redeeming')}
</>
) : (
<>
<Gift className="h-5 w-5 mr-2" />
{t('redeemNow')}
</>
)}
</Button>
<Button
variant="ghost"
onClick={() => onOpenChange(false)}
className="w-full"
>
{t('cancel')}
</Button>
</div>
</div>
</DialogContent>
</Dialog>
</>
);
}
+2 -54
View File
@@ -25,7 +25,6 @@ const baseGitStatus = {
},
ahead: 0,
behind: 0,
remoteBranchExists: false,
};
vi.mock('@/hooks/useGitStatus', () => ({
@@ -83,16 +82,7 @@ describe('GitDialog', () => {
expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed
});
it('shows sync status when branch is published', () => {
// Mock git status with published branch
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
it('shows sync status', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -143,17 +133,7 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).not.toBeDisabled();
});
it('disables push button when no commits ahead and branch is published', () => {
// Mock git status with published branch and no commits ahead
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: true,
},
refetch: mockRefetch,
});
it('disables push button when no commits ahead', () => {
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
@@ -167,38 +147,6 @@ describe('GitDialog', () => {
expect(pushButton.closest('button')).toBeDisabled();
});
it('enables push and disables pull when branch is not published', () => {
// Mock git status with unpublished branch (has commits but no remote branch)
mockUseGitStatus.mockReturnValue({
data: {
...baseGitStatus,
ahead: 0,
remoteBranchExists: false,
totalCommits: 5,
},
refetch: mockRefetch,
});
render(
<TestApp>
<GitDialog projectId="test-project" open={true} onOpenChange={() => {}}>
<button>Open Git Dialog</button>
</GitDialog>
</TestApp>
);
expect(screen.getByText('Sync Status')).toBeInTheDocument();
expect(screen.getByText('Branch not published')).toBeInTheDocument();
const pushButton = screen.getByText('Push');
expect(pushButton).toBeInTheDocument();
expect(pushButton.closest('button')).not.toBeDisabled();
const pullButton = screen.getByText('Pull');
expect(pullButton).toBeInTheDocument();
expect(pullButton.closest('button')).toBeDisabled();
});
it('does not show credentials warning when credentials are configured', () => {
render(
<TestApp>
+315 -1009
View File
File diff suppressed because it is too large. Load diff
+43 -6
View File
@@ -14,7 +14,7 @@ vi.mock('@/lib/configUtils', () => ({
// Test component that uses the hook
function TestComponent() {
const { settings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
const { settings, updateSettings, addCredential, removeCredential, updateCredential, isConfigured } = useGitSettings();
const handleAdd = () => {
const credential: GitCredential = {
@@ -32,13 +32,21 @@ function TestComponent() {
removeCredential('https://github.com');
};
const handleUpdateCorsProxy = () => {
updateSettings({ corsProxy: 'https://custom-cors.example.com' });
};
return (
<div>
<div data-testid="configured">{isConfigured ? 'configured' : 'not-configured'}</div>
<div data-testid="count">{Object.keys(settings.credentials).length}</div>
<div data-testid="cors-proxy">{settings.corsProxy}</div>
<button onClick={handleAdd}>Add GitHub</button>
<button onClick={handleUpdate}>Update GitHub</button>
<button onClick={handleRemove}>Remove GitHub</button>
<button onClick={handleUpdateCorsProxy}>Update CORS Proxy</button>
{settings.credentials['https://github.com'] && (
<div data-testid="github-creds">
{settings.credentials['https://github.com'].username}:
@@ -68,7 +76,7 @@ describe('GitSettingsProvider', () => {
const { readGitSettings } = await import('@/lib/configUtils');
vi.mocked(readGitSettings).mockResolvedValue({
credentials: {},
hostTokens: {},
corsProxy: 'https://cors.isomorphic-git.org',
});
});
@@ -170,9 +178,9 @@ describe('GitSettingsProvider', () => {
username: 'git',
password: 'test-token',
}
}
}),
'/config' // configPath
},
corsProxy: 'https://proxy.shakespeare.diy/?url={href}'
})
);
});
});
@@ -185,7 +193,7 @@ describe('GitSettingsProvider', () => {
password: 'gitlab-token',
},
},
hostTokens: {},
corsProxy: 'https://custom-cors.example.com',
};
const { readGitSettings } = await import('@/lib/configUtils');
@@ -200,8 +208,37 @@ describe('GitSettingsProvider', () => {
await waitFor(() => {
expect(screen.getByTestId('configured')).toHaveTextContent('configured');
expect(screen.getByTestId('count')).toHaveTextContent('1');
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
});
});
it('provides default CORS proxy', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
});
it('can update CORS proxy', async () => {
render(
<TestWrapper>
<TestComponent />
</TestWrapper>
);
await waitFor(() => {
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}');
});
fireEvent.click(screen.getByText('Update CORS Proxy'));
expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://custom-cors.example.com');
});
});
+10 -45
View File
@@ -1,7 +1,6 @@
import { ReactNode, useState, useEffect } from 'react';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitHostToken, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { GitSettingsContext, type GitSettings, type GitCredential, type GitSettingsContextType } from '@/contexts/GitSettingsContext';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { readGitSettings, writeGitSettings } from '@/lib/configUtils';
interface GitSettingsProviderProps {
@@ -10,12 +9,11 @@ interface GitSettingsProviderProps {
const DEFAULT_SETTINGS: GitSettings = {
credentials: {},
hostTokens: {},
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
};
export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
const { fs } = useFS();
const { configPath } = useFSPaths();
const [settings, setSettings] = useState<GitSettings>(DEFAULT_SETTINGS);
const [isInitialized, setIsInitialized] = useState(false);
@@ -23,7 +21,11 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
useEffect(() => {
const initializeSettings = async () => {
try {
const settings = await readGitSettings(fs, configPath);
const settings = await readGitSettings(fs);
// Migrate old CORS proxy format
if (settings.corsProxy === 'https://cors.isomorphic-git.org') {
settings.corsProxy = DEFAULT_SETTINGS.corsProxy;
}
setSettings(settings);
} catch (error) {
console.error('Failed to initialize Git settings:', error);
@@ -34,7 +36,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
};
initializeSettings();
}, [fs, configPath]);
}, [fs]);
// Save settings to VFS whenever they change (but not during initialization)
useEffect(() => {
@@ -42,14 +44,14 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
const saveSettings = async () => {
try {
await writeGitSettings(fs, settings, configPath);
await writeGitSettings(fs, settings);
} catch (error) {
console.error('Failed to save Git settings:', error);
}
};
saveSettings();
}, [fs, settings, isInitialized, configPath]);
}, [fs, settings, isInitialized]);
const updateSettings = (newSettings: Partial<GitSettings>) => {
setSettings(prev => ({ ...prev, ...newSettings }));
@@ -88,39 +90,6 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
}));
};
const addHostToken = (host: string, token: GitHostToken) => {
setSettings(prev => ({
...prev,
hostTokens: {
...prev.hostTokens,
[host]: token,
},
}));
};
const removeHostToken = (host: string) => {
setSettings(prev => {
const { [host]: removed, ...rest } = prev.hostTokens;
return {
...prev,
hostTokens: rest,
};
});
};
const updateHostToken = (host: string, token: Partial<GitHostToken>) => {
setSettings(prev => ({
...prev,
hostTokens: {
...prev.hostTokens,
[host]: {
...prev.hostTokens[host],
...token,
},
},
}));
};
const isConfigured = Object.entries(settings.credentials).length > 0;
const contextValue: GitSettingsContextType = {
@@ -129,11 +98,7 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) {
addCredential,
removeCredential,
updateCredential,
addHostToken,
removeHostToken,
updateHostToken,
isConfigured,
isInitialized,
};
return (
-614
View File
@@ -1,614 +0,0 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { useLocation } from 'react-router-dom';
import { X, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2, Hammer } from 'lucide-react';
import { Streamdown } from 'streamdown';
import { Button } from '@/components/ui/button';
import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipTrigger } from '@/components/ui/tooltip';
import { ModelSelector } from '@/components/ModelSelector';
import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext';
import { useAISettings } from '@/hooks/useAISettings';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useTheme } from '@/hooks/useTheme';
import { cn } from '@/lib/utils';
import type { GlobalChatMessage } from '@/contexts/GlobalChatContext';
// Message component with copy functionality
function ChatMessage({ message }: { message: GlobalChatMessage }) {
const [copied, setCopied] = useState(false);
const { displayTheme } = useTheme();
const isUser = message.role === 'user';
const handleCopy = useCallback(async () => {
try {
await navigator.clipboard.writeText(message.content);
setCopied(true);
setTimeout(() => setCopied(false), 2000);
} catch (error) {
console.error('Failed to copy:', error);
}
}, [message.content]);
return (
<div
className={cn(
'group relative flex',
isUser ? 'justify-end' : 'justify-start'
)}
>
<div
className={cn(
'relative max-w-[85%] rounded-2xl px-4 py-2.5',
isUser
? 'bg-primary text-primary-foreground rounded-br-md'
: 'bg-muted rounded-bl-md'
)}
>
{isUser ? (
<p className="text-sm whitespace-pre-wrap break-words">{message.content}</p>
) : (
<div className="text-sm break-words">
<Streamdown
className="size-full [&>*:first-child]:mt-0 [&>*:last-child]:mb-0 prose prose-sm dark:prose-invert max-w-none"
shikiTheme={displayTheme === 'dark' ? 'github-dark' : 'github-light'}
>
{message.content || '...'}
</Streamdown>
</div>
)}
{/* Copy button - shows on hover */}
<button
onClick={handleCopy}
className={cn(
'absolute -bottom-1 opacity-0 group-hover:opacity-100 transition-opacity',
'p-1 rounded bg-background/80 hover:bg-background shadow-sm border',
isUser ? 'right-0 translate-y-full' : 'left-0 translate-y-full'
)}
aria-label="Copy message"
>
{copied ? (
<Check className="h-3 w-3 text-green-500" />
) : (
<Copy className="h-3 w-3 text-muted-foreground" />
)}
</button>
</div>
</div>
);
}
interface GlobalChatPaneProps {
/** When true, renders inline without fixed positioning (for embedding in ProjectView) */
embedded?: boolean;
/** Mobile chat mode toggle - only used in embedded mode */
mobileChatMode?: 'building' | 'chatting';
onMobileChatModeChange?: (mode: 'building' | 'chatting') => void;
}
export function GlobalChatPane({ embedded = false, mobileChatMode, onMobileChatModeChange }: GlobalChatPaneProps) {
const { t } = useTranslation();
const {
messages,
isOpen,
isLoading,
sendMessage,
stopGeneration,
clearMessages,
setIsOpen,
providerModel,
setProviderModel,
} = useGlobalChat();
const { config } = useAppContext();
const { settings } = useAISettings();
const isMobile = useIsMobile();
const location = useLocation();
const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Track if user has manually scrolled up
const userScrolledUp = useRef(false);
// Track the last message content to detect streaming updates
const lastMessageContent = messages[messages.length - 1]?.content || '';
// Initialize provider model from settings if not set
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
}
}, [providerModel, settings.recentlyUsedModels, setProviderModel]);
// Scroll to bottom and focus textarea when chat opens (or when embedded mode becomes active)
useEffect(() => {
const shouldScroll = isOpen || embedded;
if (shouldScroll && scrollAreaRef.current) {
// Small delay to ensure content is rendered
requestAnimationFrame(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
// Focus the textarea so user can start typing immediately
textareaRef.current?.focus();
});
// Reset scroll tracking when opening
userScrolledUp.current = false;
}
}, [isOpen, embedded]);
// Auto-scroll to bottom when messages change or streaming content updates
useEffect(() => {
const isActive = isOpen || embedded;
if (!scrollAreaRef.current || !isActive) return;
// Only auto-scroll if user hasn't manually scrolled up
if (!userScrolledUp.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, [messages, lastMessageContent, isLoading, isOpen, embedded]);
// Handle scroll to detect user scrolling and show/hide scroll-to-bottom button
const handleScroll = useCallback(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const threshold = 100;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// Track if user scrolled away from bottom
userScrolledUp.current = !isNearBottom;
setShowScrollToBottom(!isNearBottom && messages.length > 0);
}
}, [messages.length]);
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
}
}, []);
const handleSend = useCallback(async () => {
if (!input.trim() || isLoading || !providerModel) return;
const messageContent = input.trim();
setInput('');
// Focus immediately so user can keep typing
textareaRef.current?.focus();
await sendMessage(messageContent, providerModel);
}, [input, isLoading, providerModel, sendMessage]);
// Refocus textarea when AI finishes responding
useEffect(() => {
if (!isLoading && isOpen && messages.length > 0) {
textareaRef.current?.focus();
}
}, [isLoading, isOpen, messages.length]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !isMobile) {
e.preventDefault();
handleSend();
}
}, [handleSend, isMobile]);
// For non-embedded mode: Don't render if disabled or not open
if (!embedded && (config.globalChatEnabled === false || !isOpen)) {
return null;
}
// For non-embedded mode: Don't render on settings pages
if (!embedded && location.pathname.startsWith('/settings')) {
return null;
}
const hasProviders = settings.providers.length > 0;
// Embedded mode: Render inline without fixed positioning
if (embedded) {
// Hide header when there's a mode toggle (mobile view with switching)
const showHeader = !mobileChatMode;
return (
<div className="h-full flex flex-col bg-background">
{/* Header - hidden when mobile toggle is present */}
{showHeader && (
<div className="flex items-center justify-between px-4 py-3 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<h2 className="font-semibold text-lg">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={clearMessages}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
</div>
</div>
)}
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex-1 flex items-center justify-center text-center text-muted-foreground px-8 py-12">
<div>
<p className="text-lg font-medium mb-2">{t('globalChatWelcome')}</p>
<p className="text-sm">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="absolute bottom-32 left-1/2 -translate-x-1/2 rounded-full shadow-lg"
>
<ChevronDown className="h-4 w-4" />
</Button>
)}
{/* Input */}
<div className="border-t p-4">
<div className="flex flex-col rounded-2xl border border-input bg-background shadow-sm focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
rows={1}
style={{
height: 'auto',
minHeight: '96px'
}}
onInput={(e) => {
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
/>
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* Mobile Chat Mode Toggle - single button to switch back to building mode */}
{mobileChatMode && onMobileChatModeChange && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => onMobileChatModeChange('building')}
>
<Hammer className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('building')}</TooltipContent>
</Tooltip>
)}
{/* Model Selector */}
<div className="flex-1 max-w-72 ml-auto overflow-hidden">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
disabled={isLoading}
placeholder={t('chooseModel')}
/>
</div>
{/* Send/Stop Button */}
{isLoading ? (
<Button
onClick={stopGeneration}
size="sm"
variant="ghost"
className="size-8 rounded-full p-0 bg-foreground/10 [&_svg]:size-3.5 [&_svg]:fill-foreground hover:bg-foreground/20"
>
<Square />
</Button>
) : (
<Button
onClick={handleSend}
size="sm"
disabled={!input.trim() || !providerModel || !hasProviders}
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
<ArrowUp />
</Button>
)}
</div>
</div>
</div>
</div>
);
}
// Mobile: Full screen drawer from bottom
if (isMobile) {
return (
<div className="fixed inset-0 z-50 bg-background flex flex-col animate-in slide-in-from-bottom duration-300">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/60">
<h2 className="font-semibold text-lg">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={clearMessages}
>
<Trash2 className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
<Button
variant="ghost"
size="icon"
className="h-8 w-8"
onClick={() => setIsOpen(false)}
>
<X className="h-4 w-4" />
</Button>
</div>
</div>
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex-1 flex items-center justify-center text-center text-muted-foreground px-8 py-12">
<div>
<p className="text-lg font-medium mb-2">{t('globalChatWelcome')}</p>
<p className="text-sm">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="absolute bottom-32 left-1/2 -translate-x-1/2 rounded-full shadow-lg"
>
<ChevronDown className="h-4 w-4" />
</Button>
)}
{/* Input */}
<div className="p-4 border-t bg-background space-y-3 pb-safe">
<div className="flex gap-2">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="flex-1"
disabled={isLoading}
placeholder={t('chooseModel')}
/>
</div>
<div className="flex gap-2 items-end">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 128) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="resize-none min-h-[44px] max-h-32"
rows={1}
/>
{isLoading ? (
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-11 w-11 shrink-0">
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={handleSend}
size="icon"
disabled={!input.trim() || !providerModel || !hasProviders}
className="h-11 w-11 shrink-0"
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
</div>
</div>
);
}
// Desktop: Floating panel
return (
<div className="fixed bottom-24 right-6 z-50 w-96 max-w-[calc(100vw-3rem)] bg-background border rounded-2xl shadow-2xl flex flex-col animate-in fade-in slide-in-from-bottom-4 duration-300">
{/* Header */}
<div className="flex items-center justify-between px-4 py-3 border-b">
<h2 className="font-semibold">{t('globalChat')}</h2>
<div className="flex items-center gap-1">
{messages.length > 0 && (
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={clearMessages}
>
<Trash2 className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('clearChat')}</TooltipContent>
</Tooltip>
)}
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-7 w-7"
onClick={() => setIsOpen(false)}
>
<X className="h-3.5 w-3.5" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('minimizeChat')}</TooltipContent>
</Tooltip>
</div>
</div>
{/* Messages */}
<div
ref={scrollAreaRef}
className="flex-1 overflow-y-auto p-4 space-y-4 max-h-96 min-h-48"
onScroll={handleScroll}
>
{messages.length === 0 ? (
<div className="flex items-center justify-center text-center text-muted-foreground px-4 py-8">
<div>
<p className="font-medium mb-1">{t('globalChatWelcome')}</p>
<p className="text-xs">{t('globalChatDescription')}</p>
</div>
</div>
) : (
messages.map((message) => (
<ChatMessage key={message.id} message={message} />
))
)}
{isLoading && messages[messages.length - 1]?.role !== 'assistant' && (
<div className="flex justify-start">
<div className="bg-muted rounded-2xl rounded-bl-md px-4 py-3">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
</div>
)}
</div>
{/* Scroll to bottom button */}
{showScrollToBottom && (
<div className="absolute bottom-36 left-1/2 -translate-x-1/2">
<Button
onClick={scrollToBottom}
size="sm"
variant="secondary"
className="h-7 w-7 rounded-full shadow-lg p-0"
>
<ChevronDown className="h-3.5 w-3.5" />
</Button>
</div>
)}
{/* Input */}
<div className="p-3 border-t space-y-2">
<ModelSelector
value={providerModel}
onChange={setProviderModel}
className="w-full"
disabled={isLoading}
placeholder={t('chooseModel')}
/>
<div className="flex gap-2 items-end">
<Textarea
ref={textareaRef}
value={input}
onChange={(e) => {
setInput(e.target.value);
// Auto-resize
const target = e.target as HTMLTextAreaElement;
target.style.height = 'auto';
target.style.height = Math.min(target.scrollHeight, 96) + 'px';
}}
onKeyDown={handleKeyDown}
placeholder={hasProviders ? t('typeMessage') : t('configureAIFirst')}
disabled={!hasProviders || isLoading}
className="resize-none min-h-[40px] max-h-24 text-sm"
rows={1}
/>
{isLoading ? (
<Button onClick={stopGeneration} size="icon" variant="destructive" className="h-10 w-10 shrink-0">
<Square className="h-4 w-4" />
</Button>
) : (
<Button
onClick={handleSend}
size="icon"
disabled={!input.trim() || !providerModel || !hasProviders}
className="h-10 w-10 shrink-0"
>
<ArrowUp className="h-4 w-4" />
</Button>
)}
</div>
</div>
</div>
);
}
-224
View File
@@ -1,224 +0,0 @@
import { useState, useCallback, useRef, type ReactNode } from 'react';
import OpenAI from 'openai';
import { GlobalChatContext, type GlobalChatMessage } from '@/contexts/GlobalChatContext';
import { useAISettings } from '@/hooks/useAISettings';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { createAIClient } from '@/lib/ai-client';
import { defaultGlobalChatSystemPrompt } from '@/lib/globalChatSystem';
// Maximum context size in characters (approximately 50k tokens worth)
// This leaves room for the system prompt and response
const MAX_CONTEXT_CHARS = 150000;
interface GlobalChatProviderProps {
children: ReactNode;
}
export function GlobalChatProvider({ children }: GlobalChatProviderProps) {
const [messages, setMessages] = useState<GlobalChatMessage[]>([]);
const [isOpen, setIsOpenInternal] = useState(false);
const [isLoading, setIsLoading] = useState(false);
const [hasUnread, setHasUnread] = useState(false);
const abortControllerRef = useRef<AbortController | null>(null);
const isOpenRef = useRef(false);
const loadingReleasedRef = useRef(false);
// Separate model storage for global chat (independent from project chat)
const [globalChatModel, setGlobalChatModel] = useLocalStorage<string>('shakespeare-global-chat-model', '');
const { settings } = useAISettings();
const { config } = useAppContext();
const { user } = useCurrentUser();
// When opening the chat, mark messages as read
const setIsOpen = useCallback((open: boolean) => {
isOpenRef.current = open;
setIsOpenInternal(open);
if (open) {
setHasUnread(false);
}
}, []);
// Trim messages from the top when context gets too long
const trimMessages = useCallback((msgs: GlobalChatMessage[]): GlobalChatMessage[] => {
let totalChars = msgs.reduce((sum, msg) => sum + msg.content.length, 0);
if (totalChars <= MAX_CONTEXT_CHARS) {
return msgs;
}
// Remove messages from the beginning until we're under the limit
const trimmedMessages = [...msgs];
while (trimmedMessages.length > 1 && totalChars > MAX_CONTEXT_CHARS) {
const removed = trimmedMessages.shift();
if (removed) {
totalChars -= removed.content.length;
}
}
return trimmedMessages;
}, []);
const sendMessage = useCallback(async (content: string, providerModelString: string) => {
// Parse provider and model
const { model: modelId, provider } = parseProviderModel(providerModelString, settings.providers);
if (!provider) {
console.error('Provider not found');
return;
}
// Create user message
const userMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'user',
content: content.trim(),
timestamp: Date.now(),
};
// Add user message and capture current messages for API call
let currentMessages: GlobalChatMessage[] = [];
setMessages(prev => {
currentMessages = prev;
return trimMessages([...prev, userMessage]);
});
setIsLoading(true);
// Create abort controller for this request
abortControllerRef.current = new AbortController();
// Reset the loading released flag for this new request
loadingReleasedRef.current = false;
try {
// Create AI client
const client = createAIClient(provider, user, config.corsProxy);
// Build messages for API using captured current messages
const systemPrompt = config.globalChatSystemPrompt || defaultGlobalChatSystemPrompt;
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
...currentMessages.map(msg => ({
role: msg.role as 'user' | 'assistant',
content: msg.content,
})),
{ role: 'user', content: content.trim() },
];
// Create assistant message placeholder
const assistantMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: '',
timestamp: Date.now(),
};
setMessages(prev => [...prev, assistantMessage]);
// Stream the response
const stream = await client.chat.completions.create({
model: modelId,
messages: apiMessages,
stream: true,
}, {
signal: abortControllerRef.current.signal,
});
let fullContent = '';
for await (const chunk of stream) {
const delta = chunk.choices[0]?.delta?.content || '';
fullContent += delta;
// Update the assistant message with streamed content
setMessages(prev => {
const updated = [...prev];
const lastMessage = updated[updated.length - 1];
if (lastMessage && lastMessage.role === 'assistant') {
lastMessage.content = fullContent;
}
return updated;
});
// Release loading as soon as finish_reason is received
// Don't break - let the stream drain naturally to avoid async iterator cleanup delays
const finishReason = chunk.choices[0]?.finish_reason;
if (finishReason && !loadingReleasedRef.current) {
loadingReleasedRef.current = true;
setIsLoading(false);
}
}
// Final trim after response is complete
setMessages(prev => trimMessages(prev));
// Mark as unread if chat is closed
if (!isOpenRef.current) {
setHasUnread(true);
}
} catch (error) {
if (error instanceof Error && error.name === 'AbortError') {
// User stopped generation, keep partial response
return;
}
console.error('Global chat error:', error);
// Add error message
const errorMessage: GlobalChatMessage = {
id: crypto.randomUUID(),
role: 'assistant',
content: `Sorry, I encountered an error: ${error instanceof Error ? error.message : 'Unknown error'}`,
timestamp: Date.now(),
};
setMessages(prev => {
// Remove empty assistant message if exists
const filtered = prev.filter(m => m.role !== 'assistant' || m.content.trim());
return [...filtered, errorMessage];
});
} finally {
// Only set loading to false if we haven't already released it
if (!loadingReleasedRef.current) {
setIsLoading(false);
}
abortControllerRef.current = null;
}
}, [config.corsProxy, config.globalChatSystemPrompt, settings.providers, trimMessages, user]);
const stopGeneration = useCallback(() => {
if (abortControllerRef.current) {
abortControllerRef.current.abort();
abortControllerRef.current = null;
setIsLoading(false);
}
}, []);
const clearMessages = useCallback(() => {
setMessages([]);
}, []);
return (
<GlobalChatContext.Provider
value={{
messages,
isOpen,
isLoading,
hasUnread,
providerModel: globalChatModel,
setProviderModel: setGlobalChatModel,
sendMessage,
stopGeneration,
clearMessages,
setIsOpen,
}}
>
{children}
</GlobalChatContext.Provider>
);
}
-1
View File
@@ -21,7 +21,6 @@ const { CreditsDialog } = await import('./CreditsDialog');
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
-338
View File
@@ -1,338 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Server, Trash2, Check, Plus, X } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useAISettings } from '@/hooks/useAISettings';
import { useToast } from '@/hooks/useToast';
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
import type { MCPServer } from '@/contexts/AISettingsContext';
import { cn } from '@/lib/utils';
function MCPConnectionStatus({ server }: { server: MCPServer }) {
const status = useMCPServerStatus(server);
return (
<div className="flex items-center gap-1.5 ml-auto mr-2">
<div
className={cn(
'h-2 w-2 rounded-full',
status === 'connected' && 'bg-green-500',
status === 'offline' && 'bg-red-500',
status === 'checking' && 'bg-yellow-500 animate-pulse'
)}
/>
<span className="text-xs text-muted-foreground capitalize">
{status}
</span>
</div>
);
}
interface HeadersEditorProps {
headers: Record<string, string> | undefined;
onChange: (headers: Record<string, string> | undefined) => void;
}
function HeadersEditor({ headers, onChange }: HeadersEditorProps) {
const { t } = useTranslation();
const [newHeaderName, setNewHeaderName] = useState('');
const [newHeaderValue, setNewHeaderValue] = useState('');
const headerEntries = Object.entries(headers || {});
const handleAddHeader = () => {
if (!newHeaderName.trim() || !newHeaderValue.trim()) return;
const updatedHeaders = {
...(headers || {}),
[newHeaderName.trim()]: newHeaderValue.trim(),
};
onChange(updatedHeaders);
setNewHeaderName('');
setNewHeaderValue('');
};
const handleRemoveHeader = (name: string) => {
const updatedHeaders = { ...(headers || {}) };
delete updatedHeaders[name];
// If no headers left, set to undefined
onChange(Object.keys(updatedHeaders).length > 0 ? updatedHeaders : undefined);
};
const handleUpdateHeader = (oldName: string, newName: string, newValue: string) => {
const updatedHeaders = { ...(headers || {}) };
delete updatedHeaders[oldName];
updatedHeaders[newName] = newValue;
onChange(updatedHeaders);
};
return (
<div className="space-y-3">
<Label>{t('mcpServerHeaders')}</Label>
<p className="text-xs text-muted-foreground">
{t('mcpServerHeadersDescription')}
</p>
{/* Existing Headers */}
{headerEntries.length > 0 && (
<div className="space-y-2">
{headerEntries.map(([name, value]) => (
<div key={name} className="flex gap-2">
<Input
value={name}
onChange={(e) => handleUpdateHeader(name, e.target.value, value)}
placeholder="Header name"
className="flex-1"
/>
<Input
value={value}
onChange={(e) => handleUpdateHeader(name, name, e.target.value)}
placeholder="Header value"
className="flex-1"
/>
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveHeader(name)}
className="shrink-0"
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
)}
{/* Add New Header */}
<div className="flex gap-2">
<Input
value={newHeaderName}
onChange={(e) => setNewHeaderName(e.target.value)}
placeholder="Header name (e.g., Authorization)"
className="flex-1"
/>
<Input
value={newHeaderValue}
onChange={(e) => setNewHeaderValue(e.target.value)}
placeholder="Header value"
className="flex-1"
/>
<Button
variant="outline"
size="icon"
onClick={handleAddHeader}
disabled={!newHeaderName.trim() || !newHeaderValue.trim()}
className="shrink-0"
>
<Plus className="h-4 w-4" />
</Button>
</div>
</div>
);
}
export function MCPServersSection() {
const { t } = useTranslation();
const { settings, setMCPServer, removeMCPServer } = useAISettings();
const { toast } = useToast();
const [serverName, setServerName] = useState('');
const [serverUrl, setServerUrl] = useState('');
const [serverHeaders, setServerHeaders] = useState<Record<string, string> | undefined>(undefined);
const [serverType] = useState<'streamable-http'>('streamable-http'); // Only streamable-http is supported
const mcpServers = settings.mcpServers || {};
const serverEntries = Object.entries(mcpServers);
const handleAddServer = () => {
if (!serverName.trim() || !serverUrl.trim()) return;
if (mcpServers[serverName.trim()]) {
toast({
title: t('error'),
description: t('mcpServerAddFailed'),
variant: 'destructive',
});
return;
}
const newServer: MCPServer = {
type: serverType,
url: serverUrl.trim(),
headers: serverHeaders,
};
setMCPServer(serverName.trim(), newServer);
toast({
title: t('mcpServerAdded'),
description: t('mcpServerAddedDescription', { name: serverName.trim() }),
});
setServerName('');
setServerUrl('');
setServerHeaders(undefined);
};
const handleRemoveServer = (name: string) => {
removeMCPServer(name);
toast({
title: t('mcpServerDeleted'),
description: t('mcpServerDeletedDescription', { name }),
});
};
return (
<div className="space-y-4">
{/* MCP Servers Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<Server className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('mcpServers')}</h3>
</div>
<p className="text-sm text-muted-foreground">
{t('mcpServersDescription')}
</p>
</div>
{/* Configured MCP Servers List */}
{serverEntries.length > 0 && (
<div className="space-y-2">
{serverEntries.map(([name, server]) => (
<Accordion key={name} type="single" collapsible className="w-full">
<AccordionItem value={name} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2 w-full mr-3">
<Server size={16} className="text-muted-foreground" />
<span className="font-medium">{name}</span>
<MCPConnectionStatus server={server} />
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${name}-type`}>
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={server.type} disabled>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
</SelectContent>
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor={`${name}-url`}>
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id={`${name}-url`}
value={server.url}
onChange={(e) => setMCPServer(name, { ...server, url: e.target.value })}
placeholder="https://example.com/mcp"
/>
</div>
<HeadersEditor
headers={server.headers}
onChange={(headers) => setMCPServer(name, { ...server, headers })}
/>
<Button
variant="destructive"
size="sm"
onClick={() => handleRemoveServer(name)}
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
))}
</div>
)}
{/* Add New MCP Server */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-server">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<span className="text-sm font-medium">{t('addMcpServer')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<p className="text-sm text-muted-foreground">
{t('mcpServerDescription')}
</p>
<div className="grid gap-2">
<Label htmlFor="new-server-name">
{t('mcpServerName')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-name"
placeholder="e.g., my-mcp-server"
value={serverName}
onChange={(e) => setServerName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-type">
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={serverType} disabled>
<SelectTrigger>
<SelectValue />
</SelectTrigger>
<SelectContent>
<SelectItem value="streamable-http">{t('mcpServerTypeStreamableHttp')}</SelectItem>
</SelectContent>
</Select>
<p className="text-xs text-muted-foreground">
Only Streamable HTTP transport is currently supported
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-url">
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-url"
placeholder="https://example.com/mcp"
value={serverUrl}
onChange={(e) => setServerUrl(e.target.value)}
/>
</div>
<HeadersEditor
headers={serverHeaders}
onChange={setServerHeaders}
/>
<Button
onClick={handleAddServer}
disabled={!serverName.trim() || !serverUrl.trim() || !!mcpServers[serverName.trim()]}
className="gap-2 w-full"
>
<Check className="h-4 w-4" />
{t('add')}
</Button>
{mcpServers[serverName.trim()] && (
<p className="text-sm text-destructive">
A server with this name already exists
</p>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
);
}
-50
View File
@@ -1,50 +0,0 @@
import { Decimal } from 'decimal.js';
import { cn } from '@/lib/utils';
interface ModelPricingProps {
pricing: { prompt: Decimal; completion: Decimal };
className?: string;
}
/**
* Get a single normalized "price per token" for a model,
* combining input and output pricing with agentic-coding-aware weights.
*
* Default behavior:
* - Uses inputWeight = 0.20 (based on typical 3–5x output premium seen in practice).
*
* Optional behavior:
* - If you pass observed token usage, the function will compute the weight
* as the observed share of spend from inputs over total spend.
*/
function getNormalizedModelPrice(
pricing: { prompt: Decimal; completion: Decimal },
inputWeight = 0.2,
): Decimal {
if (!(inputWeight >= 0 && inputWeight <= 1)) {
throw new Error("Computed inputWeight is out of range [0,1]. Check inputs.");
}
if (pricing.prompt.equals(0) && pricing.completion.equals(0)) {
return new Decimal(0);
}
const outputWeight = 1 - inputWeight;
return pricing.prompt.times(inputWeight).plus(pricing.completion.times(outputWeight));
}
export function ModelPricing({ pricing, className }: ModelPricingProps) {
const normalizedPrice = getNormalizedModelPrice(pricing).times(1_000_000).toNumber();
if (normalizedPrice === 0) {
return <span className={cn("text-green-600 font-semibold", className)}>Free</span>;
} else if (normalizedPrice < 10) {
return <span className={cn("text-green-600 font-semibold", className)}>$</span>;
} else if (normalizedPrice >= 10 && normalizedPrice < 15) {
return <span className={cn("text-yellow-600 font-semibold", className)}>$$</span>;
} else if (normalizedPrice >= 15 && normalizedPrice < 50) {
return <span className={cn("text-red-600 font-semibold", className)}>$$$</span>;
} else if (normalizedPrice >= 50) {
return <span className={cn("text-red-800 font-semibold", className)}>$$$$</span>;
}
return null;
}
+13 -439
View File
@@ -1,7 +1,5 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { Decimal } from 'decimal.js';
import { TestApp } from '@/test/TestApp';
import { ModelSelector } from './ModelSelector';
@@ -14,10 +12,6 @@ vi.mock('@/hooks/useProviderModels', () => ({
useProviderModels: vi.fn(),
}));
vi.mock('@/hooks/useIsMobile', () => ({
useIsMobile: vi.fn(),
}));
vi.mock('react-router-dom', async (importOriginal) => {
const actual = await importOriginal() as Record<string, unknown>;
return {
@@ -28,11 +22,9 @@ vi.mock('react-router-dom', async (importOriginal) => {
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseProviderModels = vi.mocked(useProviderModels);
const mockUseIsMobile = vi.mocked(useIsMobile);
describe('ModelSelector', () => {
const mockOnChange = vi.fn();
@@ -42,15 +34,14 @@ describe('ModelSelector', () => {
vi.clearAllMocks();
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
settings: { providers: [], recentlyUsedModels: [] },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
mockUseProviderModels.mockReturnValue({
@@ -59,8 +50,6 @@ describe('ModelSelector', () => {
error: null,
refetch: vi.fn(),
});
mockUseIsMobile.mockReturnValue(false);
});
it('hides recently used section when less than 5 models and all recently used are available', async () => {
@@ -81,23 +70,14 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
],
recentlyUsedModels,
mcpServers: {},
},
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
render(
@@ -112,17 +92,11 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('Provider 2')).toBeInTheDocument();
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 should still show with model3 (just the model ID, not the full ID)
expect(screen.getByText('model3')).toBeInTheDocument();
});
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
@@ -143,24 +117,14 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
{ id: 'provider3', name: 'Provider 3', baseURL: 'https://api.provider3.com' },
],
recentlyUsedModels,
mcpServers: {},
},
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
render(
@@ -175,7 +139,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('Provider 1')).toBeInTheDocument();
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
@@ -202,24 +166,14 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
{ id: 'provider3', name: 'Provider 3', baseURL: 'https://api.provider3.com' },
],
recentlyUsedModels,
mcpServers: {},
},
settings: { providers: [], recentlyUsedModels },
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
render(
@@ -234,19 +188,11 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('Provider 2')).toBeInTheDocument();
expect(screen.getByText('provider1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
expect(screen.getByText('Recently Used')).toBeInTheDocument();
// provider1 should be hidden since all its models are in recently used
expect(screen.queryByText('provider1')).not.toBeInTheDocument();
// provider2 and provider3 should still show (just the model IDs, not full IDs)
expect(screen.getByText('model3')).toBeInTheDocument();
expect(screen.getByText('model4')).toBeInTheDocument();
expect(screen.getByText('model5')).toBeInTheDocument();
});
it('hides recently used section when no recently used models exist', async () => {
@@ -263,16 +209,14 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} }, // No recently used models
settings: { providers: [], recentlyUsedModels: [] }, // No recently used models
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
removeProvider: vi.fn(),
setProvider: vi.fn(),
setProviders: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
render(
@@ -293,374 +237,4 @@ describe('ModelSelector', () => {
// Recently used section should NOT be visible
expect(screen.queryByText('Recently Used')).not.toBeInTheDocument();
});
it('shows caution icon for free models', async () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
const paidModel = {
fullId: 'provider1/paid-model',
provider: 'provider1',
id: 'paid-model',
pricing: {
prompt: new Decimal('0.01'),
completion: new Decimal('0.02'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel, paidModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
// Test with free model selected
const { rerender } = render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
// Should show caution icon for free model
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
// Test with paid model selected
rerender(
<TestApp>
<ModelSelector value="provider1/paid-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for paid model
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon when no model is selected', () => {
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon when no model is selected
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show caution icon for models without pricing information', () => {
const modelWithoutPricing = {
fullId: 'provider1/unknown-pricing',
provider: 'provider1',
id: 'unknown-pricing',
// No pricing property
};
mockUseProviderModels.mockReturnValue({
models: [modelWithoutPricing],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-pricing" onChange={mockOnChange} />
</TestApp>
);
// Should not show caution icon for models without pricing info
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('shows tooltip when hovering over caution icon', async () => {
const user = userEvent.setup();
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionIcon = screen.getByTestId('triangle-alert');
expect(cautionIcon).toBeInTheDocument();
// Hover over the caution icon
await user.hover(cautionIcon);
// Wait for tooltip to appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
});
it('makes caution icon tappable on mobile with click-to-toggle tooltip', async () => {
const user = userEvent.setup();
mockUseIsMobile.mockReturnValue(true);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '0'); // Should be tappable on mobile
// Click to open tooltip - just verify the click works without errors
await user.click(cautionButton);
// Tooltip should appear
await waitFor(() => {
expect(screen.getAllByText('You are using a free model. For better results, switch to a paid model.').length).toBeGreaterThan(0);
});
// The button should still be clickable (no errors)
await user.click(cautionButton);
expect(cautionButton).toBeInTheDocument();
});
it('makes caution icon not focusable on desktop', () => {
mockUseIsMobile.mockReturnValue(false);
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/free-model" onChange={mockOnChange} />
</TestApp>
);
const cautionButton = screen.getByRole('button', { name: 'Model warning' });
expect(cautionButton).toBeInTheDocument();
expect(cautionButton).toHaveAttribute('tabIndex', '-1'); // Should not be focusable on desktop
});
it('shows warning icon when selected model is not in provider models list', () => {
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
</TestApp>
);
// Should show warning icon for model not in list
expect(screen.getByTestId('triangle-alert')).toBeInTheDocument();
});
it('does not show warning icon when selected model is in provider models list', () => {
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
{ fullId: 'provider1/model2', provider: 'provider1', id: 'model2' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/model1" onChange={mockOnChange} />
</TestApp>
);
// Should not show warning icon when model is in list
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show warning icon while models are loading', () => {
mockUseProviderModels.mockReturnValue({
models: [],
isLoading: true,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show warning icon while loading
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('does not show warning icon when no models are loaded', () => {
mockUseProviderModels.mockReturnValue({
models: [],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/some-model" onChange={mockOnChange} />
</TestApp>
);
// Should not show warning icon when no models loaded
expect(screen.queryByTestId('triangle-alert')).not.toBeInTheDocument();
});
it('shows correct tooltip message for model not in list', async () => {
const user = userEvent.setup();
const availableModels = [
{ fullId: 'provider1/model1', provider: 'provider1', id: 'model1' },
];
mockUseProviderModels.mockReturnValue({
models: availableModels,
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-model" onChange={mockOnChange} />
</TestApp>
);
const warningIcon = screen.getByTestId('triangle-alert');
expect(warningIcon).toBeInTheDocument();
// Hover over the warning icon
await user.hover(warningIcon);
// Wait for tooltip to appear
await waitFor(() => {
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
});
});
it('prioritizes "not in list" warning over "free model" warning in tooltip', async () => {
const user = userEvent.setup();
const freeModel = {
fullId: 'provider1/free-model',
provider: 'provider1',
id: 'free-model',
pricing: {
prompt: new Decimal('0'),
completion: new Decimal('0'),
},
};
mockUseProviderModels.mockReturnValue({
models: [freeModel],
isLoading: false,
error: null,
refetch: vi.fn(),
});
render(
<TestApp>
<ModelSelector value="provider1/unknown-free-model" onChange={mockOnChange} />
</TestApp>
);
const warningIcon = screen.getByTestId('triangle-alert');
expect(warningIcon).toBeInTheDocument();
// Hover over the warning icon
await user.hover(warningIcon);
// Wait for tooltip to appear - should show "not in list" message, not "free model" message
await waitFor(() => {
expect(screen.getAllByText("This model is not available in your provider's model list. It may not work or may have been deprecated.").length).toBeGreaterThan(0);
});
// Should not show the free model message
expect(screen.queryByText('You are using a free model. For better results, switch to a paid model.')).not.toBeInTheDocument();
});
});
+158 -368
View File
@@ -1,18 +1,14 @@
import { useState, useMemo, useEffect, memo } from 'react';
import { useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert, Bot } from 'lucide-react';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, CommandSeparator } from '@/components/ui/command';
import { Skeleton } from '@/components/ui/skeleton';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { useAISettings } from '@/hooks/useAISettings';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useIsMobile } from '@/hooks/useIsMobile';
import { ModelPricing } from '@/components/ModelPricing';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { cn } from '@/lib/utils';
interface ModelSelectorProps {
@@ -25,7 +21,7 @@ interface ModelSelectorProps {
onOpenChange?: (open: boolean) => void;
}
export const ModelSelector = memo(function ModelSelector({
export function ModelSelector({
value,
onChange,
className,
@@ -36,7 +32,6 @@ export const ModelSelector = memo(function ModelSelector({
}: ModelSelectorProps) {
const { t } = useTranslation();
const [uncontrolledOpen, setUncontrolledOpen] = useState(false);
const [isTooltipOpen, setIsTooltipOpen] = useState(false);
// Use controlled state if provided, otherwise use local state
const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen;
@@ -47,58 +42,22 @@ export const ModelSelector = memo(function ModelSelector({
const { settings, addRecentlyUsedModel, isConfigured } = useAISettings();
const { models, isLoading, error, refetch } = useProviderModels();
const navigate = useNavigate();
const isMobile = useIsMobile();
const defaultPlaceholder = t('selectOrEnterModel');
const recentlyUsedModels = useMemo(() => settings.recentlyUsedModels || [], [settings.recentlyUsedModels]);
// Create a Set of recently used model IDs for efficient lookup
const recentlyUsedSet = useMemo(() => new Set(recentlyUsedModels), [recentlyUsedModels]);
// Group models by provider, excluding models that are in the recently used section
// Group models by provider
const modelsByProvider = useMemo(() => {
const groups: Record<string, typeof models> = {};
for (const model of models) {
// Skip models that are already shown in recently used
if (recentlyUsedSet.has(model.fullId)) {
continue;
}
if (!groups[model.provider]) {
groups[model.provider] = [];
}
groups[model.provider].push(model);
}
return groups;
}, [models, recentlyUsedSet]);
// Get provider display name and baseURL for a given provider ID
const getProviderInfo = useMemo(() => {
return (providerId: string) => {
const provider = settings.providers.find(p => p.id === providerId);
return {
displayName: provider ? provider.name : providerId,
baseURL: provider?.baseURL,
};
};
}, [settings.providers]);
// Get display info for the selected model
const selectedModelDisplay = useMemo(() => {
if (!value) return null;
const providerId = value.split('/')[0];
const modelId = value.split('/').slice(1).join('/') || value;
const providerInfo = getProviderInfo(providerId);
const modelData = models.find(m => m.fullId === value);
const displayName = modelData?.name || modelId;
return {
displayName,
baseURL: providerInfo.baseURL,
};
}, [value, getProviderInfo, models]);
}, [models]);
// Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => {
@@ -123,67 +82,9 @@ export const ModelSelector = memo(function ModelSelector({
return !allRecentlyUsedAreAvailable;
}, [recentlyUsedModels, models]);
// Check if the current model is free
const isCurrentModelFree = useMemo(() => {
if (!value) return false;
const currentModel = models.find(model => model.fullId === value);
if (!currentModel?.pricing) return false;
return currentModel.pricing.prompt.equals(0) && currentModel.pricing.completion.equals(0);
}, [value, models]);
// Check if the current model is not in the provider's model list
const isCurrentModelNotInList = useMemo(() => {
if (!value) return false;
if (isLoading) return false; // Don't show warning while loading
if (models.length === 0) return false; // Don't show warning if no models loaded
const currentModel = models.find(model => model.fullId === value);
return !currentModel;
}, [value, models, isLoading]);
// Determine if we should show the warning icon
const shouldShowWarning = isCurrentModelFree || isCurrentModelNotInList;
// Get the warning message
const warningMessage = useMemo(() => {
if (isCurrentModelNotInList) {
return "This model is not available in your provider's model list. It may not work or may have been deprecated.";
}
if (isCurrentModelFree) {
return "You are using a free model. For better results, switch to a paid model.";
}
return "";
}, [isCurrentModelNotInList, isCurrentModelFree]);
// Don't auto-initialize with recently used models
// Let the parent component handle initialization
// Close tooltip when clicking outside on mobile
useEffect(() => {
if (!isMobile || !isTooltipOpen) return;
const handleClickOutside = (event: MouseEvent | TouchEvent) => {
const target = event.target as Element;
// Check if the click is outside the tooltip and trigger
if (!target.closest('[data-radix-tooltip-content]') &&
!target.closest('[data-radix-tooltip-trigger]') &&
!target.closest('[data-testid="triangle-alert"]')) {
setIsTooltipOpen(false);
}
};
// Add both click and touch event listeners
document.addEventListener('click', handleClickOutside, true);
document.addEventListener('touchstart', handleClickOutside, true);
return () => {
document.removeEventListener('click', handleClickOutside, true);
document.removeEventListener('touchstart', handleClickOutside, true);
};
}, [isMobile, isTooltipOpen]);
const handleSelect = (selectedValue: string) => {
if (selectedValue === '__custom__') {
setIsCustomInput(true);
@@ -224,278 +125,167 @@ export const ModelSelector = memo(function ModelSelector({
if (isCustomInput) {
return (
<TooltipProvider>
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
</TooltipProvider>
<div className={cn("flex items-center gap-1", className)}>
<Input
value={customValue}
onChange={(e) => setCustomValue(e.target.value)}
onKeyDown={handleCustomKeyDown}
onBlur={handleCustomSubmit}
placeholder="provider/model (e.g., openrouter/anthropic/claude-sonnet-4)"
className="h-8 text-xs"
autoFocus
/>
<Button
size="sm"
variant="ghost"
className="h-8 w-8 p-0"
onClick={handleCustomSubmit}
>
<Check className="h-3 w-3" />
</Button>
</div>
);
}
return (
<TooltipProvider>
<div className={cn("flex justify-end gap-0.5", className)}>
{shouldShowWarning && (
<Tooltip
open={isMobile ? isTooltipOpen : undefined}
onOpenChange={isMobile ? setIsTooltipOpen : undefined}
delayDuration={isMobile ? 0 : 700}
disableHoverableContent={isMobile}
>
<TooltipTrigger asChild>
<button
type="button"
className="inline-flex items-center p-0 rounded-none border-0 bg-transparent hover:bg-transparent focus:bg-transparent active:bg-transparent focus:outline-none focus-visible:outline-none focus:ring-0 focus-visible:ring-0 focus:border-0 active:outline-none"
aria-label="Model warning"
tabIndex={isMobile ? 0 : -1}
onClick={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : undefined}
onTouchStart={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
} : undefined}
onTouchEnd={isMobile ? (e) => {
e.preventDefault();
e.stopPropagation();
setIsTooltipOpen(!isTooltipOpen);
} : undefined}
style={{
WebkitTapHighlightColor: 'transparent',
outline: 'none',
border: 'none',
boxShadow: 'none'
}}
>
<TriangleAlert className="h-3 w-3 text-amber-500 flex-shrink-0" data-testid="triangle-alert" />
</button>
</TooltipTrigger>
<TooltipContent
side="top"
sideOffset={4}
className="max-w-xs text-center"
avoidCollisions={true}
collisionPadding={8}
>
<p>{warningMessage}</p>
</TooltipContent>
</Tooltip>
)}
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-1 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
)}
disabled={disabled}
>
{selectedModelDisplay ? (
<>
{selectedModelDisplay.baseURL ? (
<ExternalFavicon
url={selectedModelDisplay.baseURL}
size={16}
fallback={<Bot size={16} />}
className="flex-shrink-0"
/>
) : (
<Bot size={16} className="flex-shrink-0" />
)}
<span className="truncate">
{selectedModelDisplay.displayName}
</span>
</>
) : (
<span className="truncate">
{placeholder || defaultPlaceholder}
</span>
)}
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="p-0 w-80" align="end">
<Command>
{(isConfigured && models.length >= 5) && (
<CommandInput placeholder={t('searchModels')} className="h-9" />
)}
<CommandList>
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</CommandEmpty>
<Popover open={open} onOpenChange={setOpen}>
<PopoverTrigger asChild>
<Button
variant="ghost"
role="combobox"
aria-expanded={open}
className={cn(
"h-8 p-0 gap-0.5 justify-between text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right",
className
)}
disabled={disabled}
>
<span className="w-full truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-96 p-0" align="end">
<Command>
{isConfigured && <CommandInput placeholder={t('searchModels')} className="h-9" />}
<CommandList className="max-h-[300px]">
<CommandEmpty>
<div className="py-6 text-center text-sm text-muted-foreground">
<p>{t('noModelsFound')}</p>
<p className="mt-2 text-xs">{t('tryCustomModel')}</p>
</div>
</CommandEmpty>
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((modelId) => {
const modelData = models.find(m => m.fullId === modelId);
const providerId = modelId.split('/')[0];
const providerInfo = getProviderInfo(providerId);
const displayModelId = modelId.split('/').slice(1).join('/') || modelId;
const displayName = modelData?.name || displayModelId;
return (
<CommandItem
key={modelId}
value={modelId}
onSelect={() => handleSelect(modelId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === modelId ? "opacity-100" : "opacity-0"
)}
/>
{providerInfo.baseURL ? (
<ExternalFavicon
url={providerInfo.baseURL}
size={16}
fallback={<Bot size={16} />}
className="mr-2 flex-shrink-0"
/>
) : (
<Bot size={16} className="mr-2 flex-shrink-0" />
)}
<span className="truncate flex-1">{displayName}</span>
{modelData?.pricing && (
<ModelPricing pricing={modelData.pricing} className="ml-2" />
)}
</CommandItem>
);
})}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</CommandGroup>
)}
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([providerId, providerModels]) => {
const providerInfo = getProviderInfo(providerId);
return (
<div key={providerId}>
<CommandSeparator />
<CommandGroup heading={providerInfo.displayName}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
{providerInfo.baseURL ? (
<ExternalFavicon
url={providerInfo.baseURL}
size={16}
fallback={<Bot size={16} />}
className="mr-2 flex-shrink-0"
/>
) : (
<Bot size={16} className="mr-2 flex-shrink-0" />
)}
<span className="truncate flex-1">{model.name || model.id}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
);
})}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
{shouldShowRecentlyUsed && (
<CommandGroup heading={t('recentlyUsed')}>
{recentlyUsedModels.map((model) => (
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
key={model}
value={model}
onSelect={() => handleSelect(model)}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
<Check
className={cn(
"mr-2 h-4 w-4",
value === model ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model}</span>
</CommandItem>
))}
</CommandGroup>
)}
{shouldShowRecentlyUsed && <CommandSeparator />}
{/* Loading state */}
{isLoading && (
<CommandGroup heading={t('loading')}>
<div className="px-2 py-1.5">
<div className="space-y-2">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-3/4" />
<Skeleton className="h-4 w-1/2" />
</div>
</div>
</CommandGroup>
)}
{/* Error state */}
{error && !isLoading && (
<CommandGroup heading={t('errorLoadingModels')}>
<div className="px-2 py-1.5 text-sm text-muted-foreground">
<div className="flex items-start gap-2">
<AlertCircle className="h-4 w-4 text-destructive flex-shrink-0 mt-0.5" />
<div className="space-y-2">
<p className="text-destructive">{error}</p>
<Button
variant="outline"
size="sm"
onClick={refetch}
className="h-7 text-xs"
>
<RefreshCw className="h-3 w-3 mr-1" />
{t('retry')}
</Button>
</div>
</div>
</div>
</CommandGroup>
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate">{model.fullId}</span>
</CommandItem>
))}
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
</div>
</TooltipProvider>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
<CommandGroup>
{isConfigured && (
<CommandItem
value="__custom_model_option__"
onSelect={() => handleSelect('__custom__')}
className="cursor-pointer"
>
<Edit3 className="mr-2 h-4 w-4" />
{t('enterCustomModel')}
</CommandItem>
)}
<CommandItem
value="__manage_providers_option__"
onSelect={() => handleSelect('__manage_providers__')}
className="cursor-pointer"
>
<Settings className="mr-2 h-4 w-4" />
{t('manageProviders')}
</CommandItem>
</CommandGroup>
</CommandList>
</Command>
</PopoverContent>
</Popover>
);
});
}
+26 -25
View File
@@ -15,24 +15,29 @@ const GIT_KINDS = [
1621, // NIP-34 Issue
];
const GIT_RELAYS = [
'wss://git.shakespeare.diy/',
'wss://relay.ngit.dev/',
'wss://gitnostr.com/',
];
const NostrProvider: React.FC<NostrProviderProps> = (props) => {
const { children } = props;
const { config } = useAppContext();
const { config, presetRelays } = useAppContext();
const gitRelays = config.ngitServers.map(server => `wss://${server}/`);
const queryClient = useQueryClient();
// Create NPool instance only once
const pool = useRef<NPool | undefined>(undefined);
// Use refs so the pool always has the latest data
const relayMetadata = useRef(config.relayMetadata);
const relayUrl = useRef<string>(config.relayUrl);
// Update refs when config changes
useEffect(() => {
relayMetadata.current = config.relayMetadata;
queryClient.invalidateQueries({ queryKey: ['nostr'] });
}, [config.relayMetadata, queryClient]);
relayUrl.current = config.relayUrl;
queryClient.resetQueries();
}, [config.relayUrl, queryClient]);
// Initialize NPool only once
if (!pool.current) {
@@ -42,40 +47,36 @@ const NostrProvider: React.FC<NostrProviderProps> = (props) => {
},
reqRouter(filters) {
const routes = new Map<string, NostrFilter[]>();
routes.set(relayUrl.current, filters);
// Route to all read relays
const readRelays = relayMetadata.current.relays
.filter(r => r.read)
.map(r => r.url);
for (const url of readRelays) {
routes.set(url, filters);
}
// If all filters are git-related, also route to all git relays
if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) {
for (const url of gitRelays) {
// If all filters are git-related, route to all git relays
for (const url of GIT_RELAYS) {
routes.set(url, filters);
}
}
return routes;
},
eventRouter(event: NostrEvent) {
// Get write relays from metadata
const writeRelays = relayMetadata.current.relays
.filter(r => r.write)
.map(r => r.url);
const allRelays = new Set<string>(writeRelays);
// Publish to the selected relay
const allRelays = new Set<string>([relayUrl.current]);
// If it's a git-related event, also publish to the git relays
if (GIT_KINDS.includes(event.kind)) {
for (const url of gitRelays) {
for (const url of GIT_RELAYS) {
allRelays.add(url);
}
}
// Also publish to the preset relays, capped to 5
for (const { url } of (presetRelays ?? [])) {
allRelays.add(url);
if (allRelays.size >= 5) {
break;
}
}
return [...allRelays];
},
});
-62
View File
@@ -1,62 +0,0 @@
import { useEffect } from 'react';
import { useNostr } from '@nostrify/react';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
/**
* NostrSync - Syncs user's Nostr data
*
* This component runs globally to sync various Nostr data when the user logs in.
* Currently syncs:
* - NIP-65 relay list (kind 10002)
*/
export function NostrSync() {
const { nostr } = useNostr();
const { user } = useCurrentUser();
const { config, updateConfig } = useAppContext();
useEffect(() => {
if (!user) return;
const syncRelaysFromNostr = async () => {
try {
const events = await nostr.query(
[{ kinds: [10002], authors: [user.pubkey], limit: 1 }],
{ signal: AbortSignal.timeout(5000) }
);
if (events.length > 0) {
const event = events[0];
// Only update if the event is newer than our stored data
if (event.created_at > config.relayMetadata.updatedAt) {
const fetchedRelays = event.tags
.filter(([name]) => name === 'r')
.map(([_, url, marker]) => ({
url,
read: !marker || marker === 'read',
write: !marker || marker === 'write',
}));
if (fetchedRelays.length > 0) {
console.log('Syncing relay list from Nostr:', fetchedRelays);
updateConfig((current) => ({
...current,
relayMetadata: {
relays: fetchedRelays,
updatedAt: event.created_at,
},
}));
}
}
}
} catch (error) {
console.error('Failed to sync relays from Nostr:', error);
}
};
syncRelaysFromNostr();
}, [user, config.relayMetadata.updatedAt, nostr, updateConfig]);
return null;
}
-55
View File
@@ -1,55 +0,0 @@
import { WifiOff, Wifi } from 'lucide-react';
import { useEffect, useState } from 'react';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useOffline } from '@/hooks/useOffline';
/**
* Component that displays an indicator when the app is offline
*/
export function OfflineIndicator() {
const { isOffline, isOnline } = useOffline();
const [showOnlineNotification, setShowOnlineNotification] = useState(false);
const [wasOffline, setWasOffline] = useState(false);
useEffect(() => {
if (isOffline) {
setWasOffline(true);
}
if (isOnline && wasOffline) {
// Show "back online" notification briefly
setShowOnlineNotification(true);
const timer = setTimeout(() => {
setShowOnlineNotification(false);
setWasOffline(false);
}, 3000);
return () => clearTimeout(timer);
}
}, [isOffline, isOnline, wasOffline]);
if (!isOffline && !showOnlineNotification) {
return null;
}
return (
<div className="fixed bottom-4 left-4 right-4 md:left-auto md:right-4 md:w-96 z-50 animate-in slide-in-from-bottom-4">
{isOffline ? (
<Alert variant="destructive" className="shadow-lg border-2">
<WifiOff className="h-4 w-4" />
<AlertDescription className="font-medium">
You're offline. Some features may be limited.
</AlertDescription>
</Alert>
) : (
<Alert className="shadow-lg border-2 border-green-500 bg-green-50 dark:bg-green-950">
<Wifi className="h-4 w-4 text-green-600 dark:text-green-400" />
<AlertDescription className="font-medium text-green-600 dark:text-green-400">
You're back online!
</AlertDescription>
</Alert>
)}
</div>
);
}
@@ -1,104 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import { TestApp } from '@/test/TestApp';
import { OnboardingCreditsBadge } from './OnboardingCreditsBadge';
import type { UseQueryResult } from '@tanstack/react-query';
import type { CreditsResponse } from '@/hooks/useAICredits';
// Mock the useAICredits hook
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: vi.fn(),
}));
import { useAICredits } from '@/hooks/useAICredits';
const mockUseAICredits = vi.mocked(useAICredits);
describe('OnboardingCreditsBadge', () => {
const mockProvider = {
id: 'shakespeare',
name: 'Shakespeare',
baseURL: 'https://ai.shakespeare.diy/v1',
nostr: true,
};
it('renders credits badge when data is available', () => {
mockUseAICredits.mockReturnValue({
data: { object: 'credits', amount: 25.50 },
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(screen.getByText('$25.50')).toBeInTheDocument();
});
it('does not render when loading', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: true,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when there is an error', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: false,
error: new Error('Provider does not support credits'),
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when no credits data is available', () => {
mockUseAICredits.mockReturnValue({
data: undefined,
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
it('does not render when credits amount is 0', () => {
mockUseAICredits.mockReturnValue({
data: { object: 'credits', amount: 0 },
isLoading: false,
error: null,
} as UseQueryResult<CreditsResponse, Error>);
const { container } = render(
<TestApp>
<OnboardingCreditsBadge provider={mockProvider} />
</TestApp>
);
expect(container.firstChild).toBeNull();
});
});
-42
View File
@@ -1,42 +0,0 @@
import { Badge } from '@/components/ui/badge';
import { AIProvider } from '@/contexts/AISettingsContext';
import { useAICredits } from '@/hooks/useAICredits';
interface OnboardingCreditsBadgeProps {
provider: AIProvider;
className?: string;
}
/**
* Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider
*/
export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) {
const { data: credits, isLoading, error } = useAICredits(provider);
// Don't render anything if there's an error (provider doesn't support credits endpoint)
if (error || isLoading) {
return null;
}
// Don't render if no credits data is available or if amount is 0
if (!credits || credits.amount === 0) {
return null;
}
// Format the amount as currency
const formattedAmount = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(credits.amount);
return (
<Badge
variant="secondary"
className={`text-xs ${className}`}
>
{formattedAmount}
</Badge>
);
}
+3 -5
View File
@@ -10,7 +10,7 @@ vi.mock('@/hooks/useAISettings', () => ({
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
updateSettings: vi.fn(),
isConfigured: false,
@@ -42,11 +42,9 @@ describe('OnboardingDialog', () => {
</TestApp>
);
// Translations are rendered, so we check for the actual English text
expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument();
expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading
expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument();
// The button now shows the translated text "Get Started"
expect(screen.getByRole('button', { name: 'Get Started' })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument();
});
it('does not render when closed', () => {
+109 -508
View File
@@ -1,166 +1,59 @@
import { useState, useEffect, useRef } from 'react';
import { Decimal } from 'decimal.js';
import { useState, useEffect } from 'react';
import { generateSecretKey } from 'nostr-tools';
import { nip19 } from 'nostr-tools';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink, Search, Coins } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react';
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
import { Card, CardHeader, CardTitle } from '@/components/ui/card';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Checkbox } from '@/components/ui/checkbox';
import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { ScrollArea } from '@/components/ui/scroll-area';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useLoginActions } from '@/hooks/useLoginActions';
import { useProviderModels } from '@/hooks/useProviderModels';
import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from '@/components/CreditsDialog';
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ModelPricing } from '@/components/ModelPricing';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
import { cn } from '@/lib/utils';
import { LoginArea } from '@/components/auth/LoginArea';
import { AIProvider } from '@/contexts/AISettingsContext';
interface OnboardingDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'nostr-identity' | 'model-selection' | 'conclusion';
type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
const SHAKESPEARE_PROVIDER = {
id: "shakespeare",
baseURL: "https://ai.shakespeare.diy/v1",
nostr: true,
};
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
const { t } = useTranslation();
const [step, setStep] = useState<OnboardingStep>('welcome');
const [selectedProvider, setSelectedProvider] = useState<PresetProvider | null>(null);
const [providerApiKey, setProviderApiKey] = useState<string>('');
const [selectedModel, setSelectedModel] = useState<string>('');
const [isSettingUp, setIsSettingUp] = useState(false);
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const [agreedToTerms, setAgreedToTerms] = useState(false);
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
const [modelSearchQuery, setModelSearchQuery] = useState('');
const [generatedNsec, setGeneratedNsec] = useState<string>('');
// Ref for the scrollable content area
const scrollableContentRef = useRef<HTMLDivElement>(null);
const { setProvider, addRecentlyUsedModel } = useAISettings();
const { user } = useCurrentUser();
const login = useLoginActions();
const { models, isLoading: isLoadingModels } = useProviderModels();
// Fetch credits for the selected provider (only if it's a Nostr provider and user is logged in)
const creditsQuery = useAICredits(
selectedProvider && selectedProvider.nostr && user
? {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr,
}
: { id: '', name: '', baseURL: '', nostr: undefined }
);
// Filter models to only show selected provider models
const providerModels = selectedProvider
? models.filter(model => model.provider === selectedProvider.id)
: [];
// Filter models by search query
const filteredModels = modelSearchQuery
? providerModels.filter(model => {
const searchLower = modelSearchQuery.toLowerCase();
const modelName = (model.name || model.id).toLowerCase();
const modelDescription = (model.description || '').toLowerCase();
return modelName.includes(searchLower) || modelDescription.includes(searchLower);
})
: providerModels;
// Determine if we should show descriptions (only if 8 or fewer models)
const showDescriptions = providerModels.length <= 8;
const handleGetStarted = () => {
setStep('open-source');
};
const handleContinueFromOpenSource = () => {
if (!agreedToTerms) return;
setStep('provider-selection');
};
const handleProviderSelect = (provider: PresetProvider) => {
setSelectedProvider(provider);
// Clear API key when switching providers
setProviderApiKey('');
// Reset provider terms agreement when switching providers
setAgreedToProviderTerms(false);
};
const handleContinueFromProviderSelection = async () => {
if (!selectedProvider) return;
// Check if user agreed to provider terms
if (!agreedToProviderTerms) return;
// Check if provider requires API key and if it's provided
const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr;
if (requiresApiKey && !providerApiKey.trim()) return;
// Filter models to only show Shakespeare provider models
const shakespeareModels = models.filter(model => model.provider === 'shakespeare');
const handleGetStarted = async () => {
setIsSettingUp(true);
try {
// If user is not logged in and provider uses Nostr auth, generate key and show identity step
if (!user && selectedProvider.nostr) {
// If user is not logged in, generate and login with secret key
if (!user) {
const secretKey = generateSecretKey();
const nsec = nip19.nsecEncode(secretKey);
setGeneratedNsec(nsec);
setStep('nostr-identity');
setIsSettingUp(false);
return;
login.nsec(nsec);
}
// Add selected provider to their config
const providerConfig: AIProvider = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
};
setProvider(providerConfig);
// Move to model selection
setStep('model-selection');
} catch (error) {
console.error('Failed to set up user:', error);
} finally {
setIsSettingUp(false);
}
};
const handleContinueFromNostrIdentity = async () => {
if (!selectedProvider) return;
setIsSettingUp(true);
try {
// If no user is logged in yet, log in with generated key
if (!user && generatedNsec) {
login.nsec(generatedNsec);
}
// Add selected provider to their config
const providerConfig: AIProvider = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
};
setProvider(providerConfig);
// Add Shakespeare provider to their config
setProvider(SHAKESPEARE_PROVIDER);
// Move to model selection
setStep('model-selection');
@@ -182,17 +75,17 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
addRecentlyUsedModel(selectedModel);
// Find the selected model to check if it's free
const model = providerModels.find(m => m.fullId === selectedModel);
const model = shakespeareModels.find(m => m.fullId === selectedModel);
const isFreeModel = !model?.pricing || (
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
);
// Only show credits dialog if the provider uses Nostr AND the model is paid
if (!isFreeModel && selectedProvider?.nostr) {
setShowCreditsDialog(true);
} else {
// Free model or non-Nostr provider, go straight to conclusion
if (isFreeModel) {
// Free model, go straight to conclusion
setStep('conclusion');
} else {
// Paid model, show credits dialog
setShowCreditsDialog(true);
}
};
@@ -205,36 +98,31 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
onOpenChange(false);
};
const formatPrice = (price: Decimal | undefined) => {
if (!price) return 'unknown';
if (price.equals(0)) return 'Free';
// Convert from per-token to per-1M tokens and format with $ prefix
const pricePerMillion = price.times(1_000_000);
return '$' + pricePerMillion.toFixed(2).toString().replace(/\.00$/, '') + '/M tokens';
};
// Reset state when dialog opens/closes
useEffect(() => {
if (open) {
setStep('welcome');
setSelectedProvider(null);
setProviderApiKey('');
setSelectedModel('');
setIsSettingUp(false);
setShowCreditsDialog(false);
setAgreedToTerms(false);
setAgreedToProviderTerms(false);
setModelSearchQuery('');
setGeneratedNsec('');
}
}, [open]);
// Scroll to top when step changes
useEffect(() => {
if (scrollableContentRef.current) {
scrollableContentRef.current.scrollTop = 0;
}
}, [step]);
return (
<>
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl h-dvh-safe sm:h-auto sm:max-h-[90vh] flex flex-col">
<DialogHeader className="flex-shrink-0">
<DialogContent className="max-w-2xl max-h-[80vh] overflow-hidden">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
{step === 'open-source' && (
{step === 'model-selection' && (
<Button
variant="ghost"
size="sm"
@@ -244,82 +132,40 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'provider-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('open-source')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'nostr-identity' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('provider-selection')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'model-selection' && (
<Button
variant="ghost"
size="sm"
onClick={() => {
// Go back to nostr-identity if we have a generated key, otherwise provider-selection
setStep(generatedNsec ? 'nostr-identity' : 'provider-selection');
}}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
{step === 'conclusion' && (
<Button
variant="ghost"
size="sm"
onClick={() => setStep('model-selection')}
className="mr-2 p-1 h-auto"
>
<ArrowLeft className="h-4 w-4" />
</Button>
)}
<span className="text-xl">
{step === 'model-selection' && t('chooseYourAIModel')}
{step === 'welcome' && 'Welcome to Shakespeare!'}
{step === 'model-selection' && 'Choose Your AI Model'}
{step === 'conclusion' && "You're All Set!"}
</span>
</DialogTitle>
</DialogHeader>
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
<div className="flex-1 overflow-hidden">
{step === 'welcome' && (
<div className="text-center space-y-6 py-4">
<div className="mb-4">
<ShakespeareLogo className="w-16 h-16 mx-auto" />
</div>
<div className="text-6xl mb-4">🎭</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
{t('welcomeToShakespeareOnboarding')}
Welcome to Shakespeare!
</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
{t('aiPoweredDevelopmentAssistant')}
Your AI-powered development assistant for building custom Nostr applications.
Simply describe what you want to build, and AI will help you create it.
</p>
</div>
<div className="space-y-4">
<div className="grid grid-cols-1 md:grid-cols-3 gap-4 max-w-lg mx-auto">
<div className="text-center space-y-2">
<div className="text-2xl">💡</div>
<p className="text-sm text-muted-foreground">{t('aiPoweredDevelopment')}</p>
<p className="text-sm text-muted-foreground">AI-Powered Development</p>
</div>
<div className="text-center space-y-2">
<div className="text-2xl">⚡</div>
<p className="text-sm text-muted-foreground">{t('nostrIntegration')}</p>
<p className="text-sm text-muted-foreground">Nostr Integration</p>
</div>
<div className="text-center space-y-2">
<div className="text-2xl">🚀</div>
<p className="text-sm text-muted-foreground">{t('instantPreview')}</p>
<p className="text-sm text-muted-foreground">Instant Preview</p>
</div>
</div>
<Button
@@ -327,260 +173,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
disabled={isSettingUp}
size="lg"
className="gap-2"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
{t('settingUp')}
</>
) : (
<>
<Sparkles className="h-4 w-4" />
{t('getStarted')}
</>
)}
</Button>
</div>
</div>
)}
{step === 'open-source' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">
{t('shakespeareOpenSource')}
</h2>
</div>
<div className="grid gap-1 max-w-md mx-auto">
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">{t('yourDeviceConnects')}</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">{t('filesStoredOnDevice')}</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">{t('carefulBrowserData')}</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">{t('responsibleBackups')}</p>
</div>
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
<p className="text-sm">{t('qualityDependsOnInput')}</p>
</div>
</div>
<div className="space-y-3 max-w-md mx-auto">
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
{t('shakespeareNotCloudService')}
</p>
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-terms"
checked={agreedToTerms}
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
/>
<label
htmlFor="agree-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('iAgree')}
</label>
</div>
</div>
<div className="flex justify-center">
<Button
onClick={handleContinueFromOpenSource}
disabled={!agreedToTerms}
className="gap-2 rounded-full w-full max-w-md"
>
{t('continueButton')}
<ArrowRight className="h-4 w-4" />
</Button>
</div>
</div>
)}
{step === 'provider-selection' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">{t('chooseAIProvider')}</h2>
<p className="text-muted-foreground max-w-md mx-auto">
{t('selectAIProviderDescription')}
</p>
</div>
<div className="grid grid-cols-1 md:grid-cols-2 p-1 gap-3 max-w-4xl mx-auto">
{AI_PROVIDER_PRESETS.map((provider) => {
const isSelected = selectedProvider?.id === provider.id;
const isShakespeare = provider.id === 'shakespeare';
return (
<Card
key={provider.id}
className={cn('cursor-pointer transition-all hover:shadow-md', {
'ring-2 ring-primary': isSelected,
})}
onClick={() => handleProviderSelect(provider)}
>
<div className="flex items-center justify-between p-3">
<div className="flex items-center gap-2 flex-1">
<ExternalFavicon
url={provider.baseURL}
size={20}
fallback={<Bot size={20} />}
/>
<CardTitle className={cn('text-lg font-semibold', {
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isShakespeare,
})}>
{provider.name}
</CardTitle>
</div>
<div className="flex items-center gap-2">
<OnboardingCreditsBadge provider={provider} />
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</div>
</Card>
);
})}
</div>
{/* API Key Input Section */}
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
<div className="space-y-3 max-w-md mx-auto">
<div className="text-center">
<h3 className="text-lg font-semibold">
{selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
</h3>
<p className="text-sm text-muted-foreground">
{selectedProvider.id === 'routstr' ? (
t('requiresCashuToken', { providerName: selectedProvider.name })
) : (
<>
{selectedProvider.name} {t('requiresAnApiKey')}{' '}
{selectedProvider.apiKeysURL ? (
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
{t('apiKey')}
<ExternalLink className="inline-block h-4 w-4 ml-1" />
</a>
) : (
t('apiKey')
)}
</>
)}
</p>
</div>
<PasswordInput
placeholder={selectedProvider.id === 'routstr' ? t('enterCashuToken') : t('enterApiKey')}
value={providerApiKey}
onChange={(e) => setProviderApiKey(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && providerApiKey.trim()) {
handleContinueFromProviderSelection();
}
}}
/>
</div>
)}
{/* Terms of Service Agreement */}
{selectedProvider && (
<div className="space-y-3 max-w-md mx-auto">
<div className="flex items-center justify-center gap-2">
<Checkbox
id="agree-provider-terms"
checked={agreedToProviderTerms}
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
/>
<label
htmlFor="agree-provider-terms"
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('agreeToTermsOfService', { providerName: selectedProvider.name })}{' '}
{selectedProvider.tosURL ? (
<a
href={selectedProvider.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-primary underline hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
{t('termsOfService')}
</a>
) : (
t('termsOfService')
)}
</label>
</div>
</div>
)}
<div className="flex justify-center">
<Button
onClick={handleContinueFromProviderSelection}
disabled={
!selectedProvider ||
isSettingUp ||
!agreedToProviderTerms ||
!!(selectedProvider?.apiKeysURL && !selectedProvider?.nostr && !providerApiKey.trim())
}
className="gap-2 rounded-full w-full max-w-md"
>
{isSettingUp ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
{t('settingUp')}
</>
) : (
<>
{t('continueButton')}
<ArrowRight className="h-4 w-4" />
</>
)}
</Button>
</div>
</div>
)}
{step === 'nostr-identity' && (
<div className="space-y-6 py-4">
<div className="text-center space-y-4">
<h2 className="text-2xl font-bold">Your Nostr Account</h2>
<p className="text-muted-foreground max-w-md mx-auto">
This is the account that will be used with {selectedProvider?.name}.
</p>
</div>
<div className="flex flex-col items-center space-y-4">
<LoginArea className="w-full max-w-xs" />
{user && creditsQuery.data && (
<div className="flex items-center gap-2 text-sm bg-muted/50 px-4 py-2 rounded-full">
<Coins className="h-4 w-4 text-primary" />
<span className="font-semibold">
{creditsQuery.data.amount.toLocaleString()} credits available
</span>
</div>
)}
</div>
<div className="flex justify-center">
<Button
onClick={handleContinueFromNostrIdentity}
disabled={isSettingUp}
className="gap-2 rounded-full w-full max-w-md"
>
{isSettingUp ? (
<>
@@ -589,8 +181,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</>
) : (
<>
Continue
<ArrowRight className="h-4 w-4" />
<Sparkles className="h-4 w-4" />
Get Started
</>
)}
</Button>
@@ -599,24 +191,15 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
)}
{step === 'model-selection' && (
<div className="flex flex-col h-full">
{/* Search filter - only show if more than 8 models */}
{!isLoadingModels && providerModels.length > 8 && (
<div className="mb-4 flex-shrink-0">
<div className="relative">
<Search className="absolute left-3 top-1/2 transform -translate-y-1/2 h-4 w-4 text-muted-foreground" />
<Input
type="text"
placeholder={t('searchModels')}
value={modelSearchQuery}
onChange={(e) => setModelSearchQuery(e.target.value)}
className="pl-9"
/>
</div>
</div>
)}
<div className="space-y-4">
<div className="text-center space-y-2">
<p className="text-muted-foreground">
Choose an AI model to power your development experience.
Different models offer various capabilities and pricing.
</p>
</div>
<div className="flex-1 overflow-y-auto min-h-0 my-4">
<ScrollArea className="h-96">
<div className="space-y-3 p-1">
{isLoadingModels ? (
<>
@@ -636,64 +219,81 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Card>
))}
</>
) : filteredModels.length === 0 ? (
) : shakespeareModels.length === 0 ? (
<Card className="p-6 text-center">
<div className="space-y-2">
<Bot className="h-8 w-8 mx-auto text-muted-foreground" />
<p className="text-muted-foreground">
{modelSearchQuery ? t('noModelsMatchingSearch') : t('noModelsAvailable')}
No models available. Please check your connection and try again.
</p>
</div>
</Card>
) : (
filteredModels.map((model) => {
shakespeareModels.map((model) => {
const isSelected = selectedModel === model.fullId;
const modelName = model.name || model.id;
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
return (
<Card
key={model.fullId}
className={`relative cursor-pointer transition-all hover:shadow-md ${
className={`cursor-pointer transition-all hover:shadow-md ${
isSelected ? 'ring-2 ring-primary' : ''
}`}
onClick={() => handleModelSelect(model.fullId)}
>
<CardHeader>
<CardHeader className="pb-3">
<div className="flex items-center justify-between">
<div className="flex-1">
<CardTitle className="text-sm font-semibold flex gap-1">
<span>{modelName}</span>
{model.pricing && <ModelPricing pricing={model.pricing} />}
<CardTitle className="text-base font-semibold">
{model.description || model.name || model.id}
</CardTitle>
{showDescriptions && model.description && (
<p className="text-lg text-muted-foreground mt-1">
{model.description.length > 500
? model.description.slice(0, 500) + '...'
: model.description}
{model.description && (
<p className="text-sm text-muted-foreground mt-1">
{model.name || model.id}
</p>
)}
</div>
{isSelected && (
<div className="absolute top-5 right-5 h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
<div className="flex items-center gap-2">
{isFree && (
<Badge variant="secondary" className="text-xs">
Free
</Badge>
)}
{isSelected && (
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
<Check className="h-3 w-3 text-primary-foreground" />
</div>
)}
</div>
</div>
</CardHeader>
<CardContent className="pt-0">
<div className="flex items-center gap-4 text-xs text-muted-foreground">
{model.pricing && (
<>
<span>Input: {formatPrice(model.pricing.prompt)}</span>
<span>Output: {formatPrice(model.pricing.completion)}</span>
</>
)}
{model.contextLength && (
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
)}
</div>
</CardContent>
</Card>
);
})
)}
</div>
</div>
</ScrollArea>
<div className="flex justify-end gap-2 pt-4 flex-shrink-0">
<div className="flex justify-end gap-2 pt-4 border-t">
<Button
onClick={handleContinue}
disabled={!selectedModel}
className="gap-2"
>
{t('continueButton')}
Continue
<ArrowRight className="h-4 w-4" />
</Button>
</div>
@@ -704,14 +304,20 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
<div className="text-center space-y-6 py-8">
<div className="text-5xl mb-4">🎉</div>
<div className="space-y-3">
<h2 className="text-2xl font-bold">{t('nowYoureReady')}</h2>
<h2 className="text-2xl font-bold">Now you're ready to build!</h2>
<p className="text-lg text-muted-foreground max-w-md mx-auto">
{t('aiAssistantConfigured')}
Your AI assistant is configured and ready to help.
Just enter your prompt to start building amazing Nostr applications.
</p>
</div>
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
<p className="text-sm text-muted-foreground italic">
"Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..."
</p>
</div>
<Button onClick={handleFinish} size="lg" className="gap-2">
<Sparkles className="h-4 w-4" />
{t('startBuilding')}
Start Building
</Button>
</div>
)}
@@ -720,7 +326,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
</Dialog>
{/* Credits Dialog */}
{showCreditsDialog && selectedModel && selectedProvider && (
{showCreditsDialog && selectedModel && (
<CreditsDialog
open={showCreditsDialog}
onOpenChange={(open) => {
@@ -728,12 +334,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
handleCreditsDialogClose();
}
}}
provider={{
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
provider={SHAKESPEARE_PROVIDER}
/>
)}
</>
-89
View File
@@ -1,89 +0,0 @@
import { useEffect, useState } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import { Sparkles, X } from 'lucide-react';
/**
* Component that prompts users to update when a new service worker is available
*/
export function PWAUpdatePrompt() {
const [showPrompt, setShowPrompt] = useState(false);
const [isUpdating, setIsUpdating] = useState(false);
const {
offlineReady: [offlineReady],
needRefresh: [needRefresh],
updateServiceWorker,
} = useRegisterSW({
onRegisteredSW(swUrl, registration) {
console.log('[PWA] Service worker registered:', swUrl);
// Check for updates periodically (every hour)
if (registration) {
const intervalId = setInterval(async () => {
try {
await registration.update();
} catch (error) {
// Registration may no longer be valid, clear the interval
console.warn('[PWA] Failed to check for updates:', error);
clearInterval(intervalId);
}
}, 60 * 60 * 1000);
}
},
onRegisterError(error) {
console.error('[PWA] Service worker registration error:', error);
},
});
useEffect(() => {
if (offlineReady) {
console.log('[PWA] App ready to work offline');
}
}, [offlineReady]);
useEffect(() => {
if (needRefresh) {
setShowPrompt(true);
}
}, [needRefresh]);
const handleUpdate = () => {
setIsUpdating(true);
updateServiceWorker(true);
};
const handleDismiss = (e: React.MouseEvent) => {
e.stopPropagation();
setShowPrompt(false);
};
if (!showPrompt) {
return null;
}
return (
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full">
<div className="relative group">
<button
onClick={handleUpdate}
disabled={isUpdating}
className={`relative flex items-center gap-2 px-4 py-2.5 ${!isUpdating ? 'pr-10' : ''} bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate`}
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
{!isUpdating && (
<button
onClick={handleDismiss}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded-full hover:bg-amber-200 dark:hover:bg-amber-800 transition-colors duration-200"
aria-label="Dismiss update notification"
>
<X className="h-4 w-4 text-amber-700 dark:text-amber-300" />
</button>
)}
</div>
</div>
);
}
-273
View File
@@ -1,273 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Puzzle, Plus, Trash2, RefreshCw, Loader2, Check } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { usePlugins } from '@/hooks/usePlugins';
import { usePluginGitInfo } from '@/hooks/usePluginGitInfo';
import { useToast } from '@/hooks/useToast';
export function PluginsSection() {
const { t } = useTranslation();
const { toast } = useToast();
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
const [gitUrl, setGitUrl] = useState('');
const handleAddPlugin = async () => {
if (!gitUrl.trim()) return;
try {
const pluginName = await clonePlugin.mutateAsync({ gitUrl: gitUrl.trim() });
toast({
title: t('pluginAdded'),
description: t('pluginAddedDescription', { name: pluginName }),
});
setGitUrl('');
} catch (error) {
toast({
title: t('pluginAddFailed'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
}
};
const handleSyncPlugin = async (pluginName: string) => {
try {
await syncPlugin.mutateAsync(pluginName);
toast({
title: t('pluginSynced'),
description: t('pluginSyncedDescription', { name: pluginName }),
});
} catch (error) {
toast({
title: t('pluginSyncFailed'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
}
};
const handleDeletePlugin = async (pluginName: string) => {
try {
await deletePlugin.mutateAsync(pluginName);
toast({
title: t('pluginDeleted'),
description: t('pluginDeletedDescription', { name: pluginName }),
});
} catch (error) {
toast({
title: t('pluginDeleteFailed'),
description: error instanceof Error ? error.message : String(error),
variant: 'destructive',
});
}
};
// Group skills by plugin
const skillsByPlugin = skills.reduce((acc, skill) => {
if (!acc[skill.plugin]) {
acc[skill.plugin] = [];
}
acc[skill.plugin].push(skill);
return acc;
}, {} as Record<string, typeof skills>);
return (
<div className="space-y-4">
{/* Plugins Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<Puzzle className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('plugins')}</h3>
</div>
<p className="text-sm text-muted-foreground">
{t('pluginsDescription')}
</p>
</div>
{/* Configured Plugins List */}
{plugins.length > 0 && (
<div className="space-y-2">
{plugins.map((pluginName) => {
const pluginSkills = skillsByPlugin[pluginName] || [];
const isSyncing = syncPlugin.isPending && syncPlugin.variables === pluginName;
const isDeleting = deletePlugin.isPending && deletePlugin.variables === pluginName;
return <PluginItem
key={pluginName}
pluginName={pluginName}
pluginSkills={pluginSkills}
isSyncing={isSyncing}
isDeleting={isDeleting}
onSync={handleSyncPlugin}
onDelete={handleDeletePlugin}
/>;
})}
</div>
)}
{/* Add Plugin Section */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-plugin">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<span className="text-sm font-medium">{t('addPlugin')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="plugin-git-url">
{t('gitRepositoryUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="plugin-git-url"
placeholder="https://github.com/user/plugin.git"
value={gitUrl}
onChange={(e) => setGitUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter' && gitUrl.trim()) {
handleAddPlugin();
}
}}
/>
</div>
<Button
onClick={handleAddPlugin}
disabled={!gitUrl.trim() || clonePlugin.isPending}
className="gap-2 w-full"
>
{clonePlugin.isPending ? (
<>
<Loader2 className="h-4 w-4 animate-spin" />
{t('cloning')}
</>
) : (
<>
<Check className="h-4 w-4" />
{t('addPlugin')}
</>
)}
</Button>
<p className="text-xs text-muted-foreground">
{t('pluginDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
);
}
interface PluginItemProps {
pluginName: string;
pluginSkills: Array<{ name: string; description: string; path: string; plugin: string }>;
isSyncing: boolean;
isDeleting: boolean;
onSync: (pluginName: string) => void;
onDelete: (pluginName: string) => void;
}
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete }: PluginItemProps) {
const { t } = useTranslation();
const { data: gitInfo } = usePluginGitInfo(pluginName);
return (
<Accordion type="single" collapsible className="w-full">
<AccordionItem value={pluginName} className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Puzzle className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{pluginName}</span>
{pluginSkills.length > 0 && (
<span className="text-xs text-muted-foreground">
({pluginSkills.length} {pluginSkills.length === 1 ? 'skill' : 'skills'})
</span>
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
{/* Skills List */}
{pluginSkills.length > 0 && (
<div className="space-y-2">
<Label className="text-xs text-muted-foreground">{t('skills')}</Label>
<div className="space-y-1">
{pluginSkills.map((skill) => (
<div
key={skill.name}
className="flex items-start gap-2 p-2 rounded-md bg-muted/50"
>
<div className="flex-1 min-w-0">
<div className="text-sm font-medium font-mono">{skill.name}</div>
<div className="text-xs text-muted-foreground line-clamp-2">
{skill.description}
</div>
</div>
</div>
))}
</div>
</div>
)}
{/* Plugin Actions and Git Info */}
<div className="space-y-2 pt-2">
{gitInfo && (
<div className="flex items-center gap-2 text-xs text-muted-foreground">
<code className="bg-muted px-1.5 py-0.5 rounded">{gitInfo.commitHash.substring(0, 7)}</code>
<span>•</span>
<span>{gitInfo.commitDate.toLocaleDateString()}</span>
</div>
)}
<div className="flex gap-2">
<Button
variant="outline"
size="sm"
onClick={() => onSync(pluginName)}
disabled={isSyncing || isDeleting}
className="flex-1"
>
{isSyncing ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('syncing')}
</>
) : (
<>
<RefreshCw className="h-4 w-4 mr-2" />
{t('sync')}
</>
)}
</Button>
<Button
variant="destructive"
size="sm"
onClick={() => onDelete(pluginName)}
disabled={isSyncing || isDeleting}
className="flex-1"
>
{isDeleting ? (
<>
<Loader2 className="h-4 w-4 mr-2 animate-spin" />
{t('deleting')}
</>
) : (
<>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</>
)}
</Button>
</div>
</div>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
);
}
+2 -61
View File
@@ -23,7 +23,6 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { useToast } from '@/hooks/useToast';
import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useNavigate } from 'react-router-dom';
import {
@@ -33,13 +32,9 @@ import {
Loader2,
Trash2,
Save,
DollarSign,
ExternalLink,
FileCode,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
import { DotAI } from '@/lib/DotAI';
interface ProjectDetailsDialogProps {
project: Project;
@@ -53,11 +48,8 @@ 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 [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const { toast } = useToast();
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
const navigate = useNavigate();
const queryClient = useQueryClient();
@@ -68,31 +60,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsRenaming(false);
}, [project.id]);
// Load total project cost and template info
useEffect(() => {
const loadProjectData = async () => {
try {
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
// Load cost
const cost = await dotAI.readCost();
setTotalCost(cost);
// Load template info
const template = await dotAI.readTemplate();
setTemplateInfo(template);
} catch (error) {
console.warn('Failed to load project data:', error);
setTotalCost(null);
setTemplateInfo(null);
}
};
if (open) {
loadProjectData();
}
}, [fs, projectsPath, project.id, open]);
const formatDistanceToNow = (date: Date) => {
const now = new Date();
const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000);
@@ -176,7 +143,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsExporting(true);
try {
const zip = new JSZip();
const projectPath = `${projectsPath}/${project.id}`;
const projectPath = `/projects/${project.id}`;
// Recursive function to add files and directories to zip from a specific project
const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => {
@@ -241,7 +208,7 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-md" onOpenAutoFocus={(e) => e.preventDefault()}>
<DialogContent className="max-w-md">
<DialogHeader>
<DialogTitle className="flex items-center gap-2">
<Folder className="h-5 w-5" />
@@ -257,32 +224,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
<span>{formatDistanceToNow(project.lastModified)}</span>
</div>
{/* Total Cost */}
{totalCost !== null && totalCost > 0 && (
<div className="flex items-center gap-2 text-sm">
<DollarSign className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Total Cost:</span>
<span className="font-mono">${totalCost.toFixed(6)}</span>
</div>
)}
{/* Template Info */}
{templateInfo && (
<div className="flex items-center gap-2 text-sm">
<FileCode className="h-4 w-4 text-muted-foreground" />
<span className="text-muted-foreground">Template:</span>
<a
href={templateInfo.url}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1 text-primary hover:underline"
>
{templateInfo.name}
<ExternalLink className="h-3 w-3" />
</a>
</div>
)}
{/* Project Name */}
<div className="space-y-2">
<Label htmlFor="project-name">Project Name</Label>
+1 -1
View File
@@ -60,7 +60,7 @@ describe('ProjectSidebar', () => {
</TestApp>
);
expect(screen.getByAltText('Shakespeare')).toBeInTheDocument();
expect(screen.getByText('🎭')).toBeInTheDocument();
expect(screen.getByText('Shakespeare')).toBeInTheDocument();
});
+73 -74
View File
@@ -1,19 +1,20 @@
import React, { useEffect, useState, useMemo } from 'react';
import React, { useEffect, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Search } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, FileArchive } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useToast } from '@/hooks/useToast';
import type { Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { useQueryClient } from '@tanstack/react-query';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
interface ProjectItemProps {
project: Project;
@@ -94,24 +95,13 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const [searchQuery, setSearchQuery] = useState('');
const projectsManager = useProjectsManager();
const { toast } = useToast();
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const isMobile = useIsMobile();
const navigate = useNavigate();
// Fast in-memory search filtering
const filteredProjects = useMemo(() => {
if (!searchQuery.trim()) {
return projects;
}
const query = searchQuery.toLowerCase();
return projects.filter(project =>
project.id.toLowerCase().includes(query) ||
project.name.toLowerCase().includes(query)
);
}, [projects, searchQuery]);
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
@@ -133,7 +123,24 @@ export function ProjectSidebar({
}
};
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
try {
// Import project from zip file
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
// Show success toast
toast({
title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully",
description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`,
});
// Navigate to the imported project
navigate(`/project/${project.id}`);
} catch (error) {
console.error('Failed to import project:', error);
throw error; // Re-throw to let the dialog handle the error display
}
};
useEffect(() => {
queryClient.invalidateQueries({ queryKey: ['projects'] });
@@ -146,47 +153,45 @@ export function ProjectSidebar({
return (
<div className={cn("flex flex-col h-full bg-gradient-to-b from-sidebar to-sidebar/95", className)}>
{/* Header with Logo */}
<div className="pt-safe bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex px-4 h-12 border-b border-sidebar-border">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigateAndClose('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<ShakespeareLogo className="w-6 h-6" />
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</button>
{(onToggleSidebar || (onClose && isMobile)) && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
) : (
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
)}
</Button>
</div>
)}
</div>
<div className="flex px-4 h-12 border-b border-sidebar-border bg-gradient-to-r from-primary/10 via-accent/5 to-primary/10">
<div className="flex items-center justify-between w-full">
<button
onClick={() => navigateAndClose('/')}
className="flex items-center gap-3 hover:opacity-80 transition-opacity text-left"
>
<span className="text-2xl">🎭</span>
<h1 className="text-xl font-semibold bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent">
Shakespeare
</h1>
</button>
{(onToggleSidebar || (onClose && isMobile)) && (
<div className="flex items-center gap-1">
<Button
variant="ghost"
size="sm"
className="h-8 w-8 p-0 hover:bg-primary/10 -mr-2"
onClick={handleToggleSidebar}
aria-label={(onClose && isMobile) ? t('closeSidebar') : t('collapseSidebar')}
>
{(onClose && isMobile) ? (
<X className="h-4 w-4 text-primary/60 hover:text-primary" />
) : (
<Columns2 className="h-4 w-4 text-primary/60 hover:text-primary" />
)}
</Button>
</div>
)}
</div>
</div>
<div className="flex-1 overflow-y-auto">
<div className="p-2">
<div className="mb-2 space-y-3">
<div className="mb-2">
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
<div className="flex">
<button
onClick={handleNewProject}
className="flex-1 flex items-center justify-center px-3 py-2.5 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
>
<Plus className="h-4 w-4 mr-2" />
{t('newProject')}
@@ -194,7 +199,7 @@ export function ProjectSidebar({
<div className="w-px bg-white/20" />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="px-3 py-2.5 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<ChevronDown className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
@@ -206,24 +211,17 @@ export function ProjectSidebar({
<GitBranch className="h-4 w-4" />
{t('importRepository')}
</DropdownMenuItem>
<DropdownMenuItem
onClick={() => setIsZipDialogOpen(true)}
className="flex items-center gap-2 w-full"
>
<FileArchive className="h-4 w-4" />
Import ZIP File
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
</div>
{/* Search Input */}
{projects.length > 0 && (
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
<Input
type="text"
placeholder={t('searchProjects')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 text-sm bg-sidebar-accent/50 border-sidebar-border focus-visible:ring-primary/50"
/>
</div>
)}
</div>
{isLoading ? (
@@ -243,15 +241,9 @@ export function ProjectSidebar({
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
</div>
) : filteredProjects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Search className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsFound')}</p>
<p className="text-xs">{t('tryDifferentSearch')}</p>
</div>
) : (
<div className="space-y-1">
{filteredProjects.map((project) => (
{projects.map((project) => (
<ProjectItem
key={project.id}
project={project}
@@ -266,8 +258,8 @@ export function ProjectSidebar({
</div>
{/* Settings and Help at Bottom */}
<div className="border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto pb-safe">
<div className="p-2 flex items-center gap-2">
<div className="p-2 border-t border-sidebar-border bg-gradient-to-r from-primary/5 to-accent/5 mt-auto">
<div className="flex items-center gap-2">
<Button
variant="ghost"
size="sm"
@@ -288,6 +280,13 @@ export function ProjectSidebar({
</Button>
</div>
</div>
{/* ZIP Import Dialog */}
<ZipImportDialog
onImport={handleImportZip}
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
</div>
);
}
-357
View File
@@ -1,357 +0,0 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { FileCode2, Trash2, Plus, GripVertical, RotateCcw } from 'lucide-react';
import {
DndContext,
closestCenter,
KeyboardSensor,
PointerSensor,
useSensor,
useSensors,
type DragEndEvent,
} from '@dnd-kit/core';
import {
arrayMove,
SortableContext,
sortableKeyboardCoordinates,
verticalListSortingStrategy,
} from '@dnd-kit/sortable';
import {
useSortable,
} from '@dnd-kit/sortable';
import { CSS } from '@dnd-kit/utilities';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Textarea } from '@/components/ui/textarea';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { useAppContext } from '@/hooks/useAppContext';
import { useToast } from '@/hooks/useToast';
interface ProjectTemplate {
name: string;
description: string;
url: string;
}
interface SortableTemplateItemProps {
template: ProjectTemplate;
index: number;
onRemove: (index: number) => void;
onUpdate: (index: number, template: ProjectTemplate) => void;
showDragHandle: boolean;
isOnlyTemplate: boolean;
}
function SortableTemplateItem({
template,
index,
onRemove,
onUpdate,
showDragHandle,
isOnlyTemplate,
}: SortableTemplateItemProps) {
const { t } = useTranslation();
const {
attributes,
listeners,
setNodeRef,
transform,
transition,
isDragging,
} = useSortable({ id: `template-${index}` });
const style = {
transform: CSS.Transform.toString(transform),
transition,
opacity: isDragging ? 0.5 : 1,
};
return (
<AccordionItem
ref={setNodeRef}
style={style}
value={`template-${index}`}
className="border rounded-lg"
>
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2 w-full mr-3">
{showDragHandle && (
<div
{...attributes}
{...listeners}
className="cursor-grab active:cursor-grabbing p-1 -ml-1 text-muted-foreground hover:text-foreground"
>
<GripVertical className="h-4 w-4" />
</div>
)}
<FileCode2 size={16} className="text-muted-foreground" />
<span className="font-medium">{template.name}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`template-name-${index}`}>
{t('templateName')} <span className="text-destructive">*</span>
</Label>
<Input
id={`template-name-${index}`}
placeholder="MKStack"
value={template.name}
onChange={(e) => onUpdate(index, { ...template, name: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`template-description-${index}`}>
{t('templateDescription')} <span className="text-destructive">*</span>
</Label>
<Textarea
id={`template-description-${index}`}
placeholder="Build Nostr clients with React."
value={template.description}
onChange={(e) => onUpdate(index, { ...template, description: e.target.value })}
className="min-h-[80px]"
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`template-url-${index}`}>
{t('templateGitUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id={`template-url-${index}`}
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={template.url}
onChange={(e) => onUpdate(index, { ...template, url: e.target.value })}
/>
</div>
<Button
variant="destructive"
size="sm"
onClick={() => onRemove(index)}
disabled={isOnlyTemplate}
title={isOnlyTemplate ? t('atLeastOneTemplateRequired') : t('delete')}
>
<Trash2 className="h-4 w-4 mr-2" />
{t('delete')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
);
}
export function ProjectTemplatesSection() {
const { t } = useTranslation();
const { config, defaultConfig, updateConfig } = useAppContext();
const { toast } = useToast();
const [newTemplateName, setNewTemplateName] = useState('');
const [newTemplateDescription, setNewTemplateDescription] = useState('');
const [newTemplateUrl, setNewTemplateUrl] = useState('');
const templates = config.templates || [];
const defaultTemplates = defaultConfig.templates || [];
const sensors = useSensors(
useSensor(PointerSensor),
useSensor(KeyboardSensor, {
coordinateGetter: sortableKeyboardCoordinates,
})
);
// Check if current templates match the default configuration
const templatesMatchDefault = JSON.stringify(templates) === JSON.stringify(defaultTemplates);
const handleAddTemplate = () => {
if (!newTemplateName.trim() || !newTemplateDescription.trim() || !newTemplateUrl.trim()) {
return;
}
const newTemplate: ProjectTemplate = {
name: newTemplateName.trim(),
description: newTemplateDescription.trim(),
url: newTemplateUrl.trim(),
};
updateConfig((current) => ({
...current,
templates: [...(current.templates || []), newTemplate],
}));
toast({
title: t('templateAdded'),
description: t('templateAddedDescription', { name: newTemplateName.trim() }),
});
setNewTemplateName('');
setNewTemplateDescription('');
setNewTemplateUrl('');
};
const handleRemoveTemplate = (index: number) => {
const templateName = templates[index]?.name || 'template';
const newTemplates = templates.filter((_, i) => i !== index);
updateConfig((current) => ({
...current,
templates: newTemplates,
}));
toast({
title: t('templateDeleted'),
description: t('templateDeletedDescription', { name: templateName }),
});
};
const handleUpdateTemplate = (index: number, updatedTemplate: ProjectTemplate) => {
const newTemplates = [...templates];
newTemplates[index] = updatedTemplate;
updateConfig((current) => ({
...current,
templates: newTemplates,
}));
};
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event;
if (active.id !== over?.id) {
const oldIndex = parseInt(active.id.toString().replace('template-', ''));
const newIndex = parseInt(over?.id.toString().replace('template-', '') || '0');
if (!isNaN(oldIndex) && !isNaN(newIndex) && oldIndex !== newIndex) {
const newTemplates = arrayMove(templates, oldIndex, newIndex);
updateConfig((current) => ({
...current,
templates: newTemplates,
}));
}
}
};
const handleResetToDefaults = () => {
// Remove the templates from local config so defaults take precedence
updateConfig((current) => {
const { templates: _, ...rest } = current;
return rest;
});
};
return (
<div className="space-y-4">
{/* Project Templates Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
<FileCode2 className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('projectTemplates')}</h3>
{!templatesMatchDefault && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
{!templatesMatchDefault && (
<button
onClick={handleResetToDefaults}
title={t('restoreToDefault')}
className="ml-auto p-1 text-muted-foreground hover:text-foreground"
>
<RotateCcw className="h-4 w-4" />
</button>
)}
</div>
<p className="text-sm text-muted-foreground">
{t('projectTemplatesDescription')}
</p>
</div>
{/* Configured Templates List */}
{templates.length > 0 && (
<div className="space-y-2">
<DndContext
sensors={sensors}
collisionDetection={closestCenter}
onDragEnd={handleDragEnd}
>
<SortableContext
items={templates.map((_, index) => `template-${index}`)}
strategy={verticalListSortingStrategy}
>
<Accordion type="multiple" className="w-full space-y-2">
{templates.map((template, index) => (
<SortableTemplateItem
key={index}
template={template}
index={index}
onRemove={handleRemoveTemplate}
onUpdate={handleUpdateTemplate}
showDragHandle={templates.length > 1}
isOnlyTemplate={templates.length === 1}
/>
))}
</Accordion>
</SortableContext>
</DndContext>
</div>
)}
{/* Add New Template */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-template">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<span className="text-sm font-medium">{t('addProjectTemplate')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="new-template-name">
{t('templateName')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-template-name"
placeholder="MKStack"
value={newTemplateName}
onChange={(e) => setNewTemplateName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-template-description">
{t('templateDescription')} <span className="text-destructive">*</span>
</Label>
<Textarea
id="new-template-description"
placeholder="Build Nostr clients with React."
value={newTemplateDescription}
onChange={(e) => setNewTemplateDescription(e.target.value)}
className="min-h-[80px]"
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-template-url">
{t('templateGitUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-template-url"
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={newTemplateUrl}
onChange={(e) => setNewTemplateUrl(e.target.value)}
/>
</div>
<Button
onClick={handleAddTemplate}
disabled={!newTemplateName.trim() || !newTemplateDescription.trim() || !newTemplateUrl.trim()}
className="gap-2 w-full"
>
<Plus className="h-4 w-4" />
{t('add')}
</Button>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
);
}
-80
View File
@@ -1,80 +0,0 @@
import { render, screen } from '@testing-library/react';
import { describe, it, expect, vi } from 'vitest';
import { Quilly } from './Quilly';
import { MalformedToolCallError } from '@/lib/errors/MalformedToolCallError';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
// Mock all required hooks and components
vi.mock('@/hooks/useAISettings', () => ({
useAISettings: () => ({
settings: {
providers: []
}
})
}));
vi.mock('@/hooks/useAICredits', () => ({
useAICredits: () => ({
data: null
})
}));
vi.mock('react-router-dom', () => ({
useNavigate: () => vi.fn()
}));
// Mock CreditsDialog to avoid NostrProvider dependency
vi.mock('./CreditsDialog', () => ({
CreditsDialog: () => null
}));
describe('Quilly', () => {
const defaultProps = {
error: new Error('Generic error'),
onDismiss: vi.fn(),
onNewChat: vi.fn(),
onOpenModelSelector: vi.fn(),
providerModel: 'test/model'
};
it('renders generic error message', () => {
render(<Quilly {...defaultProps} />);
expect(screen.getByText(/AI service error: Generic error/)).toBeInTheDocument();
});
it('renders correctly for malformed tool call errors', () => {
const error = new MalformedToolCallError(
'The AI provider sent an incomplete response.',
'call_abc123',
'test/model'
);
render(
<Quilly
{...defaultProps}
error={error}
/>
);
expect(screen.getByText(/The AI sent an incomplete response/)).toBeInTheDocument();
expect(screen.getByText(/Change model/)).toBeInTheDocument();
});
it('renders correctly for console errors', () => {
const error = new ProjectPreviewConsoleError(
'Console error',
[]
);
render(
<Quilly
{...defaultProps}
error={error}
/>
);
expect(screen.getByText(/I noticed some console errors/)).toBeInTheDocument();
expect(screen.getByText(/Help fix errors/)).toBeInTheDocument();
});
});
+43 -178
View File
@@ -1,4 +1,4 @@
import { APIError } from 'openai';
import OpenAI from 'openai';
import { useNavigate } from 'react-router-dom';
import { X } from 'lucide-react';
import { Button } from '@/components/ui/button';
@@ -7,187 +7,113 @@ import { useAISettings } from '@/hooks/useAISettings';
import { parseProviderModel } from '@/lib/parseProviderModel';
import { useAICredits } from '@/hooks/useAICredits';
import { CreditsDialog } from './CreditsDialog';
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
import { ProjectPreviewConsoleError } from '@/contexts/ConsoleContext';
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;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
onTryAgain?: () => void;
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
providerModel: string;
}
interface ErrorBody {
message: string;
actions?: Array<{
action?: {
label: string;
onClick: () => void;
}>;
};
}
interface QuillyContentProps {
error: Error;
onDismiss: () => void;
onNewChat: () => void;
onOpenModelSelector: () => void;
onTryAgain?: () => void;
onRequestConsoleErrorHelp?: (error: ProjectPreviewConsoleError) => void;
provider: AIProvider | undefined;
}
function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, provider }: QuillyContentProps) {
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const navigate = useNavigate();
const { settings } = useAISettings();
const { provider } = parseProviderModel(providerModel, settings.providers);
const credits = useAICredits(provider);
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const renderBody = (error: Error | APIError | MalformedToolCallError | ProjectPreviewConsoleError): ErrorBody & { showCreditsButton?: boolean } => {
const renderBody = (error: Error): ErrorBody => {
// Handle Project Preview Console Errors
if (error instanceof ProjectPreviewConsoleError) {
return {
message: 'I noticed some console errors in your project preview. Would you like me to take a look and help fix them?',
actions: [{
action: {
label: 'Help fix errors',
onClick: () => {
onRequestConsoleErrorHelp?.(error);
onDismiss();
},
}],
};
}
if (error instanceof MalformedToolCallError) {
return {
message: 'The AI sent an incomplete response, possibly due to a network issue or provider problem. Try sending your message again, or switch to a different model if this persists.',
actions: [{
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
}
if (error instanceof EmptyMessageError) {
return {
message: 'The AI generated an empty response. This may be due to a provider issue or model configuration problem. Try generating again, or switch to a different model.',
actions: onTryAgain ? [{
label: 'Try again',
onClick: () => {
onTryAgain();
onDismiss();
},
}] : [{
label: 'Change model',
onClick: onOpenModelSelector,
}],
},
};
}
// Handle OpenAI API errors with specific error codes
if (error instanceof APIError) {
switch (true) {
case error.code ==='invalid_api_key':
case error.code === 'invalid_request_error':
if (error instanceof OpenAI.APIError) {
switch (error.code) {
case 'invalid_api_key':
case 'invalid_request_error':
return {
message: 'Authentication error: Please check your API key in AI settings.',
actions: [{
action: {
label: 'Check API key',
onClick: () => navigate('/settings/ai'),
}],
}
};
case error.code === 'insufficient_quota': {
// Only show credits dialog if we have a provider with nostr enabled
if (provider?.nostr) {
case 'insufficient_quota': {
if (credits.data) {
return {
message: 'Your account is low on credits. Please add credits to keep creating.',
showCreditsButton: true,
actions: [],
message: `Your account has $${credits.data.amount.toFixed(2)} credits. Please add credits to keep creating.`,
action: {
label: 'Add credits',
onClick: () => setShowCreditsDialog(true),
}
};
} else {
return {
message: 'Your API key has reached its usage limit. Please check your billing or try a different provider.',
actions: [{
action: {
label: 'Check AI settings',
onClick: () => navigate('/settings/ai'),
}],
}
};
}
}
case error.code === 'rate_limit_exceeded':
case 'rate_limit_exceeded':
return {
message: 'Rate limit exceeded. Please wait a moment before trying again.',
actions: [],
};
case error.code === 'model_not_found':
case 'model_not_found':
return {
message: 'The selected AI model is not available. Please choose a different model.',
actions: [{
action: {
label: 'Choose model',
onClick: onOpenModelSelector,
}],
},
};
case error.code === 'context_length_exceeded':
case 'context_length_exceeded':
return {
message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.',
actions: [{
action: {
label: 'New chat',
onClick: onNewChat,
}, {
label: 'Change model',
onClick: onOpenModelSelector,
}],
},
};
case error.status === 403:
return {
message: `It seems your API key has been used up. Check your API provider's settings, or try a different API key or different provider/model combo:`,
actions: [{
label: 'Check API settings',
onClick: () => navigate('/settings/ai'),
}, {
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
case error.status === 400:
return {
message: 'The AI provider did not understand the message / data it got. If it persists, try stating a new conversation or using a different model.',
actions: [{
label: 'New chat',
onClick: onNewChat,
}, {
label: 'Change model',
onClick: onOpenModelSelector,
}],
};
case error.status === 422:
return {
message: 'Request rejected by AI provider. Try a different model.',
actions: [{
label: 'Choose model',
onClick: onOpenModelSelector,
}],
};
case error.code === 'server_error':
case error.code === 'service_unavailable':
case 'server_error':
case 'service_unavailable':
return {
message: 'The AI service is temporarily unavailable. Please try again in a moment.',
actions: [],
};
default:
return {
message: `AI service error: ${error.message}`,
actions: [],
};
}
}
@@ -197,17 +123,10 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
message: error.message
? `AI service error: ${error.message}`
: 'Sorry, I encountered an unexpected error. Please try again.',
actions: onTryAgain ? [{
label: 'Try again',
onClick: () => {
onTryAgain();
onDismiss();
},
}] : [],
};
};
const { message, actions = [], showCreditsButton } = renderBody(error);
const { message, action } = renderBody(error);
return (
<div className="py-2 px-3 bg-primary/5 border border-primary/20 rounded-lg">
@@ -220,24 +139,11 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
</h4>
<p className="text-sm text-muted-foreground">
{message}
{showCreditsButton && provider && (
<>
{' '}
<QuillyCreditsButton provider={provider} />
</>
)}
{actions.length > 0 && (
<>
{' '}
{actions.map((action, i) => (
<span key={action.label}>
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
{i < actions.length - 1 && <> or </>}
</span>
))}
</>
{' '}
{action && (
<button className="text-primary underline" onClick={action.onClick}>
{action.label}
</button>
)}
</p>
</div>
@@ -251,53 +157,12 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
<X className="h-4 w-4" />
</Button>
</div>
</div>
);
}
interface QuillyCreditsButtonProps {
provider: AIProvider;
}
function QuillyCreditsButton({ provider }: QuillyCreditsButtonProps) {
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
const credits = useAICredits(provider);
return (
<>
<button className="text-primary underline" onClick={() => setShowCreditsDialog(true)}>
{credits.data ? `Add credits (${credits.data.amount.toFixed(2)} remaining)` : 'Add credits'}
</button>
<CreditsDialog
open={showCreditsDialog}
onOpenChange={setShowCreditsDialog}
provider={provider}
/>
</>
);
}
export function Quilly({ error, onDismiss, onNewChat, onOpenModelSelector, onTryAgain, onRequestConsoleErrorHelp, providerModel }: QuillyProps) {
const { settings } = useAISettings();
// Handle empty provider model gracefully
let provider: AIProvider | undefined;
try {
provider = parseProviderModel(providerModel, settings.providers).provider;
} catch {
// If no valid provider model, use a default or undefined
provider = undefined;
}
return (
<QuillyContent
error={error}
onDismiss={onDismiss}
onNewChat={onNewChat}
onOpenModelSelector={onOpenModelSelector}
onTryAgain={onTryAgain}
onRequestConsoleErrorHelp={onRequestConsoleErrorHelp}
provider={provider}
/>
</div>
);
}
-287
View File
@@ -1,287 +0,0 @@
import { useState, useEffect } from 'react';
import { Plus, X, Wifi, Settings } from 'lucide-react';
import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Switch } from '@/components/ui/switch';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useAppContext } from '@/hooks/useAppContext';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostrPublish } from '@/hooks/useNostrPublish';
import { toast } from '@/hooks/useToast';
interface Relay {
url: string;
read: boolean;
write: boolean;
}
export function RelayListManager() {
const { t } = useTranslation();
const { config, updateConfig } = useAppContext();
const { user } = useCurrentUser();
const { mutate: publishEvent } = useNostrPublish();
const [relays, setRelays] = useState<Relay[]>(config.relayMetadata.relays);
const [newRelayUrl, setNewRelayUrl] = useState('');
// Sync local state with config when it changes (e.g., from NostrProvider sync)
useEffect(() => {
setRelays(config.relayMetadata.relays);
}, [config.relayMetadata.relays]);
const normalizeRelayUrl = (url: string): string => {
url = url.trim();
try {
return new URL(url).toString();
} catch {
try {
return new URL(`wss://${url}`).toString();
} catch {
return url;
}
}
};
const isValidRelayUrl = (url: string): boolean => {
const trimmed = url.trim();
if (!trimmed) return false;
const normalized = normalizeRelayUrl(trimmed);
try {
new URL(normalized);
return true;
} catch {
return false;
}
};
const handleAddRelay = () => {
if (!isValidRelayUrl(newRelayUrl)) {
toast({
title: t('invalidRelayUrl'),
description: t('invalidRelayUrlDescription'),
variant: 'destructive',
});
return;
}
const normalized = normalizeRelayUrl(newRelayUrl);
if (relays.some(r => r.url === normalized)) {
toast({
title: t('relayAlreadyExists'),
description: t('relayAlreadyExistsDescription'),
variant: 'destructive',
});
return;
}
const newRelays = [...relays, { url: normalized, read: true, write: true }];
setRelays(newRelays);
setNewRelayUrl('');
saveRelays(newRelays);
};
const handleRemoveRelay = (url: string) => {
const newRelays = relays.filter(r => r.url !== url);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleRead = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, read: !r.read } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const handleToggleWrite = (url: string) => {
const newRelays = relays.map(r =>
r.url === url ? { ...r, write: !r.write } : r
);
setRelays(newRelays);
saveRelays(newRelays);
};
const saveRelays = (newRelays: Relay[]) => {
const now = Math.floor(Date.now() / 1000);
// Update local config
updateConfig((current) => ({
...current,
relayMetadata: {
relays: newRelays,
updatedAt: now,
},
}));
// Publish to Nostr if user is logged in
if (user) {
publishNIP65RelayList(newRelays);
}
};
const publishNIP65RelayList = (relayList: Relay[]) => {
const tags = relayList.map(relay => {
if (relay.read && relay.write) {
return ['r', relay.url];
} else if (relay.read) {
return ['r', relay.url, 'read'];
} else if (relay.write) {
return ['r', relay.url, 'write'];
}
// If neither read nor write, don't include (shouldn't happen)
return null;
}).filter((tag): tag is string[] => tag !== null);
publishEvent(
{
kind: 10002,
content: '',
tags,
},
{
onSuccess: () => {
toast({
title: t('relayListPublished'),
description: t('relayListPublishedDescription'),
});
},
onError: (error) => {
console.error('Failed to publish relay list:', error);
toast({
title: t('relayListPublishFailed'),
description: t('relayListPublishFailedDescription'),
variant: 'destructive',
});
},
}
);
};
const renderRelayUrl = (url: string): string => {
try {
const parsed = new URL(url);
if (parsed.protocol === 'wss:') {
if (parsed.pathname === '/') {
return parsed.host;
} else {
return parsed.host + parsed.pathname;
}
} else {
return parsed.href;
}
} catch {
return url;
}
}
return (
<div className="space-y-4">
{/* Relay List */}
<div className="space-y-2">
{relays.map((relay) => (
<div
key={relay.url}
className="flex items-center gap-3 p-3 rounded-md border bg-muted/20"
>
<Wifi className="h-4 w-4 text-muted-foreground shrink-0" />
<span className="font-mono text-sm flex-1 truncate" title={relay.url}>
{renderRelayUrl(relay.url)}
</span>
{/* Settings Popover */}
<Popover>
<PopoverTrigger asChild>
<Button
variant="ghost"
size="icon"
className="size-5 text-muted-foreground hover:text-foreground shrink-0"
>
<Settings className="h-4 w-4" />
</Button>
</PopoverTrigger>
<PopoverContent className="w-48" align="end">
<div className="space-y-3">
<div className="flex items-center justify-between">
<Label htmlFor={`read-${relay.url}`} className="text-sm cursor-pointer">
{t('read')}
</Label>
<Switch
id={`read-${relay.url}`}
checked={relay.read}
onCheckedChange={() => handleToggleRead(relay.url)}
className="data-[state=checked]:bg-green-500 scale-75"
/>
</div>
<div className="flex items-center justify-between">
<Label htmlFor={`write-${relay.url}`} className="text-sm cursor-pointer">
{t('write')}
</Label>
<Switch
id={`write-${relay.url}`}
checked={relay.write}
onCheckedChange={() => handleToggleWrite(relay.url)}
className="data-[state=checked]:bg-blue-500 scale-75"
/>
</div>
</div>
</PopoverContent>
</Popover>
{/* Remove Button */}
<Button
variant="ghost"
size="icon"
onClick={() => handleRemoveRelay(relay.url)}
className="size-5 text-muted-foreground hover:text-destructive hover:bg-transparent shrink-0"
disabled={relays.length <= 1}
>
<X className="h-4 w-4" />
</Button>
</div>
))}
</div>
{/* Add Relay Form */}
<div className="flex gap-2">
<div className="flex-1">
<Label htmlFor="new-relay-url" className="sr-only">
{t('relayUrl')}
</Label>
<Input
id="new-relay-url"
placeholder={t('enterRelayUrl')}
value={newRelayUrl}
onChange={(e) => setNewRelayUrl(e.target.value)}
onKeyDown={(e) => {
if (e.key === 'Enter') {
handleAddRelay();
}
}}
/>
</div>
<Button
onClick={handleAddRelay}
disabled={!newRelayUrl.trim()}
variant="outline"
size="sm"
className="h-10 shrink-0"
>
<Plus className="h-4 w-4 mr-2" />
{t('addRelay')}
</Button>
</div>
{!user && (
<p className="text-xs text-muted-foreground">
{t('loginToSyncRelays')}
</p>
)}
</div>
);
}
Loaded 100 of 385 files, more files were not shown because too many files have changed in this diff. Show more