Compare commits

..
Author SHA1 Message Date
lemonknowsall 029f3f6c58 remove unused 2025-11-24 13:36:24 -08:00
lemonknowsall 1f685296de animate logo spin 2025-11-24 13:20:37 -08:00
lemonknowsall e0accea7ab chat input singleton 2025-11-24 12:55:59 -08:00
112 changed files with 1790 additions and 7570 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>
+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;
+10 -29
View File
@@ -28,7 +28,6 @@ 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';
@@ -107,23 +106,7 @@ const defaultConfig: AppConfig = {
],
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",
}
],
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
@@ -178,17 +161,15 @@ export function App() {
<GitSettingsProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<GlobalChatProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</GlobalChatProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
-5
View File
@@ -2,8 +2,6 @@ import { BrowserRouter, HashRouter, 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";
@@ -58,9 +56,6 @@ 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>
);
}
@@ -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'
}
+1 -10
View File
@@ -5,7 +5,7 @@ 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';
import { getShakespeareProvider } from '@/lib/aiProviderPresets';
interface Act1DialogProps {
open: boolean;
@@ -14,15 +14,6 @@ interface Act1DialogProps {
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());
@@ -8,7 +8,6 @@ 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',
};
@@ -93,7 +92,6 @@ describe('AddProviderDialog', () => {
// Use a provider that exists in presets
const openrouterProvider: AIProvider = {
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'sk-test-123',
};
@@ -116,7 +114,6 @@ describe('AddProviderDialog', () => {
const onOpenChange = vi.fn();
const customProvider: AIProvider = {
id: 'my-custom-provider',
name: 'My Custom Provider',
baseURL: 'https://api.custom.com/v1',
};
+1 -6
View File
@@ -5,7 +5,6 @@ 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 {
@@ -157,11 +156,7 @@ export function AddProviderDialog({ open, onOpenChange, provider }: AddProviderD
// 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" />}
/>
<Sparkles className="h-8 w-8 text-primary" />
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold">{providerName}</h2>
+2 -2
View File
@@ -99,7 +99,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 +123,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}
+1 -8
View File
@@ -22,18 +22,11 @@ const RelayMetadataSchema = z.object({
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({
theme: z.enum(['dark', 'light', 'system']),
relayMetadata: RelayMetadataSchema,
templates: z.array(ProjectTemplateSchema),
projectTemplate: z.string().url(),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
faviconUrl: z.string().url(),
-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,
+35 -148
View File
@@ -1,4 +1,4 @@
import { useState, useEffect, useCallback } from 'react';
import { useState, useEffect } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react';
@@ -85,33 +85,17 @@ const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
invoice: string;
amount: number;
paymentId: string;
provider: AIProvider;
onClose: () => void;
onPaymentCompleted: () => void;
}
function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPaymentCompleted }: LightningPaymentProps) {
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const queryClient = useQueryClient();
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
const [paymentCompleted, setPaymentCompleted] = useState(false);
const { toast } = useToast();
const formatCurrency = useCallback((amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
}, []);
useEffect(() => {
// Generate QR code
QRCode.toDataURL(invoice, {
@@ -129,98 +113,6 @@ function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPay
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
}, [invoice]);
// Poll payment status
useEffect(() => {
// Don't poll if payment already completed
if (paymentCompleted) return;
let intervalId: NodeJS.Timeout | null = null;
const pollPaymentStatus = async () => {
// Double-check in case state updated during async operation
if (paymentCompleted) return;
try {
const ai = createAIClient(provider, user, config.corsProxy);
const payment = await ai.get(`/credits/payments/${paymentId}`) as Payment;
if (payment.status === 'completed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
// Update credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Update payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Show toast
toast({
title: t('paymentCompleted'),
description: t('creditsAddedToAccount', { amount: formatCurrency(payment.amount) }),
});
// Close dialog immediately
onPaymentCompleted();
} else if (payment.status === 'failed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentFailed'),
description: t('paymentFailed'),
variant: 'destructive',
});
} else if (payment.status === 'expired') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentExpired'),
description: t('paymentExpiredMessage'),
variant: 'destructive',
});
}
} catch (error) {
console.error('Failed to poll payment status:', error);
}
};
// Poll immediately on mount
pollPaymentStatus();
// Then poll every 3 seconds
intervalId = setInterval(pollPaymentStatus, 3000);
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [paymentId, provider, user, config.corsProxy, queryClient, toast, t, onPaymentCompleted, formatCurrency, paymentCompleted]);
const handleWebLNPay = async () => {
if (!window.webln) return;
@@ -253,6 +145,15 @@ function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPay
setTimeout(() => setShowCopiedTooltip(false), 2000);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
return (
<div className="space-y-4">
<div className="text-center">
@@ -322,7 +223,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
const [amount, setAmount] = useState<number>(10);
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [lightningPaymentId, setLightningPaymentId] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
const [giftcardAmount, setGiftcardAmount] = useState<number>(10);
const [giftcardQuantity, setGiftcardQuantity] = useState<number>(1);
@@ -401,7 +301,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (payment.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
}
// Refresh payments list
@@ -587,7 +486,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (paymentPreview.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(paymentPreview.url);
setLightningPaymentId(paymentPreview.id);
}
// Refresh payments list
@@ -984,37 +882,27 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</DialogHeader>
{/* Lightning Payment Interface */}
{lightningInvoice && lightningPaymentId ? (
{lightningInvoice ? (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<LightningPayment
invoice={lightningInvoice}
amount={amount}
paymentId={lightningPaymentId}
provider={provider}
onClose={() => {
setLightningInvoice(null);
setLightningPaymentId(null);
}}
onPaymentCompleted={() => {
// Close the lightning payment view immediately
setLightningInvoice(null);
setLightningPaymentId(null);
}}
onClose={() => setLightningInvoice(null)}
/>
</div>
) : (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<Accordion type="multiple" defaultValue={["add"]} className="w-full space-y-2">
<Accordion type="multiple" defaultValue={["add"]} className="w-full">
{/* Buy Credits Accordion */}
<AccordionItem value="add">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<DollarSign className="h-4 w-4 text-muted-foreground" />
<DollarSign className="h-4 w-4" />
{t('buyCredits')}
</div>
</AccordionTrigger>
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<AccordionContent>
<div className="space-y-3 pt-2">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">{t('amountUSD')}</Label>
<div className="space-y-3">
@@ -1098,14 +986,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Transaction History Accordion */}
<AccordionItem value="history">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<History className="h-4 w-4 text-muted-foreground" />
<History className="h-4 w-4" />
{t('recentTransactions')}
</div>
</AccordionTrigger>
<AccordionContent className="px-4">
<div className="pt-2 pb-3">
<AccordionContent>
<div className="pt-2">
{isLoadingPayments ? (
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
@@ -1166,7 +1054,6 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
} else {
window.open(payment.url, '_blank');
}
@@ -1190,14 +1077,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Redeem Gift Card Accordion */}
<AccordionItem value="redeem">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4 text-muted-foreground" />
<Plus className="h-4 w-4" />
{t('redeemGiftCard')}
</div>
</AccordionTrigger>
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<AccordionContent>
<div className="space-y-3 pt-2">
<div className="flex gap-2">
<Input
id="redeem-code"
@@ -1222,14 +1109,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Create Gift Card Accordion */}
<AccordionItem value="create">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<Gift className="h-4 w-4 text-muted-foreground" />
<Gift className="h-4 w-4" />
{t('createGiftCard')}
</div>
</AccordionTrigger>
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<AccordionContent>
<div className="space-y-3 pt-2">
<div className="grid grid-cols-2 gap-2">
<div className="space-y-2">
<Label htmlFor="giftcard-amount" className="text-xs text-muted-foreground">{t('amountUSD')}</Label>
@@ -1285,15 +1172,15 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</AccordionItem>
{/* Your Gift Cards Accordion */}
<AccordionItem value="list">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<AccordionItem value="list" className="border-b-0">
<AccordionTrigger className="hover:no-underline">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4 text-muted-foreground" />
<CreditCard className="h-4 w-4" />
{t('yourGiftCards')}
</div>
</AccordionTrigger>
<AccordionContent className="px-4">
<div className="pt-2 pb-3 space-y-3">
<AccordionContent className="pb-0">
<div className="pt-2 space-y-3">
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
<div className="grid grid-cols-2 gap-2">
<Button
+3 -133
View File
@@ -27,15 +27,13 @@ import { useFS } from '@/hooks/useFS';
import { useFSPaths } from '@/hooks/useFSPaths';
import { useAppContext } from '@/hooks/useAppContext';
import { useNostr } from '@nostrify/react';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, CloudflareAdapter, DenoDeployAdapter, DeployAdapter } from '@/lib/deploy';
import { ShakespeareAdapter, NetlifyAdapter, VercelAdapter, NsiteAdapter, DeployAdapter } from '@/lib/deploy';
import { Link } from 'react-router-dom';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider, CloudflareProvider, DenoDeployProvider } from '@/contexts/DeploySettingsContext';
import type { DeployProvider, ShakespeareDeployProvider, NetlifyProvider, VercelProvider } 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
@@ -60,18 +58,6 @@ function getProviderUrl(provider: DeployProvider): string | null {
}
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;
@@ -124,14 +110,6 @@ interface VercelFormData {
teamId: string;
}
interface CloudflareFormData {
projectName: string;
}
interface DenoDeployFormData {
projectName: string;
}
export function DeployDialog({ projectId, projectName, open, onOpenChange }: DeployDialogProps) {
const { t } = useTranslation();
const { settings } = useDeploySettings();
@@ -163,12 +141,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
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
useEffect(() => {
@@ -258,42 +230,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
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');
}
@@ -333,20 +269,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
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,
},
});
}
setDeployResult(result);
@@ -366,8 +288,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setNsiteForm({ nsec: '' });
setNetlifyForm({ siteId: '', siteName: '' });
setVercelForm({ projectName: projectName || projectId, teamId: '' });
setCloudflareForm({ projectName: projectName || projectId });
setDenoDeployForm({ projectName: projectName || projectId });
onOpenChange(false);
};
@@ -391,14 +311,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
setVercelForm({ projectName, teamId });
}, []);
const handleCloudflareProjectChange = useCallback((projectName: string) => {
setCloudflareForm({ projectName });
}, []);
const handleDenoDeployProjectChange = useCallback((projectName: string) => {
setDenoDeployForm({ projectName });
}, []);
const renderProviderFields = () => {
if (!selectedProvider) return null;
@@ -461,46 +373,6 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
);
}
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;
};
@@ -631,9 +503,7 @@ export function DeployDialog({ projectId, projectName, open, onOpenChange }: Dep
(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)
(selectedProvider.type === 'netlify' && !netlifyForm.siteId && !netlifyForm.siteName)
}
>
{isDeploying ? (
-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
View File
@@ -164,7 +164,6 @@ export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: Gift
const providerConfig = {
id: matchingPreset.id,
name: matchingPreset.name,
baseURL: matchingPreset.baseURL,
nostr: matchingPreset.nostr || undefined,
};
+2
View File
@@ -182,6 +182,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
@@ -1288,6 +1289,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: pr.sourceBranch,
force: true,
});
await refetchGitStatus();
toast({
-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,
+19 -18
View File
@@ -6,6 +6,8 @@ import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Separator } from '@/components/ui/separator';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { useAISettings } from '@/hooks/useAISettings';
import { useToast } from '@/hooks/useToast';
import { useMCPServerStatus } from '@/hooks/useMCPServerStatus';
@@ -190,6 +192,9 @@ export function MCPServersSection() {
return (
<div className="space-y-4">
{/* Divider */}
<Separator className="my-6" />
{/* MCP Servers Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
@@ -202,14 +207,14 @@ export function MCPServersSection() {
</div>
{/* Configured MCP Servers List */}
{serverEntries.length > 0 && (
{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" />
<Server size={16} className="text-primary" />
<span className="font-medium">{name}</span>
<MCPConnectionStatus server={server} />
</div>
@@ -217,9 +222,7 @@ export function MCPServersSection() {
<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>
<Label htmlFor={`${name}-type`}>{t('mcpServerType')}</Label>
<Select value={server.type} disabled>
<SelectTrigger>
<SelectValue />
@@ -230,9 +233,7 @@ export function MCPServersSection() {
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor={`${name}-url`}>
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Label htmlFor={`${name}-url`}>{t('mcpServerUrl')}</Label>
<Input
id={`${name}-url`}
value={server.url}
@@ -258,11 +259,17 @@ export function MCPServersSection() {
</Accordion>
))}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noMcpServersConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add New MCP Server */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-server">
<AccordionItem value="add-server" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
@@ -275,9 +282,7 @@ export function MCPServersSection() {
{t('mcpServerDescription')}
</p>
<div className="grid gap-2">
<Label htmlFor="new-server-name">
{t('mcpServerName')} <span className="text-destructive">*</span>
</Label>
<Label htmlFor="new-server-name">{t('mcpServerName')}</Label>
<Input
id="new-server-name"
placeholder="e.g., my-mcp-server"
@@ -286,9 +291,7 @@ export function MCPServersSection() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-type">
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Label htmlFor="new-server-type">{t('mcpServerType')}</Label>
<Select value={serverType} disabled>
<SelectTrigger>
<SelectValue />
@@ -302,9 +305,7 @@ export function MCPServersSection() {
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-url">
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Label htmlFor="new-server-url">{t('mcpServerUrl')}</Label>
<Input
id="new-server-url"
placeholder="https://example.com/mcp"
+12 -35
View File
@@ -81,14 +81,7 @@ 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(),
@@ -112,7 +105,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('Provider 2')).toBeInTheDocument();
expect(screen.getByText('provider2')).toBeInTheDocument();
});
// Recently used section should NOT be visible
@@ -121,8 +114,8 @@ describe('ModelSelector', () => {
// 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();
// provider2 should still show with model3
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
});
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
@@ -143,15 +136,7 @@ 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(),
@@ -175,7 +160,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,15 +187,7 @@ 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(),
@@ -234,7 +211,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('Provider 2')).toBeInTheDocument();
expect(screen.getByText('provider2')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
@@ -243,10 +220,10 @@ describe('ModelSelector', () => {
// 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();
// provider2 and provider3 should still show
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
});
it('hides recently used section when no recently used models exist', async () => {
+31 -106
View File
@@ -1,7 +1,7 @@
import { useState, useMemo, useEffect, memo } 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, TriangleAlert } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
@@ -12,7 +12,6 @@ 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 {
@@ -73,33 +72,6 @@ export const ModelSelector = memo(function ModelSelector({
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]);
// Determine if we should show the "Recently Used" section
const shouldShowRecentlyUsed = useMemo(() => {
// If no recently used models, don't show the section
@@ -306,31 +278,13 @@ export const ModelSelector = memo(function ModelSelector({
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]"
"h-8 p-0 gap-0.5 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>
)}
<span className="truncate">
{value || placeholder || defaultPlaceholder}
</span>
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
@@ -351,11 +305,6 @@ export const ModelSelector = memo(function ModelSelector({
<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}
@@ -369,17 +318,7 @@ export const ModelSelector = memo(function ModelSelector({
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>
<span className="truncate flex-1">{modelId}</span>
{modelData?.pricing && (
<ModelPricing pricing={modelData.pricing} className="ml-2" />
)}
@@ -428,46 +367,32 @@ export const ModelSelector = memo(function ModelSelector({
)}
{/* 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" />
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
<span className="truncate flex-1">{model.name || model.id}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
);
})}
/>
<span className="truncate flex-1">{model.fullId}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
))}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
@@ -17,7 +17,6 @@ const mockUseAICredits = vi.mocked(useAICredits);
describe('OnboardingCreditsBadge', () => {
const mockProvider = {
id: 'shakespeare',
name: 'Shakespeare',
baseURL: 'https://ai.shakespeare.diy/v1',
nostr: true,
};
+3 -8
View File
@@ -23,7 +23,6 @@ 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;
@@ -58,11 +57,10 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
selectedProvider && selectedProvider.nostr && user
? {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr,
}
: { id: '', name: '', baseURL: '', nostr: undefined }
: { id: '', baseURL: '', nostr: undefined }
);
// Filter models to only show selected provider models
@@ -124,9 +122,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}
// Add selected provider to their config
const providerConfig: AIProvider = {
const providerConfig = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
@@ -154,9 +151,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}
// Add selected provider to their config
const providerConfig: AIProvider = {
const providerConfig = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
};
@@ -730,7 +726,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}}
provider={{
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
+11 -27
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import { Sparkles, X } from 'lucide-react';
import { Sparkles } from 'lucide-react';
/**
* Component that prompts users to update when a new service worker is available
@@ -52,38 +52,22 @@ export function PWAUpdatePrompt() {
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>
<button
onClick={handleUpdate}
disabled={isUpdating}
className="group relative flex items-center gap-2 px-4 py-2.5 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>
</div>
);
}
+23 -6
View File
@@ -5,9 +5,11 @@ 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 { Separator } from '@/components/ui/separator';
import { usePlugins } from '@/hooks/usePlugins';
import { usePluginGitInfo } from '@/hooks/usePluginGitInfo';
import { useToast } from '@/hooks/useToast';
import { Alert, AlertDescription } from '@/components/ui/alert';
export function PluginsSection() {
const { t } = useTranslation();
@@ -77,6 +79,9 @@ export function PluginsSection() {
return (
<div className="space-y-4">
{/* Divider */}
<Separator className="my-6" />
{/* Plugins Header */}
<div className="space-y-2">
<div className="flex items-center gap-2">
@@ -89,7 +94,7 @@ export function PluginsSection() {
</div>
{/* Configured Plugins List */}
{plugins.length > 0 && (
{plugins.length > 0 ? (
<div className="space-y-2">
{plugins.map((pluginName) => {
const pluginSkills = skillsByPlugin[pluginName] || [];
@@ -107,11 +112,17 @@ export function PluginsSection() {
/>;
})}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noPluginsConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add Plugin Section */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-plugin">
<AccordionItem value="add-plugin" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
@@ -121,9 +132,7 @@ export function PluginsSection() {
<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>
<Label htmlFor="plugin-git-url">{t('gitRepositoryUrl')}</Label>
<Input
id="plugin-git-url"
placeholder="https://github.com/user/plugin.git"
@@ -182,7 +191,7 @@ function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, o
<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" />
<Puzzle className="h-4 w-4 text-primary" />
<span className="font-medium">{pluginName}</span>
{pluginSkills.length > 0 && (
<span className="text-xs text-muted-foreground">
@@ -215,6 +224,14 @@ function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, o
</div>
)}
{pluginSkills.length === 0 && (
<Alert>
<AlertDescription className="text-xs">
{t('noSkillsFound')}
</AlertDescription>
</Alert>
)}
{/* Plugin Actions and Git Info */}
<div className="space-y-2 pt-2">
{gitInfo && (
+4 -31
View File
@@ -34,8 +34,6 @@ import {
Trash2,
Save,
DollarSign,
ExternalLink,
FileCode,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
@@ -54,7 +52,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
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();
@@ -68,28 +65,21 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsRenaming(false);
}, [project.id]);
// Load total project cost and template info
// Load total project cost
useEffect(() => {
const loadProjectData = async () => {
const loadCost = 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);
console.warn('Failed to load project cost:', error);
setTotalCost(null);
setTemplateInfo(null);
}
};
if (open) {
loadProjectData();
loadCost();
}
}, [fs, projectsPath, project.id, open]);
@@ -266,23 +256,6 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
</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>
+6 -41
View File
@@ -1,10 +1,9 @@
import React, { useEffect, useState, useMemo } from 'react';
import React, { useEffect } 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 } 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';
@@ -94,24 +93,10 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const [searchQuery, setSearchQuery] = useState('');
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);
@@ -181,12 +166,12 @@ export function ProjectSidebar({
<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 +179,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>
@@ -210,20 +195,6 @@ export function ProjectSidebar({
</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 +214,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}
-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>
);
}
+1 -7
View File
@@ -197,13 +197,7 @@ 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();
},
}] : [],
actions: [],
};
};
-99
View File
@@ -1,99 +0,0 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch } from 'lucide-react';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
interface RepositoryCardProps {
repo: Repository;
}
export function RepositoryCard({ repo }: RepositoryCardProps) {
const { data: authorData } = useAuthor(repo.pubkey);
const navigate = useNavigate();
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
// Construct Nostr clone URL
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
const handleClone = () => {
// Navigate to clone page with Nostr URL parameter
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
};
return (
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow cursor-pointer" onClick={handleClone}>
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and author */}
<div className="mb-4">
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Avatar className="h-4 w-4">
{profileImage && (
<AvatarImage src={profileImage} alt={displayName} />
)}
<AvatarFallback className="text-[8px]">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="truncate">{displayName}</span>
</div>
</div>
{/* Description */}
{repo.description && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{repo.description}
</p>
)}
{/* Tags */}
{repo.repoTags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-4">
{repo.repoTags.slice(0, 3).map((tag, index) => (
<Badge key={index} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
{repo.repoTags.length > 3 && (
<Badge variant="secondary" className="text-xs">
+{repo.repoTags.length - 3}
</Badge>
)}
</div>
)}
{/* Personal fork badge */}
{repo.isPersonalFork && (
<div className="mb-4">
<Badge variant="outline" className="text-xs">
Personal Fork
</Badge>
</div>
)}
{/* Actions */}
<div className="mt-auto">
<Button
size="sm"
className="w-full"
onClick={handleClone}
>
<GitBranch className="h-4 w-4 mr-2" />
Clone
</Button>
</div>
</CardContent>
</Card>
);
}
+4 -4
View File
@@ -27,7 +27,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
projectTemplate: 'https://test.git',
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
@@ -64,7 +64,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
projectTemplate: 'https://test.git',
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
@@ -102,7 +102,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
projectTemplate: 'https://test.git',
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
@@ -143,7 +143,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
projectTemplate: 'https://test.git',
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
-57
View File
@@ -1,57 +0,0 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isActive?: boolean;
className?: string;
}
export function SettingsItem({
icon: Icon,
title,
onClick,
isActive = false,
className,
}: SettingsItemProps) {
return (
<button
onClick={onClick}
className={cn(
'group w-full text-left p-2 rounded-lg transition-all duration-200 border',
{
'bg-primary/10 border-primary/20 shadow-sm': isActive,
'border-transparent hover:bg-muted/60 hover:shadow-sm': !isActive,
},
className
)}
>
<div className="flex items-center gap-2.5">
<div className="rounded-md transition-all duration-200">
<Icon className={cn('h-4 w-4 flex-shrink-0 transition-colors duration-200', {
'text-primary': isActive,
'text-muted-foreground group-hover:text-foreground': !isActive,
})} />
</div>
<div className="flex-1 min-w-0">
<div className={cn('text-sm font-medium transition-colors duration-200', {
'text-primary': isActive,
'text-foreground': !isActive,
})}>
{title}
</div>
</div>
<ChevronRight className={cn(
'h-4 w-4 flex-shrink-0 transition-all duration-200',
'opacity-0 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0',
{
'text-primary opacity-60': isActive,
'text-muted-foreground': !isActive,
}
)} />
</div>
</button>
);
}
-43
View File
@@ -1,43 +0,0 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemMobileProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isFirst?: boolean;
isLast?: boolean;
}
export function SettingsItemMobile({
icon: Icon,
title,
onClick,
isFirst = false,
isLast = false,
}: SettingsItemMobileProps) {
return (
<button
onClick={onClick}
className={cn(
'w-full text-left px-4 py-3.5 bg-card text-card-foreground transition-colors active:bg-muted/50',
'flex items-center gap-3',
'border-b border-border last:border-b-0',
{
'rounded-t-xl': isFirst,
'rounded-b-xl': isLast,
}
)}
>
<div className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary/10">
<Icon className="h-4 w-4 text-primary flex-shrink-0" />
</div>
<div className="flex-1 min-w-0">
<div className="text-base">
{title}
</div>
</div>
<ChevronRight className="h-5 w-5 text-muted-foreground/50 flex-shrink-0" />
</button>
);
}
+36 -31
View File
@@ -8,8 +8,8 @@ import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
import { type Project } from '@/lib/ProjectsManager';
import { getSettingsCategories } from '@/lib/settingsItems';
import { SettingsItem } from '@/components/SettingsItem';
import { cn } from '@/lib/utils';
import { getSettingsItems } from '@/lib/settingsItems';
export function SettingsLayout() {
const { t } = useTranslation();
@@ -60,11 +60,9 @@ export function SettingsLayout() {
};
// Get current settings page
const settingsCategories = getSettingsCategories(t);
const settingsItems = getSettingsItems(t);
const currentPath = location.pathname;
const currentSettingsId = settingsCategories
.flatMap(category => category.items)
.find(item => item.href === currentPath)?.id;
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
if (isMobile) {
return (
@@ -91,7 +89,7 @@ export function SettingsLayout() {
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
<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={null}
onSelectProject={(project) => {
@@ -114,7 +112,7 @@ export function SettingsLayout() {
<div className="h-screen flex bg-background overflow-hidden">
{/* Left Column - Projects Sidebar (optionally hidden) */}
{isSidebarVisible && (
<div className="w-72 border-r bg-sidebar flex-shrink-0">
<div className="w-80 border-r bg-sidebar flex-shrink-0">
<ProjectSidebar
selectedProject={null}
onSelectProject={handleProjectSelect}
@@ -125,7 +123,7 @@ export function SettingsLayout() {
)}
{/* Middle Column - Settings Navigation */}
<div className="w-72 border-r bg-background flex flex-col flex-shrink-0">
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
{/* Header with toggle button */}
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
<div className="flex items-center gap-3">
@@ -148,29 +146,36 @@ export function SettingsLayout() {
{/* Settings Navigation - Scrollable */}
<ScrollArea className="flex-1">
<div className="p-4 space-y-6">
{settingsCategories.map((category) => (
<div key={category.id}>
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-2">
{category.title}
</h3>
<div className="space-y-1">
{category.items.map((item) => {
const isActive = currentSettingsId === item.id;
<div className="p-4">
<div className="space-y-2">
{settingsItems.map((item) => {
const Icon = item.icon;
const isActive = currentSettingsId === item.id;
return (
<SettingsItem
key={item.id}
icon={item.icon}
title={item.title}
onClick={() => navigate(item.href)}
isActive={isActive}
/>
);
})}
</div>
</div>
))}
return (
<button
key={item.id}
onClick={() => navigate(item.href)}
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
'bg-primary/10 border border-primary/20': isActive,
'hover:bg-muted/50': !isActive,
})}
>
<div className="flex items-start gap-3">
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
<div className="flex-1 min-w-0">
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
{item.title}
</div>
<div className="text-sm text-muted-foreground mt-0.5">
{item.description}
</div>
</div>
</div>
</button>
);
})}
</div>
</div>
</ScrollArea>
</div>
+1 -25
View File
@@ -5,7 +5,7 @@ import { Textarea } from '@/components/ui/textarea';
import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip';
import { CircularProgress } from '@/components/ui/circular-progress';
import { FileAttachment } from '@/components/ui/file-attachment';
import { Square, ArrowUp, MessageCircle } from 'lucide-react';
import { Square, ArrowUp } from 'lucide-react';
import { ModelSelector } from '@/components/ModelSelector';
interface ChatInputProps {
@@ -28,9 +28,6 @@ interface ChatInputProps {
onDragOver: (e: React.DragEvent) => void;
onDragLeave: (e: React.DragEvent) => void;
onDrop: (e: React.DragEvent) => void;
/** Mobile chat mode toggle - only shown on mobile when global chat is enabled */
mobileChatMode?: 'building' | 'chatting';
onMobileChatModeChange?: (mode: 'building' | 'chatting') => void;
}
export const ChatInput = memo(function ChatInput({
@@ -53,8 +50,6 @@ export const ChatInput = memo(function ChatInput({
onDragOver,
onDragLeave,
onDrop,
mobileChatMode,
onMobileChatModeChange,
}: ChatInputProps) {
const { t } = useTranslation();
const [input, setInput] = useState('');
@@ -163,25 +158,6 @@ export const ChatInput = memo(function ChatInput({
{/* Bottom Controls Row */}
<div className="flex items-center gap-4 px-2 py-2">
{/* Mobile Chat Mode Toggle - single button to switch to chatting mode */}
{mobileChatMode && onMobileChatModeChange && (
<TooltipProvider>
<Tooltip>
<TooltipTrigger asChild>
<Button
variant="ghost"
size="icon"
className="h-8 w-8 shrink-0"
onClick={() => onMobileChatModeChange('chatting')}
>
<MessageCircle className="h-4 w-4" />
</Button>
</TooltipTrigger>
<TooltipContent>{t('chatting')}</TooltipContent>
</Tooltip>
</TooltipProvider>
)}
{/* File Attachment */}
<FileAttachment
onFileSelect={handleFileSelect}
+8 -104
View File
@@ -46,7 +46,6 @@ import { Quilly } from '@/components/Quilly';
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
import { ChatInput } from '@/components/Shakespeare/ChatInput';
import { buildMessageContent } from '@/lib/buildMessageContent';
import { DotAI } from '@/lib/DotAI';
// Clean interfaces now handled by proper hooks
@@ -59,9 +58,6 @@ interface ChatPaneProps {
isBuildLoading?: boolean;
consoleError?: ProjectPreviewConsoleError | null;
onDismissConsoleError?: () => void;
/** Mobile chat mode toggle - only shown on mobile when global chat is enabled */
mobileChatMode?: 'building' | 'chatting';
onMobileChatModeChange?: (mode: 'building' | 'chatting') => void;
}
export interface ChatPaneRef {
@@ -77,8 +73,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
isBuildLoading: externalIsBuildLoading,
consoleError,
onDismissConsoleError,
mobileChatMode,
onMobileChatModeChange,
}, ref) => {
const { t } = useTranslation();
const [searchParams, setSearchParams] = useSearchParams();
@@ -94,8 +88,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const [showOnboarding, setShowOnboarding] = useState(false);
const [isStuck, setIsStuck] = useState(false);
const [aiError, setAIError] = useState<Error | null>(null);
const [templateInfo, setTemplateInfo] = useState<{ name: string; description: string; url: string } | null>(null);
const [showTemplateInfo, setShowTemplateInfo] = useState(false);
// Determine which error to show - console error takes priority over AI errors
const displayError = consoleError || aiError;
@@ -182,7 +174,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
nostr_publish_events: new NostrPublishEventsTool(),
shell: new ShellTool(fs, cwd, git, config.corsProxy, user?.signer),
read_console_messages: new ReadConsoleMessagesTool(),
skill: new SkillTool(fs, pluginsPath, cwd),
skill: new SkillTool(fs, pluginsPath),
};
// Add deploy tool only if user is logged in
@@ -260,52 +252,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onAIError,
});
// Check if we should show the template info banner
useEffect(() => {
const checkTemplateInfo = async () => {
try {
// Only check if we have at least 1 message
if (messages.length === 0) {
setShowTemplateInfo(false);
return;
}
const projectCwd = `${projectsPath}/${projectId}`;
const dotAI = new DotAI(fs, projectCwd);
// Check if template.json exists
const template = await dotAI.readTemplate();
if (!template) {
setShowTemplateInfo(false);
return;
}
// Check if exactly 1 history file exists
const historyDirExists = await dotAI.historyDirExists();
if (!historyDirExists) {
setShowTemplateInfo(false);
return;
}
const historyDir = `${projectCwd}/.git/ai/history`;
const files = await fs.readdir(historyDir);
const historyFiles = files.filter(file => file.endsWith('.jsonl'));
if (historyFiles.length === 1) {
setTemplateInfo(template);
setShowTemplateInfo(true);
} else {
setShowTemplateInfo(false);
}
} catch (error) {
console.warn('Failed to check template info:', error);
setShowTemplateInfo(false);
}
};
checkTemplateInfo();
}, [fs, projectsPath, projectId, messages.length]);
// Handle console error help requests
const handleConsoleErrorHelp = useCallback(async () => {
const tool = new ReadConsoleMessagesTool();
@@ -382,8 +328,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Reset the flag so auto-scroll resumes
userScrolledUp.current = false;
}
}, []);
@@ -434,34 +378,17 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
};
}, [messages]); // Re-run when messages change to ensure proper setup
// Track whether user has manually scrolled up
const userScrolledUp = useRef(false);
// Detect when user manually scrolls
useEffect(() => {
const container = scrollAreaRef.current;
if (!container) return;
const handleUserScroll = () => {
if (scrollAreaRef.current && (messages || streamingMessage)) {
// Check if user was already at or near the bottom (within 100px threshold)
const threshold = 100;
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - threshold;
// If user scrolled away from bottom, mark it
// If user scrolled back to bottom, reset the flag
userScrolledUp.current = !isNearBottom;
};
container.addEventListener('scroll', handleUserScroll);
return () => container.removeEventListener('scroll', handleUserScroll);
}, []);
// Auto-scroll when messages change or streaming content updates
useEffect(() => {
if (!scrollAreaRef.current) return;
// Only auto-scroll if user hasn't manually scrolled up
if (!userScrolledUp.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
// Only auto-scroll if user was already near the bottom
if (isNearBottom) {
container.scrollTop = container.scrollHeight;
}
}
}, [messages, streamingMessage, isLoading]);
@@ -472,8 +399,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
const timer = setTimeout(() => {
scrollToBottom();
scrolledProjects.add(projectId);
// Reset the userScrolledUp flag when switching projects
userScrolledUp.current = false;
}, 100);
return () => clearTimeout(timer);
@@ -577,25 +502,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
<div className="flex-1 overflow-y-scroll overflow-x-hidden" ref={scrollAreaRef}>
<div className="p-4 space-y-4">
{/* Template info banner - shown when conditions are met */}
{showTemplateInfo && templateInfo && (
<div className="flex items-center gap-3 text-xs text-muted-foreground uppercase tracking-wide">
<div className="flex-1 h-px bg-border" />
<span>
Vibing with{' '}
<a
href={templateInfo.url}
target="_blank"
rel="noopener noreferrer"
className="hover:text-foreground transition-colors"
>
{templateInfo.name}
</a>
</span>
<div className="flex-1 h-px bg-border" />
</div>
)}
{/* Empty state when no messages and not loading */}
{messages.length === 0 && !streamingMessage && !isLoading && (
<div className="flex-1 flex items-center justify-center min-h-[400px]">
@@ -734,8 +640,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
onDragOver={handleDragOver}
onDragLeave={handleDragLeave}
onDrop={handleDrop}
mobileChatMode={mobileChatMode}
onMobileChatModeChange={onMobileChatModeChange}
/>
{/* Onboarding Dialog */}
-7
View File
@@ -2,7 +2,6 @@ import { useEffect, useState } from 'react';
import { useLocation, useNavigate } from 'react-router-dom';
import { AddProviderDialog } from '@/components/AddProviderDialog';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
/**
* Component that handles URL fragments for adding AI providers
@@ -31,15 +30,9 @@ export function URLFragmentHandler() {
return;
}
// Get name from URL params or derive from presets or id
const nameParam = params.get('name');
const preset = AI_PROVIDER_PRESETS.find(p => p.id === id);
const name = nameParam || preset?.name || id;
// Build the provider object
const provider: AIProvider = {
id,
name,
baseURL,
};
@@ -1,219 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface CloudflareWorkerScript {
id: string;
etag: string;
handlers: string[];
modified_on: string;
created_on: string;
has_assets: boolean;
}
interface CloudflareDeployFormProps {
apiKey: string;
accountId: string;
baseURL?: string;
baseDomain?: string;
projectId: string;
projectName?: string;
savedProjectName?: string;
onProjectChange: (projectName: string) => void;
corsProxy?: string;
}
export function CloudflareDeployForm({
apiKey,
accountId,
baseURL = 'https://api.cloudflare.com/client/v4',
baseDomain = 'workers.dev',
projectId,
projectName,
savedProjectName,
onProjectChange,
corsProxy,
}: CloudflareDeployFormProps) {
const [workers, setWorkers] = useState<CloudflareWorkerScript[]>([]);
const [workersSubdomain, setWorkersSubdomain] = useState<string | null>(null);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
const fetchWorkersData = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
// Fetch workers subdomain and workers list in parallel
const subdomainUrl = `${baseURL}/accounts/${accountId}/workers/subdomain`;
const workersUrl = `${baseURL}/accounts/${accountId}/workers/scripts`;
const [subdomainResponse, workersResponse] = await Promise.all([
fetch(corsProxy ? proxyUrl(corsProxy, subdomainUrl) : subdomainUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
fetch(corsProxy ? proxyUrl(corsProxy, workersUrl) : workersUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
}),
]);
if (!subdomainResponse.ok) {
throw new Error(`Failed to fetch workers subdomain: ${subdomainResponse.status} ${subdomainResponse.statusText}`);
}
if (!workersResponse.ok) {
throw new Error(`Failed to fetch workers: ${workersResponse.status} ${workersResponse.statusText}`);
}
const [subdomainData, workersData] = await Promise.all([
subdomainResponse.json(),
workersResponse.json(),
]);
setWorkersSubdomain(subdomainData.result?.subdomain || null);
setWorkers(workersData.result || []);
// If there's a saved project name and it exists in the list, select it
// Otherwise leave it empty (showing placeholder)
if (savedProjectName && workersData.result?.some((w: CloudflareWorkerScript) => w.id === savedProjectName)) {
setSelectedProjectName(savedProjectName);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch workers data');
} finally {
setIsLoading(false);
}
}, [apiKey, accountId, baseURL, savedProjectName, corsProxy]);
useEffect(() => {
fetchWorkersData();
}, [fetchWorkersData]);
// Update newProjectName when switching to "new" if it's empty
useEffect(() => {
if (selectedProjectName === 'new' && !newProjectName) {
setNewProjectName(projectName || projectId);
}
}, [selectedProjectName, newProjectName, projectName, projectId]);
useEffect(() => {
if (selectedProjectName === '') {
// No selection yet - don't call onProjectChange
return;
} else if (selectedProjectName === 'new') {
onProjectChange(newProjectName);
} else {
onProjectChange(selectedProjectName);
}
}, [selectedProjectName, newProjectName, onProjectChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Project</Label>
<Skeleton className="h-10 w-full" />
</div>
<Skeleton className="h-4 w-3/4" />
</div>
);
}
const selectedWorker = workers.find(w => w.id === selectedProjectName);
// Construct the URL preview
const getWorkerUrl = (scriptName: string) => {
if (workersSubdomain) {
return `https://${scriptName}.${workersSubdomain}.${baseDomain}`;
}
return `https://${scriptName}.<subdomain>.${baseDomain}`;
};
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="cloudflare-project">Select Worker</Label>
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
<SelectTrigger id="cloudflare-project">
<SelectValue placeholder="Select a worker or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new worker
</div>
</SelectItem>
{workers.map((worker) => (
<SelectItem key={worker.id} value={worker.id}>
{worker.id}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProjectName === 'new' ? (
<div className="space-y-2">
<Label htmlFor="new-project-name">New Worker Name</Label>
<Input
id="new-project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{getWorkerUrl(newProjectName || projectId)}</span>
</p>
<p className="text-xs text-muted-foreground">
A new worker will be created when you deploy
</p>
</div>
) : selectedWorker ? (
<div className="space-y-2">
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedWorker.id}</p>
<p className="text-xs text-muted-foreground font-mono">
{getWorkerUrl(selectedWorker.id)}
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(`https://dash.cloudflare.com/${accountId}/workers/services/view/${selectedWorker.id}`, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Deployment will update this existing worker
</p>
</div>
) : null}
</div>
);
}
-198
View File
@@ -1,198 +0,0 @@
import { useState, useEffect, useCallback } from 'react';
import { Plus, ExternalLink } from 'lucide-react';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Button } from '@/components/ui/button';
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
SelectValue,
} from '@/components/ui/select';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Skeleton } from '@/components/ui/skeleton';
import { proxyUrl } from '@/lib/proxyUrl';
interface DenoProject {
id: string;
name: string;
createdAt: string;
updatedAt: string;
}
interface DenoDeployFormProps {
apiKey: string;
organizationId: string;
baseURL?: string;
baseDomain?: string;
projectId: string;
projectName?: string;
savedProjectName?: string;
onProjectChange: (projectName: string) => void;
corsProxy?: string;
}
export function DenoDeployForm({
apiKey,
organizationId,
baseURL = 'https://api.deno.com/v1',
baseDomain = 'deno.dev',
projectId,
projectName,
savedProjectName,
onProjectChange,
corsProxy,
}: DenoDeployFormProps) {
const [projects, setProjects] = useState<DenoProject[]>([]);
const [isLoading, setIsLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [selectedProjectName, setSelectedProjectName] = useState<string>('');
const [newProjectName, setNewProjectName] = useState(projectName || projectId);
const fetchProjects = useCallback(async () => {
setIsLoading(true);
setError(null);
try {
const url = `${baseURL}/organizations/${organizationId}/projects?limit=100`;
const targetUrl = corsProxy ? proxyUrl(corsProxy, url) : url;
const response = await fetch(targetUrl, {
headers: { 'Authorization': `Bearer ${apiKey}` },
});
if (!response.ok) {
throw new Error(`Failed to fetch projects: ${response.status} ${response.statusText}`);
}
const data: DenoProject[] = await response.json();
setProjects(data);
// If there's a saved project name and it exists in the list, select it
// Otherwise leave it empty (showing placeholder)
if (savedProjectName && data.some((p: DenoProject) => p.name === savedProjectName)) {
setSelectedProjectName(savedProjectName);
}
} catch (err) {
setError(err instanceof Error ? err.message : 'Failed to fetch projects');
} finally {
setIsLoading(false);
}
}, [apiKey, organizationId, baseURL, savedProjectName, corsProxy]);
useEffect(() => {
fetchProjects();
}, [fetchProjects]);
// Update newProjectName when switching to "new" if it's empty
useEffect(() => {
if (selectedProjectName === 'new' && !newProjectName) {
setNewProjectName(projectName || projectId);
}
}, [selectedProjectName, newProjectName, projectName, projectId]);
useEffect(() => {
if (selectedProjectName === '') {
// No selection yet - don't call onProjectChange
return;
} else if (selectedProjectName === 'new') {
onProjectChange(newProjectName);
} else {
onProjectChange(selectedProjectName);
}
}, [selectedProjectName, newProjectName, onProjectChange]);
if (isLoading) {
return (
<div className="space-y-4">
<div className="space-y-2">
<Label>Project</Label>
<Skeleton className="h-10 w-full" />
</div>
<Skeleton className="h-4 w-3/4" />
</div>
);
}
const selectedProject = projects.find(p => p.name === selectedProjectName);
// Construct the URL preview
const getProjectUrl = (name: string) => {
return `https://${name}.${baseDomain}`;
};
return (
<div className="space-y-4">
{error && (
<Alert variant="destructive">
<AlertDescription>{error}</AlertDescription>
</Alert>
)}
<div className="space-y-2">
<Label htmlFor="deno-project">Select Project</Label>
<Select value={selectedProjectName} onValueChange={setSelectedProjectName}>
<SelectTrigger id="deno-project">
<SelectValue placeholder="Select a project or create new..." />
</SelectTrigger>
<SelectContent>
<SelectItem value="new">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
Create new project
</div>
</SelectItem>
{projects.map((project) => (
<SelectItem key={project.id} value={project.name}>
{project.name}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
{selectedProjectName === 'new' ? (
<div className="space-y-2">
<Label htmlFor="new-project-name">New Project Name</Label>
<Input
id="new-project-name"
value={newProjectName}
onChange={(e) => setNewProjectName(e.target.value)}
placeholder={projectName || projectId}
/>
<p className="text-xs text-muted-foreground">
URL: <span className="font-mono">{getProjectUrl(newProjectName || projectId)}</span>
</p>
<p className="text-xs text-muted-foreground">
A new project will be created when you deploy
</p>
</div>
) : selectedProject ? (
<div className="space-y-2">
<div className="rounded-lg border p-3 space-y-2">
<div className="flex items-center justify-between">
<div>
<p className="text-sm font-medium">{selectedProject.name}</p>
<p className="text-xs text-muted-foreground font-mono">
{getProjectUrl(selectedProject.name)}
</p>
</div>
<Button
type="button"
variant="ghost"
size="sm"
onClick={() => window.open(`https://dash.deno.com/projects/${selectedProject.name}`, '_blank')}
>
<ExternalLink className="h-4 w-4" />
</Button>
</div>
</div>
<p className="text-xs text-muted-foreground">
Deployment will create a new version for this project
</p>
</div>
) : null}
</div>
);
}
-2
View File
@@ -2,5 +2,3 @@ export { ShakespeareDeployForm } from './ShakespeareDeployForm';
export { NetlifyDeployForm } from './NetlifyDeployForm';
export { VercelDeployForm } from './VercelDeployForm';
export { NsiteDeployForm } from './NsiteDeployForm';
export { CloudflareDeployForm } from './CloudflareDeployForm';
export { DenoDeployForm } from './DenoDeployForm';
+25 -76
View File
@@ -3,7 +3,6 @@ import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
import { Textarea } from '@/components/ui/textarea';
import { TagInput } from '@/components/ui/tag-input';
import {
Dialog,
DialogContent,
@@ -34,8 +33,6 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useNostr } from '@/hooks/useNostr';
import { useToast } from '@/hooks/useToast';
import { useAppContext } from '@/hooks/useAppContext';
import { useFS } from '@/hooks/useFS';
import { DotAI } from '@/lib/DotAI';
import { nip19 } from 'nostr-tools';
import {
createRepositoryAnnouncementEvent,
@@ -78,7 +75,6 @@ export function AnnounceRepositoryDialog({
const [webUrls, setWebUrls] = useState<string[]>([]);
const [cloneUrls, setCloneUrls] = useState<string[]>([]);
const [relays, setRelays] = useState<string[]>([]);
const [tTags, setTTags] = useState<string[]>([]);
const [earliestCommit, setEarliestCommit] = useState('');
const [isCreating, setIsCreating] = useState(false);
const [error, setError] = useState<string | null>(null);
@@ -93,7 +89,6 @@ export function AnnounceRepositoryDialog({
const { nostr } = useNostr();
const { toast } = useToast();
const { config } = useAppContext();
const { fs } = useFS();
const projectPath = `${projectsPath}/${projectId}`;
@@ -151,57 +146,37 @@ export function AnnounceRepositoryDialog({
.join(' ');
setName(defaultName);
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
// Clone URLs: https://{server}/{npub}/{repo-id}.git
const npub = nip19.npubEncode(user.pubkey);
const cloneUrls = config.ngitServers.map(server =>
`https://${server}/${npub}/${defaultRepoId}.git`
);
setCloneUrls(cloneUrls);
// Only prepopulate if the arrays are empty (user hasn't made changes yet)
if (cloneUrls.length === 0 && relays.length === 0) {
// Prepopulate clone URLs and relays from ngitServers (matching original handlePushToNostr)
if (user?.pubkey && config.ngitServers && config.ngitServers.length > 0) {
// Clone URLs: https://{server}/{npub}/{repo-id}.git
const npub = nip19.npubEncode(user.pubkey);
const cloneUrls = config.ngitServers.map(server =>
`https://${server}/${npub}/${defaultRepoId}.git`
);
setCloneUrls(cloneUrls);
// Relay URLs: wss://{server}
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
setRelays(relayUrls);
} else {
// Fallback to write relays if no ngitServers configured
const writeRelays = config.relayMetadata.relays
.filter(r => r.write)
.map(r => r.url);
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
}
// Prepopulate t-tags
const defaultTTags: string[] = ['shakespeare'];
// Try to read template.json to get template name
try {
const dotAI = new DotAI(fs, projectPath);
const template = await dotAI.readTemplate();
if (template?.name) {
// Convert template name to lowercase and add as t-tag
const templateTag = template.name.toLowerCase();
if (!defaultTTags.includes(templateTag)) {
defaultTTags.push(templateTag);
}
// Relay URLs: wss://{server}
const relayUrls = config.ngitServers.map(server => `wss://${server}`);
setRelays(relayUrls);
} else {
// Fallback to write relays if no ngitServers configured
const writeRelays = config.relayMetadata.relays
.filter(r => r.write)
.map(r => r.url);
setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']);
}
} catch (error) {
console.warn('Failed to read template for t-tags:', error);
}
setTTags(defaultTTags);
// Get earliest commit
await getEarliestCommit();
}, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit]);
}, [projectId, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]);
// Load existing repository data if editing, or prepopulate fields for new repos
// Load existing repository data if editing
useEffect(() => {
// Only run when dialog opens
if (!isOpen || isPrepopulated) return;
const loadExistingRepo = async () => {
if (!editNaddr) return;
if (!editNaddr || !isOpen) return;
try {
// Decode the naddr to get repository coordinates
@@ -246,13 +221,6 @@ export function AnnounceRepositoryDialog({
setRelays(parsed.relays);
setEarliestCommit(parsed.earliestCommit || '');
// Extract t-tags from the event
const extractedTTags = parsed.event.tags
.filter(([name]) => name === 't')
.map(([, value]) => value)
.filter((value): value is string => !!value);
setTTags(extractedTTags);
setIsPrepopulated(true);
} catch (error) {
console.error('Failed to load repository data:', error);
@@ -264,13 +232,13 @@ export function AnnounceRepositoryDialog({
}
};
if (editNaddr) {
if (isOpen && editNaddr) {
loadExistingRepo();
} else {
} else if (isOpen && !isPrepopulated) {
prepopulateFields();
setIsPrepopulated(true);
}
}, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]);
}, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayMetadata, toast]);
const addWebUrl = () => {
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
@@ -345,7 +313,6 @@ export function AnnounceRepositoryDialog({
webUrls,
cloneUrls,
relays,
tTags,
earliestCommit,
});
@@ -418,7 +385,6 @@ export function AnnounceRepositoryDialog({
setWebUrls([]);
setCloneUrls([]);
setRelays(['wss://relay.nostr.band']);
setTTags([]);
setEarliestCommit('');
setError(null);
setNewWebUrl('');
@@ -670,23 +636,6 @@ export function AnnounceRepositoryDialog({
</p>
</div>
{/* Category Tags (t-tags) */}
<div className="space-y-2">
<Label htmlFor="category-tags">Category Tags</Label>
<TagInput
id="category-tags"
value={tTags}
onChange={setTTags}
placeholder="e.g., nostr, social, web"
disabled={isCreating}
transformTag={(tag) => tag.trim().toLowerCase()}
allowDuplicates={false}
/>
<p className="text-xs text-muted-foreground">
Tags for categorizing your repository. Press space or comma to add a tag.
</p>
</div>
{/* Earliest Commit */}
<div className="space-y-2">
<Label htmlFor="earliest-commit">Earliest Unique Commit</Label>
+1
View File
@@ -223,6 +223,7 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
+1 -1
View File
@@ -12,7 +12,7 @@ const AccordionItem = React.forwardRef<
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border rounded-lg bg-card text-card-foreground shadow-sm", className)}
className={cn("border-b", className)}
{...props}
/>
))
+1 -1
View File
@@ -11,7 +11,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-xs border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
+16 -24
View File
@@ -2,13 +2,8 @@ import * as React from "react"
import { Eye, EyeOff } from "lucide-react"
import { cn } from "@/lib/utils"
interface PasswordInputProps extends React.InputHTMLAttributes<HTMLInputElement> {
/** Whether to show the visibility toggle button. Defaults to true. */
showToggle?: boolean;
}
const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
({ className, showToggle = true, ...props }, ref) => {
const PasswordInput = React.forwardRef<HTMLInputElement, React.InputHTMLAttributes<HTMLInputElement>>(
({ className, ...props }, ref) => {
const [showPassword, setShowPassword] = React.useState(false)
const [isFocused, setIsFocused] = React.useState(false)
@@ -17,8 +12,7 @@ const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
<input
type={showPassword ? "text" : "password"}
className={cn(
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-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",
showToggle && "pr-10",
"flex h-10 w-full rounded-md border border-input bg-background px-3 py-2 pr-10 text-base ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium file:text-foreground placeholder:text-muted-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",
isFocused && "ring-2 ring-ring ring-offset-2"
)}
ref={ref}
@@ -32,21 +26,19 @@ const PasswordInput = React.forwardRef<HTMLInputElement, PasswordInputProps>(
}}
{...props}
/>
{showToggle && (
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
)}
<button
type="button"
onClick={() => setShowPassword(!showPassword)}
className="absolute right-3 top-1/2 -translate-y-1/2 text-muted-foreground hover:text-foreground focus:outline-none disabled:cursor-not-allowed disabled:opacity-50"
disabled={props.disabled}
aria-label={showPassword ? "Hide password" : "Show password"}
>
{showPassword ? (
<EyeOff className="h-4 w-4" />
) : (
<Eye className="h-4 w-4" />
)}
</button>
</div>
)
}
+1 -1
View File
@@ -17,7 +17,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:bg-border/20 dark:hover:bg-border/50 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
-256
View File
@@ -1,256 +0,0 @@
import { describe, it, expect, vi } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { TagInput } from './tag-input';
describe('TagInput', () => {
it('renders with placeholder when no tags', () => {
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
expect(input).toBeInTheDocument();
});
it('displays existing tags', () => {
const onChange = vi.fn();
render(
<TagInput
value={['tag1', 'tag2', 'tag3']}
onChange={onChange}
/>
);
expect(screen.getByText('tag1')).toBeInTheDocument();
expect(screen.getByText('tag2')).toBeInTheDocument();
expect(screen.getByText('tag3')).toBeInTheDocument();
});
it('adds tag on space key', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'newtag ');
expect(onChange).toHaveBeenCalledWith(['newtag']);
});
it('adds tag on comma key', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'newtag,');
expect(onChange).toHaveBeenCalledWith(['newtag']);
});
it('adds tag on Enter key', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'newtag{Enter}');
expect(onChange).toHaveBeenCalledWith(['newtag']);
});
it('removes last tag on Backspace when input is empty', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['tag1', 'tag2']}
onChange={onChange}
/>
);
const input = screen.getByRole('textbox');
await user.click(input);
await user.keyboard('{Backspace}');
expect(onChange).toHaveBeenCalledWith(['tag1']);
});
it('removes tag when clicking X button', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['tag1', 'tag2', 'tag3']}
onChange={onChange}
/>
);
const removeButtons = screen.getAllByRole('button');
await user.click(removeButtons[1]); // Remove tag2
expect(onChange).toHaveBeenCalledWith(['tag1', 'tag3']);
});
it('transforms tags using transformTag function', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
transformTag={(tag) => tag.toUpperCase()}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, 'lowercase ');
expect(onChange).toHaveBeenCalledWith(['LOWERCASE']);
});
it('prevents duplicate tags by default', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['existing']}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByRole('textbox');
await user.type(input, 'existing ');
expect(onChange).not.toHaveBeenCalled();
});
it('allows duplicate tags when allowDuplicates is true', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={['existing']}
onChange={onChange}
allowDuplicates={true}
placeholder="Add tags..."
/>
);
const input = screen.getByRole('textbox');
await user.type(input, 'existing ');
expect(onChange).toHaveBeenCalledWith(['existing', 'existing']);
});
it('validates tags using validateTag function', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
validateTag={(tag) => tag.length >= 3}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
// Try adding tag that's too short
await user.type(input, 'ab ');
expect(onChange).not.toHaveBeenCalled();
// Add valid tag
await user.type(input, 'valid ');
expect(onChange).toHaveBeenCalledWith(['valid']);
});
it('does not add empty tags', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
render(
<TagInput
value={[]}
onChange={onChange}
placeholder="Add tags..."
/>
);
const input = screen.getByPlaceholderText('Add tags...');
await user.type(input, ' '); // Just spaces
expect(onChange).not.toHaveBeenCalled();
});
it('focuses input when container is clicked', async () => {
const user = userEvent.setup();
const onChange = vi.fn();
const { container } = render(
<TagInput
value={['tag1']}
onChange={onChange}
/>
);
const inputContainer = container.querySelector('div');
if (inputContainer) {
await user.click(inputContainer);
}
const input = screen.getByRole('textbox');
expect(input).toHaveFocus();
});
it('is disabled when disabled prop is true', () => {
const onChange = vi.fn();
render(
<TagInput
value={['tag1']}
onChange={onChange}
disabled={true}
/>
);
const input = screen.getByRole('textbox');
expect(input).toBeDisabled();
});
});
-172
View File
@@ -1,172 +0,0 @@
import * as React from 'react';
import { X } from 'lucide-react';
import { Badge } from '@/components/ui/badge';
import { cn } from '@/lib/utils';
export interface TagInputProps
extends Omit<React.InputHTMLAttributes<HTMLInputElement>, 'value' | 'onChange'> {
value: string[];
onChange: (tags: string[]) => void;
/** Character(s) that trigger tag creation. Default: [' ', ','] */
delimiters?: string[];
/** Transform tag before adding (e.g., toLowerCase). Default: (tag) => tag.trim() */
transformTag?: (tag: string) => string;
/** Validate tag before adding. Return false to reject. */
validateTag?: (tag: string) => boolean;
/** Allow duplicate tags. Default: false */
allowDuplicates?: boolean;
}
export const TagInput = React.forwardRef<HTMLInputElement, TagInputProps>(
(
{
className,
value = [],
onChange,
delimiters = [' ', ','],
transformTag = (tag) => tag.trim(),
validateTag,
allowDuplicates = false,
disabled,
placeholder,
...props
},
ref
) => {
const [inputValue, setInputValue] = React.useState('');
const inputRef = React.useRef<HTMLInputElement>(null);
const containerRef = React.useRef<HTMLDivElement>(null);
// Combine external ref with internal ref
React.useImperativeHandle(ref, () => inputRef.current!);
const addTag = (tag: string) => {
const transformed = transformTag(tag);
if (!transformed) return;
// Check for duplicates if not allowed
if (!allowDuplicates && value.includes(transformed)) {
setInputValue('');
return;
}
// Validate if validator provided
if (validateTag && !validateTag(transformed)) {
setInputValue('');
return;
}
onChange([...value, transformed]);
setInputValue('');
};
const removeTag = (index: number) => {
onChange(value.filter((_, i) => i !== index));
};
const handleKeyDown = (e: React.KeyboardEvent<HTMLInputElement>) => {
// Handle delimiters (space, comma, etc.)
if (delimiters.includes(e.key)) {
e.preventDefault();
if (inputValue.trim()) {
addTag(inputValue);
}
return;
}
// Handle Enter key
if (e.key === 'Enter') {
e.preventDefault();
if (inputValue.trim()) {
addTag(inputValue);
}
return;
}
// Handle Backspace - delete last tag if input is empty
if (e.key === 'Backspace' && !inputValue && value.length > 0) {
e.preventDefault();
removeTag(value.length - 1);
return;
}
};
const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const newValue = e.target.value;
// Check if any delimiter was typed
const hasDelimiter = delimiters.some(delimiter => newValue.includes(delimiter));
if (hasDelimiter) {
// Extract the part before the delimiter
const parts = newValue.split(new RegExp(`[${delimiters.map(d => d === ' ' ? '\\s' : d).join('')}]`));
const tagToAdd = parts[0];
if (tagToAdd.trim()) {
addTag(tagToAdd);
}
} else {
setInputValue(newValue);
}
};
const handleContainerClick = () => {
inputRef.current?.focus();
};
return (
<div
ref={containerRef}
className={cn(
'flex min-h-10 w-full flex-wrap gap-1.5 rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background',
'focus-within:outline-none focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2',
disabled && 'cursor-not-allowed opacity-50',
className
)}
onClick={handleContainerClick}
>
{/* Render tags */}
{value.map((tag, index) => (
<Badge
key={index}
variant="secondary"
className="gap-1 pr-1.5 pl-2.5 py-0.5 h-6"
>
<span>{tag}</span>
<button
type="button"
className="ml-1 rounded-sm hover:bg-secondary-foreground/20 focus:outline-none focus:ring-1 focus:ring-ring"
onClick={(e) => {
e.stopPropagation();
removeTag(index);
}}
disabled={disabled}
>
<X className="h-3 w-3" />
<span className="sr-only">Remove {tag}</span>
</button>
</Badge>
))}
{/* Input field */}
<input
ref={inputRef}
type="text"
value={inputValue}
onChange={handleInputChange}
onKeyDown={handleKeyDown}
disabled={disabled}
placeholder={value.length === 0 ? placeholder : undefined}
className={cn(
'flex-1 min-w-[120px] bg-transparent outline-none placeholder:text-muted-foreground',
'disabled:cursor-not-allowed'
)}
{...props}
/>
</div>
);
}
);
TagInput.displayName = 'TagInput';
-1
View File
@@ -2,7 +2,6 @@ import { createContext } from 'react';
export interface AIProvider {
id: string;
name: string;
baseURL: string;
apiKey?: string;
nostr?: boolean;
+2 -15
View File
@@ -9,22 +9,13 @@ export interface RelayMetadata {
updatedAt: number;
}
export interface ProjectTemplate {
/** Template name */
name: string;
/** Template description */
description: string;
/** Git repository URL */
url: string;
}
export interface AppConfig {
/** Current theme */
theme: Theme;
/** NIP-65 relay list metadata */
relayMetadata: RelayMetadata;
/** Available project templates */
templates: ProjectTemplate[];
/** Git repository URL to use as project template */
projectTemplate: string;
/** ESM CDN URL for package imports */
esmUrl: string;
/** HTTP proxy used to bypass CORS for AI and Git operations */
@@ -57,10 +48,6 @@ export interface AppConfig {
sentryEnabled: boolean;
/** System prompt EJS template */
systemPrompt?: string;
/** Whether the global floating chat is enabled */
globalChatEnabled?: boolean;
/** Custom system prompt for global chat */
globalChatSystemPrompt?: string;
}
export interface AppContextType {
+1 -19
View File
@@ -32,25 +32,7 @@ export interface NsiteProvider extends BaseDeployProvider {
blossomServers: string[];
}
export interface CloudflareProvider extends BaseDeployProvider {
type: 'cloudflare';
apiKey: string;
accountId: string;
baseURL?: string;
baseDomain?: string;
proxy?: boolean;
}
export interface DenoDeployProvider extends BaseDeployProvider {
type: 'deno';
apiKey: string;
organizationId: string;
baseURL?: string;
baseDomain?: string;
proxy?: boolean;
}
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider | CloudflareProvider | DenoDeployProvider;
export type DeployProvider = ShakespeareDeployProvider | NetlifyProvider | VercelProvider | NsiteProvider;
export interface DeploySettings {
providers: DeployProvider[];
-23
View File
@@ -1,23 +0,0 @@
import { createContext } from 'react';
export interface GlobalChatMessage {
id: string;
role: 'user' | 'assistant';
content: string;
timestamp: number;
}
export interface GlobalChatContextType {
messages: GlobalChatMessage[];
isOpen: boolean;
isLoading: boolean;
hasUnread: boolean;
providerModel: string;
setProviderModel: (model: string) => void;
sendMessage: (content: string, providerModel: string) => Promise<void>;
stopGeneration: () => void;
clearMessages: () => void;
setIsOpen: (open: boolean) => void;
}
export const GlobalChatContext = createContext<GlobalChatContextType | undefined>(undefined);
+526
View File
@@ -0,0 +1,526 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useAIProjectId } from './useAIProjectId';
import { useAISettings } from './useAISettings';
import { useCurrentUser } from './useCurrentUser';
import { useAppContext } from './useAppContext';
import { useProjectsManager } from './useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
import type { ProjectsManager } from '@/lib/ProjectsManager';
// Mock the hooks and dependencies
vi.mock('./useAISettings');
vi.mock('./useCurrentUser');
vi.mock('./useAppContext');
vi.mock('./useProjectsManager');
vi.mock('@/lib/ai-client');
vi.mock('@/lib/parseProviderModel');
describe('useAIProjectId', () => {
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseCurrentUser = vi.mocked(useCurrentUser);
const mockUseAppContext = vi.mocked(useAppContext);
const mockUseProjectsManager = vi.mocked(useProjectsManager);
const mockCreateAIClient = vi.mocked(createAIClient);
const mockParseProviderModel = vi.mocked(parseProviderModel);
beforeEach(() => {
vi.clearAllMocks();
// Mock fetch globally
global.fetch = vi.fn();
// Mock useCurrentUser to return undefined user by default
mockUseCurrentUser.mockReturnValue({
user: undefined,
users: [],
});
// Mock useAppContext
const config = {
theme: 'dark' as const,
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://github.com/example/template',
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
mockUseAppContext.mockReturnValue({
config,
defaultConfig: config,
updateConfig: vi.fn(),
});
// Mock useProjectsManager
const mockProjectsManager = {
getProject: vi.fn().mockResolvedValue(null),
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
// Mock parseProviderModel
mockParseProviderModel.mockReturnValue({
provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
model: 'gpt-4',
});
// Mock createAIClient
const mockCompletion = {
choices: [{ message: { content: 'test-project-name' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
});
it('should return not configured when AI settings are not configured', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isConfigured).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('should throw error when trying to generate ID without configuration', async () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
await expect(result.current.generateProjectId('openai/gpt-4', 'test prompt')).rejects.toThrow(
'AI settings not configured'
);
});
it('should throw error when prompt is empty', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
await expect(result.current.generateProjectId('openai/gpt-4', '')).rejects.toThrow(
'Prompt cannot be empty'
);
});
it('should have configured status when providers are available', () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isConfigured).toBe(true);
expect(result.current.isLoading).toBe(false);
});
it('should successfully generate project ID', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('test-project-name');
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
]);
expect(mockCreateAIClient).toHaveBeenCalledWith(
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
undefined,
'https://proxy.example.com/{href}'
);
});
it('should fallback to untitled when project exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI response - returns a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'existing-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValueOnce(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - first call returns project (exists), second returns null (untitled is available)
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'existing-project', name: 'Existing Project', path: '/projects/existing-project', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(2);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'existing-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled-1 when untitled exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to return a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - taken-project exists, untitled exists, untitled-1 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled-1');
expect(mockGetProject).toHaveBeenCalledTimes(3);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates too long name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to return a very long project name (over 50 characters)
const mockCompletion = {
choices: [{ message: { content: 'this-is-a-very-long-project-name-that-exceeds-the-maximum-allowed-length-limit' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled when AI generates invalid name', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to return an invalid project name (doesn't match regex)
const mockCompletion = {
choices: [{ message: { content: 'Invalid Project Name!' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - untitled is available
const mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled');
expect(mockGetProject).toHaveBeenCalledTimes(1);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'untitled');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to return a project name that already exists
const mockCompletion = {
choices: [{ message: { content: 'taken-project' } }]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
// Mock getProject - taken-project exists, untitled exists, untitled-1 exists, untitled-2 is available
const mockGetProject = vi.fn()
.mockResolvedValueOnce({ id: 'taken-project', name: 'Taken Project', path: '/projects/taken-project', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled', name: 'Untitled', path: '/projects/untitled', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'untitled-1', name: 'Untitled 1', path: '/projects/untitled-1', lastModified: new Date() })
.mockResolvedValueOnce(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
const { result } = renderHook(() => useAIProjectId());
const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers');
expect(projectId).toBe('untitled-2');
expect(mockGetProject).toHaveBeenCalledTimes(4);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'taken-project');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'untitled');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'untitled-1');
expect(mockGetProject).toHaveBeenNthCalledWith(4, 'untitled-2');
// Should have called AI only once
expect(mockOpenAI.chat.completions.create).toHaveBeenCalledTimes(1);
});
it('should handle loading state correctly', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: []
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useAIProjectId());
expect(result.current.isLoading).toBe(false);
const promise = result.current.generateProjectId('openai/gpt-4', 'Test prompt');
await waitFor(() => {
expect(result.current.isLoading).toBe(false); // Should be false after completion
});
await promise;
});
});
+96
View File
@@ -0,0 +1,96 @@
import { useState, useCallback } from 'react';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
interface UseAIProjectIdOptions {
onError?: (error: string) => void;
}
export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) {
const [isLoading, setIsLoading] = useState(false);
const { settings, isConfigured } = useAISettings();
const { user } = useCurrentUser();
const { config } = useAppContext();
const projectsManager = useProjectsManager();
const generateProjectId = useCallback(async (providerModel: string, prompt: string): Promise<string> => {
if (!isConfigured) {
throw new Error('AI settings not configured');
}
if (!prompt.trim()) {
throw new Error('Prompt cannot be empty');
}
setIsLoading(true);
try {
// Initialize OpenAI client
const { model, provider } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(provider, user, config.corsProxy);
const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`;
const messages = [
{ role: 'system' as const, content: systemPrompt },
{ role: 'user' as const, content: prompt }
];
// Try once to generate a project name
const completion = await openai.chat.completions.create({
model,
messages,
temperature: 1,
});
const projectId = completion.choices[0]?.message?.content?.trim();
if (!projectId) {
throw new Error('Failed to generate project name');
}
// Validate the generated ID directly (no conversion)
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (projectId.length <= 50 && validIdRegex.test(projectId)) {
// Check if project exists
const existingProject = await projectsManager.getProject(projectId);
if (existingProject === null) {
// Valid and unique project ID
return projectId;
}
}
// If we reach here, either the regex failed or the project already exists
// Fall back to "untitled" with number suffixes
let fallbackId = 'untitled';
let counter = 1;
// Check if base "untitled" exists
let existingProject = await projectsManager.getProject(fallbackId);
// Keep incrementing until we find an available name
while (existingProject !== null) {
fallbackId = `untitled-${counter}`;
existingProject = await projectsManager.getProject(fallbackId);
counter++;
}
return fallbackId;
} catch (error) {
const errorMessage = error instanceof Error ? error.message : 'Failed to generate project ID';
onError?.(errorMessage);
throw error;
} finally {
setIsLoading(false);
}
}, [isConfigured, settings, onError, user, projectsManager, config.corsProxy]);
return {
generateProjectId,
isLoading,
isConfigured
};
}
-43
View File
@@ -1,43 +0,0 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
/**
* Hook to get the user's contact list (kind 3 follow list)
* Returns an array of pubkeys that the user follows
*/
export function useContacts(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'contacts', userPubkey],
queryFn: async (): Promise<string[]> => {
if (!userPubkey) {
return [];
}
// Get the user's contact list (kind 3)
const events = await nostr.query([{
kinds: [3],
authors: [userPubkey],
limit: 1,
}], { signal: AbortSignal.timeout(3000) });
if (events.length === 0) {
return [];
}
// Get the most recent contact list event
const contactList = events.sort((a, b) => b.created_at - a.created_at)[0];
// Extract pubkeys from 'p' tags
const followedPubkeys = contactList.tags
.filter(tag => tag[0] === 'p' && tag[1])
.map(tag => tag[1]);
return followedPubkeys;
},
enabled: !!userPubkey,
staleTime: 60000, // 1 minute
refetchInterval: 300000, // 5 minutes
});
}
-92
View File
@@ -1,92 +0,0 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import type { Repository } from './useUserRepositories';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
/**
* Hook to get repositories from a list of followed users
*/
export function useFollowedRepositories(followedPubkeys: string[] = []) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
queryFn: async (): Promise<Repository[]> => {
if (followedPubkeys.length === 0) {
return [];
}
// Get all repository announcements from followed users
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: followedPubkeys,
limit: 500, // Increased limit to get more repos from follows
}], { signal: AbortSignal.timeout(5000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by author+d-tag to get latest version of each repo
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const key = `${event.pubkey}:${dTag}`;
const existing = repoMap.get(key);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(key, event);
}
}
// Convert to Repository objects
for (const [, event] of repoMap) {
try {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
// Sort by created_at (newest first)
return repositories.sort((a, b) => b.created_at - a.created_at);
},
enabled: followedPubkeys.length > 0,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
-503
View File
@@ -1,503 +0,0 @@
import { describe, it, expect, vi, beforeEach } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { useGenerateProjectInfo } from './useGenerateProjectInfo';
import { useAISettings } from './useAISettings';
import { useCurrentUser } from './useCurrentUser';
import { useAppContext } from './useAppContext';
import { useProjectsManager } from './useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
import type { ProjectsManager } from '@/lib/ProjectsManager';
import type { ProjectTemplate } from '@/contexts/AppContext';
// Mock the hooks and dependencies
vi.mock('./useAISettings');
vi.mock('./useCurrentUser');
vi.mock('./useAppContext');
vi.mock('./useProjectsManager');
vi.mock('@/lib/ai-client');
vi.mock('@/lib/parseProviderModel');
describe('useGenerateProjectInfo', () => {
const mockUseAISettings = vi.mocked(useAISettings);
const mockUseCurrentUser = vi.mocked(useCurrentUser);
const mockUseAppContext = vi.mocked(useAppContext);
const mockUseProjectsManager = vi.mocked(useProjectsManager);
const mockCreateAIClient = vi.mocked(createAIClient);
const mockParseProviderModel = vi.mocked(parseProviderModel);
const defaultTemplates: ProjectTemplate[] = [
{
name: "MKStack",
description: "Build Nostr clients with React.",
url: "https://gitlab.com/soapbox-pub/mkstack.git"
},
{
name: "VanillaJS",
description: "Simple vanilla JavaScript template.",
url: "https://github.com/example/vanilla-template.git"
}
];
let mockGetProject: ReturnType<typeof vi.fn>;
beforeEach(() => {
vi.clearAllMocks();
// Mock fetch globally
global.fetch = vi.fn();
// Mock useCurrentUser to return undefined user by default
mockUseCurrentUser.mockReturnValue({
user: undefined,
users: [],
});
// Mock useAppContext
const config = {
theme: 'dark' as const,
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
templates: defaultTemplates,
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
mockUseAppContext.mockReturnValue({
config,
defaultConfig: config,
updateConfig: vi.fn(),
});
// Mock useProjectsManager
mockGetProject = vi.fn().mockResolvedValue(null);
const mockProjectsManager = {
getProject: mockGetProject,
} as unknown as ProjectsManager;
mockUseProjectsManager.mockReturnValue(mockProjectsManager);
// Mock parseProviderModel
mockParseProviderModel.mockReturnValue({
provider: { id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
model: 'gpt-4',
});
// Mock createAIClient
const mockCompletion = {
choices: [{
message: {
tool_calls: [{
type: 'function' as const,
function: {
name: 'create_project',
arguments: JSON.stringify({
project_name: 'test-project-name',
template_url: 'https://gitlab.com/soapbox-pub/mkstack.git'
})
}
}]
}
}]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
});
it('should return not configured when AI settings are not configured', () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
expect(result.current.isConfigured).toBe(false);
expect(result.current.isLoading).toBe(false);
});
it('should throw error when trying to generate without configuration', async () => {
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels: [], mcpServers: {} },
isConfigured: false,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow(
'AI settings not configured'
);
});
it('should throw error when prompt is empty', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
await expect(result.current.generateProjectInfo('openai/gpt-4', '')).rejects.toThrow(
'Prompt cannot be empty'
);
});
it('should throw error when no templates are configured', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock config with no templates
const config = {
theme: 'dark' as const,
relayMetadata: {
relays: [{ url: 'wss://relay.damus.io', read: true, write: true }],
updatedAt: 0,
},
templates: [],
esmUrl: 'https://esm.sh',
corsProxy: 'https://proxy.example.com/{href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
previewDomain: 'local-shakespeare.dev',
showcaseEnabled: true,
showcaseModerator: 'npub1jvnpg4c6ljadf5t6ry0w9q0rnm4mksde87kglkrc993z46c39axsgq89sc',
ngitServers: ['git.shakespeare.diy', 'relay.ngit.dev'],
fsPathProjects: '/projects',
fsPathConfig: '/config',
fsPathTmp: '/tmp',
fsPathPlugins: '/plugins',
fsPathTemplates: '/templates',
sentryDsn: '',
sentryEnabled: false,
};
mockUseAppContext.mockReturnValue({
config,
defaultConfig: config,
updateConfig: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
await expect(result.current.generateProjectInfo('openai/gpt-4', 'test prompt')).rejects.toThrow(
'No templates configured'
);
});
it('should successfully generate project info with template selection', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A social media app for developers');
expect(projectInfo).toEqual({
projectId: 'test-project-name',
template: {
name: 'MKStack',
description: 'Build Nostr clients with React.',
url: 'https://gitlab.com/soapbox-pub/mkstack.git'
}
});
expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
]);
expect(mockCreateAIClient).toHaveBeenCalledWith(
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' },
undefined,
'https://proxy.example.com/{href}'
);
});
it('should fallback to first template when AI selects invalid template URL', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to return invalid template URL
const mockCompletion = {
choices: [{
message: {
tool_calls: [{
type: 'function' as const,
function: {
name: 'create_project',
arguments: JSON.stringify({
project_name: 'test-project',
template_url: 'https://invalid-url.com/template.git'
})
}
}]
}
}]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(projectInfo.projectId).toBe('untitled');
});
it('should increment AI-generated ID when project already exists', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Reset and override the mock to return project on first call, null on second
mockGetProject.mockReset();
mockGetProject
.mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() })
.mockResolvedValue(null);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.projectId).toBe('test-project-name-1');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(mockGetProject).toHaveBeenCalledTimes(2);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1');
});
it('should increment multiple times when necessary', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Reset and override the mock - base and -1 exist, -2 is available
mockGetProject.mockReset();
mockGetProject
.mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() })
.mockResolvedValueOnce({ id: 'test-project-name-1', name: 'Test Project 1', path: '/projects/test-project-name-1', lastModified: new Date() })
.mockResolvedValue(null);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt');
expect(projectInfo.projectId).toBe('test-project-name-2');
expect(projectInfo.template.url).toBe('https://gitlab.com/soapbox-pub/mkstack.git');
expect(mockGetProject).toHaveBeenCalledTimes(3);
expect(mockGetProject).toHaveBeenNthCalledWith(1, 'test-project-name');
expect(mockGetProject).toHaveBeenNthCalledWith(2, 'test-project-name-1');
expect(mockGetProject).toHaveBeenNthCalledWith(3, 'test-project-name-2');
});
it('should handle loading state correctly', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
const { result } = renderHook(() => useGenerateProjectInfo());
expect(result.current.isLoading).toBe(false);
const promise = result.current.generateProjectInfo('openai/gpt-4', 'Test prompt');
await waitFor(() => {
expect(result.current.isLoading).toBe(false); // Should be false after completion
});
await promise;
});
it('should select second template when AI chooses it', async () => {
mockUseAISettings.mockReturnValue({
settings: {
providers: [
{ id: 'openai', name: 'OpenAI', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }
],
recentlyUsedModels: [],
mcpServers: {}
},
isConfigured: true,
updateSettings: vi.fn(),
setProvider: vi.fn(),
removeProvider: vi.fn(),
setProviders: vi.fn(),
addRecentlyUsedModel: vi.fn(),
setMCPServer: vi.fn(),
removeMCPServer: vi.fn(),
});
// Mock AI to select the second template
const mockCompletion = {
choices: [{
message: {
tool_calls: [{
type: 'function' as const,
function: {
name: 'create_project',
arguments: JSON.stringify({
project_name: 'vanilla-app',
template_url: 'https://github.com/example/vanilla-template.git'
})
}
}]
}
}]
};
const mockOpenAI = {
chat: {
completions: {
create: vi.fn().mockResolvedValue(mockCompletion)
}
}
} as unknown as ReturnType<typeof createAIClient>;
mockCreateAIClient.mockReturnValue(mockOpenAI);
const { result } = renderHook(() => useGenerateProjectInfo());
const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'A simple vanilla JS app');
expect(projectInfo).toEqual({
projectId: 'vanilla-app',
template: {
name: 'VanillaJS',
description: 'Simple vanilla JavaScript template.',
url: 'https://github.com/example/vanilla-template.git'
}
});
});
});
-187
View File
@@ -1,187 +0,0 @@
import { useState, useCallback } from 'react';
import { useAISettings } from '@/hooks/useAISettings';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { createAIClient } from '@/lib/ai-client';
import { parseProviderModel } from '@/lib/parseProviderModel';
import type { ChatCompletionMessageParam, ChatCompletionTool } from 'openai/resources/chat/completions';
interface UseGenerateProjectInfoOptions {
onError?: (error: string) => void;
}
interface ProjectInfo {
projectId: string;
template: {
name: string;
description: string;
url: string;
};
}
export function useGenerateProjectInfo({ onError }: UseGenerateProjectInfoOptions = {}) {
const [isLoading, setIsLoading] = useState(false);
const { settings, isConfigured } = useAISettings();
const { user } = useCurrentUser();
const { config } = useAppContext();
const projectsManager = useProjectsManager();
// Helper function to generate incremented project name
// Note: This assumes the baseId already exists (caller has verified this)
const generateIncrementedId = useCallback(async (baseId: string, template: { url: string; name: string; description: string }, baseExists: boolean = true): Promise<ProjectInfo> => {
// If base doesn't exist, just use it
if (!baseExists) {
const existingProject = await projectsManager.getProject(baseId);
if (existingProject === null) {
return {
projectId: baseId,
template,
};
}
}
// Start incrementing from -1
let counter = 1;
let fallbackId = `${baseId}-${counter}`;
let existingProject = await projectsManager.getProject(fallbackId);
// Keep incrementing until we find an available name
while (existingProject !== null) {
counter++;
fallbackId = `${baseId}-${counter}`;
existingProject = await projectsManager.getProject(fallbackId);
}
return {
projectId: fallbackId,
template,
};
}, [projectsManager]);
const generateProjectInfo = useCallback(async (providerModel: string, prompt: string): Promise<ProjectInfo> => {
if (!isConfigured) {
throw new Error('AI settings not configured');
}
if (!prompt.trim()) {
throw new Error('Prompt cannot be empty');
}
if (config.templates.length === 0) {
throw new Error('No templates configured');
}
setIsLoading(true);
try {
// Initialize OpenAI client
const { model, provider } = parseProviderModel(providerModel, settings.providers);
const openai = createAIClient(provider, user, config.corsProxy);
// Create project creation tool
const createProjectTool: ChatCompletionTool = {
type: 'function',
function: {
name: 'create_project',
description: 'Create a new project by choosing a name and selecting the most appropriate template. You must call this tool to create the project.',
parameters: {
type: 'object',
properties: {
project_name: {
type: 'string',
description: 'A short, unique, and memorable name for the project. Should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens.',
},
template_url: {
type: 'string',
description: `The Git URL of the selected template. Must be one of: ${config.templates.map(t => t.url).join(', ')}`,
enum: config.templates.map(t => t.url),
},
},
required: ['project_name', 'template_url'],
},
},
};
const systemPrompt = `You are a product expert helping users create new projects. Given the user's project description, you must:
1. Generate a short, unique, and memorable name for their product or brand. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.
2. Select the most appropriate template from the available options:
${config.templates.map(t => ` - ${t.name}: ${t.description} (${t.url})`).join('\n')}
You MUST call the create_project tool with your choices.`;
const messages: ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
{ role: 'user', content: prompt }
];
// Call AI with tool
const completion = await openai.chat.completions.create({
model,
messages,
tools: [createProjectTool],
tool_choice: { type: 'function', function: { name: 'create_project' } },
temperature: 1,
});
const toolCall = completion.choices[0]?.message?.tool_calls?.[0];
if (!toolCall || toolCall.type !== 'function' || toolCall.function.name !== 'create_project') {
throw new Error('AI failed to create the project');
}
const args = JSON.parse(toolCall.function.arguments);
const templateUrl = args.template_url as string;
const projectId = args.project_name as string;
// Validate template URL
const selectedTemplate = config.templates.find(t => t.url === templateUrl);
if (!selectedTemplate) {
// Fallback to first template if invalid URL selected
console.warn(`Invalid template URL selected: ${templateUrl}, falling back to first template`);
return await generateIncrementedId('untitled', config.templates[0], false);
}
// Validate the generated project ID
const validIdRegex = /^[a-z0-9]+(-[a-z0-9]+)*$/;
if (projectId && projectId.length <= 50 && validIdRegex.test(projectId)) {
// Check if project exists
const existingProject = await projectsManager.getProject(projectId);
if (existingProject === null) {
// Valid and unique project ID
return {
projectId,
template: selectedTemplate,
};
}
// Project already exists - increment the AI-generated ID (baseExists = true)
return await generateIncrementedId(projectId, selectedTemplate, true);
}
// If we reach here, the regex failed - fall back to "untitled" with number suffixes
return await generateIncrementedId('untitled', selectedTemplate, false);
} catch (error) {
// On any error, fall back to first template with untitled name
console.error('Error generating project info:', error);
if (config.templates.length === 0) {
const errorMessage = 'No templates configured';
onError?.(errorMessage);
throw new Error(errorMessage);
}
return await generateIncrementedId('untitled', config.templates[0], false);
} finally {
setIsLoading(false);
}
}, [isConfigured, settings, onError, user, projectsManager, config.corsProxy, config.templates, generateIncrementedId]);
return {
generateProjectInfo,
isLoading,
isConfigured
};
}
+1 -1
View File
@@ -37,7 +37,7 @@ function createWrapper(corsProxy: string) {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
esmUrl: 'https://esm.test',
corsProxy,
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
-10
View File
@@ -1,10 +0,0 @@
import { useContext } from 'react';
import { GlobalChatContext, type GlobalChatContextType } from '@/contexts/GlobalChatContext';
export function useGlobalChat(): GlobalChatContextType {
const context = useContext(GlobalChatContext);
if (!context) {
throw new Error('useGlobalChat must be used within a GlobalChatProvider');
}
return context;
}
+3 -3
View File
@@ -1,7 +1,7 @@
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import { useFS } from './useFS';
import { useFSPaths } from './useFSPaths';
import { getPlugins, getPluginSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPlugins, getAllSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { useGit } from './useGit';
import { join } from 'path-browserify';
@@ -22,11 +22,11 @@ export function usePlugins() {
},
});
// Query to get all plugin skills (not including project skills)
// Query to get all skills
const skillsQuery = useQuery({
queryKey: ['skills', pluginsPath],
queryFn: async () => {
return await getPluginSkills(fs, pluginsPath);
return await getAllSkills(fs, pluginsPath);
},
});
+1 -15
View File
@@ -31,21 +31,7 @@ export interface VercelProjectConfig {
};
}
export interface CloudflareProjectConfig {
type: 'cloudflare';
data: {
projectName?: string;
};
}
export interface DenoDeployProjectConfig {
type: 'deno';
data: {
projectName?: string;
};
}
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig | CloudflareProjectConfig | DenoDeployProjectConfig;
export type ProjectProviderConfig = ShakespeareProjectConfig | NsiteProjectConfig | NetlifyProjectConfig | VercelProjectConfig;
export interface ProjectDeploySettings {
providers: Record<string, ProjectProviderConfig>;
-96
View File
@@ -1,96 +0,0 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
export interface Repository extends NostrEvent {
repoId: string;
name: string;
description: string;
webUrls: string[];
cloneUrls: string[];
relays: string[];
maintainers: string[];
repoTags: string[];
earliestUniqueCommit?: string;
isPersonalFork: boolean;
}
export function useUserRepositories(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'user-repositories', userPubkey],
queryFn: async (): Promise<Repository[]> => {
if (!userPubkey) {
return [];
}
// Get all repository announcements for this user
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: [userPubkey],
limit: 100,
}], { signal: AbortSignal.timeout(3000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by d-tag (repo-id) to get latest version
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const existing = repoMap.get(dTag);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(dTag, event);
}
}
// Convert to Repository objects
for (const [dTag, event] of repoMap) {
try {
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
return repositories;
},
enabled: !!userPubkey,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
+1 -1
View File
@@ -37,7 +37,7 @@
--input: 220 13% 91%;
--ring: 271 81% 56%;
--radius: 0.75rem;
--radius: 0.375rem;
/* Sidebar colors - Enhanced purple theme */
--sidebar-background: 271 81% 96%;
-46
View File
@@ -312,50 +312,4 @@ export class DotAI {
console.warn(`Failed to write .git/shakespeare/COST file: ${error}`);
}
}
/**
* Read template metadata from .git/shakespeare/template.json file
* @returns Template metadata object or null if not found or invalid
*/
async readTemplate(): Promise<{ name: string; description: string; url: string } | null> {
try {
const templatePath = join(this.workingDir, ".git", "shakespeare", "template.json");
const content = await this.fs.readFile(templatePath, "utf8");
const template = JSON.parse(content);
// Validate that required fields exist
if (template && typeof template.name === 'string' &&
typeof template.description === 'string' &&
typeof template.url === 'string') {
return {
name: template.name,
description: template.description,
url: template.url,
};
}
return null;
} catch {
return null;
}
}
/**
* Write template metadata to .git/shakespeare/template.json file
* @param template Template metadata with name, description, and url
*/
async writeTemplate(template: { name: string; description: string; url: string }): Promise<void> {
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
const templatePath = join(shakespeareDir, "template.json");
try {
// Ensure .git/shakespeare directory exists
await this.fs.mkdir(shakespeareDir, { recursive: true });
// Write the template metadata as formatted JSON
await this.fs.writeFile(templatePath, JSON.stringify(template, null, 2) + "\n");
} catch (error) {
console.warn(`Failed to write .git/shakespeare/template.json file: ${error}`);
}
}
}
+7 -50
View File
@@ -3,7 +3,6 @@ import JSZip from 'jszip';
import { Git } from '@/lib/git';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import { ensurePersistentStorage } from '@/lib/persistentStorage';
import { DotAI } from '@/lib/DotAI';
// Polyfill Buffer for browser
if (typeof window !== 'undefined') {
@@ -107,53 +106,26 @@ export class ProjectsManager {
/**
* Force pull the template repository to match remote, discarding any local changes.
* This ensures the template is always up-to-date with the remote.
*
* Since templates are cloned with depth=1 (shallow), we can't use merge because
* isomorphic-git can't verify the commit history. Instead, we fetch and directly
* checkout the remote branch, which is safe since we always want templates to
* exactly match the remote.
*/
private async forcePullTemplate(templatePath: string): Promise<void> {
// Fetch the latest changes from remote (shallow fetch for efficiency)
// Fetch the latest changes from remote
const fetchResult = await this.git.fetch({
dir: templatePath,
singleBranch: true,
depth: 1,
});
// Get the current branch name (e.g., "refs/heads/main")
const branchRef = fetchResult.defaultBranch;
// Get the current branch name
const branch = fetchResult.defaultBranch;
if (!branchRef) {
if (!branch) {
throw new Error('Could not determine current branch');
}
// Extract just the branch name (e.g., "main" from "refs/heads/main")
const branchName = branchRef.replace(/^refs\/heads\//, '');
// Get the remote ref OID
// The fetch stores it as refs/remotes/origin/{branchName}, not refs/remotes/origin/refs/heads/{branchName}
const remoteRef = `refs/remotes/origin/${branchName}`;
const remoteOid = await this.git.resolveRef({
dir: templatePath,
ref: remoteRef,
});
// Update the local branch ref to point to the remote commit
await this.git.writeRef({
dir: templatePath,
ref: branchRef, // Use the full ref like "refs/heads/main"
value: remoteOid,
force: true,
});
// Directly checkout the remote commit to update working directory
// This bypasses merge entirely and just makes the working directory
// match the remote commit exactly. Safe for templates.
// Using force: true to overwrite any local changes
// Reset hard to the remote branch, discarding all local changes
await this.git.checkout({
dir: templatePath,
ref: remoteOid,
ref: branch,
force: true,
});
}
@@ -225,7 +197,7 @@ export class ProjectsManager {
}
}
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void, templateMetadata?: { name: string; description: string }): Promise<Project> {
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
@@ -258,21 +230,6 @@ export class ProjectsManager {
defaultBranch: 'main',
});
// Save template metadata to .git/shakespeare/template.json if provided
if (templateMetadata) {
try {
const dotAI = new DotAI(this.fs, projectPath);
await dotAI.writeTemplate({
name: templateMetadata.name,
description: templateMetadata.description,
url: templateUrl,
});
} catch (error) {
// Don't fail project creation if template metadata save fails
console.warn('Failed to save template metadata:', error);
}
}
// Add all files to git
const files = await this.getAllFiles(projectPath);
for (const file of files) {
+1 -2
View File
@@ -40,7 +40,7 @@ const testConfig: AppConfig = {
],
updatedAt: 0,
},
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
esmUrl: 'https://esm.shakespeare.diy',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
@@ -64,7 +64,6 @@ describe('SessionManager', () => {
providers: [
{
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com',
apiKey: 'test-key'
}
-11
View File
@@ -266,16 +266,6 @@ export class SessionManager {
// No repository URL available
}
// Get project template metadata if available
let projectTemplate: { name: string; description: string; url: string } | undefined;
try {
const dotai = new DotAI(this.fs, `${config.fsPathProjects}/${projectId}`);
const template = await dotai.readTemplate();
projectTemplate = template || undefined;
} catch {
// Template metadata not available
}
const systemPrompt = await makeSystemPrompt({
cwd: `${config.fsPathProjects}/${projectId}`,
fs: this.fs,
@@ -287,7 +277,6 @@ export class SessionManager {
metadata,
repositoryUrl,
template: config.systemPrompt,
projectTemplate,
});
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
+13 -5
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { AI_PROVIDER_PRESETS } from './aiProviderPresets';
import { AI_PROVIDER_PRESETS, getPresetProvider, getShakespeareProvider } from './aiProviderPresets';
describe('AI Provider Presets', () => {
it('should export preset providers array', () => {
@@ -22,14 +22,22 @@ describe('AI Provider Presets', () => {
});
it('should get preset provider by id', () => {
const openai = AI_PROVIDER_PRESETS.find(p => p.id === 'openai');
const openai = getPresetProvider('openai');
expect(openai).toBeDefined();
expect(openai?.name).toBe('OpenAI');
const nonExistent = AI_PROVIDER_PRESETS.find(p => p.id === 'non-existent');
const nonExistent = getPresetProvider('non-existent');
expect(nonExistent).toBeUndefined();
});
it('should get Shakespeare provider', () => {
const shakespeare = getShakespeareProvider();
expect(shakespeare).toBeDefined();
expect(shakespeare.id).toBe('shakespeare');
expect(shakespeare.name).toBe('Shakespeare AI');
expect(shakespeare.nostr).toBe(true);
});
it('should have valid preset structure', () => {
AI_PROVIDER_PRESETS.forEach(preset => {
expect(preset.id).toBeDefined();
@@ -39,7 +47,7 @@ describe('AI Provider Presets', () => {
expect(preset.baseURL).toBeDefined();
expect(typeof preset.baseURL).toBe('string');
expect(preset.baseURL).toMatch(/^https?:\/\//);
// Optional fields
if (preset.apiKeysURL) {
expect(typeof preset.apiKeysURL).toBe('string');
+15 -1
View File
@@ -89,4 +89,18 @@ export const AI_PROVIDER_PRESETS: PresetProvider[] = [
tosURL: "https://vercel.com/legal/terms",
proxy: true,
},
];
];
// Helper function to get a specific preset by ID
export function getPresetProvider(id: string): PresetProvider | undefined {
return AI_PROVIDER_PRESETS.find(preset => preset.id === id);
}
// Helper function to get the Shakespeare provider preset
export function getShakespeareProvider(): PresetProvider {
const shakespeare = getPresetProvider("shakespeare");
if (!shakespeare) {
throw new Error("Shakespeare provider preset not found");
}
return shakespeare;
}
-10
View File
@@ -15,8 +15,6 @@ export interface RepositoryAnnouncementData {
cloneUrls: string[];
/** Relays for patch submissions */
relays?: string[];
/** Category tags for the repository */
tTags?: string[];
/** Earliest unique commit (root commit) */
earliestCommit?: string;
}
@@ -97,14 +95,6 @@ export function createRepositoryAnnouncementEvent(
}
}
// Add t-tags for categorization (each as a separate tag for relay-level filtering)
if (data.tTags && data.tTags.length > 0) {
const trimmedTags = data.tTags.map(tag => tag.trim().toLowerCase()).filter(tag => tag);
for (const tag of trimmedTags) {
tags.push(['t', tag]);
}
}
// Add earliest unique commit (euc) for repository identification
if (data.earliestCommit?.trim()) {
tags.push(['r', data.earliestCommit.trim(), 'euc']);
+2
View File
@@ -122,6 +122,7 @@ export class GitCheckoutCommand implements GitSubcommand {
await this.git.checkout({
dir: cwd,
ref: branchName,
force: true,
});
return createSuccessResult(`Switched to branch '${branchName}'\n`);
@@ -164,6 +165,7 @@ export class GitCheckoutCommand implements GitSubcommand {
await this.git.checkout({
dir: cwd,
ref: branchName,
force: true,
});
return createSuccessResult(`Switched to a new branch '${branchName}'\n`);
-16
View File
@@ -60,7 +60,6 @@ describe('configUtils', () => {
providers: [
{
id: 'openai',
name: 'OpenAI',
baseURL: 'https://api.openai.com/v1',
apiKey: 'sk-test123',
},
@@ -77,14 +76,6 @@ describe('configUtils', () => {
expect(mockFS.readFile).toHaveBeenCalledWith('/config/ai.json', 'utf8');
expect(result).toEqual({
...sampleAISettings,
providers: [
{
id: 'openai',
baseURL: 'https://api.openai.com/v1',
apiKey: 'sk-test123',
name: 'OpenAI', // Name is now filled in from presets
},
],
mcpServers: {},
});
});
@@ -228,13 +219,6 @@ describe('configUtils', () => {
name: 'Shakespeare',
type: 'shakespeare',
},
{
id: 'provider-4',
name: 'My Cloudflare',
type: 'cloudflare',
apiKey: 'cloudflare-token-789',
accountId: 'account-123',
},
],
};
+3 -44
View File
@@ -1,8 +1,7 @@
import z from 'zod';
import { filteredArray } from '@/lib/schema';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
import type { AIProvider, AISettings, MCPServer } from '@/contexts/AISettingsContext';
import type { GitSettings } from '@/contexts/GitSettingsContext';
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
@@ -30,9 +29,8 @@ function getDeployConfigPath(configPath = '/config'): string {
return `${configPath}/deploy.json`;
}
const aiProviderSchema = z.object({
const aiProviderSchema: z.ZodType<AIProvider> = z.object({
id: z.string(),
name: z.string().optional(),
baseURL: z.string().url(),
apiKey: z.string().optional(),
nostr: z.boolean().optional(),
@@ -106,29 +104,11 @@ const nsiteProviderSchema = baseDeployProviderSchema.extend({
blossomServers: z.array(z.string()),
});
const cloudflareProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('cloudflare'),
apiKey: z.string(),
accountId: z.string(),
baseURL: z.string().optional(),
baseDomain: z.string().optional(),
});
const denoDeployProviderSchema = baseDeployProviderSchema.extend({
type: z.literal('deno'),
apiKey: z.string(),
organizationId: z.string(),
baseURL: z.string().optional(),
baseDomain: z.string().optional(),
});
const deployProviderSchema: z.ZodType<DeployProvider> = z.discriminatedUnion('type', [
shakespeareDeployProviderSchema,
netlifyProviderSchema,
vercelProviderSchema,
nsiteProviderSchema,
cloudflareProviderSchema,
denoDeployProviderSchema,
]);
const deploySettingsSchema = z.object({
@@ -165,30 +145,9 @@ export async function readAISettings(fs: JSRuntimeFS, configPath = '/config'): P
const content = await fs.readFile(aiConfigPath, 'utf8');
const data = JSON.parse(content);
const parsed = aiSettingsSchema.parse(data);
// Ensure mcpServers exists even if not in parsed data
return {
...parsed,
providers: parsed.providers.map((provider) => {
let name = provider.name;
// Fill in name from presets if missing
if (typeof name !== 'string') {
const presetProvider = AI_PROVIDER_PRESETS.find(preset => preset.id === provider.id);
if (presetProvider) {
name = presetProvider.name;
}
}
// Fallback to id if name is still missing
if (typeof name !== 'string') {
name = provider.id;
}
return {
...provider,
name,
}
}),
mcpServers: parsed.mcpServers || {},
};
} catch (error) {
-406
View File
@@ -1,406 +0,0 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, CloudflareDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface AssetManifest {
[path: string]: { hash: string; size: number };
}
interface InitializeAssetsResponse {
buckets: string[][];
jwt: string;
}
interface UploadResponse {
jwt?: string;
}
interface WorkerScript {
id: string;
etag: string;
handlers: string[];
modified_on: string;
created_on: string;
has_assets: boolean;
}
interface FileInfo {
hash: string;
content: Uint8Array;
size: number;
contentType: string;
}
/**
* Cloudflare Workers Deploy Adapter
* Uses Cloudflare Workers API with static assets support
*
* Implements the Workers Assets upload workflow:
* 1. Build asset manifest with file hashes
* 2. Initialize upload session to get buckets of files to upload
* 3. Upload files in buckets using FormData with base64 content
* 4. Deploy worker with assets JWT
*/
export class CloudflareAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private accountId: string;
private baseURL: string;
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: CloudflareDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.accountId = config.accountId;
this.baseURL = config.baseURL || 'https://api.cloudflare.com/client/v4';
this.baseDomain = config.baseDomain || 'workers.dev';
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
const scriptName = this.projectName || projectId;
// Step 1: Collect all files and build manifest
const files = new Map<string, FileInfo>();
await this.collectFiles(distPath, '', files);
const manifest: AssetManifest = {};
for (const [filePath, fileInfo] of files) {
// Normalize path with leading slash
const normalizedPath = '/' + filePath.replace(/\\/g, '/');
manifest[normalizedPath] = {
hash: fileInfo.hash,
size: fileInfo.size,
};
}
// Step 2: Initialize upload session
const initResponse = await this.initializeUploadSession(scriptName, manifest);
// Step 3: Upload files in buckets (in parallel for speed)
let completionJwt = initResponse.jwt;
if (initResponse.buckets.flat().length > 0) {
// Create lookup from hash to file info
const hashToFile = new Map<string, { path: string; info: FileInfo }>();
for (const [filePath, fileInfo] of files) {
hashToFile.set(fileInfo.hash, { path: filePath, info: fileInfo });
}
// Upload all buckets in parallel
const uploadResults = await Promise.all(
initResponse.buckets.map((bucket) =>
this.uploadBucket(initResponse.jwt, bucket, hashToFile)
)
);
// Get the completion JWT from the last result that has one
const lastJwtResult = [...uploadResults].reverse().find((r) => r.jwt);
if (lastJwtResult?.jwt) {
completionJwt = lastJwtResult.jwt;
}
}
// Step 4: Deploy the worker with assets
const deployment = await this.deployWorker(scriptName, completionJwt);
// Step 5: Enable the workers.dev subdomain for this script
await this.enableWorkersDevSubdomain(scriptName);
// Step 6: Get the account's workers subdomain
const subdomain = await this.getWorkersSubdomain();
// Construct the URL using the configurable base domain
const workerUrl = `https://${scriptName}.${subdomain}.${this.baseDomain}`;
return {
url: workerUrl,
metadata: {
scriptId: deployment.id,
scriptName: scriptName,
provider: 'cloudflare-workers',
hasAssets: deployment.has_assets,
modifiedOn: deployment.modified_on,
},
};
}
private async getWorkersSubdomain(): Promise<string> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
},
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to get workers subdomain: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result.subdomain;
}
private async enableWorkersDevSubdomain(scriptName: string): Promise<void> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/subdomain`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
enabled: true,
previews_enabled: true,
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to enable workers.dev subdomain: ${response.status} ${response.statusText}. ${errorText}`);
}
}
private async initializeUploadSession(
scriptName: string,
manifest: AssetManifest
): Promise<InitializeAssetsResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}/assets-upload-session`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({ manifest }),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to initialize upload session: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result;
}
private async uploadBucket(
jwt: string,
bucket: string[],
hashToFile: Map<string, { path: string; info: FileInfo }>
): Promise<UploadResponse> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/assets/upload?base64=true`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const formData = new FormData();
for (const fileHash of bucket) {
const fileData = hashToFile.get(fileHash);
if (!fileData) {
throw new Error(`File with hash ${fileHash} not found in manifest`);
}
// Convert content to base64
const base64Content = this.uint8ArrayToBase64(fileData.info.content);
// Use content type or "application/null" to signal no content-type header
const contentType = fileData.info.contentType || 'application/null';
// Create a File/Blob with the base64 content
const blob = new Blob([base64Content], { type: contentType });
formData.append(fileHash, blob, fileHash);
}
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${jwt}`,
},
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to upload assets: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result || {};
}
private async deployWorker(scriptName: string, assetsJwt: string): Promise<WorkerScript> {
const url = `${this.baseURL}/accounts/${this.accountId}/workers/scripts/${scriptName}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
// Create a minimal worker script that serves static assets
// This is an assets-only worker - Cloudflare will automatically serve the uploaded assets
const workerScript = `
export default {
async fetch(request, env) {
// This worker only serves static assets
// The assets are automatically served by Cloudflare's asset handler
return new Response('Not Found', { status: 404 });
}
};
`;
const formData = new FormData();
// Add the worker script as the main module
const scriptBlob = new Blob([workerScript], { type: 'application/javascript+module' });
formData.append('worker.js', scriptBlob, 'worker.js');
// Add metadata with assets configuration
const metadata = {
main_module: 'worker.js',
compatibility_date: new Date().toISOString().split('T')[0],
assets: {
jwt: assetsJwt,
config: {
html_handling: 'auto-trailing-slash',
not_found_handling: 'single-page-application',
},
},
};
formData.append('metadata', new Blob([JSON.stringify(metadata)], { type: 'application/json' }));
const response = await fetch(targetUrl, {
method: 'PUT',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
},
body: formData,
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to deploy worker: ${response.status} ${response.statusText}. ${errorText}`);
}
const data = await response.json();
return data.result;
}
private async collectFiles(
dirPath: string,
relativePath: string,
files: Map<string, FileInfo>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFiles(fullPath, entryRelativePath, files);
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
// Convert to Uint8Array
let content: Uint8Array;
if (typeof fileContent === 'string') {
content = new TextEncoder().encode(fileContent);
} else {
content = fileContent;
}
// Calculate hash (same algorithm as Wrangler uses)
const hash = await this.calculateHash(content);
// Determine content type
const contentType = this.getContentType(entry.name);
files.set(entryRelativePath, {
hash,
content,
size: content.length,
contentType,
});
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
private async calculateHash(content: Uint8Array): Promise<string> {
// Use xxHash algorithm like Wrangler does, but fall back to SHA-256 for browser compatibility
const hashBuffer = await crypto.subtle.digest('SHA-256', content);
const hashArray = Array.from(new Uint8Array(hashBuffer));
// Take first 16 bytes (32 hex chars) to match Wrangler's hash length
const hashHex = hashArray.slice(0, 16).map(b => b.toString(16).padStart(2, '0')).join('');
return hashHex;
}
private uint8ArrayToBase64(bytes: Uint8Array): string {
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
private getContentType(filename: string): string {
const ext = filename.split('.').pop()?.toLowerCase() || '';
const mimeTypes: Record<string, string> = {
'html': 'text/html',
'htm': 'text/html',
'css': 'text/css',
'js': 'application/javascript',
'mjs': 'application/javascript',
'json': 'application/json',
'png': 'image/png',
'jpg': 'image/jpeg',
'jpeg': 'image/jpeg',
'gif': 'image/gif',
'svg': 'image/svg+xml',
'ico': 'image/x-icon',
'webp': 'image/webp',
'avif': 'image/avif',
'woff': 'font/woff',
'woff2': 'font/woff2',
'ttf': 'font/ttf',
'eot': 'application/vnd.ms-fontobject',
'otf': 'font/otf',
'txt': 'text/plain',
'xml': 'application/xml',
'pdf': 'application/pdf',
'zip': 'application/zip',
'mp4': 'video/mp4',
'webm': 'video/webm',
'mp3': 'audio/mpeg',
'wav': 'audio/wav',
'ogg': 'audio/ogg',
'wasm': 'application/wasm',
};
return mimeTypes[ext] || 'application/octet-stream';
}
}
-287
View File
@@ -1,287 +0,0 @@
import type { JSRuntimeFS } from '../JSRuntime';
import type { DeployAdapter, DeployOptions, DeployResult, DenoDeployConfig } from './types';
import { proxyUrl } from '../proxyUrl';
interface Project {
id: string;
name: string;
createdAt: string;
updatedAt: string;
}
interface Deployment {
id: string;
projectId: string;
status: string;
domains: string[];
createdAt: string;
updatedAt: string;
}
/**
* Deno Deploy Adapter
* Uses Deno Deploy API to deploy static sites
*
* Implements the Deno Deploy workflow:
* 1. Create or find existing project
* 2. Build asset manifest with file contents
* 3. Create deployment with assets
* 4. Attach domain to deployment
*/
export class DenoDeployAdapter implements DeployAdapter {
private fs: JSRuntimeFS;
private apiKey: string;
private organizationId: string;
private baseURL: string;
private baseDomain: string;
private projectName?: string;
private corsProxy?: string;
constructor(config: DenoDeployConfig) {
this.fs = config.fs;
this.apiKey = config.apiKey;
this.organizationId = config.organizationId;
this.baseURL = config.baseURL || 'https://api.deno.com/v1';
this.baseDomain = config.baseDomain || 'deno.dev';
this.projectName = config.projectName;
this.corsProxy = config.corsProxy;
}
async deploy(options: DeployOptions): Promise<DeployResult> {
const { projectId, projectPath } = options;
// Check if dist directory exists and contains index.html
const distPath = `${projectPath}/dist`;
try {
await this.fs.readFile(`${distPath}/index.html`, 'utf8');
} catch {
throw new Error('No index.html found in dist directory. Please build the project first.');
}
const projectName = this.projectName || projectId;
// Step 1: Get or create project
const project = await this.getOrCreateProject(projectName);
// Step 2: Collect all files and build assets
const assets: Record<string, { kind: string; content: string; encoding: string }> = {};
await this.collectFiles(distPath, '', assets);
// Step 3: Create deployment with assets and domain
const domain = `${project.name}.${this.baseDomain}`;
const deployment = await this.createDeployment(project.id, assets, domain);
return {
url: `https://${domain}`,
metadata: {
deploymentId: deployment.id,
projectId: project.id,
projectName: project.name,
provider: 'deno-deploy',
status: deployment.status,
},
};
}
private async getOrCreateProject(projectName: string): Promise<Project> {
// First, try to find existing project
const existingProject = await this.findProject(projectName);
if (existingProject) {
return existingProject;
}
// Create new project
return this.createProject(projectName);
}
private async findProject(projectName: string): Promise<Project | null> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects?q=${encodeURIComponent(projectName)}`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'GET',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
},
});
if (!response.ok) {
// If we can't list projects, just return null and try to create
return null;
}
const projects: Project[] = await response.json();
return projects.find(p => p.name === projectName) || null;
}
private async createProject(projectName: string): Promise<Project> {
const url = `${this.baseURL}/organizations/${this.organizationId}/projects`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
name: projectName,
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create project: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async createDeployment(
projectId: string,
assets: Record<string, { kind: string; content: string; encoding: string }>,
domain: string
): Promise<Deployment> {
const url = `${this.baseURL}/projects/${projectId}/deployments`;
const targetUrl = this.corsProxy ? proxyUrl(this.corsProxy, url) : url;
// Create a minimal server script that serves static files
// For static sites, we use a simple file server entry point
const entryPointUrl = 'main.ts';
// Add the entry point script that serves static files
const serverScript = `
import { serveDir } from "jsr:@std/http/file-server";
Deno.serve((req) => {
return serveDir(req, {
fsRoot: ".",
showIndex: true,
enableCors: true,
});
});
`;
// Add the server script to assets
assets['main.ts'] = {
kind: 'file',
content: serverScript,
encoding: 'utf-8',
};
const response = await fetch(targetUrl, {
method: 'POST',
headers: {
'Authorization': `Bearer ${this.apiKey}`,
'Content-Type': 'application/json',
},
body: JSON.stringify({
entryPointUrl,
assets,
importMapUrl: null,
lockFileUrl: null,
compilerOptions: null,
envVars: {},
// Attach domain during deployment creation instead of separately
domains: [domain],
}),
});
if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error');
throw new Error(`Failed to create deployment: ${response.status} ${response.statusText}. ${errorText}`);
}
return response.json();
}
private async collectFiles(
dirPath: string,
relativePath: string,
assets: Record<string, { kind: string; content: string; encoding: string }>
): Promise<void> {
try {
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
for (const entry of entries) {
const fullPath = `${dirPath}/${entry.name}`;
const entryRelativePath = relativePath ? `${relativePath}/${entry.name}` : entry.name;
if (entry.isDirectory()) {
await this.collectFiles(fullPath, entryRelativePath, assets);
} else if (entry.isFile()) {
try {
const fileContent = await this.fs.readFile(fullPath);
// Determine if file is text or binary based on extension
const isText = this.isTextFile(entry.name);
let content: string;
let encoding: 'utf-8' | 'base64';
if (isText) {
if (typeof fileContent === 'string') {
content = fileContent;
} else {
content = new TextDecoder().decode(fileContent);
}
encoding = 'utf-8';
} else {
// Binary file - encode as base64
let bytes: Uint8Array;
if (typeof fileContent === 'string') {
bytes = new TextEncoder().encode(fileContent);
} else {
bytes = fileContent;
}
content = this.uint8ArrayToBase64(bytes);
encoding = 'base64';
}
assets[entryRelativePath] = {
kind: 'file',
content,
encoding,
};
} catch (error) {
console.warn(`Failed to read file ${fullPath}:`, error);
}
}
}
} catch (error) {
console.warn(`Failed to read directory ${dirPath}:`, error);
}
}
private isTextFile(filename: string): boolean {
const textExtensions = [
'html', 'htm', 'css', 'js', 'mjs', 'cjs', 'ts', 'tsx', 'jsx',
'json', 'xml', 'svg', 'txt', 'md', 'yaml', 'yml', 'toml',
'sh', 'bash', 'zsh', 'fish', 'bat', 'cmd', 'ps1',
'py', 'rb', 'php', 'java', 'c', 'cpp', 'h', 'hpp',
'rs', 'go', 'swift', 'kt', 'scala', 'clj', 'ex', 'exs',
'vue', 'svelte', 'astro', 'njk', 'ejs', 'pug', 'hbs',
'graphql', 'gql', 'sql', 'csv', 'tsv', 'log', 'ini', 'cfg',
'env', 'gitignore', 'dockerignore', 'editorconfig',
'prettierrc', 'eslintrc', 'babelrc', 'npmrc',
'map', // source maps
];
const ext = filename.split('.').pop()?.toLowerCase() || '';
// Also check if filename itself is a known text file
const textFilenames = [
'dockerfile', 'makefile', 'gemfile', 'rakefile', 'procfile',
'license', 'readme', 'changelog', 'authors', 'contributors',
];
return textExtensions.includes(ext) || textFilenames.includes(filename.toLowerCase());
}
private uint8ArrayToBase64(bytes: Uint8Array): string {
let binary = '';
for (let i = 0; i < bytes.length; i++) {
binary += String.fromCharCode(bytes[i]);
}
return btoa(binary);
}
}
-2
View File
@@ -3,5 +3,3 @@ export * from './ShakespeareAdapter';
export * from './NetlifyAdapter';
export * from './VercelAdapter';
export * from './NsiteAdapter';
export * from './CloudflareAdapter';
export * from './DenoDeployAdapter';
-20
View File
@@ -54,23 +54,3 @@ export interface NsiteDeployConfig {
relayUrls: string[];
blossomServers: string[];
}
export interface CloudflareDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
accountId: string;
baseURL?: string;
baseDomain?: string;
projectName?: string;
corsProxy?: string;
}
export interface DenoDeployConfig {
fs: JSRuntimeFS;
apiKey: string;
organizationId: string;
baseURL?: string;
baseDomain?: string;
projectName?: string;
corsProxy?: string;
}
+1
View File
@@ -1244,6 +1244,7 @@ export class Git {
fs: this.fs,
dir: options.dir,
ref: expectedBranch,
force: true,
});
} catch (checkoutError) {
console.warn(`Failed to checkout branch ${expectedBranch}:`, checkoutError);
-96
View File
@@ -1,96 +0,0 @@
/**
* Default system prompt for global chat.
* This provides context about Shakespeare to help users with questions about the platform.
*/
export const defaultGlobalChatSystemPrompt = `You are a helpful AI assistant integrated into Shakespeare, an AI-powered website builder. You're here to have a friendly conversation and help answer questions on any topic.
Keep your responses concise but informative. Be friendly and conversational.
# Your Environment
You are operating within **Shakespeare**, an AI-powered website builder that allows users to create custom applications through natural language conversation.
Users can add or remove templates in Settings > AI.
## What Shakespeare Is
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant. The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**Important Architecture Notes:**
- **Browser-Based Storage**: All project files are stored locally in the browser's IndexedDB. If users clear browser data, they may lose their projects.
- **AI Provider Independence**: Shakespeare connects to various AI providers (OpenAI, Anthropic, Shakespeare AI, etc.). Each provider has its own pricing and authentication.
- **Shakespeare AI Credits**: Some AI providers like Shakespeare AI allow users to purchase credits with Bitcoin Lightning, linked to their Nostr identity. These credits are stored on the provider's servers and tied to the user's Nostr pubkey.
- **Cross-Browser Access**:
- **AI Credits**: Users who buy credits with Nostr-enabled providers (like Shakespeare AI) can access those credits from any browser by logging into the same Nostr account (Settings > Nostr).
- **Project Files**: Files are browser-specific. Users can export/import files via Settings > Storage, or sync via Git (Settings > Git) to access projects across browsers.
- **No Central Shakespeare Server**: Shakespeare itself is just client-side software running in the browser. It doesn't store user data or AI credits centrally.
## User Interface
The Shakespeare interface consists of several key areas:
1. **Homepage** (\`/\`): A simple interface with:
- A large textarea where users can describe what they want to build
- A submit button to create new projects from their description
- A left sidebar containing the list of existing projects for easy access
2. **Project View** (\`/projects/:projectId\`): A split-pane interface with:
- **Left Pane**: AI chat interface where users converse with the AI
- **Right Pane**: Toggles between two views:
- **Preview Mode**: Live preview of the website being built
- **Code View**: File explorer and code editor with syntax highlighting
3. **Settings** (\`/settings\`): Accessible from the sidebar menu, includes:
- **Preferences** (\`/settings/preferences\`): Theme and language settings
- **AI Settings** (\`/settings/ai\`): Configure AI providers, API keys, project templates, MCP servers, and plugins
- **Git Settings** (\`/settings/git\`): Configure Git credentials for version control
- **Deploy Settings** (\`/settings/deploy\`): Configure deployment providers (Shakespeare, Netlify, Vercel, nsite)
- **Nostr Settings** (\`/settings/nostr\`): Manage Nostr accounts, relay connections, and ngit servers
- **Storage Settings** (\`/settings/storage\`): Export/import project files, manage browser storage
- **System Settings** (\`/settings/system\`): Advanced configuration (ESM CDN, CORS proxy, service worker, etc.)
- **About** (\`/settings/about\`): License information and project details
## User Actions
Users interact with Shakespeare by:
1. **Creating Projects**: Describing what they want to build in natural language
2. **Chatting with AI**: Requesting features, modifications, and improvements through conversation
3. **Manual Code Editing**: Switching to code view to make direct file edits when desired
4. **Previewing Changes**: Viewing their website in real-time as it's being built
5. **Project Management**: Organizing and accessing multiple projects from the homepage
6. **Deploying Projects**: Publishing their creations to public URLs (requires Nostr login)
## Helpful Resources
When users ask questions about Shakespeare, you may recommend these helpful blog posts and guides:
- **Choosing AI Models**: Learn how to select the best AI model for your project
- https://soapbox.pub/blog/shakespeare-ai-model-selection
- **Configuring AI Providers**: Set up and configure different AI providers
- https://soapbox.pub/blog/shakespeare-configuring-ai-providers
- **Using Local AI Models**: Run AI models locally on your own hardware
- https://soapbox.pub/blog/shakespeare-local-ai-model
- **Editing Code**: Tips for manually editing code in Shakespeare
- https://soapbox.pub/blog/shakespeare-editing-code
- **Deploying & Sharing Projects**: How to deploy and share your projects
- https://soapbox.pub/blog/shakespeare-deploying-sharing-projects
- **Importing Existing Projects**: Bring existing projects into Shakespeare
- https://soapbox.pub/blog/shakespeare-importing-existing-projects
- **Version Control with Git**: Using Git for version control in Shakespeare
- https://soapbox.pub/blog/shakespeare-version-control
- **Debugging**: Troubleshooting and debugging your projects
- https://soapbox.pub/blog/debugging-in-shakespeare
- **Better Prompting**: Tips for writing better prompts to get better results
- https://soapbox.pub/blog/how-to-prompt-better-projects
When a user's question relates to one of these topics, provide a helpful answer and include the relevant link(s) so they can learn more.`;
-7
View File
@@ -6,25 +6,21 @@ describe('parseProviderModel', () => {
const mockProviders: AIProvider[] = [
{
id: 'openai',
name: 'OpenAI',
baseURL: 'https://api.openai.com/v1',
apiKey: 'sk-test-key',
},
{
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'sk-or-test-key',
},
{
id: 'anthropic',
name: 'Anthropic',
baseURL: 'https://api.anthropic.com',
apiKey: 'sk-ant-test-key',
},
{
id: 'unconfigured',
name: 'Unconfigured',
baseURL: 'https://example.com/v1',
apiKey: '',
},
@@ -36,7 +32,6 @@ describe('parseProviderModel', () => {
expect(result.model).toBe('gpt-4o');
expect(result.provider).toEqual({
id: 'openai',
name: mockProviders[0].name,
baseURL: mockProviders[0].baseURL,
apiKey: mockProviders[0].apiKey,
nostr: mockProviders[0].nostr,
@@ -49,7 +44,6 @@ describe('parseProviderModel', () => {
expect(result.model).toBe('anthropic/claude-sonnet-4');
expect(result.provider).toEqual({
id: 'openrouter',
name: mockProviders[1].name,
baseURL: mockProviders[1].baseURL,
apiKey: mockProviders[1].apiKey,
nostr: mockProviders[1].nostr,
@@ -62,7 +56,6 @@ describe('parseProviderModel', () => {
expect(result.model).toBe('meta/llama-3.1-405b-instruct');
expect(result.provider).toEqual({
id: 'openrouter',
name: mockProviders[1].name,
baseURL: mockProviders[1].baseURL,
apiKey: mockProviders[1].apiKey,
nostr: mockProviders[1].nostr,
+28 -234
View File
@@ -3,7 +3,6 @@ import type { JSRuntimeFS } from './JSRuntime';
import {
getPlugins,
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
@@ -201,12 +200,14 @@ describe('plugins', () => {
});
describe('getPluginSkills', () => {
it('should return empty array when no plugins exist', async () => {
const skills = await getPluginSkills(fs, '/plugins');
it('should return empty array when plugin has no skills', async () => {
await fs.mkdir('/plugins/plugin1', { recursive: true });
const skills = await getPluginSkills(fs, '/plugins', 'plugin1');
expect(skills).toEqual([]);
});
it('should return skills from all plugins', async () => {
it('should return skills with valid SKILL.md files', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
@@ -221,7 +222,7 @@ description: A test skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins');
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
@@ -244,7 +245,7 @@ description: Has uppercase letters
Content`
);
const skills = await getPluginSkills(fs, '/plugins');
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
expect(skills).toEqual([]);
});
@@ -260,131 +261,48 @@ name: incomplete
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins');
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
expect(skills).toEqual([]);
});
});
describe('getAllSkills', () => {
it('should combine plugin and project skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
it('should return skills from all plugins', async () => {
// Plugin 1
const skill1Path = '/plugins/plugin1/skills/skill1';
await fs.mkdir(skill1Path, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`${skill1Path}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
name: skill1
description: First skill
---
Content`
);
// Create project skill
await fs.mkdir(projectSkillPath, { recursive: true });
// Plugin 2
const skill2Path = '/plugins/plugin2/skills/skill2';
await fs.mkdir(skill2Path, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`${skill2Path}/SKILL.md`,
`---
name: project-skill
description: A project skill
name: skill2
description: Second skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
const skills = await getAllSkills(fs, '/plugins');
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('plugin-skill');
expect(skills.map((s) => s.name)).toContain('project-skill');
});
it('should give precedence to project skills over plugin skills with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: same-name
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: same-name
description: Project version
---
Project content`
);
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('same-name');
expect(skills[0].description).toBe('Project version');
expect(skills[0].plugin).toBe('project');
});
it('should return only plugin skills when project has no skills', async () => {
const pluginPath = '/plugins/testplugin/skills/pluginskill';
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: plugin-skill
description: A plugin skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins', '/projects/emptyproject');
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('plugin-skill');
expect(skills[0].plugin).toBe('testplugin');
});
it('should return only project skills when there are no plugins', async () => {
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/empty-plugins', projectPath);
expect(skills).toHaveLength(1);
expect(skills[0].name).toBe('project-skill');
expect(skills[0].plugin).toBe('project');
expect(skills.map((s) => s.name)).toContain('skill1');
expect(skills.map((s) => s.name)).toContain('skill2');
});
});
describe('findSkill', () => {
it('should find a plugin skill by name', async () => {
it('should find a skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
@@ -397,76 +315,17 @@ description: Find this skill
Content`
);
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'findme');
const skill = await findSkill(fs, '/plugins', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
expect(skill?.plugin).toBe('testplugin');
});
it('should find a project skill by name', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/projectskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: projectskill
description: A project skill
---
Content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'projectskill');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('projectskill');
expect(skill?.plugin).toBe('project');
});
it('should prefer project skill over plugin skill with same name', async () => {
const pluginPath = '/plugins/testplugin/skills/samename';
const projectPath = '/projects/myproject';
const projectSkillPath = `${projectPath}/skills/samename`;
// Create plugin skill
await fs.mkdir(pluginPath, { recursive: true });
await fs.writeFile(
`${pluginPath}/SKILL.md`,
`---
name: samename
description: Plugin version
---
Plugin content`
);
// Create project skill with same name
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${projectSkillPath}/SKILL.md`,
`---
name: samename
description: Project version
---
Project content`
);
const skill = await findSkill(fs, '/plugins', projectPath, 'samename');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('samename');
expect(skill?.description).toBe('Project version');
expect(skill?.plugin).toBe('project');
});
it('should return null when skill not found in either plugins or project', async () => {
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'nonexistent');
it('should return null when skill not found', async () => {
const skill = await findSkill(fs, '/plugins', 'nonexistent');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
@@ -493,69 +352,4 @@ This is the skill content.`;
expect(readContent).toBe(content);
});
});
describe('getProjectSkills', () => {
it('should get skills from project skills directory', async () => {
const projectPath = '/projects/myproject';
const skillPath1 = `${projectPath}/skills/skill1`;
const skillPath2 = `${projectPath}/skills/skill2`;
await fs.mkdir(skillPath1, { recursive: true });
await fs.mkdir(skillPath2, { recursive: true });
await fs.writeFile(
`${skillPath1}/SKILL.md`,
`---
name: project-skill-1
description: First project skill
---
Content`
);
await fs.writeFile(
`${skillPath2}/SKILL.md`,
`---
name: project-skill-2
description: Second project skill
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toHaveLength(2);
expect(skills[0].name).toBe('project-skill-1');
expect(skills[0].plugin).toBe('project');
expect(skills[1].name).toBe('project-skill-2');
expect(skills[1].plugin).toBe('project');
});
it('should return empty array when project has no skills directory', async () => {
const skills = await getProjectSkills(fs, '/projects/emptyproject');
expect(skills).toEqual([]);
});
it('should skip skills with invalid names', async () => {
const projectPath = '/projects/myproject';
const skillPath = `${projectPath}/skills/badskill`;
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
`${skillPath}/SKILL.md`,
`---
name: Invalid_Skill_Name
description: This has uppercase and underscores
---
Content`
);
const skills = await getProjectSkills(fs, projectPath);
expect(skills).toEqual([]);
});
});
});
+10 -60
View File
@@ -56,25 +56,15 @@ export async function getPlugins(fs: JSRuntimeFS, pluginsPath: string): Promise<
}
/**
* Get all skills from a single plugin
* Get all skills from a plugin
*/
function getSkillsFromPlugin(
export async function getPluginSkills(
fs: JSRuntimeFS,
pluginsPath: string,
pluginName: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(pluginsPath, pluginName, 'skills'), pluginName);
}
/**
* Get skills from a directory with a given plugin/source name
*/
async function getSkillsFromDirectory(
fs: JSRuntimeFS,
skillsDir: string,
sourceName: string
): Promise<Skill[]> {
const skills: Skill[] = [];
const skillsDir = join(pluginsPath, pluginName, 'skills');
try {
const skillDirs = await fs.readdir(skillsDir);
@@ -109,7 +99,7 @@ async function getSkillsFromDirectory(
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: sourceName,
plugin: pluginName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
@@ -117,7 +107,7 @@ async function getSkillsFromDirectory(
}
}
} catch {
// Skills directory doesn't exist
// Skills directory doesn't exist for this plugin
return [];
}
@@ -125,24 +115,14 @@ async function getSkillsFromDirectory(
}
/**
* Get all skills from a project's skills directory
* Get all skills from all plugins
*/
export async function getProjectSkills(
fs: JSRuntimeFS,
projectPath: string
): Promise<Skill[]> {
return getSkillsFromDirectory(fs, join(projectPath, 'skills'), 'project');
}
/**
* Get all skills from all plugins (without project skills)
*/
export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
export async function getAllSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
const skills = await getPluginSkills(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
@@ -150,44 +130,14 @@ export async function getPluginSkills(fs: JSRuntimeFS, pluginsPath: string): Pro
}
/**
* Get all skills from both plugins and project, with project skills taking precedence
*/
export async function getAllSkills(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string
): Promise<Skill[]> {
// Get skills from both sources
const pluginSkills = await getPluginSkills(fs, pluginsPath);
const projectSkills = await getProjectSkills(fs, projectPath);
// Create a map to handle name collisions, with project skills taking precedence
const skillsMap = new Map<string, Skill>();
// Add plugin skills first
for (const skill of pluginSkills) {
skillsMap.set(skill.name, skill);
}
// Add project skills, overwriting any plugin skills with the same name
for (const skill of projectSkills) {
skillsMap.set(skill.name, skill);
}
// Return all skills as an array
return Array.from(skillsMap.values());
}
/**
* Find a skill by name across both plugins and project, with project skills taking precedence
* Find a skill by name across all plugins
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath, projectPath);
const skills = await getAllSkills(fs, pluginsPath);
return skills.find(skill => skill.name === skillName) || null;
}
+55 -70
View File
@@ -2,87 +2,72 @@ import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } fro
export interface SettingsItem {
id: string;
icon: React.ComponentType<{ className?: string }>;
title: string;
description: string;
icon: React.ComponentType<{ className?: string }>;
href: string;
}
export interface SettingsCategory {
id: string;
title: string;
items: SettingsItem[];
}
/**
* Get the categorized list of settings items with translations
* Get the list of settings items with translations
* @param t - Translation function from useTranslation hook
* @returns Array of settings categories with translated items
* @returns Array of settings items
*/
export const getSettingsCategories = (t: (key: string) => string): SettingsCategory[] => [
export const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
{
id: 'general',
title: t('general'),
items: [
{
id: 'preferences',
icon: Settings2,
title: t('preferences'),
href: '/settings/preferences',
},
],
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
},
{
id: 'integrations',
title: t('integrations'),
items: [
{
id: 'ai',
icon: Bot,
title: t('aiSettings'),
href: '/settings/ai',
},
{
id: 'git',
icon: GitBranch,
title: t('gitSettings'),
href: '/settings/git',
},
{
id: 'nostr',
icon: Wifi,
title: t('nostrSettings'),
href: '/settings/nostr',
},
{
id: 'deploy',
icon: Rocket,
title: t('deploySettings'),
href: '/settings/deploy',
},
],
id: 'ai',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
icon: Bot,
href: '/settings/ai',
},
{
id: 'advanced',
title: t('advanced'),
items: [
{
id: 'storage',
icon: Database,
title: t('storageSettings'),
href: '/settings/storage',
},
{
id: 'system',
icon: Settings,
title: t('systemSettings'),
href: '/settings/system',
},
{
id: 'about',
icon: Info,
title: t('aboutShakespeare'),
href: '/settings/about',
},
],
id: 'git',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
icon: GitBranch,
href: '/settings/git',
},
{
id: 'deploy',
title: t('deploySettings'),
description: t('deploySettingsDescription'),
icon: Rocket,
href: '/settings/deploy',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'storage',
title: t('storageSettings'),
description: t('storageSettingsDescription'),
icon: Database,
href: '/settings/storage',
},
{
id: 'system',
title: t('systemSettings'),
description: t('systemSettingsDescription'),
icon: Settings,
href: '/settings/system',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
},
];
+13 -100
View File
@@ -27,7 +27,7 @@ const testConfig: AppConfig = {
],
updatedAt: 0,
},
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
esmUrl: 'https://esm.shakespeare.diy',
corsProxy: 'https://proxy.shakespeare.diy/?url={href}',
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
@@ -185,11 +185,10 @@ describe('makeSystemPrompt', () => {
});
describe('tools section', () => {
it('should show no tools message when no tools are provided', async () => {
it('should not include tools section when no tools are provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Available Tools');
expect(result).toContain('There are no tools available to you.');
expect(result).not.toContain('## Available Tools');
});
it('should list available tools with descriptions', async () => {
@@ -253,7 +252,7 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins', '/projects/test-project');
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins');
});
it('should list available skills when they exist', async () => {
@@ -291,6 +290,15 @@ describe('makeSystemPrompt', () => {
});
describe('CORS proxy section', () => {
it('should not include CORS proxy section when not provided', async () => {
const result = await makeSystemPrompt({
...baseOpts,
config: { ...testConfig, corsProxy: '' },
});
expect(result).not.toContain('## Working Around CORS Issues');
});
it('should include CORS proxy information when provided', async () => {
const result = await makeSystemPrompt(baseOpts);
@@ -417,7 +425,6 @@ describe('makeSystemPrompt', () => {
expect(result).toContain('## User Actions');
expect(result).toContain('## Virtual Filesystem Structure');
expect(result).toContain('## Your Role');
expect(result).toContain('## Project Templates');
expect(result).toContain('## Skills');
expect(result).toContain('## Working Around CORS Issues');
expect(result).toContain('## Edit with Shakespeare');
@@ -513,98 +520,4 @@ Skills: {{ skills.length }}`;
expect(result).toContain('Skills: 0');
});
});
describe('project template metadata', () => {
it('should include template name when projectTemplate is provided', async () => {
const projectTemplate = {
name: 'MKStack',
description: 'Build Nostr clients with React.',
url: 'https://gitlab.com/soapbox-pub/mkstack.git',
};
const result = await makeSystemPrompt({
...baseOpts,
projectTemplate,
});
expect(result).toContain('**Project Template**: MKStack');
});
it('should not include template section when projectTemplate is undefined', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).not.toContain('**Project Template**:');
});
it('should make projectTemplate accessible in custom templates', async () => {
const projectTemplate = {
name: 'MKStack',
description: 'Build Nostr clients with React.',
url: 'https://gitlab.com/soapbox-pub/mkstack.git',
};
const customTemplate = `{% if projectTemplate %}Template: {{ projectTemplate.name }} - {{ projectTemplate.description }}{% else %}No template{% endif %}`;
const result = await makeSystemPrompt({
...baseOpts,
projectTemplate,
template: customTemplate,
});
expect(result).toContain('Template: MKStack - Build Nostr clients with React.');
});
it('should handle missing projectTemplate in custom templates', async () => {
const customTemplate = `{% if projectTemplate %}Template: {{ projectTemplate.name }}{% else %}No template{% endif %}`;
const result = await makeSystemPrompt({
...baseOpts,
template: customTemplate,
});
expect(result).toContain('No template');
});
it('should list all available templates from config', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('## Project Templates');
expect(result).toContain('**Available Templates:**');
expect(result).toContain('**MKStack**');
expect(result).toContain('Build Nostr clients with React.');
expect(result).toContain('https://gitlab.com/soapbox-pub/mkstack.git');
expect(result).toContain('Settings > AI');
});
it('should highlight current template when it matches a configured template', async () => {
const projectTemplate = {
name: 'MKStack',
description: 'Build Nostr clients with React.',
url: 'https://gitlab.com/soapbox-pub/mkstack.git',
};
const result = await makeSystemPrompt({
...baseOpts,
projectTemplate,
});
expect(result).toContain('**MKStack** **(CURRENT TEMPLATE)**');
});
it('should not highlight any template when current template does not match configured templates', async () => {
const projectTemplate = {
name: 'Custom Template',
description: 'A custom template.',
url: 'https://example.com/custom-template.git',
};
const result = await makeSystemPrompt({
...baseOpts,
projectTemplate,
});
expect(result).toContain('**MKStack**');
expect(result).not.toContain('**(CURRENT TEMPLATE)**');
});
});
});
+16 -36
View File
@@ -19,7 +19,6 @@ export interface MakeSystemPromptOpts {
metadata?: NostrMetadata;
repositoryUrl?: string;
template?: string;
projectTemplate?: { name: string; description: string; url: string };
}
/**
@@ -30,19 +29,16 @@ export const defaultSystemPrompt = `{% if mode === "init" %}You are Shakespeare,
# Your Environment
You are operating within **Shakespeare**, an AI-powered website builder that allows users to create custom applications through natural language conversation.
You are operating within **Shakespeare**, an AI-powered Nostr website builder that allows users to create custom Nostr applications through natural language conversation.
- **Current Date**: {{ date }}
- **Current Page**: {{ location.href }}
- **Current Working Directory**: {{ cwd }}
- **Repository URL**: {% if repositoryUrl %}{{ repositoryUrl }}{% else %}none{% endif %}
{% if projectTemplate %}- **Project Template**: {{ projectTemplate.name }}{% endif %}
Users can add or remove templates in Settings > AI (\`{{ location.origin }}/settings/ai\`).
- **Repository URL**: {{ repositoryUrl }}
## What Shakespeare Is
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
Shakespeare is a web-based development environment where users can build Nostr websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**Important Architecture Notes:**
@@ -68,7 +64,7 @@ Shakespeare is a web-based development environment where users can build website
- **NIP-05**: {{ user.nip05 }}{% endif %}{% if user.lud16 %}
- **Lightning Address**: {{ user.lud16 }}{% endif %}
Since the user is logged in, they can use Nostr-enabled AI, git, and deployment providers.{% else %}The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to use Nostr-enabled AI, git, and deployment providers.{% endif %}
Since the user is logged in, they can deploy their creations to public URLs and use Nostr-enabled AI providers.{% else %}The user is not logged in. The user can log into Nostr by clicking the "Login" button in the sidebar menu. Logging in will allow the user to deploy their creations to public URLs and use Nostr-enabled AI providers.{% endif %}
## User Interface
@@ -91,12 +87,12 @@ The Shakespeare interface consists of several key areas:
4. **Settings** (\`/settings\`): Accessible from the sidebar menu, includes:
- **Preferences** (\`/settings/preferences\`): Theme and language settings
- **AI Settings** (\`/settings/ai\`): Configure AI providers, API keys, project templates, MCP servers, and plugins
- **AI Settings** (\`/settings/ai\`): Configure AI providers and API keys
- **Git Settings** (\`/settings/git\`): Configure Git credentials for version control
- **Deploy Settings** (\`/settings/deploy\`): Configure deployment providers (Shakespeare, Netlify, Vercel, nsite)
- **Nostr Settings** (\`/settings/nostr\`): Manage Nostr accounts, relay connections, and ngit servers
- **Storage Settings** (\`/settings/storage\`): Export/import project files, manage browser storage
- **System Settings** (\`/settings/system\`): Advanced configuration (ESM CDN, CORS proxy, service worker, etc.)
- **System Settings** (\`/settings/system\`): Advanced configuration (project template, ESM CDN, CORS proxy, etc.)
- **About** (\`/settings/about\`): License information and project details
## User Actions
@@ -144,33 +140,22 @@ Shakespeare operates on a browser-based virtual filesystem (VFS) that persists a
As the AI assistant in Shakespeare, you help users by:
- Understanding their requirements through natural conversation
- Writing and modifying code files to build their applications
- Writing and modifying code files to build their Nostr applications
- Explaining technical concepts in accessible terms
- Providing suggestions and best practices
- Troubleshooting issues and implementing fixes
- Building complete, functional websites and applications
- Building complete, functional Nostr websites and applications
- Learning from existing projects in the VFS to provide better solutions
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.
## Project Templates
When a project is first created, you (the AI) choose an appropriate template from the available options based on the user's requirements. Once a project is created, the template cannot be changed—the user would need to create a new project to use a different template.
**Available Templates:**
{% for template in config.templates %}
- **{{ template.name }}**{% if projectTemplate and projectTemplate.url === template.url %} **(CURRENT TEMPLATE)**{% endif %}: {{ template.description }}
- URL: {{ template.url }}
{% endfor %}
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.{% if tools.length > 0 %}
## Available Tools
{% if tools.length > 0 %}
You have access to the following tools:
{% for tool in tools %}{% if tool.type === 'function' %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% else %}
There are no tools available to you.{% endif %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% endif %}
## Skills
@@ -185,7 +170,7 @@ Available skills:
**Important**: When a task matches a skill's description, you MUST use that skill by calling the skill tool. Skills contain specialized workflows and best practices for specific tasks.{% else %}No skills are currently configured. Skills are reusable AI workflows that can be added via plugins.{% endif %}
Users can configure skills in Settings > AI (\`{{ location.origin }}/settings/ai\`) by adding plugins that contain skills.
Users can configure skills in Settings > AI ({{ location.origin }}/settings/ai) by adding plugins that contain skills.{% if config.corsProxy %}
## Working Around CORS Issues
@@ -193,11 +178,7 @@ If you encounter CORS (Cross-Origin Resource Sharing) errors when fetching exter
**CORS Proxy URL Template**: \`{{ config.corsProxy }}\`
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.
## "Vibed with Shakespeare"
When building a site for the first time, include "Vibed with Shakespeare" somewhere in the UI, linked to this URL: https://shakespeare.diy
Replace \`{href}\`, \`{hostname}\`, or other URL components in the template as needed.{% endif %}
## Edit with Shakespeare
@@ -226,7 +207,7 @@ Note: the badge should be displayed at its natural size. It is recommended to om
{{ AGENTS }}{% endif %}`;
export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<string> {
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template, projectTemplate } = opts;
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template } = opts;
// Add current date
const date = new Date().toLocaleDateString("en-US", {
@@ -236,11 +217,11 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
day: "numeric",
});
// Get skills from both plugins and project
// Get skills
let skills: Array<{ name: string; description: string; plugin: string; path: string }> = [];
if (config.fsPathPlugins) {
try {
skills = await getAllSkills(fs, config.fsPathPlugins, cwd);
skills = await getAllSkills(fs, config.fsPathPlugins);
} catch {
// Skills not available, use empty array
skills = [];
@@ -307,7 +288,6 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
editUrl,
README: readmeText,
AGENTS: agentsText,
projectTemplate,
};
// Render the template with the context
-54
View File
@@ -185,58 +185,4 @@ describe('GitCommitTool', () => {
expect(result).toContain('✅ Successfully committed');
});
it('should error when HEAD is detached (currentBranch returns null)', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state - currentBranch returns null
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(null);
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Cannot commit: Git is in a detached HEAD state');
// Verify commit was never called
expect(mockGitInstance.commit).not.toHaveBeenCalled();
});
it('should error when HEAD is detached (currentBranch returns undefined)', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state - currentBranch returns undefined
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(undefined);
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Cannot commit: Git is in a detached HEAD state');
// Verify commit was never called
expect(mockGitInstance.commit).not.toHaveBeenCalled();
});
it('should provide helpful instructions when HEAD is detached', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(null);
try {
await tool.execute({ message: 'Test commit' });
expect.fail('Should have thrown an error');
} catch (error) {
const errorMessage = (error as Error).message;
// Verify the error message contains safe instructions that preserve changes
expect(errorMessage).toContain('git checkout -b temp-branch');
expect(errorMessage).toContain('try the commit again');
expect(errorMessage).toContain('preserving all changes');
}
});
});
+10 -20
View File
@@ -41,26 +41,6 @@ export class GitCommitTool implements Tool<GitCommitParams> {
throw new Error(`❌ Commit message cannot be empty.`);
}
// Check for detached HEAD state before doing any work
// currentBranch returns null when HEAD is detached
const currentBranch = await this.git.currentBranch({
dir: this.cwd,
});
if (currentBranch === null || currentBranch === undefined) {
throw new Error(
`❌ Cannot commit: Git is in a detached HEAD state.\n\n` +
`This usually happens after checking out a specific commit. ` +
`Your changes need to be on a branch before committing.\n\n` +
`To fix this and preserve your staged changes:\n` +
` 1. Run: git checkout -b temp-branch\n` +
` (This creates a new branch from your current state, preserving all changes)\n` +
` 2. Then try the commit again\n` +
` 3. After committing, you can merge to main with:\n` +
` git checkout main && git merge temp-branch`
);
}
// Get git status to see what files have changed
const statusMatrix = await this.git.statusMatrix({
dir: this.cwd,
@@ -99,6 +79,16 @@ export class GitCommitTool implements Tool<GitCommitParams> {
}
}
// Get current branch name
let currentBranch = 'main';
try {
currentBranch = await this.git.currentBranch({
dir: this.cwd,
}) || 'main';
} catch {
// Default to 'main' if we can't get the current branch
}
// Commit the changes (author/committer will be set automatically by Git class)
const commitSha = await this.git.commit({
dir: this.cwd,
+5 -7
View File
@@ -10,26 +10,24 @@ interface SkillParams {
export class SkillTool implements Tool<SkillParams> {
private fs: JSRuntimeFS;
private pluginsPath: string;
private projectPath: string;
readonly description = 'Load and execute a skill from the configured plugins or project. Skills are reusable AI workflows that can be invoked by name.';
readonly description = 'Load and execute a skill from the configured plugins. Skills are reusable AI workflows that can be invoked by name.';
readonly inputSchema = z.object({
name: z.string().describe('The name of the skill to execute (lowercase alphanumeric with hyphens)'),
});
constructor(fs: JSRuntimeFS, pluginsPath: string, projectPath: string) {
constructor(fs: JSRuntimeFS, pluginsPath: string) {
this.fs = fs;
this.pluginsPath = pluginsPath;
this.projectPath = projectPath;
}
async execute(args: SkillParams): Promise<string> {
const { name } = args;
try {
// Find the skill across all plugins and project
const skill = await findSkill(this.fs, this.pluginsPath, this.projectPath, name);
// Find the skill across all plugins
const skill = await findSkill(this.fs, this.pluginsPath, name);
if (!skill) {
throw new Error(`Skill "${name}" not found. Use the skill tool to list available skills or configure plugins in Settings > AI.`);
@@ -40,7 +38,7 @@ export class SkillTool implements Tool<SkillParams> {
return `# Skill: ${skill.name}
**Source**: ${skill.plugin === 'project' ? 'Project' : `Plugin: ${skill.plugin}`}
**Plugin**: ${skill.plugin}
**Description**: ${skill.description}
**Path**: ${skill.path}
+10 -41
View File
@@ -3,9 +3,6 @@
"settings": "Settings",
"backToSettings": "Back to Settings",
"help": "Help",
"general": "General",
"integrations": "Integrations",
"advanced": "Advanced",
"anonymous": "Anonymous",
"logIn": "Log in",
"signUp": "Sign up",
@@ -18,8 +15,8 @@
"systemSettingsDescription": "Configure system-level settings and advanced options.",
"esmUrl": "Javascript CDN",
"esmUrlDescription": "Javascript CDN URL for package imports.",
"projectTemplates": "Project Templates",
"projectTemplatesDescription": "Templates available to the AI when creating new projects.",
"projectTemplate": "Project Template",
"projectTemplateDescription": "Git repository URL to use as the starting template for new projects.",
"previewDomain": "Preview Domain",
"previewDomainDescription": "Domain used for iframe preview sandboxing.",
"corsProxy": "CORS Proxy",
@@ -63,13 +60,7 @@
"shareErrorReports": "Share error reports",
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
"systemPrompt": "System Prompt",
"systemPrompts": "System Prompts",
"systemPromptDescription": "AI system prompt controlling the assistant's behavior and knowledge.",
"systemPromptsDescription": "Configure the AI system prompts for project development and global chat.",
"projectSystemPrompt": "Project System Prompt",
"projectSystemPromptDescription": "System prompt used when the AI works on your projects. Supports Nunjucks templating for dynamic content.",
"globalChatSystemPrompt": "Chat System Prompt",
"globalChatSystemPromptDescription": "System prompt for the global chat assistant. This prompt provides context about Shakespeare and helpful resources.",
"systemPromptDescription": "Customize the AI assistant's system prompt using Jinja-like template syntax. This controls the assistant's behavior and knowledge.",
"english": "English",
"portuguese": "Portuguese",
"chinese": "Chinese",
@@ -97,19 +88,20 @@
"remove": "Remove",
"retry": "Retry",
"name": "Name",
"id": "ID",
"email": "Email",
"buildNostrApps": "Build apps with AI",
"whatToBuild": "What would you like to build?",
"chooseModel": "Choose a model...",
"selectModelToDescribe": "Please select a model below, then describe what you'd like to build...",
"examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...",
"settingsDescription": "Manage your application settings and preferences.",
"aiSettings": "AI",
"aiSettingsDescription": "Configure AI providers and API keys",
"gitSettings": "Git",
"gitSettingsDescription": "Configure Git credentials for HTTP authentication",
"deploySettings": "Deployment",
"deploySettingsDescription": "Configure deployment providers",
"deploySettingsDescriptionLong": "Configure deployment providers to deploy your projects to various hosting platforms.",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "Configure relay connections and Nostr preferences",
"storageSettings": "Storage",
@@ -120,9 +112,6 @@
"importRepository": "Import Repository",
"noProjectsYet": "No projects yet",
"createFirstProject": "Create your first project to get started",
"searchProjects": "Search projects...",
"noProjectsFound": "No projects found",
"tryDifferentSearch": "Try a different search term",
"closeSidebar": "Close sidebar",
"collapseSidebar": "Collapse sidebar",
"welcomeToShakespeare": "Welcome to Shakespeare",
@@ -190,6 +179,7 @@
"pushFailed": "Push failed",
"pullSuccessful": "Pull successful",
"pullFailed": "Pull failed",
"aiSettingsDescriptionLong": "Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser.",
"configuredProviders": "Configured Providers",
"addProvider": "Add Provider",
"getApiKey": "Get API key",
@@ -215,6 +205,7 @@
"shakespeareDeployNostrAuth": "This provider uses Nostr authentication. Make sure you are logged in to deploy.",
"providerType": "Provider Type",
"selectProviderType": "Select a provider type",
"gitSettingsDescriptionLong": "Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.",
"configuredCredentials": "Configured Credentials",
"origin": "Origin",
"username": "Username",
@@ -235,6 +226,7 @@
"license": "License",
"loadingLicense": "Loading license...",
"failedToLoadLicense": "Failed to load license",
"dataSettingsDescriptionLong": "Export files and manage local data.",
"offlineCache": "Offline Cache",
"offlineCacheDescription": "Shakespeare caches files locally to enable offline functionality. Clear the cache to free up space or troubleshoot issues.",
"cacheSize": "Cache size",
@@ -302,6 +294,7 @@
"untracked": "untracked",
"toggleSidebar": "Toggle sidebar",
"openSidebar": "Open sidebar",
"nostrSettingsDescriptionLong": "Configure your Nostr connection settings and relay preferences.",
"nostrAccounts": "Nostr Accounts",
"noAccountsLoggedIn": "No accounts logged in. Add an account to get started.",
"createAccount": "Create Account",
@@ -520,29 +513,5 @@
"templateUpdateFailedDescription": "Failed to update the project template from the remote repository. Using the cached version instead.",
"templatesDirectory": "Templates Directory",
"templatesDirectoryDescription": "Directory where project templates are cached in the virtual filesystem.",
"terminal": "Terminal",
"templateName": "Template Name",
"templateDescription": "Description",
"templateGitUrl": "Git URL",
"addProjectTemplate": "Add Project Template",
"templateAdded": "Template Added",
"templateAddedDescription": "Project template '{{name}}' has been added successfully.",
"templateDeleted": "Template Deleted",
"templateDeletedDescription": "Project template '{{name}}' has been deleted.",
"noTemplatesConfigured": "No project templates configured yet. Add a template to get started.",
"atLeastOneTemplateRequired": "At least one template is required",
"globalChat": "Chat",
"globalChatWelcome": "Hi there! 👋",
"globalChatDescription": "Ask me anything. I'm here to help with questions, ideas, and conversation.",
"clearChat": "Clear chat",
"popOutChat": "Pop out",
"minimizeChat": "Minimize",
"typeMessage": "Type a message...",
"configureAIFirst": "Configure AI provider first",
"globalChatEnabled": "Floating Chat Button",
"globalChatEnabledDescription": "Show a floating chat button for quick AI conversations",
"globalChatSystemPrompt": "Chat System Prompt",
"globalChatSystemPromptDescription": "Custom system prompt for the floating chat assistant",
"building": "Building",
"chatting": "Chatting"
"terminal": "Terminal"
}
+5 -22
View File
@@ -3,9 +3,6 @@
"settings": "Saitunan",
"backToSettings": "Koma zuwa Saitunan",
"help": "Taimako",
"general": "Gabaɗaya",
"integrations": "Haɗin Kai",
"advanced": "Ci Gaba",
"anonymous": "Maras Suna",
"logIn": "Shiga",
"signUp": "Yi Rajista",
@@ -87,7 +84,6 @@
"remove": "Cire",
"retry": "Sake gwadawa",
"name": "Suna",
"id": "ID",
"email": "Imel",
"buildNostrApps": "Gina aikace-aikace da AI",
"whatToBuild": "Me kuke son ginawa?",
@@ -109,9 +105,6 @@
"importRepository": "Shigo da Repository",
"noProjectsYet": "Babu ayyuka har yanzu",
"createFirstProject": "Ƙirƙiri aikin farko don farawa",
"searchProjects": "Nemo ayyuka...",
"noProjectsFound": "Ba a sami ayyuka ba",
"tryDifferentSearch": "Gwada kalmar nema daban",
"closeSidebar": "Rufe gefen mashigi",
"collapseSidebar": "Rufe gefen mashigi",
"welcomeToShakespeare": "Maraba da Shakespeare",
@@ -179,6 +172,7 @@
"pushFailed": "Turawa ta gaza",
"pullSuccessful": "Ja ya yi nasara",
"pullFailed": "Ja ya gaza",
"aiSettingsDescriptionLong": "Saita masu samar da AI ta hanyar ƙara maɓallan API. Saitunan ana ajiye su kai tsaye kuma ana adana su a cikin burauzar ku.",
"configuredProviders": "Masu Samarwa da aka Saita",
"addProvider": "Ƙara Mai Samarwa",
"getApiKey": "Sami maɓallin API",
@@ -204,6 +198,7 @@
"shakespeareDeployNostrAuth": "Wannan mai samarwa yana amfani da tabbatar da Nostr. Tabbatar cewa kun shiga don tura.",
"providerType": "Nau'in Mai Samarwa",
"selectProviderType": "Zaɓi nau'in mai samarwa",
"gitSettingsDescriptionLong": "Saita bayanan shaidar Git don tabbatar da HTTP. Saitunan ana ajiye su kai tsaye kuma ana adana su a cikin burauzar ku.",
"configuredCredentials": "Bayanan Shaidar da aka Saita",
"origin": "Asali",
"username": "Sunan mai amfani",
@@ -215,6 +210,7 @@
"gitEmail": "Imel Git",
"coAuthoredByShakespeare": "Haɗin marubuta da Shakespeare",
"gitIdentityDescription": "Idan an saita suna da imel, za a yi amfani da su azaman marubucin aikin. In ba haka ba, za a yi amfani da shakespeare.diy. Lokacin da aka kunna haɗin marubuta, za a ƙara Shakespeare azaman haɗin marubuta.",
"dataSettingsDescriptionLong": "Fitar da fayiloli da sarrafa bayanan gida.",
"exportFiles": "Fitar da Fayiloli",
"exportFilesDescription": "Sauke duk ayyukanku da fayiloli azaman ajiyar ZIP. Wannan ya haɗa da duk fayilolin aikin, saitunan, da bayanan da aka adana a gida.",
"exportAllFiles": "Fitar da Duk Fayiloli",
@@ -284,6 +280,7 @@
"untracked": "ba a bi ba",
"toggleSidebar": "Juya gefen mashigi",
"openSidebar": "Buɗe gefen mashigi",
"nostrSettingsDescriptionLong": "Saita saitunan haɗin Nostr da zaɓuɓɓukan relay.",
"nostrAccounts": "Asusun Nostr",
"noAccountsLoggedIn": "Babu asusun da aka shiga. Ƙara asusu don farawa.",
"createAccount": "Ƙirƙiri Asusu",
@@ -431,19 +428,5 @@
"modified": "An Canza",
"restoreToDefault": "Mayar da asali",
"restoredToDefault": "An Mayar da Asali",
"terminal": "Terminal",
"globalChat": "Tattaunawa",
"globalChatWelcome": "Sannu! 👋",
"globalChatDescription": "Tambayi komai. Ina nan don taimaka da tambayoyi, ra'ayoyi, da tattaunawa.",
"clearChat": "Share tattaunawa",
"popOutChat": "Fitar da waje",
"minimizeChat": "Ragewa",
"typeMessage": "Rubuta sako...",
"configureAIFirst": "Da fari ka saita mai ba da AI",
"globalChatEnabled": "Maballin Tattaunawa Mai Yawo",
"globalChatEnabledDescription": "Nuna maballin tattaunawa mai yawo don saurin tattaunawa da AI",
"globalChatSystemPrompt": "Jagorar Tsarin Tattaunawa",
"globalChatSystemPromptDescription": "Jagorar tsarin da aka keɓe don mataimakin tattaunawa mai yawo",
"building": "Ginawa",
"chatting": "Tattaunawa"
"terminal": "Terminal"
}
+5 -22
View File
@@ -3,9 +3,6 @@
"settings": "Ntọala",
"backToSettings": "Laghachi na Ntọala",
"help": "Enyemaka",
"general": "Izugbe",
"integrations": "Njikọta",
"advanced": "Dị elu",
"anonymous": "Onye na-amaghị aha",
"logIn": "Banye",
"signUp": "Debanye aha",
@@ -87,7 +84,6 @@
"remove": "Wepụ",
"retry": "Nwaa ọzọ",
"name": "Aha",
"id": "ID",
"email": "Ozi-eletrọniki",
"buildNostrApps": "Wuo ngwa na AI",
"whatToBuild": "Gịnị ka ị chọrọ iwu?",
@@ -109,9 +105,6 @@
"importRepository": "Bubata Repository",
"noProjectsYet": "Enwebeghị ọrụ ọ bụla",
"createFirstProject": "Mepụta ọrụ mbụ gị iji malite",
"searchProjects": "Chọọ ọrụ...",
"noProjectsFound": "Achọtaghị ọrụ ọ bụla",
"tryDifferentSearch": "Nwalee okwu ọchụchọ dị iche",
"closeSidebar": "Mechie sidebar",
"collapseSidebar": "Gbakọọ sidebar",
"welcomeToShakespeare": "Nnọọ na Shakespeare",
@@ -179,6 +172,7 @@
"pushFailed": "Nkwanye dara",
"pullSuccessful": "Ndọta gara nke ọma",
"pullFailed": "Ndọta dara",
"aiSettingsDescriptionLong": "Hazie ndị na-enye AI site na ịtinye igodo API gị. Ntọala na-echekwa onwe ya ma chekwaa ya na mpaghara na browser gị.",
"configuredProviders": "Ndị Na-enye Ahaziri",
"addProvider": "Tinye Onye Na-enye",
"getApiKey": "Nweta igodo API",
@@ -204,6 +198,7 @@
"shakespeareDeployNostrAuth": "Onye na-enye a na-eji nkwenye Nostr. Jide n'aka na ị banyere iji bufee.",
"providerType": "Ụdị Onye Na-enye",
"selectProviderType": "Họrọ ụdị onye na-enye",
"gitSettingsDescriptionLong": "Hazie nzere Git maka nkwenye HTTP. Ntọala na-echekwa onwe ya ma chekwaa ya na mpaghara na browser gị.",
"configuredCredentials": "Nzere Ahaziri",
"origin": "Mmalite",
"username": "Aha onye ọrụ",
@@ -215,6 +210,7 @@
"gitEmail": "Ozi-eletrọniki Git",
"coAuthoredByShakespeare": "Ndekọ ọnụ na Shakespeare",
"gitIdentityDescription": "Ọ bụrụ na ahaziri aha na ozi-eletrọniki, a ga-eji ha dị ka onye dere ya. Ma ọ bụghị, a ga-eji shakespeare.diy. Mgbe emere ndekọ ọnụ, a ga-etinye Shakespeare dị ka ndekọ ọnụ.",
"dataSettingsDescriptionLong": "Bupụta faịlụ ma jikwaa data mpaghara.",
"exportFiles": "Bupụta Faịlụ",
"exportFilesDescription": "Budata ọrụ gị niile na faịlụ dị ka mkpokọta ZIP. Nke a gụnyere faịlụ ọrụ niile, ntọala, na data echekwara na mpaghara.",
"exportAllFiles": "Bupụta Faịlụ Niile",
@@ -281,6 +277,7 @@
"untracked": "na-esoghị",
"toggleSidebar": "Gbanwee sidebar",
"openSidebar": "Meghee sidebar",
"nostrSettingsDescriptionLong": "Hazie ntọala njikọ Nostr gị na nhọrọ relay.",
"nostrAccounts": "Akaụntụ Nostr",
"noAccountsLoggedIn": "Enweghị akaụntụ banyere. Tinye akaụntụ iji malite.",
"createAccount": "Mepụta Akaụntụ",
@@ -428,19 +425,5 @@
"modified": "Gbanwere",
"restoreToDefault": "Weghachi na nke mbụ",
"restoredToDefault": "Weghachiri na Nke Mbụ",
"terminal": "Terminal",
"globalChat": "Nkata",
"globalChatWelcome": "Ndewo! 👋",
"globalChatDescription": "Jụọ ihe ọ bụla. Anọ m ebe a inyere gị aka na ajụjụ, echiche, na nkata.",
"clearChat": "Kpochapụ nkata",
"popOutChat": "Wepụta",
"minimizeChat": "Belata",
"typeMessage": "Dee ozi...",
"configureAIFirst": "Bụrụ ụzọ hazie onye na-enye AI",
"globalChatEnabled": "Bọtịnụ Nkata Na-epupụta",
"globalChatEnabledDescription": "Gosi bọtịnụ nkata na-epupụta maka nkata AI ngwa ngwa",
"globalChatSystemPrompt": "Usoro Nkata",
"globalChatSystemPromptDescription": "Usoro nke gị maka onye enyemaka nkata na-epupụta",
"building": "Nrụpụta",
"chatting": "Nkwurịta"
"terminal": "Terminal"
}
+6 -22
View File
@@ -3,9 +3,6 @@
"settings": "Configurações",
"backToSettings": "Voltar às Configurações",
"help": "Ajuda",
"general": "Geral",
"integrations": "Integrações",
"advanced": "Avançado",
"anonymous": "Anônimo",
"logIn": "Entrar",
"signUp": "Cadastrar",
@@ -87,7 +84,6 @@
"remove": "Remover",
"retry": "Tentar novamente",
"name": "Nome",
"id": "ID",
"email": "Email",
"buildNostrApps": "Construa aplicativos com IA",
"whatToBuild": "O que você gostaria de construir?",
@@ -101,6 +97,7 @@
"gitSettingsDescription": "Configure credenciais do Git para autenticação HTTP",
"deploySettings": "Implantação",
"deploySettingsDescription": "Configure provedores de implantação",
"deploySettingsDescriptionLong": "Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr",
"storageSettings": "Armazenamento",
@@ -111,9 +108,6 @@
"importRepository": "Importar Repositório",
"noProjectsYet": "Nenhum projeto ainda",
"createFirstProject": "Crie seu primeiro projeto para começar",
"searchProjects": "Pesquisar projetos...",
"noProjectsFound": "Nenhum projeto encontrado",
"tryDifferentSearch": "Tente um termo de pesquisa diferente",
"closeSidebar": "Fechar barra lateral",
"collapseSidebar": "Recolher barra lateral",
"welcomeToShakespeare": "Bem-vindo ao Shakespeare",
@@ -181,6 +175,7 @@
"pushFailed": "Push falhou",
"pullSuccessful": "Pull realizado com sucesso",
"pullFailed": "Pull falhou",
"aiSettingsDescriptionLong": "Configure provedores de IA adicionando suas chaves de API. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.",
"configuredProviders": "Provedores Configurados",
"addProvider": "Adicionar Provedor",
"getApiKey": "Obter chave de API",
@@ -206,6 +201,7 @@
"shakespeareDeployNostrAuth": "Este provedor usa autenticação Nostr. Certifique-se de estar logado para implantar.",
"providerType": "Tipo de Provedor",
"selectProviderType": "Selecione um tipo de provedor",
"gitSettingsDescriptionLong": "Configure credenciais do Git para autenticação HTTP. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.",
"configuredCredentials": "Credenciais Configuradas",
"origin": "Origem",
"username": "Nome de usuário",
@@ -217,6 +213,7 @@
"gitEmail": "Email Git",
"coAuthoredByShakespeare": "Co-autoria de Shakespeare",
"gitIdentityDescription": "Se nome e email estiverem configurados, eles serão usados como autor do commit. Caso contrário, shakespeare.diy será usado. Quando co-autoria estiver ativada, Shakespeare será adicionado como co-autor.",
"dataSettingsDescriptionLong": "Exporte arquivos e gerencie dados locais.",
"offlineCache": "Cache Offline",
"offlineCacheDescription": "O Shakespeare armazena arquivos localmente para permitir funcionalidade offline. Limpe o cache para liberar espaço ou solucionar problemas.",
"cacheSize": "Tamanho do cache",
@@ -293,6 +290,7 @@
"untracked": "não rastreado",
"toggleSidebar": "Alternar barra lateral",
"openSidebar": "Abrir barra lateral",
"nostrSettingsDescriptionLong": "Configure suas configurações de conexão Nostr e preferências de relay.",
"nostrAccounts": "Contas Nostr",
"noAccountsLoggedIn": "Nenhuma conta logada. Adicione uma conta para começar.",
"createAccount": "Criar Conta",
@@ -440,19 +438,5 @@
"modified": "Modificado",
"restoreToDefault": "Restaurar para padrão",
"restoredToDefault": "Restaurado para Padrão",
"terminal": "Terminal",
"globalChat": "Chat",
"globalChatWelcome": "Olá! 👋",
"globalChatDescription": "Pergunte-me qualquer coisa. Estou aqui para ajudar com perguntas, ideias e conversas.",
"clearChat": "Limpar chat",
"popOutChat": "Destacar",
"minimizeChat": "Minimizar",
"typeMessage": "Digite uma mensagem...",
"configureAIFirst": "Configure o provedor de IA primeiro",
"globalChatEnabled": "Botão de Chat Flutuante",
"globalChatEnabledDescription": "Mostrar um botão de chat flutuante para conversas rápidas com IA",
"globalChatSystemPrompt": "Prompt do Sistema do Chat",
"globalChatSystemPromptDescription": "Prompt do sistema personalizado para o assistente de chat flutuante",
"building": "Construindo",
"chatting": "Conversando"
"terminal": "Terminal"
}
+5 -22
View File
@@ -3,9 +3,6 @@
"settings": "Awọn eto",
"backToSettings": "Pada si Awọn eto",
"help": "Iranlọwọ",
"general": "Gbogbogbo",
"integrations": "Awọn isopọ",
"advanced": "To siwaju",
"anonymous": "Alainidamọ",
"logIn": "Wọle",
"signUp": "Forukọsilẹ",
@@ -87,7 +84,6 @@
"remove": "Yọ kuro",
"retry": "Tun gbiyanju",
"name": "Orukọ",
"id": "ID",
"email": "Imeeli",
"buildNostrApps": "Kọ awọn ohun elo pẹlu AI",
"whatToBuild": "Kini o fẹ kọ?",
@@ -109,9 +105,6 @@
"importRepository": "Gbe Repository wọle",
"noProjectsYet": "Ko si awọn iṣẹ akanṣe sibẹsibẹ",
"createFirstProject": "Ṣẹda iṣẹ akanṣe akọkọ rẹ lati bẹrẹ",
"searchProjects": "Wa awọn iṣẹ akanṣe...",
"noProjectsFound": "Ko ri awọn iṣẹ akanṣe",
"tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran",
"closeSidebar": "Ti ẹgbẹ sidebar",
"collapseSidebar": "Subu sidebar",
"welcomeToShakespeare": "Kaabo si Shakespeare",
@@ -179,6 +172,7 @@
"pushFailed": "Titari kuna",
"pullSuccessful": "Fifa ni aṣeyọri",
"pullFailed": "Fifa kuna",
"aiSettingsDescriptionLong": "Tunto awọn olupese AI nipa fifi awọn bọtini API rẹ kun. Awọn eto ni a fi pamọ laifọwọyi ati pe a tọju wọn ni agbegbe ninu awọn aṣawakiri rẹ.",
"configuredProviders": "Awọn Olupese Ti a Tunto",
"addProvider": "Fi Olupese kun",
"getApiKey": "Gba bọtini API",
@@ -204,6 +198,7 @@
"shakespeareDeployNostrAuth": "Olupese yii nlo ijẹrisi Nostr. Rii daju pe o ti wọle lati gbe jade.",
"providerType": "Iru Olupese",
"selectProviderType": "Yan iru olupese kan",
"gitSettingsDescriptionLong": "Tunto awọn ẹri Git fun ijẹrisi HTTP. Awọn eto ni a fi pamọ laifọwọyi ati pe a tọju wọn ni agbegbe ninu awọn aṣawakiri rẹ.",
"configuredCredentials": "Awọn Ẹri Ti a Tunto",
"origin": "Ipilẹṣẹ",
"username": "Orukọ olumulo",
@@ -215,6 +210,7 @@
"gitEmail": "Imeeli Git",
"coAuthoredByShakespeare": "Ajọpọ onkọwe pẹlu Shakespeare",
"gitIdentityDescription": "Ti a ba tunto orukọ ati imeeli, wọn yoo jẹ lilo bi onkọwe. Bibẹẹkọ, shakespeare.diy yoo jẹ lilo. Nigbati a ba mu ajọpọ onkọwe ṣiṣẹ, Shakespeare yoo jẹ fifikun bi ajọpọ onkọwe.",
"dataSettingsDescriptionLong": "Gbe awọn faili jade ati ṣakoso data agbegbe.",
"exportFiles": "Gbe Awọn faili jade",
"exportFilesDescription": "Gba gbogbo awọn iṣẹ akanṣe ati awọn faili rẹ gẹgẹbi apo ZIP. Eyi pẹlu gbogbo awọn faili iṣẹ akanṣe, awọn eto, ati data ti a tọju ni agbegbe.",
"exportAllFiles": "Gbe Gbogbo Awọn faili jade",
@@ -281,6 +277,7 @@
"untracked": "ti a ko tọpa",
"toggleSidebar": "Yipada sidebar",
"openSidebar": "Ṣi sidebar",
"nostrSettingsDescriptionLong": "Tunto awọn eto asopọ Nostr rẹ ati awọn ayanfẹ relay.",
"nostrAccounts": "Awọn Akọọlẹ Nostr",
"noAccountsLoggedIn": "Ko si awọn akọọlẹ ti o wọle. Fi akọọlẹ kun lati bẹrẹ.",
"createAccount": "Ṣẹda Akọọlẹ",
@@ -428,19 +425,5 @@
"modified": "Ti Yipada",
"restoreToDefault": "Pada si atilẹwa",
"restoredToDefault": "Ti Pada si Atilẹwa",
"terminal": "Terminal",
"globalChat": "Ibanisọrọ",
"globalChatWelcome": "Pẹlẹ o! 👋",
"globalChatDescription": "Beere ohunkohun. Mo wa nibi lati ran ọ lọwọ pẹlu awọn ibeere, awọn ero, ati ibaraẹnisọrọ.",
"clearChat": "Pa ibanisọrọ rẹ",
"popOutChat": "Ya jade",
"minimizeChat": "Din ku",
"typeMessage": "Tẹ ifiranṣẹ...",
"configureAIFirst": "Ṣeto olupese AI ni akọkọ",
"globalChatEnabled": "Bọtini Ibanisọrọ Ti O N Lọ",
"globalChatEnabledDescription": "Fi bọtini ibanisọrọ ti o n lọ han fun ibaraẹnisọrọ AI ni iyara",
"globalChatSystemPrompt": "Itọsọna Eto Ibanisọrọ",
"globalChatSystemPromptDescription": "Itọsọna eto aṣa fun oluranlọwọ ibanisọrọ ti o n lọ",
"building": "Kíkọ́",
"chatting": "Sísọ̀rọ̀"
"terminal": "Terminal"
}
+6 -22
View File
@@ -3,9 +3,6 @@
"settings": "设置",
"backToSettings": "返回设置",
"help": "帮助",
"general": "常规",
"integrations": "集成",
"advanced": "高级",
"anonymous": "匿名",
"logIn": "登录",
"signUp": "注册",
@@ -87,7 +84,6 @@
"remove": "移除",
"retry": "重试",
"name": "名称",
"id": "ID",
"email": "邮箱",
"buildNostrApps": "使用AI构建应用",
"whatToBuild": "您想构建什么?",
@@ -101,6 +97,7 @@
"gitSettingsDescription": "配置HTTP身份验证的Git凭据",
"deploySettings": "部署",
"deploySettingsDescription": "配置部署提供商",
"deploySettingsDescriptionLong": "配置部署提供商以将您的项目部署到各种托管平台。",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "配置中继连接和Nostr偏好",
"storageSettings": "存储",
@@ -111,9 +108,6 @@
"importRepository": "导入仓库",
"noProjectsYet": "还没有项目",
"createFirstProject": "创建您的第一个项目开始使用",
"searchProjects": "搜索项目...",
"noProjectsFound": "未找到项目",
"tryDifferentSearch": "尝试不同的搜索词",
"closeSidebar": "关闭侧边栏",
"collapseSidebar": "折叠侧边栏",
"welcomeToShakespeare": "欢迎使用Shakespeare",
@@ -181,6 +175,7 @@
"pushFailed": "推送失败",
"pullSuccessful": "拉取成功",
"pullFailed": "拉取失败",
"aiSettingsDescriptionLong": "通过添加您的API密钥来配置AI提供商。设置会自动保存并存储在您的浏览器本地。",
"configuredProviders": "已配置的提供商",
"addProvider": "添加提供商",
"getApiKey": "获取API密钥",
@@ -206,6 +201,7 @@
"shakespeareDeployNostrAuth": "此提供商使用Nostr身份验证。请确保您已登录以进行部署。",
"providerType": "提供商类型",
"selectProviderType": "选择提供商类型",
"gitSettingsDescriptionLong": "配置HTTP身份验证的Git凭据。设置会自动保存并存储在您的浏览器本地。",
"configuredCredentials": "已配置的凭据",
"origin": "源",
"username": "用户名",
@@ -217,6 +213,7 @@
"gitEmail": "Git邮箱",
"coAuthoredByShakespeare": "Shakespeare共同作者",
"gitIdentityDescription": "如果配置了名称和邮箱,它们将用作提交作者。否则,将使用shakespeare.diy。启用共同作者时,Shakespeare将被添加为共同作者。",
"dataSettingsDescriptionLong": "导出文件和管理本地数据。",
"offlineCache": "离线缓存",
"offlineCacheDescription": "Shakespeare在本地缓存文件以启用离线功能。清除缓存以释放空间或解决问题。",
"cacheSize": "缓存大小",
@@ -293,6 +290,7 @@
"untracked": "未跟踪",
"toggleSidebar": "切换侧边栏",
"openSidebar": "打开侧边栏",
"nostrSettingsDescriptionLong": "配置您的Nostr连接设置和中继偏好。",
"nostrAccounts": "Nostr账户",
"noAccountsLoggedIn": "没有账户登录。添加账户开始使用。",
"createAccount": "创建账户",
@@ -440,19 +438,5 @@
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值",
"terminal": "终端",
"globalChat": "聊天",
"globalChatWelcome": "你好! 👋",
"globalChatDescription": "随便问我什么。我在这里帮助回答问题、提供想法和进行对话。",
"clearChat": "清除聊天",
"popOutChat": "弹出窗口",
"minimizeChat": "最小化",
"typeMessage": "输入消息...",
"configureAIFirst": "请先配置AI提供商",
"globalChatEnabled": "浮动聊天按钮",
"globalChatEnabledDescription": "显示浮动聊天按钮以便快速AI对话",
"globalChatSystemPrompt": "聊天系统提示",
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示",
"building": "构建",
"chatting": "聊天"
"terminal": "终端"
}
+113 -342
View File
@@ -1,6 +1,6 @@
import { useState, useMemo } from 'react';
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit, ExternalLink, MessageCircle } from 'lucide-react';
import { Check, Bot, ArrowLeft, Trash2, GripVertical } from 'lucide-react';
import {
DndContext,
closestCenter,
@@ -25,26 +25,19 @@ import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Checkbox } from '@/components/ui/checkbox';
import { Textarea } from '@/components/ui/textarea';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Card, CardContent } from '@/components/ui/card';
import { CreditsBadge } from '@/components/CreditsBadge';
import { CreditsDialog } from '@/components/CreditsDialog';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { Separator } from '@/components/ui/separator';
import { useAISettings } from '@/hooks/useAISettings';
import { useIsMobile } from '@/hooks/useIsMobile';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useAppContext } from '@/hooks/useAppContext';
import { useNavigate, Link } from 'react-router-dom';
import type { AIProvider } from '@/contexts/AISettingsContext';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
import { ExternalFavicon } from '@/components/ExternalFavicon';
import { MCPServersSection } from '@/components/MCPServersSection';
import { PluginsSection } from '@/components/PluginsSection';
import { ProjectTemplatesSection } from '@/components/ProjectTemplatesSection';
import { defaultSystemPrompt } from '@/lib/system';
import { defaultGlobalChatSystemPrompt } from '@/lib/globalChatSystem';
interface SortableProviderItemProps {
provider: AIProvider;
@@ -100,7 +93,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
<Bot size={16} />
)}
<span className="font-medium">
{provider.name}
{preset?.name || provider.id}
</span>
<div className="ml-auto">
<CreditsBadge
@@ -113,20 +106,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${provider.id}-name`}>
{t('name')} <span className="text-destructive">*</span>
</Label>
<Input
id={`${provider.id}-name`}
placeholder={preset?.name || provider.id}
value={provider.name || ''}
onChange={(e) => onSetProvider({ ...provider, name: e.target.value })}
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${provider.id}-baseURL`}>
{t('baseUrl')} <span className="text-destructive">*</span>
</Label>
<Label htmlFor={`${provider.id}-baseURL`}>{t('baseUrl')}</Label>
<Input
id={`${provider.id}-baseURL`}
placeholder="https://api.example.com/v1"
@@ -191,24 +171,13 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
);
}
// Helper function to generate ID from name
function generateIdFromName(name: string): string {
return name
.toLowerCase()
.replace(/[^a-z0-9]+/g, '-') // Replace non-alphanumeric chars with hyphens
.replace(/^-+|-+$/g, ''); // Remove leading/trailing hyphens
}
export function AISettings() {
const { t } = useTranslation();
const { settings, setProvider, removeProvider, setProviders } = useAISettings();
const isMobile = useIsMobile();
const navigate = useNavigate();
const { user } = useCurrentUser();
const { config, defaultConfig, updateConfig } = useAppContext();
const [customProviderName, setCustomProviderName] = useState('');
const [customProviderId, setCustomProviderId] = useState('');
const [customIdManuallyEdited, setCustomIdManuallyEdited] = useState(false);
const [customBaseURL, setCustomBaseURL] = useState('');
const [customApiKey, setCustomApiKey] = useState('');
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
@@ -216,38 +185,6 @@ export function AISettings() {
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
const [presetTermsAgreements, setPresetTermsAgreements] = useState<Record<string, boolean>>({});
const [activeCreditsDialog, setActiveCreditsDialog] = useState<string | null>(null);
const [showAdvanced, setShowAdvanced] = useState(false);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
const [chatSystemPromptInput, setChatSystemPromptInput] = useState(
config.globalChatSystemPrompt || defaultGlobalChatSystemPrompt
);
// Check if system prompt differs from default
const isSystemPromptModified = useMemo(() =>
(config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
[config, defaultConfig]);
// Check if chat system prompt differs from default
const isChatSystemPromptModified = useMemo(() =>
(config.globalChatSystemPrompt || defaultGlobalChatSystemPrompt) !== defaultGlobalChatSystemPrompt,
[config]);
const restoreSystemPrompt = () => {
const defaultValue = defaultSystemPrompt;
setSystemPromptInput(defaultValue);
updateConfig((current) => {
const { systemPrompt, ...rest } = current;
return rest;
});
};
const restoreChatSystemPrompt = () => {
setChatSystemPromptInput(defaultGlobalChatSystemPrompt);
updateConfig((current) => {
const { globalChatSystemPrompt, ...rest } = current;
return rest;
});
};
const sensors = useSensors(
useSensor(PointerSensor),
@@ -264,7 +201,6 @@ export function AISettings() {
const newProvider: AIProvider = {
id: preset.id,
name: preset.name,
baseURL: preset.baseURL,
};
@@ -293,11 +229,10 @@ export function AISettings() {
};
const handleAddCustomProvider = () => {
if (!customProviderName.trim() || !customProviderId.trim() || !customBaseURL.trim()) return;
if (!customProviderName.trim() || !customBaseURL.trim()) return;
const newProvider: AIProvider = {
id: customProviderId.trim(),
name: customProviderName.trim(),
id: customProviderName.trim(),
baseURL: customBaseURL.trim(),
apiKey: customAuthMethod === 'nostr' ? undefined : customApiKey.trim(),
nostr: customAuthMethod === 'nostr' || undefined,
@@ -308,8 +243,6 @@ export function AISettings() {
setProvider(newProvider);
setCustomProviderName('');
setCustomProviderId('');
setCustomIdManuallyEdited(false);
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
@@ -352,7 +285,7 @@ export function AISettings() {
const availablePresets = AI_PROVIDER_PRESETS.filter(preset => !configuredProviderIds.includes(preset.id));
return (
<div className="p-6 space-y-6 pb-16">
<div className="p-6 space-y-6">
{isMobile && (
<div className="space-y-3">
<Button
@@ -370,7 +303,7 @@ export function AISettings() {
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
{t('aiSettingsDescription')}
{t('aiSettingsDescriptionLong')}
</p>
</div>
</div>
@@ -383,7 +316,7 @@ export function AISettings() {
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
{t('aiSettingsDescription')}
{t('aiSettingsDescriptionLong')}
</p>
</div>
)}
@@ -435,8 +368,8 @@ export function AISettings() {
const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr;
return (
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
@@ -445,101 +378,98 @@ export function AISettings() {
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button
asChild
className="w-full"
>
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : (
<div className="space-y-2">
<div className="flex gap-2">
{!preset.nostr && (
<PasswordInput
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' &&
presetApiKeys[preset.id]?.trim() &&
presetTermsAgreements[preset.id]) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
asChild
className="w-full"
onClick={() => handleAddPresetProvider(preset)}
disabled={
!presetTermsAgreements[preset.id] ||
(!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim())
}
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
>
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
{t('add')}
</Button>
</div>
) : (
<div className="space-y-2">
<div className="flex gap-2">
{!preset.nostr && (
<div className="relative flex-1">
<PasswordInput
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' &&
presetApiKeys[preset.id]?.trim() &&
presetTermsAgreements[preset.id]) {
handleAddPresetProvider(preset);
}
}}
showToggle={!!presetApiKeys[preset.id]}
/>
{preset.apiKeysURL && !presetApiKeys[preset.id] && (
<button
type="button"
className="absolute right-3 top-1/2 -translate-y-1/2 inline-flex items-center gap-1 px-2 py-1 text-xs font-medium text-muted-foreground hover:text-foreground transition-colors rounded-md hover:bg-muted"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
Get Key
<ExternalLink className="h-3 w-3" />
</button>
)}
</div>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
!presetTermsAgreements[preset.id] ||
(!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim())
}
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
</Button>
</div>
{/* Terms of Service Agreement */}
<div className="flex items-center gap-1.5">
<Checkbox
id={`agree-terms-${preset.id}`}
checked={presetTermsAgreements[preset.id] || false}
onCheckedChange={(checked) => setPresetTermsAgreements(prev => ({
...prev,
[preset.id]: checked === true,
}))}
className="size-3 [&_svg]:size-3"
/>
<label
htmlFor={`agree-terms-${preset.id}`}
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
{preset.tosURL ? (
<a
href={preset.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-muted-foreground underline hover:text-foreground hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
{t('termsOfService')}
</a>
) : (
t('termsOfService')
)}
</label>
</div>
{/* Terms of Service Agreement */}
<div className="flex items-center gap-1.5">
<Checkbox
id={`agree-terms-${preset.id}`}
checked={presetTermsAgreements[preset.id] || false}
onCheckedChange={(checked) => setPresetTermsAgreements(prev => ({
...prev,
[preset.id]: checked === true,
}))}
className="size-3 [&_svg]:size-3"
/>
<label
htmlFor={`agree-terms-${preset.id}`}
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
>
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
{preset.tosURL ? (
<a
href={preset.tosURL}
target="_blank"
rel="noopener noreferrer"
className="text-muted-foreground underline hover:text-foreground hover:no-underline"
onClick={(e) => e.stopPropagation()}
>
{t('termsOfService')}
</a>
) : (
t('termsOfService')
)}
</label>
</div>
)}
</CardContent>
</Card>
</div>
)}
</div>
);
})}
</div>
@@ -549,54 +479,23 @@ export function AISettings() {
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider">
<AccordionItem value="custom-provider" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</div>
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid grid-cols-2 gap-3">
<div className="grid gap-2">
<Label htmlFor="custom-name">
{t('name')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-name"
placeholder="e.g., My Custom API"
value={customProviderName}
onChange={(e) => {
const newName = e.target.value;
setCustomProviderName(newName);
// Auto-generate ID from name if ID hasn't been manually edited
if (!customIdManuallyEdited) {
setCustomProviderId(generateIdFromName(newName));
}
}}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-id">
{t('id')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-id"
placeholder="e.g., my-custom-api"
value={customProviderId}
onChange={(e) => {
setCustomProviderId(e.target.value);
setCustomIdManuallyEdited(true);
}}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-name">{t('providerName')}</Label>
<Input
id="custom-name"
placeholder="e.g., my-custom-api"
value={customProviderName}
onChange={(e) => setCustomProviderName(e.target.value)}
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">
{t('baseUrl')} <span className="text-destructive">*</span>
</Label>
<Label htmlFor="custom-baseurl">{t('baseUrl')}</Label>
<Input
id="custom-baseurl"
placeholder="https://api.example.com/v1"
@@ -649,16 +548,15 @@ export function AISettings() {
onClick={handleAddCustomProvider}
disabled={
!customProviderName.trim() ||
!customProviderId.trim() ||
!customBaseURL.trim() ||
settings.providers.some(p => p.id === customProviderId.trim())
settings.providers.some(p => p.id === customProviderName.trim())
}
className="gap-2 ml-auto"
>
<Check className="h-4 w-4" />
{t('addCustomProviderButton')}
</Button>
{settings.providers.some(p => p.id === customProviderId.trim()) && (
{settings.providers.some(p => p.id === customProviderName.trim()) && (
<p className="text-sm text-destructive">
{t('providerExists')}
</p>
@@ -669,138 +567,11 @@ export function AISettings() {
</Accordion>
</div>
{/* Advanced Settings */}
<div className="space-y-4">
<Separator className="my-6" />
<button
type="button"
onClick={() => setShowAdvanced(!showAdvanced)}
className="flex items-center gap-2 text-sm text-muted-foreground hover:text-foreground transition-colors"
>
<span>{t('advanced')}</span>
<ChevronDown
className={`h-4 w-4 transition-transform ${showAdvanced ? 'rotate-180' : ''}`}
/>
</button>
{/* MCP Servers Section */}
<MCPServersSection />
{showAdvanced && (
<div className="space-y-6">
{/* Project Templates Section */}
<ProjectTemplatesSection />
<Separator />
{/* MCP Servers Section */}
<MCPServersSection />
<Separator />
{/* Plugins Section */}
<PluginsSection />
<Separator />
{/* System Prompt Configuration */}
<div className="space-y-4">
<div className="space-y-2">
<div className="flex items-center gap-2">
<FileText className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('systemPrompts')}</h3>
{(isSystemPromptModified || isChatSystemPromptModified) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<p className="text-sm text-muted-foreground">
{t('systemPromptsDescription')}
</p>
</div>
<Accordion type="single" collapsible className="w-full space-y-2">
<AccordionItem value="system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Edit className="h-4 w-4" />
<span className="font-medium">{t('projectSystemPrompt')}</span>
{isSystemPromptModified && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-2">
<p className="text-xs text-muted-foreground mb-2">
{t('projectSystemPromptDescription')}
</p>
<Textarea
id="system-prompt"
placeholder="Enter Nunjucks template..."
value={systemPromptInput}
onChange={(e) => {
const value = e.target.value;
setSystemPromptInput(value);
updateConfig((current) => ({
...current,
systemPrompt: value,
}));
}}
className="flex-1 font-mono text-xs min-h-[400px]"
/>
{isSystemPromptModified && (
<Button
variant="outline"
onClick={restoreSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
</div>
</AccordionContent>
</AccordionItem>
<AccordionItem value="chat-system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<MessageCircle className="h-4 w-4" />
<span className="font-medium">{t('globalChatSystemPrompt')}</span>
{isChatSystemPromptModified && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-2">
<p className="text-xs text-muted-foreground mb-2">
{t('globalChatSystemPromptDescription')}
</p>
<Textarea
id="chat-system-prompt"
placeholder="Enter system prompt..."
value={chatSystemPromptInput}
onChange={(e) => {
const value = e.target.value;
setChatSystemPromptInput(value);
updateConfig((current) => ({
...current,
globalChatSystemPrompt: value,
}));
}}
className="flex-1 font-mono text-xs min-h-[300px]"
/>
{isChatSystemPromptModified && (
<Button
variant="outline"
onClick={restoreChatSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
)}
</div>
{/* Plugins Section */}
<PluginsSection />
</div>
{/* Render credits dialog outside of accordion structure */}
+18 -23
View File
@@ -5,7 +5,6 @@ import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code, Globe } fr
import { Button } from '@/components/ui/button';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Card, CardContent } from '@/components/ui/card';
import { useIsMobile } from '@/hooks/useIsMobile';
import { EmailSubscription } from '@/components/EmailSubscription';
@@ -86,10 +85,10 @@ export function AboutSettings() {
<div className="space-y-3">
{/* Mirrors */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="mirrors">
<AccordionItem value="mirrors" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Globe className="size-5 text-muted-foreground" />
<Globe className="h-5 w-5" />
{t('mirrors')}
</div>
</AccordionTrigger>
@@ -103,7 +102,7 @@ export function AboutSettings() {
>
<a href="https://shakespeare.diy" target="_blank" rel="noopener noreferrer">
<span className="font-mono text-sm">shakespeare.diy</span>
<ExternalLink className="ml-auto h-4 w-4 text-muted-foreground" />
<ExternalLink className="ml-auto h-4 w-4" />
</a>
</Button>
<Button
@@ -113,7 +112,7 @@ export function AboutSettings() {
>
<a href="https://shakespeare-diy.github.io" target="_blank" rel="noopener noreferrer">
<span className="font-mono text-sm">shakespeare-diy.github.io</span>
<ExternalLink className="ml-auto h-4 w-4 text-muted-foreground" />
<ExternalLink className="ml-auto h-4 w-4" />
</a>
</Button>
<Button
@@ -123,7 +122,7 @@ export function AboutSettings() {
>
<a href="https://shakespeare-b0b9c8.gitlab.io" target="_blank" rel="noopener noreferrer">
<span className="font-mono text-sm">shakespeare-b0b9c8.gitlab.io</span>
<ExternalLink className="ml-auto h-4 w-4 text-muted-foreground" />
<ExternalLink className="ml-auto h-4 w-4" />
</a>
</Button>
</div>
@@ -132,28 +131,24 @@ export function AboutSettings() {
</Accordion>
{/* Project Information */}
<Card>
<CardContent className="p-0">
<Button
variant="ghost"
className="w-full h-12 flex items-center gap-2 justify-start text-base"
asChild
>
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
<Code className="!size-5 text-muted-foreground" />
{t('sourceCode')}
<ExternalLink className="ml-auto" />
</a>
</Button>
</CardContent>
</Card>
<Button
variant="outline"
className="w-full h-12 flex items-center gap-2 justify-start text-base"
asChild
>
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
<Code className="!size-5" />
{t('sourceCode')}
<ExternalLink className="ml-auto" />
</a>
</Button>
{/* License */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="license-text">
<AccordionItem value="license-text" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Info className="size-5 text-muted-foreground" />
<Info className="h-5 w-5" />
{t('license')}
</div>
</AccordionTrigger>
-135
View File
@@ -10,14 +10,6 @@ import { useToast } from '@/hooks/useToast';
import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useSeoMeta } from '@unhead/react';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useUserRepositories } from '@/hooks/useUserRepositories';
import { useContacts } from '@/hooks/useContacts';
import { useFollowedRepositories } from '@/hooks/useFollowedRepositories';
import { RepositoryCard } from '@/components/RepositoryCard';
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
export default function Clone() {
const { t } = useTranslation();
@@ -30,11 +22,6 @@ export default function Clone() {
const { toast } = useToast();
const autoCloneInitiatedRef = useRef(false);
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const { user } = useCurrentUser();
const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey);
const { data: contacts = [] } = useContacts(user?.pubkey);
const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts);
const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('my-projects');
useSeoMeta({
title: `${t('importRepository')} - Shakespeare`,
@@ -289,128 +276,6 @@ export default function Clone() {
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
{/* NIP-34 Repositories with Tabs */}
{user && (
<div className="mt-16 max-w-7xl mx-auto">
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'my-projects' | 'follows')}>
<TabsList className="mb-6">
<TabsTrigger value="my-projects">
My Projects
</TabsTrigger>
<TabsTrigger value="follows">
Follows
</TabsTrigger>
</TabsList>
<TabsContent value="my-projects">
{isLoadingRepos ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 3 }).map((_, i) => (
<Card key={i} className="h-full flex flex-col">
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start gap-3 mb-4">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-4 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-9 flex-1" />
<Skeleton className="h-9 w-9" />
</div>
</CardContent>
</Card>
))}
</div>
) : repositories.length > 0 ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{repositories.map((repo) => (
<RepositoryCard key={repo.id} repo={repo} />
))}
</div>
) : (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
No repositories found. Publish your first repository to Nostr to see it here.
</p>
</div>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="follows">
{isLoadingFollowedRepos ? (
<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">
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start gap-3 mb-4">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-4 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-9 flex-1" />
<Skeleton className="h-9 w-9" />
</div>
</CardContent>
</Card>
))}
</div>
) : followedRepositories.length > 0 ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{followedRepositories.map((repo) => (
<RepositoryCard key={repo.id} repo={repo} />
))}
</div>
) : contacts.length > 0 ? (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
None of the people you follow have published repositories yet.
</p>
</div>
</CardContent>
</Card>
) : (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
You're not following anyone yet. Follow people on Nostr to see their repositories here.
</p>
</div>
</CardContent>
</Card>
)}
</TabsContent>
</Tabs>
</div>
)}
</AppLayout>
);
}
Loaded 100 of 112 files, more files were not shown because too many files have changed in this diff. Show more