Compare commits

..
60 Commits
Author SHA1 Message Date
MK Fain e23c843ef9 Fix GlobalChatProvider parseProviderModel usage
The parseProviderModel function returns { model, provider } but the code
was trying to destructure { providerId, modelId }. Fixed to correctly
use the actual return values and pass the required providers array
parameter to the function.
2025-12-03 20:10:18 -06:00
MK Fain 0c4de2e2c0 Fix global chat issues and move chat system prompt setting
1. Fixed user message not appearing in global chat
2. Made project chat and global chat remember separate models
   - Added separate localStorage storage for global chat model
   - Project chat continues to use recentlyUsedModels from AISettings
   - Global chat now stores its model independently
3. Moved Chat System Prompt setting from Preferences to System Settings
4. Removed chat pop-out functionality
   - Removed isPoppedOut state from GlobalChatContext
   - Removed handlePopOut function from GlobalChatPane
   - Removed pop-out button from desktop chat header
   - Removed isPoppedOut check from FloatingChatButton
2025-12-03 20:03:53 -06:00
MK Fain 477d055797 Improve unread message indicator for floating chat
- Add hasUnread state to track whether user has seen new messages
- Mark messages as read when chat is opened
- Mark as unread when assistant responds while chat is closed
- Change indicator from message count to simple dot for cleaner UX
2025-12-03 19:50:10 -06:00
MK Fain 15c8040e35 Fix: Move FloatingChatButton and GlobalChatPane inside Router
The ModelSelector component uses useNavigate which requires Router context.
Move the floating chat components from App.tsx into AppRouter.tsx where
they have access to the BrowserRouter/HashRouter context.
2025-12-03 19:47:29 -06:00
MK Fain 68702abc41 Add floating global chat feature
- Add GlobalChatContext, GlobalChatProvider for managing chat state
- Create FloatingChatButton component with unread message indicator
- Create GlobalChatPane with desktop (floating panel) and mobile (full screen) views
- Features include:
  - Streaming AI responses with markdown rendering
  - Auto context trimming when messages exceed ~50k tokens
  - Easy text copy from messages (hover to reveal copy button)
  - Pop-out to separate window
  - Minimize/dismiss functionality
  - Clear chat history
  - Mobile-optimized full-screen drawer
- Add settings in Preferences page:
  - Enable/disable floating chat button
  - Customize chat system prompt
- Add translations for all supported languages (en, pt, zh, ha, yo, ig)
- Integrate with existing AI provider configuration
2025-12-03 19:44:12 -06:00
Alex Gleason f41d70442a Prevent the Nostr settings dialog from refreshing 2025-12-03 17:06:29 -06:00
Alex Gleason 6f94aaa45e Allow editing t-tags on Nostr repos 2025-12-03 16:40:01 -06:00
Alex Gleason a2ffc7bf9c Display provider favicon in Add Provider dialog 2025-12-03 12:49:45 -06:00
Alex Gleason 4bc223e5af Revert "Merge branch 'text-chats' into 'main'"
This reverts commit 7badd0113f, reversing
changes made to 02dcd5cbe8.
2025-12-03 12:01:53 -06:00
Alex Gleason 2179c8fdce Revert "Don't display toast on own chat page"
This reverts commit 00b476085d.
2025-12-03 12:00:09 -06:00
Alex Gleason 00b476085d Don't display toast on own chat page 2025-12-03 02:47:11 -06:00
Alex Gleason 7badd0113f Merge branch 'text-chats' into 'main'
Text chats

See merge request soapbox-pub/shakespeare!79
2025-12-03 08:40:15 +00:00
Alex Gleason b3f47d41cb Don't use flexible sidebar in ChatView 2025-12-03 02:36:40 -06:00
Alex Gleason 8cf2b8a9d4 Display spinner for text chats 2025-12-03 02:31:13 -06:00
Alex Gleason f8743e3c63 Fix chat autostart 2025-12-03 02:25:28 -06:00
Alex Gleason ca0ae22cd3 Add start_project tool to text chats 2025-12-03 02:00:47 -06:00
Alex Gleason 01df64fce0 No useless escape 2025-12-03 01:53:05 -06:00
Alex Gleason 300fd26268 Add max width to text chats 2025-12-03 01:51:29 -06:00
Alex Gleason 0c42af082a Improve Chat Not Found design 2025-12-03 01:41:10 -06:00
Alex Gleason 4f552334b2 Allow deleting a chat 2025-12-03 01:40:28 -06:00
Alex Gleason bb9245118c Refresh sidebar when starting new chat, allow more characters in chat title 2025-12-03 01:33:34 -06:00
Alex Gleason 2c42efd4e1 Skip somethings for chats idk 2025-12-03 01:27:37 -06:00
Alex Gleason d3187d8c77 Improve chats icon 2025-12-03 01:11:39 -06:00
Alex Gleason ab039d2fb7 Text chats 2025-12-03 01:05:00 -06:00
Alex Gleason 02dcd5cbe8 Add Git Identity icon 2025-12-03 00:37:22 -06:00
Alex Gleason 69d8dfa9cd Add asterisks near required fields in Settings forms 2025-12-03 00:33:05 -06:00
Alex Gleason 43ad67b048 Add icons to Settings pages 2025-12-03 00:25:12 -06:00
Alex Gleason 5d1e2ddea0 Add "Vibed with Shakespeare" to system prompt 2025-12-02 20:29:53 -06:00
Alex Gleason e83ff56722 Fix CreditsDialog padding 2025-12-02 13:39:59 -06:00
Alex Gleason 56d9bca5c7 Increment the generated project id instead of falling back to untitled 2025-12-01 23:47:06 -06:00
Alex Gleason 89244d88e5 Fix updating templates 2025-12-01 23:34:06 -06:00
Alex Gleason 2096d526c4 Load skills from project dir in addition to plugins 2025-12-01 23:19:02 -06:00
Alex Gleason 367a6834eb typecheck fixes 2025-12-01 21:06:47 -06:00
Alex Gleason 9ede6bbd21 Provider name is a required field - backfill it when parsing config 2025-12-01 20:51:38 -06:00
Alex Gleason c1ad18bab7 Display nice model name in ModeleSelector if it's available 2025-12-01 17:52:18 -06:00
Alex Gleason 0e27c4d394 Display provider favicons instead of fullId in ModelSelector 2025-12-01 17:32:41 -06:00
Alex Gleason cd77a8edd5 Add background color to Nostr accounts in settings 2025-12-01 17:22:23 -06:00
Alex Gleason e05baee1f4 Allow setting AI Provider display name 2025-12-01 17:19:34 -06:00
Alex Gleason efbfd19f10 Started with -> Vibing with 2025-12-01 16:46:14 -06:00
Alex Gleason f256de7ab3 Improve icons in About Shakespeare page 2025-12-01 16:42:13 -06:00
Alex Gleason 5d65638f32 Improve icons in AI settings 2025-12-01 16:37:34 -06:00
Alex Gleason 2e65e1ee6c Improve design of Nostr settings 2025-12-01 16:32:30 -06:00
Alex Gleason dfc372e1d4 Preferences design improvements 2025-12-01 16:26:19 -06:00
Alex Gleason e8c3406e55 Add icons to all accordions in System settings 2025-12-01 16:21:00 -06:00
Alex Gleason 0a191be435 Let the system prompt be managed on the AI settings page 2025-12-01 16:12:21 -06:00
Alex Gleason 40062b6b92 Add Advanced section to bottom of AI Settings 2025-12-01 16:02:06 -06:00
Alex Gleason 6540ab28e6 Improve project templates description 2025-12-01 15:41:30 -06:00
Alex Gleason 93ae204e5e Improve design of mobile settings navigation 2025-12-01 15:38:12 -06:00
Alex Gleason 2c9e8abf5d Let project templates be re-ordered and reset to default 2025-12-01 15:36:06 -06:00
Alex Gleason b47f715362 Remove unnecessary empty states from AI settings sub-sections 2025-12-01 15:24:39 -06:00
Alex Gleason eadb628094 Fix linter issues 2025-12-01 15:21:23 -06:00
Alex Gleason db05223c68 Move project templates to AI settings 2025-12-01 15:18:34 -06:00
Alex Gleason 0a20d736ab Small system prompt tweaks 2025-12-01 15:08:29 -06:00
Alex Gleason fe0becb2c8 Expose templates to the system prompt 2025-12-01 14:59:24 -06:00
Alex Gleason 6941710a3d Clarify that mkstack should be chosen when the assistant isn't sure 2025-12-01 14:37:30 -06:00
Alex Gleason b67417115c Display template used to start project at top of messages history 2025-12-01 14:36:58 -06:00
Alex Gleason 23ad0a9d35 Remember the chosen project template 2025-12-01 14:26:58 -06:00
Alex Gleason 7112591aa3 Use textarea for template description 2025-12-01 14:05:46 -06:00
Alex Gleason 8a65c76197 Add nutstack and luvstack 2025-12-01 13:57:30 -06:00
Alex Gleason 009142b854 Allow multiple project templates to be configured 2025-12-01 13:20:25 -06:00
74 changed files with 4008 additions and 1751 deletions

No files matched your search

@@ -38,14 +38,7 @@ class JSONRPCClient {
}
}
/**
* Generic JSON-RPC call method
* @param {string} method - The RPC method name
* @param {object} params - Parameters for the method
* @param {number} timeout - Timeout in milliseconds (default: 10000)
* @returns {Promise} - Resolves with the result or rejects with error
*/
async call(method, params, timeout = 10000) {
async fetch(request) {
const id = ++this.requestId;
return new Promise((resolve, reject) => {
@@ -54,25 +47,21 @@ class JSONRPCClient {
// Send JSON-RPC request to parent
window.parent.postMessage({
jsonrpc: "2.0",
method,
params,
method: "fetch",
params: { request },
id,
}, "*");
// Timeout handling
// Timeout after 10 seconds
setTimeout(() => {
if (this.pendingRequests.has(id)) {
this.pendingRequests.delete(id);
reject(new Error(`RPC call to ${method} with ID ${id} timed out`));
reject(new Error(`Timeout fetching: ${request.url}`));
}
}, timeout);
}, 10000);
});
}
async fetch(request) {
return this.call("fetch", { request }, 10000);
}
handleResponse(message) {
const { id, result, error } = message;
const pending = this.pendingRequests.get(id);
@@ -164,38 +153,6 @@ class ConsoleInterceptor {
}
}
// Nostr Bridge - proxies window.nostr calls to parent window
class NostrBridge {
constructor(rpcClient) {
this.rpcClient = rpcClient;
console.log('[NostrBridge] initializing...');
this.injectNostr();
}
injectNostr() {
// Create the window.nostr object
window.nostr = {
getPublicKey: () => this.callNostrMethod('getPublicKey', []),
signEvent: (event) => this.callNostrMethod('signEvent', [event]),
nip04: {
encrypt: (pubkey, plaintext) => this.callNostrMethod('nip04.encrypt', [pubkey, plaintext]),
decrypt: (pubkey, ciphertext) => this.callNostrMethod('nip04.decrypt', [pubkey, ciphertext]),
},
nip44: {
encrypt: (pubkey, plaintext) => this.callNostrMethod('nip44.encrypt', [pubkey, plaintext]),
decrypt: (pubkey, ciphertext) => this.callNostrMethod('nip44.decrypt', [pubkey, ciphertext]),
},
};
console.log('[NostrBridge] window.nostr injected');
}
async callNostrMethod(method, args) {
// Use the generic RPC client call method
// Extension prompts may take time, so use 30 second timeout
return this.rpcClient.call('nostr', { method, args }, 30000);
}
}
// Navigation Handler - manages iframe navigation and history
class NavigationHandler {
constructor() {
@@ -362,8 +319,8 @@ class NavigationHandler {
// Main Fetch Client
class FetchClient {
constructor(rpcClient) {
this.rpcClient = rpcClient;
constructor() {
this.rpcClient = new JSONRPCClient();
this.consoleInterceptor = new ConsoleInterceptor();
this.navigationHandler = new NavigationHandler();
this.init();
@@ -436,8 +393,8 @@ class FetchClient {
active: navigator.serviceWorker.controller,
installing: null,
waiting: null,
addEventListener: () => { },
removeEventListener: () => { },
addEventListener: () => {},
removeEventListener: () => {},
});
};
}
@@ -612,14 +569,8 @@ const setupGlobalErrorHandlers = () => {
// Initialize
setupGlobalErrorHandlers();
const init = () => {
const rpcClient = new JSONRPCClient();
new FetchClient(rpcClient);
new NostrBridge(rpcClient);
}
if (document.readyState === "loading") {
document.addEventListener("DOMContentLoaded", init);
document.addEventListener("DOMContentLoaded", () => new FetchClient());
} else {
init();
}
new FetchClient();
}
+29 -10
View File
@@ -28,6 +28,7 @@ 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';
@@ -106,7 +107,23 @@ const defaultConfig: AppConfig = {
],
updatedAt: 0,
},
projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git",
templates: [
{
name: "MKStack",
description: "Build Nostr clients with React. This is the default template that you should choose in the majority of cases. It ships with complete Nostr integration out of the box, enabling a variety of use-cases from social media to blogging to AI-powered apps. If you're not sure which template to choose, choose this one.",
url: "https://gitlab.com/soapbox-pub/mkstack.git",
},
{
name: "Nutstack",
description: "This is a variant of MKStack extended to support Cashu integration. Choose this template only if the user has indicated they require Cashu integration.",
url: "https://gitlab.com/lemonknowsall/nutstack.git",
},
{
name: "Luvstack",
description: "Barebones React template. Choose this to build mockups or demo sites that don't require Nostr functionality. Only choose this if the user has indicated they want to create a demo or mockup site, as it cannot support any sort of backend functionality or remote storage. It might also work for simple PWAs.",
url: "https://gitlab.com/soapbox-pub/luvstack.git",
}
],
esmUrl: "https://esm.sh",
corsProxy: "https://proxy.shakespeare.diy/?url={href}",
faviconUrl: "https://favicon.shakespeare.diy/?url={href}",
@@ -161,15 +178,17 @@ export function App() {
<GitSettingsProvider>
<DeploySettingsProvider>
<SessionManagerProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
<GlobalChatProvider>
<TooltipProvider>
<Toaster />
<DynamicFavicon />
<OfflineIndicator />
<PWAUpdatePrompt />
<Suspense>
<AppRouter />
</Suspense>
</TooltipProvider>
</GlobalChatProvider>
</SessionManagerProvider>
</DeploySettingsProvider>
</GitSettingsProvider>
+5
View File
@@ -2,6 +2,8 @@ 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";
@@ -56,6 +58,9 @@ 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,6 +125,7 @@ describe('AISettingsProvider', () => {
providers: [
{
id: 'openrouter',
name: 'OpenRouter',
baseURL: 'https://openrouter.ai/api/v1',
apiKey: 'test-key'
}
@@ -173,6 +174,7 @@ describe('AISettingsProvider', () => {
providers: [
{
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key'
}
+10 -1
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 { getShakespeareProvider } from '@/lib/aiProviderPresets';
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
interface Act1DialogProps {
open: boolean;
@@ -14,6 +14,15 @@ 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,6 +8,7 @@ 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',
};
@@ -92,6 +93,7 @@ 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',
};
@@ -114,6 +116,7 @@ describe('AddProviderDialog', () => {
const onOpenChange = vi.fn();
const customProvider: AIProvider = {
id: 'my-custom-provider',
name: 'My Custom Provider',
baseURL: 'https://api.custom.com/v1',
};
+6 -1
View File
@@ -5,6 +5,7 @@ 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 {
@@ -156,7 +157,11 @@ 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">
<Sparkles className="h-8 w-8 text-primary" />
<ExternalFavicon
url={provider.baseURL}
size={32}
fallback={<Sparkles className="h-8 w-8 text-primary" />}
/>
</div>
<div className="text-center space-y-2">
<h2 className="text-2xl font-bold">{providerName}</h2>
+8 -1
View File
@@ -22,11 +22,18 @@ 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,
projectTemplate: z.string().url(),
templates: z.array(ProjectTemplateSchema),
esmUrl: z.string().url(),
corsProxy: z.string().url(),
faviconUrl: z.string().url(),
+1
View File
@@ -17,6 +17,7 @@ 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,6 +9,7 @@ global.fetch = vi.fn();
const mockProvider: AIProvider = {
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com/v1',
apiKey: 'test-key',
nostr: false,
+21 -21
View File
@@ -1004,17 +1004,17 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</div>
) : (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<Accordion type="multiple" defaultValue={["add"]} className="w-full">
<Accordion type="multiple" defaultValue={["add"]} className="w-full space-y-2">
{/* Buy Credits Accordion */}
<AccordionItem value="add">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<DollarSign className="h-4 w-4" />
<DollarSign className="h-4 w-4 text-muted-foreground" />
{t('buyCredits')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<div className="space-y-3">
<Label htmlFor="amount" className="text-sm font-medium">{t('amountUSD')}</Label>
<div className="space-y-3">
@@ -1098,14 +1098,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Transaction History Accordion */}
<AccordionItem value="history">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<History className="h-4 w-4" />
<History className="h-4 w-4 text-muted-foreground" />
{t('recentTransactions')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="pt-2">
<AccordionContent className="px-4">
<div className="pt-2 pb-3">
{isLoadingPayments ? (
<div className="p-3 border rounded-lg space-y-2">
<div className="flex items-center gap-2">
@@ -1190,14 +1190,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Redeem Gift Card Accordion */}
<AccordionItem value="redeem">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<Plus className="h-4 w-4 text-muted-foreground" />
{t('redeemGiftCard')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<div className="flex gap-2">
<Input
id="redeem-code"
@@ -1222,14 +1222,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Create Gift Card Accordion */}
<AccordionItem value="create">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<Gift className="h-4 w-4" />
<Gift className="h-4 w-4 text-muted-foreground" />
{t('createGiftCard')}
</div>
</AccordionTrigger>
<AccordionContent>
<div className="space-y-3 pt-2">
<AccordionContent className="px-4">
<div className="space-y-3 pt-2 pb-3">
<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>
@@ -1286,14 +1286,14 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
{/* Your Gift Cards Accordion */}
<AccordionItem value="list">
<AccordionTrigger className="hover:no-underline">
<AccordionTrigger className="hover:no-underline px-4 py-3">
<div className="flex items-center gap-2">
<CreditCard className="h-4 w-4" />
<CreditCard className="h-4 w-4 text-muted-foreground" />
{t('yourGiftCards')}
</div>
</AccordionTrigger>
<AccordionContent className="pb-0">
<div className="pt-2 space-y-3">
<AccordionContent className="px-4">
<div className="pt-2 pb-3 space-y-3">
{giftcards && giftcards.filter(gc => !gc.redeemed).length > 0 && (
<div className="grid grid-cols-2 gap-2">
<Button
+36
View File
@@ -0,0 +1,36 @@
import { MessageCircle } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { useGlobalChat } from '@/hooks/useGlobalChat';
import { useAppContext } from '@/hooks/useAppContext';
import { cn } from '@/lib/utils';
export function FloatingChatButton() {
const { isOpen, setIsOpen, hasUnread } = useGlobalChat();
const { config } = useAppContext();
// Don't render if disabled in settings
if (config.globalChatEnabled === false) {
return null;
}
return (
<Button
onClick={() => setIsOpen(!isOpen)}
size="lg"
className={cn(
'fixed bottom-6 right-6 z-40 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>
);
}
+1
View File
@@ -164,6 +164,7 @@ export function GiftCardRedeemDialog({ open, onOpenChange, baseURL, code }: Gift
const providerConfig = {
id: matchingPreset.id,
name: matchingPreset.name,
baseURL: matchingPreset.baseURL,
nostr: matchingPreset.nostr || undefined,
};
+410
View File
@@ -0,0 +1,410 @@
import { useState, useRef, useEffect, useCallback } from 'react';
import { useTranslation } from 'react-i18next';
import { X, Minimize2, Trash2, Copy, Check, ChevronDown, ArrowUp, Square, Loader2 } 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>
);
}
export function GlobalChatPane() {
const { t } = useTranslation();
const {
messages,
isOpen,
isLoading,
sendMessage,
stopGeneration,
clearMessages,
setIsOpen,
providerModel,
setProviderModel,
} = useGlobalChat();
const { config } = useAppContext();
const { settings } = useAISettings();
const isMobile = useIsMobile();
const [input, setInput] = useState('');
const [showScrollToBottom, setShowScrollToBottom] = useState(false);
const scrollAreaRef = useRef<HTMLDivElement>(null);
const textareaRef = useRef<HTMLTextAreaElement>(null);
// Initialize provider model from settings if not set
useEffect(() => {
if (!providerModel && settings.recentlyUsedModels?.length) {
setProviderModel(settings.recentlyUsedModels[0]);
}
}, [providerModel, settings.recentlyUsedModels, setProviderModel]);
// Auto-scroll to bottom when new messages arrive
useEffect(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
if (isNearBottom || messages.length <= 1) {
container.scrollTop = container.scrollHeight;
}
}
}, [messages]);
// Handle scroll to show/hide scroll-to-bottom button
const handleScroll = useCallback(() => {
if (scrollAreaRef.current) {
const container = scrollAreaRef.current;
const isNearBottom = container.scrollTop + container.clientHeight >= container.scrollHeight - 100;
setShowScrollToBottom(!isNearBottom && messages.length > 0);
}
}, [messages.length]);
const scrollToBottom = useCallback(() => {
if (scrollAreaRef.current) {
scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight;
}
}, []);
const handleSend = useCallback(async () => {
if (!input.trim() || isLoading || !providerModel) return;
const messageContent = input.trim();
setInput('');
await sendMessage(messageContent, providerModel);
// Focus back on textarea
textareaRef.current?.focus();
}, [input, isLoading, providerModel, sendMessage]);
const handleKeyDown = useCallback((e: React.KeyboardEvent<HTMLTextAreaElement>) => {
if (e.key === 'Enter' && !e.shiftKey && !isMobile) {
e.preventDefault();
handleSend();
}
}, [handleSend, isMobile]);
// Don't render if disabled or not open
if (config.globalChatEnabled === false || !isOpen) {
return null;
}
const hasProviders = settings.providers.length > 0;
// 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)}
>
<Minimize2 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>
);
}
+211
View File
@@ -0,0 +1,211 @@
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';
// Maximum context size in characters (approximately 50k tokens worth)
// This leaves room for the system prompt and response
const MAX_CONTEXT_CHARS = 150000;
// Default system prompt for global chat
const DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT = `You are a helpful AI assistant. 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.`;
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);
// 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) => {
if (!content.trim() || isLoading) return;
// 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 trim if necessary
setMessages(prev => trimMessages([...prev, userMessage]));
setIsLoading(true);
// Create abort controller for this request
abortControllerRef.current = new AbortController();
try {
// Create AI client
const client = createAIClient(provider, config.corsProxy, user?.signer);
// Build messages for API
const systemPrompt = config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT;
const apiMessages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = [
{ role: 'system', content: systemPrompt },
...messages.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;
});
}
// 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 {
setIsLoading(false);
abortControllerRef.current = null;
}
}, [config.corsProxy, config.globalChatSystemPrompt, isLoading, messages, settings.providers, trimMessages, user?.signer]);
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,6 +21,7 @@ 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,
+17 -18
View File
@@ -6,8 +6,6 @@ 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';
@@ -192,9 +190,6 @@ 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">
@@ -207,14 +202,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-primary" />
<Server size={16} className="text-muted-foreground" />
<span className="font-medium">{name}</span>
<MCPConnectionStatus server={server} />
</div>
@@ -222,7 +217,9 @@ 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')}</Label>
<Label htmlFor={`${name}-type`}>
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={server.type} disabled>
<SelectTrigger>
<SelectValue />
@@ -233,7 +230,9 @@ export function MCPServersSection() {
</Select>
</div>
<div className="grid gap-2">
<Label htmlFor={`${name}-url`}>{t('mcpServerUrl')}</Label>
<Label htmlFor={`${name}-url`}>
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id={`${name}-url`}
value={server.url}
@@ -259,12 +258,6 @@ export function MCPServersSection() {
</Accordion>
))}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noMcpServersConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add New MCP Server */}
@@ -282,7 +275,9 @@ export function MCPServersSection() {
{t('mcpServerDescription')}
</p>
<div className="grid gap-2">
<Label htmlFor="new-server-name">{t('mcpServerName')}</Label>
<Label htmlFor="new-server-name">
{t('mcpServerName')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-name"
placeholder="e.g., my-mcp-server"
@@ -291,7 +286,9 @@ export function MCPServersSection() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-type">{t('mcpServerType')}</Label>
<Label htmlFor="new-server-type">
{t('mcpServerType')} <span className="text-destructive">*</span>
</Label>
<Select value={serverType} disabled>
<SelectTrigger>
<SelectValue />
@@ -305,7 +302,9 @@ export function MCPServersSection() {
</p>
</div>
<div className="grid gap-2">
<Label htmlFor="new-server-url">{t('mcpServerUrl')}</Label>
<Label htmlFor="new-server-url">
{t('mcpServerUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="new-server-url"
placeholder="https://example.com/mcp"
+35 -12
View File
@@ -81,7 +81,14 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
settings: {
providers: [
{ id: 'provider1', name: 'Provider 1', baseURL: 'https://api.provider1.com' },
{ id: 'provider2', name: 'Provider 2', baseURL: 'https://api.provider2.com' },
],
recentlyUsedModels,
mcpServers: {},
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
@@ -105,7 +112,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider2')).toBeInTheDocument();
expect(screen.getByText('Provider 2')).toBeInTheDocument();
});
// Recently used section should NOT be visible
@@ -114,8 +121,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
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
// provider2 should still show with model3 (just the model ID, not the full ID)
expect(screen.getByText('model3')).toBeInTheDocument();
});
it('shows recently used section when less than 5 models but some recently used are not available', async () => {
@@ -136,7 +143,15 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
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: {},
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
@@ -160,7 +175,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider1')).toBeInTheDocument();
expect(screen.getByText('Provider 1')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
@@ -187,7 +202,15 @@ describe('ModelSelector', () => {
});
mockUseAISettings.mockReturnValue({
settings: { providers: [], recentlyUsedModels },
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: {},
},
addRecentlyUsedModel: mockAddRecentlyUsedModel,
isConfigured: true,
updateSettings: vi.fn(),
@@ -211,7 +234,7 @@ describe('ModelSelector', () => {
// Wait for the dropdown to open
await waitFor(() => {
expect(screen.getByText('provider2')).toBeInTheDocument();
expect(screen.getByText('Provider 2')).toBeInTheDocument();
});
// Recently used section SHOULD be visible
@@ -220,10 +243,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
expect(screen.getByText('provider2/model3')).toBeInTheDocument();
expect(screen.getByText('provider2/model4')).toBeInTheDocument();
expect(screen.getByText('provider3/model5')).toBeInTheDocument();
// provider2 and provider3 should still show (just the model IDs, not full IDs)
expect(screen.getByText('model3')).toBeInTheDocument();
expect(screen.getByText('model4')).toBeInTheDocument();
expect(screen.getByText('model5')).toBeInTheDocument();
});
it('hides recently used section when no recently used models exist', async () => {
+106 -31
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 } from 'lucide-react';
import { Check, ChevronDown, Edit3, RefreshCw, AlertCircle, Settings, TriangleAlert, Bot } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
@@ -12,6 +12,7 @@ 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 {
@@ -72,6 +73,33 @@ 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
@@ -278,13 +306,31 @@ export const ModelSelector = memo(function ModelSelector({
role="combobox"
aria-expanded={open}
className={cn(
"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]"
"h-8 p-0 gap-1 text-xs border-0 bg-transparent hover:bg-transparent hover:text-foreground focus-visible:ring-0 focus-visible:ring-offset-0 text-muted-foreground text-right min-w-0 max-w-[280px]"
)}
disabled={disabled}
>
<span className="truncate">
{value || placeholder || defaultPlaceholder}
</span>
{selectedModelDisplay ? (
<>
{selectedModelDisplay.baseURL ? (
<ExternalFavicon
url={selectedModelDisplay.baseURL}
size={16}
fallback={<Bot size={16} />}
className="flex-shrink-0"
/>
) : (
<Bot size={16} className="flex-shrink-0" />
)}
<span className="truncate">
{selectedModelDisplay.displayName}
</span>
</>
) : (
<span className="truncate">
{placeholder || defaultPlaceholder}
</span>
)}
<ChevronDown className="size-3 shrink-0 opacity-50" />
</Button>
</PopoverTrigger>
@@ -305,6 +351,11 @@ 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}
@@ -318,7 +369,17 @@ export const ModelSelector = memo(function ModelSelector({
value === modelId ? "opacity-100" : "opacity-0"
)}
/>
<span className="truncate flex-1">{modelId}</span>
{providerInfo.baseURL ? (
<ExternalFavicon
url={providerInfo.baseURL}
size={16}
fallback={<Bot size={16} />}
className="mr-2 flex-shrink-0"
/>
) : (
<Bot size={16} className="mr-2 flex-shrink-0" />
)}
<span className="truncate flex-1">{displayName}</span>
{modelData?.pricing && (
<ModelPricing pricing={modelData.pricing} className="ml-2" />
)}
@@ -367,32 +428,46 @@ export const ModelSelector = memo(function ModelSelector({
)}
{/* Provider models */}
{!isLoading && Object.entries(modelsByProvider).map(([provider, providerModels]) => (
<div key={provider}>
<CommandSeparator />
<CommandGroup heading={provider}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
{!isLoading && Object.entries(modelsByProvider).map(([providerId, providerModels]) => {
const providerInfo = getProviderInfo(providerId);
return (
<div key={providerId}>
<CommandSeparator />
<CommandGroup heading={providerInfo.displayName}>
{providerModels.map((model) => (
<CommandItem
key={model.fullId}
value={model.fullId}
onSelect={() => handleSelect(model.fullId)}
className="cursor-pointer"
>
<Check
className={cn(
"mr-2 h-4 w-4",
value === model.fullId ? "opacity-100" : "opacity-0"
)}
/>
{providerInfo.baseURL ? (
<ExternalFavicon
url={providerInfo.baseURL}
size={16}
fallback={<Bot size={16} />}
className="mr-2 flex-shrink-0"
/>
) : (
<Bot size={16} className="mr-2 flex-shrink-0" />
)}
/>
<span className="truncate flex-1">{model.fullId}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
))}
<span className="truncate flex-1">{model.name || model.id}</span>
{model.pricing && (
<ModelPricing pricing={model.pricing} className="ml-2" />
)}
</CommandItem>
))}
</CommandGroup>
</div>
);
})}
{/* Custom model option and manage providers - moved to bottom */}
<CommandSeparator />
-67
View File
@@ -1,67 +0,0 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import {
Alert,
AlertDescription,
AlertTitle,
} from '@/components/ui/alert';
import { Button } from '@/components/ui/button';
interface NostrPermissionDialogProps {
open: boolean;
onResponse: (granted: boolean) => void;
}
export function NostrPermissionDialog({ open, onResponse }: NostrPermissionDialogProps) {
return (
<Dialog open={open} onOpenChange={(isOpen) => {
if (!isOpen) {
onResponse(false);
}
}}>
<DialogContent>
<DialogHeader>
<DialogTitle>Allow Nostr Access?</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This project is requesting access to your Nostr signer (window.nostr).
</p>
<Alert variant="destructive">
<AlertTitle>Warning</AlertTitle>
<AlertDescription>
Granting access will allow this app to take actions on your behalf, including:
<ul className="list-disc list-inside mt-2 space-y-1">
<li>Read your public key</li>
<li>Sign events (publish posts, reactions, etc.)</li>
<li>Encrypt and decrypt messages</li>
</ul>
</AlertDescription>
</Alert>
<p className="text-sm text-muted-foreground">
Only grant access if you trust this application.
</p>
</DialogDescription>
</DialogHeader>
<DialogFooter className="gap-2">
<Button
variant="outline"
onClick={() => onResponse(false)}
>
Deny
</Button>
<Button
onClick={() => onResponse(true)}
>
Allow
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -1,65 +0,0 @@
import {
Dialog,
DialogContent,
DialogDescription,
DialogFooter,
DialogHeader,
DialogTitle,
} from '@/components/ui/dialog';
import { Button } from '@/components/ui/button';
interface NostrSignerRequiredDialogProps {
open: boolean;
onOpenChange: (open: boolean) => void;
}
export function NostrSignerRequiredDialog({ open, onOpenChange }: NostrSignerRequiredDialogProps) {
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent>
<DialogHeader>
<DialogTitle>Nostr Signer Required</DialogTitle>
<DialogDescription className="space-y-3">
<p>
This page tried to use a NIP-07 signer, but you don't have one installed!
</p>
<p>
Please install a Nostr signer extension to continue:
</p>
<div className="space-y-2 mt-4">
<a
href="https://github.com/soapbox-pub/soapbox-signer"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• Soapbox Signer
</a>
<a
href="https://getalby.com/"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• Alby
</a>
<a
href="https://github.com/fiatjaf/nos2x"
target="_blank"
rel="noopener noreferrer"
className="block text-primary hover:underline"
>
• nos2x
</a>
</div>
</DialogDescription>
</DialogHeader>
<DialogFooter>
<Button variant="outline" onClick={() => onOpenChange(false)}>
Close
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
);
}
@@ -17,6 +17,7 @@ const mockUseAICredits = vi.mocked(useAICredits);
describe('OnboardingCreditsBadge', () => {
const mockProvider = {
id: 'shakespeare',
name: 'Shakespeare',
baseURL: 'https://ai.shakespeare.diy/v1',
nostr: true,
};
+8 -3
View File
@@ -23,6 +23,7 @@ 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;
@@ -57,10 +58,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
selectedProvider && selectedProvider.nostr && user
? {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr,
}
: { id: '', baseURL: '', nostr: undefined }
: { id: '', name: '', baseURL: '', nostr: undefined }
);
// Filter models to only show selected provider models
@@ -122,8 +124,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}
// Add selected provider to their config
const providerConfig = {
const providerConfig: AIProvider = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
@@ -151,8 +154,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}
// Add selected provider to their config
const providerConfig = {
const providerConfig: AIProvider = {
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
};
@@ -726,6 +730,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
}}
provider={{
id: selectedProvider.id,
name: selectedProvider.name,
baseURL: selectedProvider.baseURL,
nostr: selectedProvider.nostr || undefined,
}}
+5 -22
View File
@@ -5,11 +5,9 @@ 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();
@@ -79,9 +77,6 @@ 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">
@@ -94,7 +89,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] || [];
@@ -112,12 +107,6 @@ export function PluginsSection() {
/>;
})}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noPluginsConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add Plugin Section */}
@@ -132,7 +121,9 @@ 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')}</Label>
<Label htmlFor="plugin-git-url">
{t('gitRepositoryUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="plugin-git-url"
placeholder="https://github.com/user/plugin.git"
@@ -191,7 +182,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-primary" />
<Puzzle className="h-4 w-4 text-muted-foreground" />
<span className="font-medium">{pluginName}</span>
{pluginSkills.length > 0 && (
<span className="text-xs text-muted-foreground">
@@ -224,14 +215,6 @@ 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 && (
+31 -4
View File
@@ -34,6 +34,8 @@ import {
Trash2,
Save,
DollarSign,
ExternalLink,
FileCode,
} from 'lucide-react';
import JSZip from 'jszip';
import { Separator } from './ui/separator';
@@ -52,6 +54,7 @@ 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();
@@ -65,21 +68,28 @@ export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDel
setIsRenaming(false);
}, [project.id]);
// Load total project cost
// Load total project cost and template info
useEffect(() => {
const loadCost = async () => {
const loadProjectData = async () => {
try {
const dotAI = new DotAI(fs, `${projectsPath}/${project.id}`);
// Load cost
const cost = await dotAI.readCost();
setTotalCost(cost);
// Load template info
const template = await dotAI.readTemplate();
setTemplateInfo(template);
} catch (error) {
console.warn('Failed to load project cost:', error);
console.warn('Failed to load project data:', error);
setTotalCost(null);
setTemplateInfo(null);
}
};
if (open) {
loadCost();
loadProjectData();
}
}, [fs, projectsPath, project.id, open]);
@@ -256,6 +266,23 @@ 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>
+357
View File
@@ -0,0 +1,357 @@
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>
);
}
+4 -4
View File
@@ -27,7 +27,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: '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,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: '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,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: '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,
},
projectTemplate: 'https://test.git',
templates: [{ name: 'Test', description: 'Test template', url: 'https://test.git' }],
esmUrl: 'https://esm.test',
corsProxy: 'https://proxy.test/{href}',
faviconUrl: 'https://favicon.test/{href}',
+2 -2
View File
@@ -20,7 +20,7 @@ export function SettingsItemMobile({
<button
onClick={onClick}
className={cn(
'w-full text-left px-4 py-3.5 bg-background transition-colors active:bg-muted/50',
'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',
{
@@ -33,7 +33,7 @@ export function SettingsItemMobile({
<Icon className="h-4 w-4 text-primary flex-shrink-0" />
</div>
<div className="flex-1 min-w-0">
<div className="text-base text-foreground">
<div className="text-base">
{title}
</div>
</div>
+69 -1
View File
@@ -46,6 +46,7 @@ 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
@@ -88,6 +89,8 @@ 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;
@@ -174,7 +177,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),
skill: new SkillTool(fs, pluginsPath, cwd),
};
// Add deploy tool only if user is logged in
@@ -252,6 +255,52 @@ 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();
@@ -502,6 +551,25 @@ 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]">
+3 -180
View File
@@ -7,7 +7,6 @@ import { useFSPaths } from '@/hooks/useFSPaths';
import { addConsoleMessage, getConsoleMessages, type ConsoleMessage } from '@/lib/consoleMessages';
import { useConsoleError } from '@/hooks/useConsoleError';
import { useBuildProject } from '@/hooks/useBuildProject';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { Tabs, TabsContent } from '@/components/ui/tabs';
import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area';
import { Button } from '@/components/ui/button';
@@ -26,8 +25,6 @@ import {
PopoverContent,
PopoverTrigger,
} from '@/components/ui/popover';
import { NostrPermissionDialog } from '@/components/NostrPermissionDialog';
import { NostrSignerRequiredDialog } from '@/components/NostrSignerRequiredDialog';
import { cn } from '@/lib/utils';
import { FileTree } from './FileTree';
import { FileEditor } from './FileEditor';
@@ -60,16 +57,6 @@ interface JSONRPCRequest {
id: number;
}
interface NostrRPCRequest {
jsonrpc: '2.0';
method: 'nostr';
params: {
method: string;
args: unknown[];
};
id: number;
}
interface JSONRPCResponse {
jsonrpc: '2.0';
result?: {
@@ -106,7 +93,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
const { fs } = useFS();
const { projectsPath } = useFSPaths();
const projectsManager = useProjectsManager();
const { user } = useCurrentUser();
// Use console error state from provider
const { hasErrors: hasConsoleErrors, clearErrors } = useConsoleError();
@@ -333,155 +319,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
}
}, [historyIndex, navigationHistory, sendNavigationCommand]);
// Track which projects have been granted Nostr access
const [nostrPermissions, setNostrPermissions] = useState<Set<string>>(new Set());
const [nostrPermissionDialog, setNostrPermissionDialog] = useState<{
open: boolean;
projectId: string;
resolve: (granted: boolean) => void;
} | null>(null);
const [noSignerDialog, setNoSignerDialog] = useState(false);
const requestNostrPermission = useCallback(async (projectId: string): Promise<boolean> => {
// Check if permission already granted
if (nostrPermissions.has(projectId)) {
return true;
}
// Show permission dialog and wait for user response
return new Promise<boolean>((resolve) => {
setNostrPermissionDialog({
open: true,
projectId,
resolve,
});
});
}, [nostrPermissions]);
const handleNostrPermissionResponse = useCallback((granted: boolean) => {
if (nostrPermissionDialog) {
const { projectId, resolve } = nostrPermissionDialog;
if (granted) {
// Grant permission for this project
setNostrPermissions(prev => new Set([...prev, projectId]));
}
// Close dialog and resolve the promise
setNostrPermissionDialog(null);
resolve(granted);
}
}, [nostrPermissionDialog]);
const handleNostr = useCallback(async (request: NostrRPCRequest) => {
const { params, id } = request;
const { method, args } = params;
console.log('[NOSTR BRIDGE] Handling request:', method, args);
try {
// Check if user is logged in with a signer
if (!user?.signer) {
// Show the "no signer" dialog
setNoSignerDialog(true);
throw new Error('NO_SIGNER_INSTALLED');
}
// Request permission if this is the first Nostr access from this project
const hasPermission = await requestNostrPermission(projectId);
if (!hasPermission) {
throw new Error('User denied Nostr access');
}
let result: unknown;
// Route to appropriate signer method
switch (method) {
case 'getPublicKey':
result = await user.signer.getPublicKey();
break;
case 'signEvent':
if (!args[0] || typeof args[0] !== 'object') {
throw new Error('Invalid event object');
}
result = await user.signer.signEvent(args[0] as Parameters<typeof user.signer.signEvent>[0]);
break;
case 'nip04.encrypt':
if (!user.signer.nip04?.encrypt) {
throw new Error('NIP-04 encryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip04.encrypt');
}
result = await user.signer.nip04.encrypt(args[0], args[1]);
break;
case 'nip04.decrypt':
if (!user.signer.nip04?.decrypt) {
throw new Error('NIP-04 decryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip04.decrypt');
}
result = await user.signer.nip04.decrypt(args[0], args[1]);
break;
case 'nip44.encrypt':
if (!user.signer.nip44?.encrypt) {
throw new Error('NIP-44 encryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip44.encrypt');
}
result = await user.signer.nip44.encrypt(args[0], args[1]);
break;
case 'nip44.decrypt':
if (!user.signer.nip44?.decrypt) {
throw new Error('NIP-44 decryption not supported by signer');
}
if (typeof args[0] !== 'string' || typeof args[1] !== 'string') {
throw new Error('Invalid arguments for nip44.decrypt');
}
result = await user.signer.nip44.decrypt(args[0], args[1]);
break;
default:
throw new Error(`Unsupported Nostr method: ${method}`);
}
console.log('[NOSTR BRIDGE] Success:', method, result);
// Send success response
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage({
jsonrpc: '2.0',
result,
id
}, targetOrigin);
}
} catch (error) {
console.error('[NOSTR BRIDGE] Error:', method, error);
// Send error response
if (iframeRef.current?.contentWindow) {
const targetOrigin = `https://${projectId}.${previewDomain}`;
iframeRef.current.contentWindow.postMessage({
jsonrpc: '2.0',
error: {
code: -32000,
message: error instanceof Error ? error.message : String(error),
},
id
}, targetOrigin);
}
}
}, [user, projectId, previewDomain, requestNostrPermission]);
const handleFetch = useCallback(async (request: JSONRPCRequest) => {
const { params, id } = request;
const { request: fetchRequest } = params;
@@ -604,7 +441,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
// Verify origin for security
const expectedOrigin = `https://${projectId}.${previewDomain}`;
if (event.origin !== expectedOrigin) {
console.log(`Ignoring message with source ${event.data.source} from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
console.log(`Ignoring message from unexpected origin: ${event.origin}, expected: ${expectedOrigin}`);
return;
}
@@ -612,8 +449,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
console.log('Received message from iframe:', message);
if (message.jsonrpc === '2.0' && message.method === 'fetch') {
handleFetch(message);
} else if (message.jsonrpc === '2.0' && message.method === 'nostr') {
handleNostr(message);
} else if (message.jsonrpc === '2.0' && message.method === 'console') {
handleConsoleMessage(message);
} else if (message.jsonrpc === '2.0' && message.method === 'updateNavigationState') {
@@ -623,7 +458,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
window.addEventListener('message', handleMessage);
return () => window.removeEventListener('message', handleMessage);
}, [handleFetch, handleNostr, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
}, [handleFetch, handleConsoleMessage, handleUpdateNavigationState, projectId, previewDomain]);
useEffect(() => {
if (selectedFile) {
@@ -1113,18 +948,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
onOpenChange={setDeployDialogOpen}
/>
)}
{/* Nostr Permission Dialog */}
<NostrPermissionDialog
open={nostrPermissionDialog?.open ?? false}
onResponse={handleNostrPermissionResponse}
/>
{/* No Signer Installed Dialog */}
<NostrSignerRequiredDialog
open={noSignerDialog}
onOpenChange={setNoSignerDialog}
/>
</div>
);
}
}
+7
View File
@@ -2,6 +2,7 @@ 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
@@ -30,9 +31,15 @@ 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,
};
+77 -26
View File
@@ -3,6 +3,7 @@ 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,
@@ -33,6 +34,8 @@ 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,
@@ -75,6 +78,7 @@ 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);
@@ -89,6 +93,7 @@ export function AnnounceRepositoryDialog({
const { nostr } = useNostr();
const { toast } = useToast();
const { config } = useAppContext();
const { fs } = useFS();
const projectPath = `${projectsPath}/${projectId}`;
@@ -146,37 +151,57 @@ export function AnnounceRepositoryDialog({
.join(' ');
setName(defaultName);
// 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);
// 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']);
}
// 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);
}
}
} catch (error) {
console.warn('Failed to read template for t-tags:', error);
}
setTTags(defaultTTags);
// Get earliest commit
await getEarliestCommit();
}, [projectId, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]);
}, [projectId, projectPath, fs, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit]);
// Load existing repository data if editing
// Load existing repository data if editing, or prepopulate fields for new repos
useEffect(() => {
// Only run when dialog opens
if (!isOpen || isPrepopulated) return;
const loadExistingRepo = async () => {
if (!editNaddr || !isOpen) return;
if (!editNaddr) return;
try {
// Decode the naddr to get repository coordinates
@@ -221,6 +246,13 @@ 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);
@@ -232,13 +264,13 @@ export function AnnounceRepositoryDialog({
}
};
if (isOpen && editNaddr) {
if (editNaddr) {
loadExistingRepo();
} else if (isOpen && !isPrepopulated) {
} else {
prepopulateFields();
setIsPrepopulated(true);
}
}, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayMetadata, toast]);
}, [isOpen, isPrepopulated, editNaddr, nostr, config.relayMetadata, toast, prepopulateFields]);
const addWebUrl = () => {
if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) {
@@ -313,6 +345,7 @@ export function AnnounceRepositoryDialog({
webUrls,
cloneUrls,
relays,
tTags,
earliestCommit,
});
@@ -385,6 +418,7 @@ export function AnnounceRepositoryDialog({
setWebUrls([]);
setCloneUrls([]);
setRelays(['wss://relay.nostr.band']);
setTTags([]);
setEarliestCommit('');
setError(null);
setNewWebUrl('');
@@ -636,6 +670,23 @@ 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>
+256
View File
@@ -0,0 +1,256 @@
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
@@ -0,0 +1,172 @@
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,6 +2,7 @@ import { createContext } from 'react';
export interface AIProvider {
id: string;
name: string;
baseURL: string;
apiKey?: string;
nostr?: boolean;
+15 -2
View File
@@ -9,13 +9,22 @@ 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;
/** Git repository URL to use as project template */
projectTemplate: string;
/** Available project templates */
templates: ProjectTemplate[];
/** ESM CDN URL for package imports */
esmUrl: string;
/** HTTP proxy used to bypass CORS for AI and Git operations */
@@ -48,6 +57,10 @@ 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 {
+23
View File
@@ -0,0 +1,23 @@
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
@@ -1,526 +0,0 @@
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
@@ -1,96 +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';
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
};
}
+503
View File
@@ -0,0 +1,503 @@
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
@@ -0,0 +1,187 @@
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,
},
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: 'https://gitlab.com/soapbox-pub/mkstack.git' }],
esmUrl: 'https://esm.test',
corsProxy,
faviconUrl: 'https://external-content.duckduckgo.com/ip3/{hostname}.ico',
+10
View File
@@ -0,0 +1,10 @@
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, getAllSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
import { getPlugins, getPluginSkills, 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 skills
// Query to get all plugin skills (not including project skills)
const skillsQuery = useQuery({
queryKey: ['skills', pluginsPath],
queryFn: async () => {
return await getAllSkills(fs, pluginsPath);
return await getPluginSkills(fs, pluginsPath);
},
});
+46
View File
@@ -312,4 +312,50 @@ 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}`);
}
}
}
+50 -7
View File
@@ -3,6 +3,7 @@ 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') {
@@ -106,26 +107,53 @@ 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
// Fetch the latest changes from remote (shallow fetch for efficiency)
const fetchResult = await this.git.fetch({
dir: templatePath,
singleBranch: true,
depth: 1,
});
// Get the current branch name
const branch = fetchResult.defaultBranch;
// Get the current branch name (e.g., "refs/heads/main")
const branchRef = fetchResult.defaultBranch;
if (!branch) {
if (!branchRef) {
throw new Error('Could not determine current branch');
}
// Reset hard to the remote branch, discarding all local changes
// 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
await this.git.checkout({
dir: templatePath,
ref: branch,
ref: remoteOid,
force: true,
});
}
@@ -197,7 +225,7 @@ export class ProjectsManager {
}
}
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void): Promise<Project> {
async createProject(name: string, templateUrl: string, customId?: string, onTemplateUpdateError?: (error: Error) => void, templateMetadata?: { name: string; description: string }): Promise<Project> {
const id = customId || await this.generateUniqueProjectId(name);
// Check if project with this ID already exists when using custom ID
@@ -230,6 +258,21 @@ 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) {
+2 -1
View File
@@ -40,7 +40,7 @@ const testConfig: AppConfig = {
],
updatedAt: 0,
},
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: '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,6 +64,7 @@ describe('SessionManager', () => {
providers: [
{
id: 'test-provider',
name: 'Test Provider',
baseURL: 'https://api.test.com',
apiKey: 'test-key'
}
+11
View File
@@ -266,6 +266,16 @@ 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,
@@ -277,6 +287,7 @@ export class SessionManager {
metadata,
repositoryUrl,
template: config.systemPrompt,
projectTemplate,
});
// Helper function to filter out unsupported image formats (keep only JPG/JPEG/PNG)
+5 -13
View File
@@ -1,5 +1,5 @@
import { describe, it, expect } from 'vitest';
import { AI_PROVIDER_PRESETS, getPresetProvider, getShakespeareProvider } from './aiProviderPresets';
import { AI_PROVIDER_PRESETS } from './aiProviderPresets';
describe('AI Provider Presets', () => {
it('should export preset providers array', () => {
@@ -22,20 +22,12 @@ describe('AI Provider Presets', () => {
});
it('should get preset provider by id', () => {
const openai = getPresetProvider('openai');
const openai = AI_PROVIDER_PRESETS.find(p => p.id === 'openai');
expect(openai).toBeDefined();
expect(openai?.name).toBe('OpenAI');
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);
const nonExistent = AI_PROVIDER_PRESETS.find(p => p.id === 'non-existent');
expect(nonExistent).toBeUndefined();
});
it('should have valid preset structure', () => {
@@ -47,7 +39,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');
+1 -15
View File
@@ -89,18 +89,4 @@ 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,6 +15,8 @@ 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;
}
@@ -95,6 +97,14 @@ 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']);
+9
View File
@@ -60,6 +60,7 @@ describe('configUtils', () => {
providers: [
{
id: 'openai',
name: 'OpenAI',
baseURL: 'https://api.openai.com/v1',
apiKey: 'sk-test123',
},
@@ -76,6 +77,14 @@ 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: {},
});
});
+26 -3
View File
@@ -1,7 +1,8 @@
import z from 'zod';
import { filteredArray } from '@/lib/schema';
import { AI_PROVIDER_PRESETS } from '@/lib/aiProviderPresets';
import type { JSRuntimeFS } from '@/lib/JSRuntime';
import type { AIProvider, AISettings, MCPServer } from '@/contexts/AISettingsContext';
import type { AISettings, MCPServer } from '@/contexts/AISettingsContext';
import type { GitSettings } from '@/contexts/GitSettingsContext';
import type { DeployProvider, DeploySettings } from '@/contexts/DeploySettingsContext';
@@ -29,8 +30,9 @@ function getDeployConfigPath(configPath = '/config'): string {
return `${configPath}/deploy.json`;
}
const aiProviderSchema: z.ZodType<AIProvider> = z.object({
const aiProviderSchema = z.object({
id: z.string(),
name: z.string().optional(),
baseURL: z.string().url(),
apiKey: z.string().optional(),
nostr: z.boolean().optional(),
@@ -145,9 +147,30 @@ 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) {
+7
View File
@@ -6,21 +6,25 @@ 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: '',
},
@@ -32,6 +36,7 @@ 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,
@@ -44,6 +49,7 @@ 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,
@@ -56,6 +62,7 @@ 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,
+234 -28
View File
@@ -3,6 +3,7 @@ import type { JSRuntimeFS } from './JSRuntime';
import {
getPlugins,
getPluginSkills,
getProjectSkills,
getAllSkills,
findSkill,
readSkillContent,
@@ -200,14 +201,12 @@ describe('plugins', () => {
});
describe('getPluginSkills', () => {
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');
it('should return empty array when no plugins exist', async () => {
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
it('should return skills with valid SKILL.md files', async () => {
it('should return skills from all plugins', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
@@ -222,7 +221,7 @@ description: A test skill
This is a test skill.`
);
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toHaveLength(1);
expect(skills[0]).toEqual({
name: 'myskill',
@@ -245,7 +244,7 @@ description: Has uppercase letters
Content`
);
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
@@ -261,48 +260,131 @@ name: incomplete
Missing description`
);
const skills = await getPluginSkills(fs, '/plugins', 'testplugin');
const skills = await getPluginSkills(fs, '/plugins');
expect(skills).toEqual([]);
});
});
describe('getAllSkills', () => {
it('should return skills from all plugins', async () => {
// Plugin 1
const skill1Path = '/plugins/plugin1/skills/skill1';
await fs.mkdir(skill1Path, { recursive: true });
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 });
await fs.writeFile(
`${skill1Path}/SKILL.md`,
`${pluginPath}/SKILL.md`,
`---
name: skill1
description: First skill
name: plugin-skill
description: A plugin skill
---
Content`
);
// Plugin 2
const skill2Path = '/plugins/plugin2/skills/skill2';
await fs.mkdir(skill2Path, { recursive: true });
// Create project skill
await fs.mkdir(projectSkillPath, { recursive: true });
await fs.writeFile(
`${skill2Path}/SKILL.md`,
`${projectSkillPath}/SKILL.md`,
`---
name: skill2
description: Second skill
name: project-skill
description: A project skill
---
Content`
);
const skills = await getAllSkills(fs, '/plugins');
const skills = await getAllSkills(fs, '/plugins', projectPath);
expect(skills).toHaveLength(2);
expect(skills.map((s) => s.name)).toContain('skill1');
expect(skills.map((s) => s.name)).toContain('skill2');
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');
});
});
describe('findSkill', () => {
it('should find a skill by name', async () => {
it('should find a plugin skill by name', async () => {
const skillPath = '/plugins/testplugin/skills/findme';
await fs.mkdir(skillPath, { recursive: true });
await fs.writeFile(
@@ -315,17 +397,76 @@ description: Find this skill
Content`
);
const skill = await findSkill(fs, '/plugins', 'findme');
const skill = await findSkill(fs, '/plugins', '/projects/myproject', 'findme');
expect(skill).not.toBeNull();
expect(skill?.name).toBe('findme');
expect(skill?.plugin).toBe('testplugin');
});
it('should return null when skill not found', async () => {
const skill = await findSkill(fs, '/plugins', 'nonexistent');
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');
expect(skill).toBeNull();
});
});
describe('readSkillContent', () => {
it('should read the full SKILL.md content', async () => {
const skillPath = '/plugins/testplugin/skills/myskill';
@@ -352,4 +493,69 @@ 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([]);
});
});
});
+60 -10
View File
@@ -56,15 +56,25 @@ export async function getPlugins(fs: JSRuntimeFS, pluginsPath: string): Promise<
}
/**
* Get all skills from a plugin
* Get all skills from a single plugin
*/
export async function getPluginSkills(
function getSkillsFromPlugin(
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);
@@ -99,7 +109,7 @@ export async function getPluginSkills(
name: frontmatter.name,
description: frontmatter.description,
path: skillPath,
plugin: pluginName,
plugin: sourceName,
});
} catch {
// SKILL.md not found or invalid, skip this directory
@@ -107,7 +117,7 @@ export async function getPluginSkills(
}
}
} catch {
// Skills directory doesn't exist for this plugin
// Skills directory doesn't exist
return [];
}
@@ -115,14 +125,24 @@ export async function getPluginSkills(
}
/**
* Get all skills from all plugins
* Get all skills from a project's skills directory
*/
export async function getAllSkills(fs: JSRuntimeFS, pluginsPath: string): Promise<Skill[]> {
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[]> {
const plugins = await getPlugins(fs, pluginsPath);
const allSkills: Skill[] = [];
for (const plugin of plugins) {
const skills = await getPluginSkills(fs, pluginsPath, plugin);
const skills = await getSkillsFromPlugin(fs, pluginsPath, plugin);
allSkills.push(...skills);
}
@@ -130,14 +150,44 @@ export async function getAllSkills(fs: JSRuntimeFS, pluginsPath: string): Promis
}
/**
* Find a skill by name across all plugins
* 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
*/
export async function findSkill(
fs: JSRuntimeFS,
pluginsPath: string,
projectPath: string,
skillName: string
): Promise<Skill | null> {
const skills = await getAllSkills(fs, pluginsPath);
const skills = await getAllSkills(fs, pluginsPath, projectPath);
return skills.find(skill => skill.name === skillName) || null;
}
+100 -13
View File
@@ -27,7 +27,7 @@ const testConfig: AppConfig = {
],
updatedAt: 0,
},
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
templates: [{ name: 'MKStack', description: 'Build Nostr clients with React.', url: '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,10 +185,11 @@ describe('makeSystemPrompt', () => {
});
describe('tools section', () => {
it('should not include tools section when no tools are provided', async () => {
it('should show no tools message when no tools are provided', async () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).not.toContain('## Available Tools');
expect(result).toContain('## Available Tools');
expect(result).toContain('There are no tools available to you.');
});
it('should list available tools with descriptions', async () => {
@@ -252,7 +253,7 @@ describe('makeSystemPrompt', () => {
const result = await makeSystemPrompt(baseOpts);
expect(result).toContain('No skills are currently configured');
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins');
expect(getAllSkills).toHaveBeenCalledWith(mockFs, '/plugins', '/projects/test-project');
});
it('should list available skills when they exist', async () => {
@@ -290,15 +291,6 @@ 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);
@@ -425,6 +417,7 @@ 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');
@@ -520,4 +513,98 @@ 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)**');
});
});
});
+32 -12
View File
@@ -19,6 +19,7 @@ export interface MakeSystemPromptOpts {
metadata?: NostrMetadata;
repositoryUrl?: string;
template?: string;
projectTemplate?: { name: string; description: string; url: string };
}
/**
@@ -34,7 +35,10 @@ You are operating within **Shakespeare**, an AI-powered website builder that all
- **Current Date**: {{ date }}
- **Current Page**: {{ location.href }}
- **Current Working Directory**: {{ cwd }}
- **Repository URL**: {{ repositoryUrl }}
- **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\`).
## What Shakespeare Is
@@ -64,7 +68,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 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 %}
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 %}
## User Interface
@@ -87,12 +91,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 and API keys
- **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 (project template, ESM CDN, CORS proxy, etc.)
- **System Settings** (\`/settings/system\`): Advanced configuration (ESM CDN, CORS proxy, service worker, etc.)
- **About** (\`/settings/about\`): License information and project details
## User Actions
@@ -149,13 +153,24 @@ As the AI assistant in Shakespeare, you help users by:
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.{% if tools.length > 0 %}
**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 %}
## 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 %}{% endif %}
- **{{ tool.function.name }}**: {{ tool.function.description or 'No description available' }}{% endif %}{% endfor %}{% else %}
There are no tools available to you.{% endif %}
## Skills
@@ -170,7 +185,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.{% if config.corsProxy %}
Users can configure skills in Settings > AI (\`{{ location.origin }}/settings/ai\`) by adding plugins that contain skills.
## Working Around CORS Issues
@@ -178,7 +193,11 @@ 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.{% endif %}
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
## Edit with Shakespeare
@@ -207,7 +226,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 } = opts;
const { tools, mode, fs, cwd, config, defaultConfig, user, metadata, repositoryUrl, template, projectTemplate } = opts;
// Add current date
const date = new Date().toLocaleDateString("en-US", {
@@ -217,11 +236,11 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
day: "numeric",
});
// Get skills
// Get skills from both plugins and project
let skills: Array<{ name: string; description: string; plugin: string; path: string }> = [];
if (config.fsPathPlugins) {
try {
skills = await getAllSkills(fs, config.fsPathPlugins);
skills = await getAllSkills(fs, config.fsPathPlugins, cwd);
} catch {
// Skills not available, use empty array
skills = [];
@@ -288,6 +307,7 @@ export async function makeSystemPrompt(opts: MakeSystemPromptOpts): Promise<stri
editUrl,
README: readmeText,
AGENTS: agentsText,
projectTemplate,
};
// Render the template with the context
+7 -5
View File
@@ -10,24 +10,26 @@ 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. Skills are reusable AI workflows that can be invoked by name.';
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 inputSchema = z.object({
name: z.string().describe('The name of the skill to execute (lowercase alphanumeric with hyphens)'),
});
constructor(fs: JSRuntimeFS, pluginsPath: string) {
constructor(fs: JSRuntimeFS, pluginsPath: string, projectPath: 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
const skill = await findSkill(this.fs, this.pluginsPath, name);
// Find the skill across all plugins and project
const skill = await findSkill(this.fs, this.pluginsPath, this.projectPath, name);
if (!skill) {
throw new Error(`Skill "${name}" not found. Use the skill tool to list available skills or configure plugins in Settings > AI.`);
@@ -38,7 +40,7 @@ export class SkillTool implements Tool<SkillParams> {
return `# Skill: ${skill.name}
**Plugin**: ${skill.plugin}
**Source**: ${skill.plugin === 'project' ? 'Project' : `Plugin: ${skill.plugin}`}
**Description**: ${skill.description}
**Path**: ${skill.path}
+27 -4
View File
@@ -18,8 +18,8 @@
"systemSettingsDescription": "Configure system-level settings and advanced options.",
"esmUrl": "Javascript CDN",
"esmUrlDescription": "Javascript CDN URL for package imports.",
"projectTemplate": "Project Template",
"projectTemplateDescription": "Git repository URL to use as the starting template for new projects.",
"projectTemplates": "Project Templates",
"projectTemplatesDescription": "Templates available to the AI when creating new projects.",
"previewDomain": "Preview Domain",
"previewDomainDescription": "Domain used for iframe preview sandboxing.",
"corsProxy": "CORS Proxy",
@@ -63,7 +63,7 @@
"shareErrorReports": "Share error reports",
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
"systemPrompt": "System Prompt",
"systemPromptDescription": "Customize the AI assistant's system prompt using Jinja-like template syntax. This controls the assistant's behavior and knowledge.",
"systemPromptDescription": "AI system prompt controlling the assistant's behavior and knowledge.",
"english": "English",
"portuguese": "Portuguese",
"chinese": "Chinese",
@@ -91,6 +91,7 @@
"remove": "Remove",
"retry": "Retry",
"name": "Name",
"id": "ID",
"email": "Email",
"buildNostrApps": "Build apps with AI",
"whatToBuild": "What would you like to build?",
@@ -513,5 +514,27 @@
"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"
"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"
}
+14 -1
View File
@@ -87,6 +87,7 @@
"remove": "Cire",
"retry": "Sake gwadawa",
"name": "Suna",
"id": "ID",
"email": "Imel",
"buildNostrApps": "Gina aikace-aikace da AI",
"whatToBuild": "Me kuke son ginawa?",
@@ -430,5 +431,17 @@
"modified": "An Canza",
"restoreToDefault": "Mayar da asali",
"restoredToDefault": "An Mayar da Asali",
"terminal": "Terminal"
"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"
}
+14 -1
View File
@@ -87,6 +87,7 @@
"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?",
@@ -427,5 +428,17 @@
"modified": "Gbanwere",
"restoreToDefault": "Weghachi na nke mbụ",
"restoredToDefault": "Weghachiri na Nke Mbụ",
"terminal": "Terminal"
"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"
}
+14 -1
View File
@@ -87,6 +87,7 @@
"remove": "Remover",
"retry": "Tentar novamente",
"name": "Nome",
"id": "ID",
"email": "Email",
"buildNostrApps": "Construa aplicativos com IA",
"whatToBuild": "O que você gostaria de construir?",
@@ -439,5 +440,17 @@
"modified": "Modificado",
"restoreToDefault": "Restaurar para padrão",
"restoredToDefault": "Restaurado para Padrão",
"terminal": "Terminal"
"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"
}
+14 -1
View File
@@ -87,6 +87,7 @@
"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ọ?",
@@ -427,5 +428,17 @@
"modified": "Ti Yipada",
"restoreToDefault": "Pada si atilẹwa",
"restoredToDefault": "Ti Pada si Atilẹwa",
"terminal": "Terminal"
"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ọ"
}
+14 -1
View File
@@ -87,6 +87,7 @@
"remove": "移除",
"retry": "重试",
"name": "名称",
"id": "ID",
"email": "邮箱",
"buildNostrApps": "使用AI构建应用",
"whatToBuild": "您想构建什么?",
@@ -439,5 +440,17 @@
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值",
"terminal": "终端"
"terminal": "终端",
"globalChat": "聊天",
"globalChatWelcome": "你好! 👋",
"globalChatDescription": "随便问我什么。我在这里帮助回答问题、提供想法和进行对话。",
"clearChat": "清除聊天",
"popOutChat": "弹出窗口",
"minimizeChat": "最小化",
"typeMessage": "输入消息...",
"configureAIFirst": "请先配置AI提供商",
"globalChatEnabled": "浮动聊天按钮",
"globalChatEnabledDescription": "显示浮动聊天按钮以便快速AI对话",
"globalChatSystemPrompt": "聊天系统提示",
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示"
}
+245 -85
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useState, useMemo } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, Bot, ArrowLeft, Trash2, GripVertical } from 'lucide-react';
import { Check, Bot, ArrowLeft, Trash2, GripVertical, ChevronDown, RotateCcw, FileText, Plus, Edit } from 'lucide-react';
import {
DndContext,
closestCenter,
@@ -25,20 +25,25 @@ 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';
interface SortableProviderItemProps {
provider: AIProvider;
@@ -94,7 +99,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
<Bot size={16} />
)}
<span className="font-medium">
{preset?.name || provider.id}
{provider.name}
</span>
<div className="ml-auto">
<CreditsBadge
@@ -107,7 +112,20 @@ 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}-baseURL`}>{t('baseUrl')}</Label>
<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>
<Input
id={`${provider.id}-baseURL`}
placeholder="https://api.example.com/v1"
@@ -172,13 +190,24 @@ 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');
@@ -186,6 +215,22 @@ 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);
// Check if system prompt differs from default
const isSystemPromptModified = useMemo(() =>
(config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
[config, defaultConfig]);
const restoreSystemPrompt = () => {
const defaultValue = defaultSystemPrompt;
setSystemPromptInput(defaultValue);
updateConfig((current) => {
const { systemPrompt, ...rest } = current;
return rest;
});
};
const sensors = useSensors(
useSensor(PointerSensor),
@@ -202,6 +247,7 @@ export function AISettings() {
const newProvider: AIProvider = {
id: preset.id,
name: preset.name,
baseURL: preset.baseURL,
};
@@ -230,10 +276,11 @@ export function AISettings() {
};
const handleAddCustomProvider = () => {
if (!customProviderName.trim() || !customBaseURL.trim()) return;
if (!customProviderName.trim() || !customProviderId.trim() || !customBaseURL.trim()) return;
const newProvider: AIProvider = {
id: customProviderName.trim(),
id: customProviderId.trim(),
name: customProviderName.trim(),
baseURL: customBaseURL.trim(),
apiKey: customAuthMethod === 'nostr' ? undefined : customApiKey.trim(),
nostr: customAuthMethod === 'nostr' || undefined,
@@ -244,6 +291,8 @@ export function AISettings() {
setProvider(newProvider);
setCustomProviderName('');
setCustomProviderId('');
setCustomIdManuallyEdited(false);
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
@@ -286,7 +335,7 @@ export function AISettings() {
const availablePresets = AI_PROVIDER_PRESETS.filter(preset => !configuredProviderIds.includes(preset.id));
return (
<div className="p-6 space-y-6">
<div className="p-6 space-y-6 pb-16">
{isMobile && (
<div className="space-y-3">
<Button
@@ -407,70 +456,70 @@ export function AISettings() {
</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
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')
<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);
}
}}
/>
)}
</label>
<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>
</div>
</div>
)}
)}
</CardContent>
</Card>
);
@@ -484,21 +533,52 @@ export function AISettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<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 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>
<div className="grid gap-2">
<Label htmlFor="custom-baseurl">{t('baseUrl')}</Label>
<Label htmlFor="custom-baseurl">
{t('baseUrl')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-baseurl"
placeholder="https://api.example.com/v1"
@@ -551,15 +631,16 @@ export function AISettings() {
onClick={handleAddCustomProvider}
disabled={
!customProviderName.trim() ||
!customProviderId.trim() ||
!customBaseURL.trim() ||
settings.providers.some(p => p.id === customProviderName.trim())
settings.providers.some(p => p.id === customProviderId.trim())
}
className="gap-2 ml-auto"
>
<Check className="h-4 w-4" />
{t('addCustomProviderButton')}
</Button>
{settings.providers.some(p => p.id === customProviderName.trim()) && (
{settings.providers.some(p => p.id === customProviderId.trim()) && (
<p className="text-sm text-destructive">
{t('providerExists')}
</p>
@@ -570,11 +651,90 @@ export function AISettings() {
</Accordion>
</div>
{/* MCP Servers Section */}
<MCPServersSection />
{/* 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>
{/* Plugins Section */}
<PluginsSection />
{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('systemPrompt')}</h3>
{isSystemPromptModified && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
<p className="text-sm text-muted-foreground">
{t('systemPromptDescription')}
</p>
</div>
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="system-prompt" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Edit className="h-4 w-4" />
<span className="font-medium">{t('systemPrompt')}</span>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-2">
<Textarea
id="system-prompt"
placeholder="Enter EJS template..."
value={systemPromptInput}
onChange={(e) => {
const value = e.target.value;
setSystemPromptInput(value);
updateConfig((current) => ({
...current,
systemPrompt: value,
}));
}}
className="flex-1 font-mono text-xs min-h-[400px]"
/>
{isSystemPromptModified && (
<Button
variant="outline"
onClick={restoreSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
</div>
</div>
)}
</div>
</div>
{/* Render credits dialog outside of accordion structure */}
+6 -6
View File
@@ -89,7 +89,7 @@ export function AboutSettings() {
<AccordionItem value="mirrors">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Globe className="h-5 w-5" />
<Globe className="size-5 text-muted-foreground" />
{t('mirrors')}
</div>
</AccordionTrigger>
@@ -103,7 +103,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" />
<ExternalLink className="ml-auto h-4 w-4 text-muted-foreground" />
</a>
</Button>
<Button
@@ -113,7 +113,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" />
<ExternalLink className="ml-auto h-4 w-4 text-muted-foreground" />
</a>
</Button>
<Button
@@ -123,7 +123,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" />
<ExternalLink className="ml-auto h-4 w-4 text-muted-foreground" />
</a>
</Button>
</div>
@@ -140,7 +140,7 @@ export function AboutSettings() {
asChild
>
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
<Code className="!size-5" />
<Code className="!size-5 text-muted-foreground" />
{t('sourceCode')}
<ExternalLink className="ml-auto" />
</a>
@@ -153,7 +153,7 @@ export function AboutSettings() {
<AccordionItem value="license-text">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Info className="h-5 w-5" />
<Info className="size-5 text-muted-foreground" />
{t('license')}
</div>
</AccordionTrigger>
+125 -110
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown } from 'lucide-react';
import { Rocket, ArrowLeft, Trash2, Check, GripVertical, ChevronDown, Plus } from 'lucide-react';
import { Checkbox } from '@/components/ui/checkbox';
import {
DropdownMenu,
@@ -116,7 +116,9 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-name`}>Name</Label>
<Label htmlFor={`provider-${index}-name`}>
Name <span className="text-destructive">*</span>
</Label>
<Input
id={`provider-${index}-name`}
placeholder="Provider name"
@@ -144,7 +146,9 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
) : provider.type === 'nsite' ? (
<>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-gateway`}>Gateway</Label>
<Label htmlFor={`provider-${index}-gateway`}>
Gateway <span className="text-destructive">*</span>
</Label>
<Input
id={`provider-${index}-gateway`}
placeholder="nsite.lol"
@@ -153,7 +157,9 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-relays`}>Relay URLs (comma-separated)</Label>
<Label htmlFor={`provider-${index}-relays`}>
Relay URLs (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id={`provider-${index}-relays`}
placeholder="wss://relay.nostr.band, wss://relay.damus.io"
@@ -165,7 +171,9 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-blossom`}>Blossom Servers (comma-separated)</Label>
<Label htmlFor={`provider-${index}-blossom`}>
Blossom Servers (comma-separated) <span className="text-destructive">*</span>
</Label>
<Input
id={`provider-${index}-blossom`}
placeholder="https://blossom.primal.net/"
@@ -181,7 +189,7 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
<>
<div className="grid gap-2">
<Label htmlFor={`provider-${index}-apiKey`}>
{preset?.apiKeyLabel || t('apiKey')}
{preset?.apiKeyLabel || t('apiKey')} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id={`provider-${index}-apiKey`}
@@ -622,109 +630,109 @@ export function DeploySettings() {
<p className="text-sm text-muted-foreground">{preset.description}</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>
) : isOAuthConfigured && !forceManualEntry[preset.id] ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
</>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setForceManualEntry(prev => ({ ...prev, [preset.id]: true }))}
>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
)}
</div>
) : (
// Show manual token input
<div className="space-y-2">
<div className="flex gap-2">
{!preset.requiresNostr && preset.type !== 'nsite' && (
<PasswordInput
placeholder={preset.apiKeyLabel || 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()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
}
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
<Button asChild className="w-full">
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
</div>
)}
) : isOAuthConfigured && !forceManualEntry[preset.id] ? (
// Show OAuth button if OAuth is configured and not forced to manual
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={() => oauthHook?.initiateOAuth()}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<span className="truncate text-ellipsis overflow-hidden">
Connect to {preset.name}
</span>
</>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setForceManualEntry(prev => ({ ...prev, [preset.id]: true }))}
>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
// Show manual token input
<div className="space-y-2">
<div className="flex gap-2">
{!preset.requiresNostr && preset.type !== 'nsite' && (
<PasswordInput
placeholder={preset.apiKeyLabel || 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()) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
(preset.requiresNostr && !isLoggedIntoNostr) ||
(!preset.requiresNostr && preset.type !== 'nsite' && !presetApiKeys[preset.id]?.trim())
}
className={(preset.requiresNostr || preset.type === 'nsite') ? "w-full" : "h-10 px-4 ml-auto"}
>
{t('add')}
</Button>
</div>
</div>
)}
</CardContent>
</Card>
);
@@ -738,12 +746,17 @@ export function DeploySettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="custom-provider-type">{t('providerType')}</Label>
<Label htmlFor="custom-provider-type">
{t('providerType')} <span className="text-destructive">*</span>
</Label>
<Select
value={customProviderType}
onValueChange={(value: 'shakespeare' | 'netlify' | 'vercel' | 'nsite') => {
@@ -773,7 +786,9 @@ export function DeploySettings() {
{customProviderType && (
<>
<div className="grid gap-2">
<Label htmlFor="custom-name">{t('providerName')}</Label>
<Label htmlFor="custom-name">
{t('providerName')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-name"
placeholder="e.g., My Production Deploy"
@@ -834,7 +849,7 @@ export function DeploySettings() {
<>
<div className="grid gap-2">
<Label htmlFor="custom-apikey">
{customProviderType === 'netlify' ? 'Personal Access Token' : 'Access Token'}
{customProviderType === 'netlify' ? 'Personal Access Token' : 'Access Token'} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-apikey"
+106 -88
View File
@@ -1,6 +1,6 @@
import { useState } from 'react';
import { useTranslation } from 'react-i18next';
import { Check, GitBranch, ArrowLeft, Trash2, ChevronDown } from 'lucide-react';
import { Check, GitBranch, ArrowLeft, Trash2, ChevronDown, Plus, User } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Input } from '@/components/ui/input';
import { Label } from '@/components/ui/label';
@@ -174,7 +174,9 @@ export function GitSettings() {
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor={`${origin}-origin`}>{t('origin')}</Label>
<Label htmlFor={`${origin}-origin`}>
{t('origin')} <span className="text-destructive">*</span>
</Label>
<Input
id={`${origin}-origin`}
placeholder="https://github.com"
@@ -184,7 +186,9 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${origin}-username`}>{t('username')}</Label>
<Label htmlFor={`${origin}-username`}>
{t('username')} <span className="text-destructive">*</span>
</Label>
<Input
id={`${origin}-username`}
placeholder="git"
@@ -193,7 +197,9 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor={`${origin}-password`}>{t('password')}</Label>
<Label htmlFor={`${origin}-password`}>
{t('password')} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id={`${origin}-password`}
placeholder={t('enterPassword')}
@@ -247,60 +253,86 @@ export function GitSettings() {
</div>
{preset.id === 'github' ? (
// Special rendering for GitHub - OAuth button if configured, otherwise token input
isOAuthConfigured && !forceManualEntry[preset.id] ? (
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={initiateOAuth}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
<ExternalFavicon
url="https://github.com"
size={16}
fallback={<GitBranch size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to GitHub
</span>
</>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setForceManualEntry(prev => ({ ...prev, [preset.id]: true }))}
>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
// Special rendering for GitHub - OAuth button if configured, otherwise token input
isOAuthConfigured && !forceManualEntry[preset.id] ? (
<div className="space-y-3">
<div className="flex gap-0">
<Button
onClick={initiateOAuth}
disabled={isOAuthLoading}
className="flex-1 rounded-r-none gap-2"
variant="default"
>
{isOAuthLoading ? (
<>
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white"></div>
Connecting...
</>
) : (
<>
<ExternalFavicon
url="https://github.com"
size={16}
fallback={<GitBranch size={16} />}
/>
<span className="truncate text-ellipsis overflow-hidden">
Connect to GitHub
</span>
</>
)}
</Button>
<DropdownMenu>
<DropdownMenuTrigger asChild>
<Button
variant="default"
className="rounded-l-none border-l border-primary-foreground/20 px-2"
disabled={isOAuthLoading}
>
<ChevronDown className="h-4 w-4" />
</Button>
</DropdownMenuTrigger>
<DropdownMenuContent align="end">
<DropdownMenuItem
onClick={() => setForceManualEntry(prev => ({ ...prev, [preset.id]: true }))}
>
Enter API key
</DropdownMenuItem>
</DropdownMenuContent>
</DropdownMenu>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
</div>
) : (
<div className="flex gap-2">
<PasswordInput
placeholder={t('enterToken')}
className="flex-1"
value={presetTokens[preset.id] || ''}
onChange={(e) => setPresetTokens(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!presetTokens[preset.id]?.trim()}
size="sm"
>
{t('add')}
</Button>
</div>
)
) : (
// Standard rendering for other providers
<div className="flex gap-2">
<PasswordInput
placeholder={t('enterToken')}
@@ -324,33 +356,7 @@ export function GitSettings() {
{t('add')}
</Button>
</div>
)
) : (
// Standard rendering for other providers
<div className="flex gap-2">
<PasswordInput
placeholder={t('enterToken')}
className="flex-1"
value={presetTokens[preset.id] || ''}
onChange={(e) => setPresetTokens(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' && presetTokens[preset.id]?.trim()) {
handleAddPresetProvider(preset);
}
}}
/>
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={!presetTokens[preset.id]?.trim()}
size="sm"
>
{t('add')}
</Button>
</div>
)}
)}
</CardContent>
</Card>
))}
@@ -363,12 +369,17 @@ export function GitSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
<h4 className="text-sm font-medium">{t('addCustomProvider')}</h4>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-3">
<div className="grid gap-2">
<Label htmlFor="custom-origin">{t('origin')}</Label>
<Label htmlFor="custom-origin">
{t('origin')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-origin"
placeholder="https://git.example.com"
@@ -377,7 +388,9 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-username">{t('username')}</Label>
<Label htmlFor="custom-username">
{t('username')} <span className="text-destructive">*</span>
</Label>
<Input
id="custom-username"
placeholder="git"
@@ -386,7 +399,9 @@ export function GitSettings() {
/>
</div>
<div className="grid gap-2">
<Label htmlFor="custom-password">{t('password')}</Label>
<Label htmlFor="custom-password">
{t('password')} <span className="text-destructive">*</span>
</Label>
<PasswordInput
id="custom-password"
placeholder={t('enterPassword')}
@@ -424,7 +439,10 @@ export function GitSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="git-identity">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('gitIdentity')}</h4>
<div className="flex items-center gap-2">
<User className="h-4 w-4" />
<h4 className="text-sm font-medium">{t('gitIdentity')}</h4>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="space-y-4">
+14 -13
View File
@@ -2,7 +2,7 @@ import { useState, useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useAIProjectId } from '@/hooks/useAIProjectId';
import { useGenerateProjectInfo } from '@/hooks/useGenerateProjectInfo';
import { useFS } from '@/hooks/useFS';
import { useLocalStorage } from '@/hooks/useLocalStorage';
import { useIsMobile } from '@/hooks/useIsMobile';
@@ -41,7 +41,7 @@ export default function Index() {
const location = useLocation();
const projectsManager = useProjectsManager();
const { fs } = useFS();
const { generateProjectId, isLoading: isGeneratingId } = useAIProjectId();
const { generateProjectInfo, isLoading: isGeneratingInfo } = useGenerateProjectInfo();
const { settings, addRecentlyUsedModel } = useAISettings();
const { config } = useAppContext();
const [providerModel, setProviderModel] = useState(() => {
@@ -155,7 +155,7 @@ export default function Index() {
e.stopPropagation();
setIsDragOver(false);
if (isCreating || isGeneratingId || !providerModel.trim()) return;
if (isCreating || isGeneratingInfo || !providerModel.trim()) return;
const files = Array.from(e.dataTransfer.files);
if (files.length === 0) return;
@@ -223,16 +223,16 @@ export default function Index() {
setIsCreating(true);
try {
// Use AI to generate project ID
const projectId = await generateProjectId(providerModel, prompt.trim());
// Use AI to generate project ID and select template
const { projectId, template } = await generateProjectInfo(providerModel, prompt.trim());
// Add model to recently used when creating project with AI
addRecentlyUsedModel(providerModel.trim());
// Create project with AI-generated ID and handle template update errors
// Create project with AI-generated ID and selected template
const project = await projectsManager.createProject(
prompt.trim(),
config.projectTemplate,
template.url,
projectId,
() => {
// Show a toast if template update fails (non-critical)
@@ -241,7 +241,8 @@ export default function Index() {
description: t('templateUpdateFailedDescription'),
variant: 'default',
});
}
},
{ name: template.name, description: template.description }
);
// Build message content from input and attached files
@@ -335,7 +336,7 @@ export default function Index() {
onKeyDown={handleKeyDown}
onClick={handleTextareaClick}
className="min-h-[120px] max-h-64 resize-none border-0 bg-transparent px-4 py-3 pb-16 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground"
disabled={isCreating || isGeneratingId || (hasProvidersConfigured && !providerModel.trim())}
disabled={isCreating || isGeneratingInfo || (hasProvidersConfigured && !providerModel.trim())}
rows={4}
style={{
height: 'auto',
@@ -356,7 +357,7 @@ export default function Index() {
onFileSelect={handleFileSelect}
onFileRemove={handleFileRemove}
selectedFiles={attachedFiles}
disabled={isCreating || isGeneratingId}
disabled={isCreating || isGeneratingInfo}
multiple={true}
/>
@@ -366,7 +367,7 @@ export default function Index() {
value={providerModel}
onChange={setProviderModel}
className="w-full"
disabled={isCreating || isGeneratingId}
disabled={isCreating || isGeneratingInfo}
placeholder={t('chooseModel')}
/>
</div>
@@ -377,13 +378,13 @@ export default function Index() {
disabled={
!prompt.trim() ||
isCreating ||
isGeneratingId ||
isGeneratingInfo ||
(hasProvidersConfigured && !providerModel.trim())
}
size="sm"
className="size-8 [&_svg]:size-5 rounded-full p-0"
>
{isCreating || isGeneratingId ? (
{isCreating || isGeneratingInfo ? (
<div className="animate-spin rounded-full h-3 w-3 border-b-2 border-white" />
) : (
<ArrowUp />
+30 -34
View File
@@ -3,9 +3,9 @@ import { useTranslation } from 'react-i18next';
import { Button } from '@/components/ui/button';
import { Label } from '@/components/ui/label';
import { Input } from '@/components/ui/input';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar';
import { Skeleton } from '@/components/ui/skeleton';
import { Separator } from '@/components/ui/separator';
import { RelayListManager } from '@/components/RelayListManager';
import SimpleLoginDialog from '@/components/auth/SimpleLoginDialog';
import SimpleSignupDialog from '@/components/auth/SimpleSignupDialog';
@@ -168,16 +168,14 @@ export function NostrSettings() {
</div>
)}
<div className="space-y-6">
<div className="space-y-6 max-w-xl">
{/* Account Management */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Users className="h-5 w-5" />
{t('nostrAccounts')}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-4">
<div className="flex items-center gap-2">
<Users className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('nostrAccounts')}</h3>
</div>
<div className="space-y-4">
{isLoading ? (
<div className="border rounded-lg overflow-hidden">
{/* Loading skeleton for accounts */}
@@ -216,7 +214,7 @@ export function NostrSettings() {
) : (
<>
{/* Account List - Joined Together */}
<div className="border rounded-lg overflow-hidden">
<div className="border rounded-lg bg-card text-card-foreground shadow-sm overflow-hidden">
{authors.map((account) => (
<div
key={account.id}
@@ -287,31 +285,29 @@ export function NostrSettings() {
</div>
</>
)}
</CardContent>
</Card>
</div>
</div>
<Separator />
{/* Relay Configuration */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Wifi className="h-5 w-5" />
{t('relayConfiguration')}
</CardTitle>
</CardHeader>
<CardContent>
<RelayListManager />
</CardContent>
</Card>
<div className="space-y-4">
<div className="flex items-center gap-2">
<Wifi className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('relayConfiguration')}</h3>
</div>
<RelayListManager />
</div>
<Separator />
{/* Nostr Git Servers */}
<Card>
<CardHeader>
<CardTitle className="flex items-center gap-2">
<Server className="h-5 w-5" />
{t('nostrGitServers')}
</CardTitle>
</CardHeader>
<CardContent className="space-y-4">
<div className="space-y-4">
<div className="flex items-center gap-2">
<Server className="h-5 w-5 text-primary" />
<h3 className="text-lg font-semibold">{t('nostrGitServers')}</h3>
</div>
<div className="space-y-4">
{/* Server List */}
<div className="space-y-2">
{config.ngitServers.map((hostname) => (
@@ -365,8 +361,8 @@ export function NostrSettings() {
{t('addServer')}
</Button>
</div>
</CardContent>
</Card>
</div>
</div>
</div>
{/* Login Dialog */}
+72 -40
View File
@@ -1,10 +1,12 @@
import { Settings2, ArrowLeft } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { Button } from "@/components/ui/button";
import { Card, CardContent } from "@/components/ui/card";
import { ThemePicker } from "@/components/ThemePicker";
import { LanguagePicker } from "@/components/LanguagePicker";
import { Switch } from "@/components/ui/switch";
import { Label } from "@/components/ui/label";
import { Separator } from "@/components/ui/separator";
import { useIsMobile } from "@/hooks/useIsMobile";
import { useNavigate } from "react-router-dom";
import { useAppContext } from "@/hooks/useAppContext";
@@ -52,50 +54,80 @@ export function Preferences() {
</div>
)}
<div className="space-y-6 max-w-sm">
<div className="space-y-2">
<Label htmlFor="theme-picker">{t('theme')}</Label>
<div className="w-full">
<ThemePicker />
</div>
<p className="text-sm text-muted-foreground">
{t('themeDescription')}
</p>
</div>
<Card className="max-w-md">
<CardContent className="pt-6">
<div className="space-y-6">
<div className="space-y-2">
<Label htmlFor="theme-picker">{t('theme')}</Label>
<div className="w-full">
<ThemePicker />
</div>
<p className="text-sm text-muted-foreground">
{t('themeDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="language-picker">{t('language')}</Label>
<div className="w-full">
<LanguagePicker />
</div>
<p className="text-sm text-muted-foreground">
{t('languageDescription')}
</p>
</div>
<div className="space-y-2">
<Label htmlFor="language-picker">{t('language')}</Label>
<div className="w-full">
<LanguagePicker />
</div>
<p className="text-sm text-muted-foreground">
{t('languageDescription')}
</p>
</div>
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="sentry-enabled" className="text-sm font-medium">
{t('shareErrorReports')}
</Label>
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="sentry-enabled" className="text-sm font-medium">
{t('shareErrorReports')}
</Label>
</div>
<Switch
id="sentry-enabled"
checked={config.sentryEnabled}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
sentryEnabled: checked,
}));
}}
/>
</div>
<p className="text-sm text-muted-foreground">
{t('shareErrorReportsDescription')}
</p>
</div>
<Separator className="my-4" />
{/* Global Chat Settings */}
<div className="space-y-2">
<div className="flex items-center justify-between">
<div className="space-y-0.5">
<Label htmlFor="global-chat-enabled" className="text-sm font-medium">
{t('globalChatEnabled')}
</Label>
</div>
<Switch
id="global-chat-enabled"
checked={config.globalChatEnabled !== false}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
globalChatEnabled: checked,
}));
}}
/>
</div>
<p className="text-sm text-muted-foreground">
{t('globalChatEnabledDescription')}
</p>
</div>
<Switch
id="sentry-enabled"
checked={config.sentryEnabled}
onCheckedChange={(checked) => {
updateConfig((current) => ({
...current,
sentryEnabled: checked,
}));
}}
/>
</div>
<p className="text-sm text-muted-foreground">
{t('shareErrorReportsDescription')}
</p>
</div>
</div>
</CardContent>
</Card>
</div>
);
}
+55 -99
View File
@@ -1,4 +1,4 @@
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw } from "lucide-react";
import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Cog, Globe, Image, Code, Monitor, Award, Bug, FolderTree, Terminal as TerminalIcon, MessageCircle } from "lucide-react";
import { useTranslation } from 'react-i18next';
import { useState, useEffect, useMemo } from "react";
import { Button } from "@/components/ui/button";
@@ -12,9 +12,13 @@ import { useNavigate } from "react-router-dom";
import { useAppContext } from "@/hooks/useAppContext";
import { useOffline } from "@/hooks/useOffline";
import { useToast } from "@/hooks/useToast";
import { defaultSystemPrompt } from "@/lib/system";
import { Terminal } from "@/components/Terminal";
// Default system prompt for global chat
const DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT = `You are a helpful AI assistant. 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.`;
export function SystemSettings() {
const { t } = useTranslation();
const isMobile = useIsMobile();
@@ -23,7 +27,6 @@ export function SystemSettings() {
const { toast } = useToast();
const { serviceWorkerRegistration, updateServiceWorker, clearCache } = useOffline();
const [projectTemplateInput, setProjectTemplateInput] = useState(config.projectTemplate);
const [esmUrlInput, setEsmUrlInput] = useState(config.esmUrl);
const [corsProxyInput, setCorsProxyInput] = useState(config.corsProxy);
const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl);
@@ -35,11 +38,12 @@ export function SystemSettings() {
const [fsPathPluginsInput, setFsPathPluginsInput] = useState(config.fsPathPlugins);
const [fsPathTemplatesInput, setFsPathTemplatesInput] = useState(config.fsPathTemplates);
const [sentryDsnInput, setSentryDsnInput] = useState(config.sentryDsn);
const [systemPromptInput, setSystemPromptInput] = useState(config.systemPrompt || defaultSystemPrompt);
const [chatSystemPromptInput, setChatSystemPromptInput] = useState(
config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT
);
// Check which settings differ from defaults
const isModified = useMemo(() => ({
projectTemplate: config.projectTemplate !== defaultConfig.projectTemplate,
esmUrl: config.esmUrl !== defaultConfig.esmUrl,
corsProxy: config.corsProxy !== defaultConfig.corsProxy,
faviconUrl: config.faviconUrl !== defaultConfig.faviconUrl,
@@ -52,19 +56,10 @@ export function SystemSettings() {
fsPathPlugins: config.fsPathPlugins !== defaultConfig.fsPathPlugins,
fsPathTemplates: config.fsPathTemplates !== defaultConfig.fsPathTemplates,
sentryDsn: config.sentryDsn !== defaultConfig.sentryDsn,
systemPrompt: (config.systemPrompt || defaultSystemPrompt) !== (defaultConfig.systemPrompt || defaultSystemPrompt),
globalChatSystemPrompt: (config.globalChatSystemPrompt || DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT) !== DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT,
}), [config, defaultConfig]);
// Restore functions - clear the value from config to use the default
const restoreProjectTemplate = () => {
const defaultValue = defaultConfig.projectTemplate;
setProjectTemplateInput(defaultValue);
updateConfig((current) => {
const { projectTemplate, ...rest } = current;
return rest;
});
};
const restoreEsmUrl = () => {
const defaultValue = defaultConfig.esmUrl;
setEsmUrlInput(defaultValue);
@@ -171,11 +166,10 @@ export function SystemSettings() {
});
};
const restoreSystemPrompt = () => {
const defaultValue = defaultSystemPrompt;
setSystemPromptInput(defaultValue);
const restoreChatSystemPrompt = () => {
setChatSystemPromptInput(DEFAULT_GLOBAL_CHAT_SYSTEM_PROMPT);
updateConfig((current) => {
const { systemPrompt, ...rest } = current;
const { globalChatSystemPrompt, ...rest } = current;
return rest;
});
};
@@ -310,7 +304,10 @@ export function SystemSettings() {
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="service-worker">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<h4 className="text-sm font-medium">{t('serviceWorker')}</h4>
<div className="flex items-center gap-2">
<Cog className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('serviceWorker')}</h4>
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-4">
@@ -409,59 +406,12 @@ export function SystemSettings() {
</AccordionItem>
</Accordion>
{/* Project Template Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="project-template">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('projectTemplate')}</h4>
{isModified.projectTemplate && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<div className="flex gap-2">
<Input
id="project-template"
type="url"
placeholder="https://gitlab.com/soapbox-pub/mkstack.git"
value={projectTemplateInput}
onChange={(e) => {
const value = e.target.value;
setProjectTemplateInput(value);
updateConfig((current) => ({
...current,
projectTemplate: value,
}));
}}
className="flex-1"
/>
{isModified.projectTemplate && (
<Button
variant="outline"
size="icon"
onClick={restoreProjectTemplate}
title={t('restoreToDefault')}
>
<RotateCcw className="h-4 w-4" />
</Button>
)}
</div>
<p className="text-xs text-muted-foreground">
{t('projectTemplateDescription')}
</p>
</div>
</AccordionContent>
</AccordionItem>
</Accordion>
{/* CORS Proxy Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="cors-proxy">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Globe className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('corsProxy')}</h4>
{isModified.corsProxy && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
@@ -510,6 +460,7 @@ export function SystemSettings() {
<AccordionItem value="favicon-url">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Image className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('faviconUrl')}</h4>
{isModified.faviconUrl && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
@@ -558,6 +509,7 @@ export function SystemSettings() {
<AccordionItem value="esm-url">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Code className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('esmUrl')}</h4>
{isModified.esmUrl && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
@@ -607,6 +559,7 @@ export function SystemSettings() {
<AccordionItem value="preview-domain">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Monitor className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('previewDomain')}</h4>
{isModified.previewDomain && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
@@ -655,6 +608,7 @@ export function SystemSettings() {
<AccordionItem value="showcase">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Award className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('showcase')}</h4>
{(isModified.showcaseEnabled || isModified.showcaseModerator) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
@@ -749,6 +703,7 @@ export function SystemSettings() {
<AccordionItem value="sentry-dsn">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Bug className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('sentryDsn')}</h4>
{isModified.sentryDsn && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
@@ -797,6 +752,7 @@ export function SystemSettings() {
<AccordionItem value="filesystem-paths">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<FolderTree className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('filesystemPaths')}</h4>
{(isModified.fsPathProjects || isModified.fsPathConfig || isModified.fsPathTmp || isModified.fsPathPlugins || isModified.fsPathTemplates) && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
@@ -1014,47 +970,46 @@ export function SystemSettings() {
</AccordionItem>
</Accordion>
{/* System Prompt Configuration */}
{/* Chat System Prompt Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="system-prompt">
<AccordionItem value="chat-system-prompt">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('systemPrompt')}</h4>
{isModified.systemPrompt && (
<MessageCircle className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('globalChatSystemPrompt')}</h4>
{isModified.globalChatSystemPrompt && (
<div className="h-2 w-2 rounded-full bg-yellow-500" title={t('modified')} />
)}
</div>
</AccordionTrigger>
<AccordionContent className="px-4 pb-4">
<div className="py-1 space-y-2">
<div className="flex gap-2 flex-col">
<Textarea
id="system-prompt"
placeholder="Enter EJS template..."
value={systemPromptInput}
onChange={(e) => {
const value = e.target.value;
setSystemPromptInput(value);
updateConfig((current) => ({
...current,
systemPrompt: value,
}));
}}
className="flex-1 font-mono text-xs min-h-[400px]"
/>
{isModified.systemPrompt && (
<Button
variant="outline"
onClick={restoreSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
</div>
<Textarea
placeholder="Enter system prompt..."
value={chatSystemPromptInput}
onChange={(e) => {
const value = e.target.value;
setChatSystemPromptInput(value);
updateConfig((current) => ({
...current,
globalChatSystemPrompt: value,
}));
}}
className="font-mono text-xs min-h-[150px]"
/>
{isModified.globalChatSystemPrompt && (
<Button
variant="outline"
size="sm"
onClick={restoreChatSystemPrompt}
className="w-full"
>
<RotateCcw className="h-4 w-4 mr-2" />
{t('restoreToDefault')}
</Button>
)}
<p className="text-xs text-muted-foreground">
{t('systemPromptDescription')}
{t('globalChatSystemPromptDescription')}
</p>
</div>
</AccordionContent>
@@ -1066,6 +1021,7 @@ export function SystemSettings() {
<AccordionItem value="terminal">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<TerminalIcon className="h-4 w-4 text-muted-foreground" />
<h4 className="text-sm font-medium">{t('terminal')}</h4>
</div>
</AccordionTrigger>
+7 -1
View File
@@ -35,7 +35,13 @@ export function TestApp({ children }: TestAppProps) {
],
updatedAt: 0,
},
projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git',
templates: [
{
name: "MKStack",
description: "Build Nostr clients with React.",
url: "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',