Compare commits

...
81 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
Alex Gleason f0c1784288 Clone from Nostr URL 2025-11-28 21:32:46 -06:00
Alex Gleason 94b4dcbda6 Filter out invalid repos 2025-11-28 21:29:23 -06:00
Alex Gleason c49e8811af Show follows repositories in Clone tab 2025-11-28 21:25:55 -06:00
Alex Gleason 37c72391a0 Projects Sidebar improvements 2025-11-28 21:16:41 -06:00
Alex Gleason 6c92b2dc4d Shrink down settings navigation again 2025-11-28 21:14:37 -06:00
Alex Gleason 676655ef66 Improve hover state of select 2025-11-28 21:01:01 -06:00
Alex Gleason 27f9435be9 Add foreground to many elements in settings 2025-11-28 20:58:31 -06:00
Alex Gleason 32656a8f5c Improve Settings Items hover states 2025-11-28 20:21:23 -06:00
Alex Gleason bd9a276275 Let PWA update nag be dismissed 2025-11-28 20:14:56 -06:00
Alex Gleason 7fa4330249 Remove Nostr pigeonholing from system prompt 2025-11-28 20:08:53 -06:00
Alex Gleason b5c2c79feb Remove pointless buttons from RepositoryCard 2025-11-28 20:05:42 -06:00
Alex Gleason f3a3d31977 Add a list of your own ngit repos to clone on the import page 2025-11-28 20:03:06 -06:00
Alex Gleason 68eee82c92 Make everything a bit rounder 2025-11-28 15:10:49 -06:00
Alex Gleason cd006889c8 Add search to projects sidebar 2025-11-28 15:02:37 -06:00
Alex Gleason d23778547f Clean up unused settings i18n strings 2025-11-28 14:42:14 -06:00
Alex Gleason 627a43309c Improve mobile settings design 2025-11-28 14:33:33 -06:00
Alex Gleason 07d594a373 Settings design improvements 2025-11-28 14:28:36 -06:00
DanConwayDev 5b8cb25675 Revert "Checkout branch with "force" so it updates the tree"
This reverts commit d13bc84232.

proceed with caution on this as i dont know what you were fixing
with this change
2025-11-28 11:34:19 -06:00
DanConwayDev 89de28cb0c fix: recovered for detached HEAD
git_commit tool was showing a false positive when in reality no
commits were changed. there are also other issues in the UI whilst
in this state. eg. current branch doesn't show, cannot push or pull,
or 'push to nostr' or github or other remote.

warning this must be done in combination with reverting
d13bc84232 or the user will lose all
uncomitted changes
2025-11-28 11:34:19 -06:00
Alex Gleason c5e5cafb77 Add "Try again" action to Quilly fallback 2025-11-26 12:05:33 -06:00
Alex Gleason 926e63bb81 Poll the Lightning invoice screen for payment 2025-11-25 17:36:42 -06:00
97 changed files with 5145 additions and 1709 deletions

No files matched your search

+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>
+2 -2
View File
@@ -99,7 +99,7 @@ export function AppLayout({
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={(project) => {
@@ -123,7 +123,7 @@ export function AppLayout({
<div className="min-h-screen flex bg-background">
{/* Fixed Sidebar - show if showSidebar is true and sidebar is visible */}
{showSidebar && isSidebarVisible && (
<div className="w-80 border-r bg-sidebar transition-all duration-300">
<div className="w-72 border-r bg-sidebar transition-all duration-300">
<ProjectSidebar
selectedProject={selectedProject}
onSelectProject={handleProjectSelect}
+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,
+148 -35
View File
@@ -1,4 +1,4 @@
import { useState, useEffect } from 'react';
import { useState, useEffect, useCallback } from 'react';
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
import QRCode from 'qrcode';
import { CreditCard, Zap, ExternalLink, RefreshCw, Check, X, Clock, AlertCircle, Copy, RotateCcw, ArrowLeft, Gift, Plus, History, DollarSign, Printer, Download } from 'lucide-react';
@@ -85,17 +85,33 @@ const PRESET_AMOUNTS = [5, 10, 25, 50, 100];
interface LightningPaymentProps {
invoice: string;
amount: number;
paymentId: string;
provider: AIProvider;
onClose: () => void;
onPaymentCompleted: () => void;
}
function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
function LightningPayment({ invoice, amount, paymentId, provider, onClose, onPaymentCompleted }: LightningPaymentProps) {
const { t } = useTranslation();
const { user } = useCurrentUser();
const { config } = useAppContext();
const queryClient = useQueryClient();
const [qrDataUrl, setQrDataUrl] = useState<string>('');
const [isWebLNAvailable, setIsWebLNAvailable] = useState(false);
const [isPayingWithWebLN, setIsPayingWithWebLN] = useState(false);
const [showCopiedTooltip, setShowCopiedTooltip] = useState(false);
const [paymentCompleted, setPaymentCompleted] = useState(false);
const { toast } = useToast();
const formatCurrency = useCallback((amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
}, []);
useEffect(() => {
// Generate QR code
QRCode.toDataURL(invoice, {
@@ -113,6 +129,98 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
setIsWebLNAvailable(typeof window !== 'undefined' && 'webln' in window);
}, [invoice]);
// Poll payment status
useEffect(() => {
// Don't poll if payment already completed
if (paymentCompleted) return;
let intervalId: NodeJS.Timeout | null = null;
const pollPaymentStatus = async () => {
// Double-check in case state updated during async operation
if (paymentCompleted) return;
try {
const ai = createAIClient(provider, user, config.corsProxy);
const payment = await ai.get(`/credits/payments/${paymentId}`) as Payment;
if (payment.status === 'completed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
// Update credits balance
queryClient.invalidateQueries({
queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Update payments list
queryClient.invalidateQueries({
queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id],
});
// Show toast
toast({
title: t('paymentCompleted'),
description: t('creditsAddedToAccount', { amount: formatCurrency(payment.amount) }),
});
// Close dialog immediately
onPaymentCompleted();
} else if (payment.status === 'failed') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentFailed'),
description: t('paymentFailed'),
variant: 'destructive',
});
} else if (payment.status === 'expired') {
// Mark as completed to prevent further polling
setPaymentCompleted(true);
// Clear the interval immediately
if (intervalId) {
clearInterval(intervalId);
intervalId = null;
}
toast({
title: t('paymentExpired'),
description: t('paymentExpiredMessage'),
variant: 'destructive',
});
}
} catch (error) {
console.error('Failed to poll payment status:', error);
}
};
// Poll immediately on mount
pollPaymentStatus();
// Then poll every 3 seconds
intervalId = setInterval(pollPaymentStatus, 3000);
return () => {
if (intervalId) {
clearInterval(intervalId);
}
};
}, [paymentId, provider, user, config.corsProxy, queryClient, toast, t, onPaymentCompleted, formatCurrency, paymentCompleted]);
const handleWebLNPay = async () => {
if (!window.webln) return;
@@ -145,15 +253,6 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) {
setTimeout(() => setShowCopiedTooltip(false), 2000);
};
const formatCurrency = (amount: number) => {
return new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'USD',
minimumFractionDigits: 2,
maximumFractionDigits: 2,
}).format(amount);
};
return (
<div className="space-y-4">
<div className="text-center">
@@ -223,6 +322,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
const [amount, setAmount] = useState<number>(10);
const [paymentMethod, setPaymentMethod] = useState<'stripe' | 'lightning'>('stripe');
const [lightningInvoice, setLightningInvoice] = useState<string | null>(null);
const [lightningPaymentId, setLightningPaymentId] = useState<string | null>(null);
const [refreshingPayments, setRefreshingPayments] = useState<Set<string>>(new Set());
const [giftcardAmount, setGiftcardAmount] = useState<number>(10);
const [giftcardQuantity, setGiftcardQuantity] = useState<number>(1);
@@ -301,6 +401,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (payment.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
}
// Refresh payments list
@@ -486,6 +587,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
} else if (paymentPreview.method === 'lightning') {
// Show Lightning payment interface
setLightningInvoice(paymentPreview.url);
setLightningPaymentId(paymentPreview.id);
}
// Refresh payments list
@@ -882,27 +984,37 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</DialogHeader>
{/* Lightning Payment Interface */}
{lightningInvoice ? (
{lightningInvoice && lightningPaymentId ? (
<div className="flex-1 overflow-y-auto px-1 -mx-1">
<LightningPayment
invoice={lightningInvoice}
amount={amount}
onClose={() => setLightningInvoice(null)}
paymentId={lightningPaymentId}
provider={provider}
onClose={() => {
setLightningInvoice(null);
setLightningPaymentId(null);
}}
onPaymentCompleted={() => {
// Close the lightning payment view immediately
setLightningInvoice(null);
setLightningPaymentId(null);
}}
/>
</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">
@@ -986,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">
@@ -1054,6 +1166,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
onClick={() => {
if (payment.method === 'lightning') {
setLightningInvoice(payment.url);
setLightningPaymentId(payment.id);
} else {
window.open(payment.url, '_blank');
}
@@ -1077,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"
@@ -1109,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>
@@ -1172,15 +1285,15 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro
</AccordionItem>
{/* Your Gift Cards Accordion */}
<AccordionItem value="list" className="border-b-0">
<AccordionTrigger className="hover:no-underline">
<AccordionItem value="list">
<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,
};
-2
View File
@@ -182,7 +182,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
@@ -1289,7 +1288,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
await git.checkout({
dir: projectPath,
ref: pr.sourceBranch,
force: true,
});
await refetchGitStatus();
toast({
+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,
+18 -19
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,17 +258,11 @@ export function MCPServersSection() {
</Accordion>
))}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noMcpServersConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add New MCP Server */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-server" className="border rounded-lg">
<AccordionItem value="add-server">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
@@ -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 />
@@ -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,
}}
+27 -11
View File
@@ -1,6 +1,6 @@
import { useEffect, useState } from 'react';
import { useRegisterSW } from 'virtual:pwa-register/react';
import { Sparkles } from 'lucide-react';
import { Sparkles, X } from 'lucide-react';
/**
* Component that prompts users to update when a new service worker is available
@@ -52,22 +52,38 @@ export function PWAUpdatePrompt() {
updateServiceWorker(true);
};
const handleDismiss = (e: React.MouseEvent) => {
e.stopPropagation();
setShowPrompt(false);
};
if (!showPrompt) {
return null;
}
return (
<div className="fixed bottom-4 left-1/2 -translate-x-1/2 md:top-4 md:right-4 md:bottom-auto md:left-auto md:translate-x-0 z-50 animate-in slide-in-from-bottom-4 md:slide-in-from-top-4 duration-500 max-w-full">
<button
onClick={handleUpdate}
disabled={isUpdating}
className="group relative flex items-center gap-2 px-4 py-2.5 bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate"
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
<div className="relative group">
<button
onClick={handleUpdate}
disabled={isUpdating}
className={`relative flex items-center gap-2 px-4 py-2.5 ${!isUpdating ? 'pr-10' : ''} bg-gradient-to-r from-amber-100 to-yellow-100 dark:from-amber-900 dark:to-yellow-900 border border-amber-300 dark:border-amber-700 rounded-full shadow-lg hover:shadow-xl transition-all duration-300 hover:scale-105 active:scale-95 disabled:cursor-not-allowed disabled:hover:scale-100 max-w-full truncate`}
>
<Sparkles className={`h-4 w-4 text-amber-600 dark:text-amber-400 ${isUpdating ? 'animate-spin' : 'group-hover:rotate-12 transition-transform duration-300'}`} />
<span className="text-sm font-medium whitespace-nowrap max-w-full truncate text-amber-900 dark:text-amber-100">
{isUpdating ? 'Updating...' : 'Update available — Click to refresh'}
</span>
</button>
{!isUpdating && (
<button
onClick={handleDismiss}
className="absolute right-2 top-1/2 -translate-y-1/2 p-1 rounded-full hover:bg-amber-200 dark:hover:bg-amber-800 transition-colors duration-200"
aria-label="Dismiss update notification"
>
<X className="h-4 w-4 text-amber-700 dark:text-amber-300" />
</button>
)}
</div>
</div>
);
}
+6 -23
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,17 +107,11 @@ export function PluginsSection() {
/>;
})}
</div>
) : (
<Alert>
<AlertDescription className="text-sm">
{t('noPluginsConfigured')}
</AlertDescription>
</Alert>
)}
{/* Add Plugin Section */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="add-plugin" className="border rounded-lg">
<AccordionItem value="add-plugin">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<Plus className="h-4 w-4" />
@@ -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>
+41 -6
View File
@@ -1,9 +1,10 @@
import React, { useEffect } from 'react';
import React, { useEffect, useState, useMemo } from 'react';
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle } from 'lucide-react';
import { Plus, Folder, GitBranch, Loader2, ChevronDown, Star, Columns2, X, Settings, HelpCircle, Search } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Skeleton } from '@/components/ui/skeleton';
import { Input } from '@/components/ui/input';
import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from '@/components/ui/dropdown-menu';
import { useProjects } from '@/hooks/useProjects';
import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus';
@@ -93,10 +94,24 @@ export function ProjectSidebar({
const queryClient = useQueryClient();
const { data: projects = [], isLoading, error } = useProjects();
const [favorites] = useLocalStorage<string[]>('project-favorites', []);
const [searchQuery, setSearchQuery] = useState('');
const isMobile = useIsMobile();
const navigate = useNavigate();
// Fast in-memory search filtering
const filteredProjects = useMemo(() => {
if (!searchQuery.trim()) {
return projects;
}
const query = searchQuery.toLowerCase();
return projects.filter(project =>
project.id.toLowerCase().includes(query) ||
project.name.toLowerCase().includes(query)
);
}, [projects, searchQuery]);
// Custom navigate function that closes sidebar on mobile
const navigateAndClose = (path: string) => {
navigate(path);
@@ -166,12 +181,12 @@ export function ProjectSidebar({
<div className="flex-1 overflow-y-auto">
<div className="p-2">
<div className="mb-2">
<div className="mb-2 space-y-3">
<div className="relative rounded-md bg-gradient-to-r from-primary to-accent hover:from-primary/90 hover:to-accent/90 transition-all duration-200">
<div className="flex">
<button
onClick={handleNewProject}
className="flex-1 flex items-center justify-center px-3 py-2 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
className="flex-1 flex items-center justify-center px-3 py-2.5 text-sm font-medium text-primary-foreground rounded-l-md hover:bg-white/10 transition-colors"
>
<Plus className="h-4 w-4 mr-2" />
{t('newProject')}
@@ -179,7 +194,7 @@ export function ProjectSidebar({
<div className="w-px bg-white/20" />
<DropdownMenu>
<DropdownMenuTrigger asChild>
<button className="px-2 py-2 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<button className="px-3 py-2.5 text-primary-foreground hover:bg-white/10 rounded-r-md transition-colors">
<ChevronDown className="h-4 w-4" />
</button>
</DropdownMenuTrigger>
@@ -195,6 +210,20 @@ export function ProjectSidebar({
</DropdownMenu>
</div>
</div>
{/* Search Input */}
{projects.length > 0 && (
<div className="relative">
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-muted-foreground pointer-events-none" />
<Input
type="text"
placeholder={t('searchProjects')}
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
className="pl-9 h-9 text-sm bg-sidebar-accent/50 border-sidebar-border focus-visible:ring-primary/50"
/>
</div>
)}
</div>
{isLoading ? (
@@ -214,9 +243,15 @@ export function ProjectSidebar({
<p className="text-sm">{t('noProjectsYet')}</p>
<p className="text-xs">{t('createFirstProject')}</p>
</div>
) : filteredProjects.length === 0 ? (
<div className="text-center p-6 text-muted-foreground">
<Search className="h-8 w-8 mx-auto mb-2 opacity-50" />
<p className="text-sm">{t('noProjectsFound')}</p>
<p className="text-xs">{t('tryDifferentSearch')}</p>
</div>
) : (
<div className="space-y-1">
{projects.map((project) => (
{filteredProjects.map((project) => (
<ProjectItem
key={project.id}
project={project}
+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>
);
}
+7 -1
View File
@@ -197,7 +197,13 @@ function QuillyContent({ error, onDismiss, onNewChat, onOpenModelSelector, onTry
message: error.message
? `AI service error: ${error.message}`
: 'Sorry, I encountered an unexpected error. Please try again.',
actions: [],
actions: onTryAgain ? [{
label: 'Try again',
onClick: () => {
onTryAgain();
onDismiss();
},
}] : [],
};
};
+99
View File
@@ -0,0 +1,99 @@
import React from 'react';
import { Button } from '@/components/ui/button';
import { Card, CardContent } from '@/components/ui/card';
import { Badge } from '@/components/ui/badge';
import { GitBranch } from 'lucide-react';
import type { Repository } from '@/hooks/useUserRepositories';
import { useAuthor } from '@/hooks/useAuthor';
import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar';
import { genUserName } from '@/lib/genUserName';
import { useNavigate } from 'react-router-dom';
import { nip19 } from 'nostr-tools';
interface RepositoryCardProps {
repo: Repository;
}
export function RepositoryCard({ repo }: RepositoryCardProps) {
const { data: authorData } = useAuthor(repo.pubkey);
const navigate = useNavigate();
const displayName = authorData?.metadata?.name || genUserName(repo.pubkey);
const profileImage = authorData?.metadata?.picture;
// Construct Nostr clone URL
const nostrCloneUrl = `nostr://${nip19.npubEncode(repo.pubkey)}/${repo.repoId}`;
const handleClone = () => {
// Navigate to clone page with Nostr URL parameter
navigate(`/clone?url=${encodeURIComponent(nostrCloneUrl)}`);
};
return (
<Card className="h-full flex flex-col hover:shadow-lg transition-shadow cursor-pointer" onClick={handleClone}>
<CardContent className="p-6 flex flex-col flex-1">
{/* Header with name and author */}
<div className="mb-4">
<h3 className="font-semibold text-lg leading-tight mb-2 truncate">
{repo.name}
</h3>
<div className="flex items-center gap-2 text-sm text-muted-foreground">
<Avatar className="h-4 w-4">
{profileImage && (
<AvatarImage src={profileImage} alt={displayName} />
)}
<AvatarFallback className="text-[8px]">
{displayName.slice(0, 2).toUpperCase()}
</AvatarFallback>
</Avatar>
<span className="truncate">{displayName}</span>
</div>
</div>
{/* Description */}
{repo.description && (
<p className="text-sm text-muted-foreground line-clamp-2 mb-4">
{repo.description}
</p>
)}
{/* Tags */}
{repo.repoTags.length > 0 && (
<div className="flex flex-wrap gap-1 mb-4">
{repo.repoTags.slice(0, 3).map((tag, index) => (
<Badge key={index} variant="secondary" className="text-xs">
{tag}
</Badge>
))}
{repo.repoTags.length > 3 && (
<Badge variant="secondary" className="text-xs">
+{repo.repoTags.length - 3}
</Badge>
)}
</div>
)}
{/* Personal fork badge */}
{repo.isPersonalFork && (
<div className="mb-4">
<Badge variant="outline" className="text-xs">
Personal Fork
</Badge>
</div>
)}
{/* Actions */}
<div className="mt-auto">
<Button
size="sm"
className="w-full"
onClick={handleClone}
>
<GitBranch className="h-4 w-4 mr-2" />
Clone
</Button>
</div>
</CardContent>
</Card>
);
}
+4 -4
View File
@@ -27,7 +27,7 @@ describe('SentryProvider', () => {
relays: [{ url: 'wss://relay.test', read: true, write: true }],
updatedAt: 0,
},
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}',
+57
View File
@@ -0,0 +1,57 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isActive?: boolean;
className?: string;
}
export function SettingsItem({
icon: Icon,
title,
onClick,
isActive = false,
className,
}: SettingsItemProps) {
return (
<button
onClick={onClick}
className={cn(
'group w-full text-left p-2 rounded-lg transition-all duration-200 border',
{
'bg-primary/10 border-primary/20 shadow-sm': isActive,
'border-transparent hover:bg-muted/60 hover:shadow-sm': !isActive,
},
className
)}
>
<div className="flex items-center gap-2.5">
<div className="rounded-md transition-all duration-200">
<Icon className={cn('h-4 w-4 flex-shrink-0 transition-colors duration-200', {
'text-primary': isActive,
'text-muted-foreground group-hover:text-foreground': !isActive,
})} />
</div>
<div className="flex-1 min-w-0">
<div className={cn('text-sm font-medium transition-colors duration-200', {
'text-primary': isActive,
'text-foreground': !isActive,
})}>
{title}
</div>
</div>
<ChevronRight className={cn(
'h-4 w-4 flex-shrink-0 transition-all duration-200',
'opacity-0 -translate-x-1 group-hover:opacity-100 group-hover:translate-x-0',
{
'text-primary opacity-60': isActive,
'text-muted-foreground': !isActive,
}
)} />
</div>
</button>
);
}
+43
View File
@@ -0,0 +1,43 @@
import { ChevronRight } from 'lucide-react';
import { cn } from '@/lib/utils';
interface SettingsItemMobileProps {
icon: React.ComponentType<{ className?: string }>;
title: string;
onClick: () => void;
isFirst?: boolean;
isLast?: boolean;
}
export function SettingsItemMobile({
icon: Icon,
title,
onClick,
isFirst = false,
isLast = false,
}: SettingsItemMobileProps) {
return (
<button
onClick={onClick}
className={cn(
'w-full text-left px-4 py-3.5 bg-card text-card-foreground transition-colors active:bg-muted/50',
'flex items-center gap-3',
'border-b border-border last:border-b-0',
{
'rounded-t-xl': isFirst,
'rounded-b-xl': isLast,
}
)}
>
<div className="flex items-center justify-center w-7 h-7 rounded-lg bg-primary/10">
<Icon className="h-4 w-4 text-primary flex-shrink-0" />
</div>
<div className="flex-1 min-w-0">
<div className="text-base">
{title}
</div>
</div>
<ChevronRight className="h-5 w-5 text-muted-foreground/50 flex-shrink-0" />
</button>
);
}
+31 -36
View File
@@ -8,8 +8,8 @@ import { ProjectSidebar } from '@/components/ProjectSidebar';
import { useProjectsManager } from '@/hooks/useProjectsManager';
import { useIsMobile } from '@/hooks/useIsMobile';
import { type Project } from '@/lib/ProjectsManager';
import { cn } from '@/lib/utils';
import { getSettingsItems } from '@/lib/settingsItems';
import { getSettingsCategories } from '@/lib/settingsItems';
import { SettingsItem } from '@/components/SettingsItem';
export function SettingsLayout() {
const { t } = useTranslation();
@@ -60,9 +60,11 @@ export function SettingsLayout() {
};
// Get current settings page
const settingsItems = getSettingsItems(t);
const settingsCategories = getSettingsCategories(t);
const currentPath = location.pathname;
const currentSettingsId = settingsItems.find(item => item.href === currentPath)?.id;
const currentSettingsId = settingsCategories
.flatMap(category => category.items)
.find(item => item.href === currentPath)?.id;
if (isMobile) {
return (
@@ -89,7 +91,7 @@ export function SettingsLayout() {
className="absolute inset-0"
onClick={() => setIsSidebarVisible(false)}
/>
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={null}
onSelectProject={(project) => {
@@ -112,7 +114,7 @@ export function SettingsLayout() {
<div className="h-screen flex bg-background overflow-hidden">
{/* Left Column - Projects Sidebar (optionally hidden) */}
{isSidebarVisible && (
<div className="w-80 border-r bg-sidebar flex-shrink-0">
<div className="w-72 border-r bg-sidebar flex-shrink-0">
<ProjectSidebar
selectedProject={null}
onSelectProject={handleProjectSelect}
@@ -123,7 +125,7 @@ export function SettingsLayout() {
)}
{/* Middle Column - Settings Navigation */}
<div className="w-96 border-r bg-background flex flex-col flex-shrink-0">
<div className="w-72 border-r bg-background flex flex-col flex-shrink-0">
{/* Header with toggle button */}
<div className="h-12 px-4 py-2 border-b flex-shrink-0">
<div className="flex items-center gap-3">
@@ -146,36 +148,29 @@ export function SettingsLayout() {
{/* Settings Navigation - Scrollable */}
<ScrollArea className="flex-1">
<div className="p-4">
<div className="space-y-2">
{settingsItems.map((item) => {
const Icon = item.icon;
const isActive = currentSettingsId === item.id;
<div className="p-4 space-y-6">
{settingsCategories.map((category) => (
<div key={category.id}>
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-2">
{category.title}
</h3>
<div className="space-y-1">
{category.items.map((item) => {
const isActive = currentSettingsId === item.id;
return (
<button
key={item.id}
onClick={() => navigate(item.href)}
className={cn('w-full text-left p-3 rounded-lg transition-colors border border-transparent', {
'bg-primary/10 border border-primary/20': isActive,
'hover:bg-muted/50': !isActive,
})}
>
<div className="flex items-start gap-3">
<Icon className={`h-5 w-5 mt-0.5 ${isActive ? 'text-primary' : 'text-muted-foreground'}`} />
<div className="flex-1 min-w-0">
<div className={`font-medium ${isActive ? 'text-primary' : 'text-foreground'}`}>
{item.title}
</div>
<div className="text-sm text-muted-foreground mt-0.5">
{item.description}
</div>
</div>
</div>
</button>
);
})}
</div>
return (
<SettingsItem
key={item.id}
icon={item.icon}
title={item.title}
onClick={() => navigate(item.href)}
isActive={isActive}
/>
);
})}
</div>
</div>
))}
</div>
</ScrollArea>
</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]">
+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>
-1
View File
@@ -223,7 +223,6 @@ export function BranchManager({ projectId, currentBranch, onBranchChange }: Bran
await git.checkout({
dir: projectPath,
ref: branchName,
force: true,
});
toast({
+1 -1
View File
@@ -12,7 +12,7 @@ const AccordionItem = React.forwardRef<
>(({ className, ...props }, ref) => (
<AccordionPrimitive.Item
ref={ref}
className={cn("border-b", className)}
className={cn("border rounded-lg bg-card text-card-foreground shadow-sm", className)}
{...props}
/>
))
+1 -1
View File
@@ -11,7 +11,7 @@ const Checkbox = React.forwardRef<
<CheckboxPrimitive.Root
ref={ref}
className={cn(
"peer h-4 w-4 shrink-0 rounded-sm border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
"peer h-4 w-4 shrink-0 rounded-xs border border-primary ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 data-[state=checked]:bg-primary data-[state=checked]:text-primary-foreground",
className
)}
{...props}
+1 -1
View File
@@ -17,7 +17,7 @@ const SelectTrigger = React.forwardRef<
<SelectPrimitive.Trigger
ref={ref}
className={cn(
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
"flex h-10 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm ring-offset-background placeholder:text-muted-foreground hover:bg-border/20 dark:hover:bg-border/50 focus:outline-none focus:ring-2 focus:ring-ring focus:ring-offset-2 disabled:cursor-not-allowed disabled:opacity-50 [&>span]:line-clamp-1",
className
)}
{...props}
+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
};
}
+43
View File
@@ -0,0 +1,43 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
/**
* Hook to get the user's contact list (kind 3 follow list)
* Returns an array of pubkeys that the user follows
*/
export function useContacts(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'contacts', userPubkey],
queryFn: async (): Promise<string[]> => {
if (!userPubkey) {
return [];
}
// Get the user's contact list (kind 3)
const events = await nostr.query([{
kinds: [3],
authors: [userPubkey],
limit: 1,
}], { signal: AbortSignal.timeout(3000) });
if (events.length === 0) {
return [];
}
// Get the most recent contact list event
const contactList = events.sort((a, b) => b.created_at - a.created_at)[0];
// Extract pubkeys from 'p' tags
const followedPubkeys = contactList.tags
.filter(tag => tag[0] === 'p' && tag[1])
.map(tag => tag[1]);
return followedPubkeys;
},
enabled: !!userPubkey,
staleTime: 60000, // 1 minute
refetchInterval: 300000, // 5 minutes
});
}
+92
View File
@@ -0,0 +1,92 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
import type { Repository } from './useUserRepositories';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
/**
* Hook to get repositories from a list of followed users
*/
export function useFollowedRepositories(followedPubkeys: string[] = []) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'followed-repositories', followedPubkeys.sort().join(',')],
queryFn: async (): Promise<Repository[]> => {
if (followedPubkeys.length === 0) {
return [];
}
// Get all repository announcements from followed users
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: followedPubkeys,
limit: 500, // Increased limit to get more repos from follows
}], { signal: AbortSignal.timeout(5000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by author+d-tag to get latest version of each repo
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const key = `${event.pubkey}:${dTag}`;
const existing = repoMap.get(key);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(key, event);
}
}
// Convert to Repository objects
for (const [, event] of repoMap) {
try {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
// Sort by created_at (newest first)
return repositories.sort((a, b) => b.created_at - a.created_at);
},
enabled: followedPubkeys.length > 0,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
+503
View File
@@ -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);
},
});
+96
View File
@@ -0,0 +1,96 @@
import { useNostr } from '@nostrify/react';
import { useQuery } from '@tanstack/react-query';
import type { NostrEvent } from '@nostrify/nostrify';
// Kind 30617 for repository announcements (NIP-34)
const REPOSITORY_KIND = 30617;
export interface Repository extends NostrEvent {
repoId: string;
name: string;
description: string;
webUrls: string[];
cloneUrls: string[];
relays: string[];
maintainers: string[];
repoTags: string[];
earliestUniqueCommit?: string;
isPersonalFork: boolean;
}
export function useUserRepositories(userPubkey?: string) {
const { nostr } = useNostr();
return useQuery({
queryKey: ['nostr', 'user-repositories', userPubkey],
queryFn: async (): Promise<Repository[]> => {
if (!userPubkey) {
return [];
}
// Get all repository announcements for this user
const events = await nostr.query([{
kinds: [REPOSITORY_KIND],
authors: [userPubkey],
limit: 100,
}], { signal: AbortSignal.timeout(3000) });
// Process repository events
const repositories: Repository[] = [];
const repoMap = new Map<string, NostrEvent>();
// Group by d-tag (repo-id) to get latest version
for (const event of events) {
const dTag = event.tags.find(tag => tag[0] === 'd')?.[1];
if (!dTag) continue;
const existing = repoMap.get(dTag);
if (!existing || event.created_at > existing.created_at) {
repoMap.set(dTag, event);
}
}
// Convert to Repository objects
for (const [dTag, event] of repoMap) {
try {
const name = event.tags.find(tag => tag[0] === 'name')?.[1] || dTag;
const description = event.tags.find(tag => tag[0] === 'description')?.[1] || '';
const webUrls = event.tags.filter(tag => tag[0] === 'web').map(tag => tag[1]).filter(Boolean);
const cloneUrls = event.tags.filter(tag => tag[0] === 'clone').map(tag => tag[1]).filter(Boolean);
const relays = event.tags.filter(tag => tag[0] === 'relays').map(tag => tag[1]).filter(Boolean);
const maintainers = event.tags.filter(tag => tag[0] === 'maintainers').map(tag => tag[1]).filter(Boolean);
const repoTags = event.tags.filter(tag => tag[0] === 't' && tag[1] !== 'personal-fork').map(tag => tag[1]);
const earliestUniqueCommit = event.tags.find(tag => tag[0] === 'r' && tag[2] === 'euc')?.[1];
const isPersonalFork = event.tags.some(tag => tag[0] === 't' && tag[1] === 'personal-fork');
// Filter out invalid repositories without clone URLs
if (cloneUrls.length === 0) {
console.warn('Skipping repository without clone URLs:', dTag);
continue;
}
repositories.push({
...event,
repoId: dTag,
name,
description,
webUrls,
cloneUrls,
relays,
maintainers,
repoTags,
earliestUniqueCommit,
isPersonalFork,
});
} catch (error) {
console.warn('Failed to parse repository:', error);
}
}
return repositories;
},
enabled: !!userPubkey,
staleTime: 30000, // 30 seconds
refetchInterval: 60000, // 1 minute
});
}
+1 -1
View File
@@ -37,7 +37,7 @@
--input: 220 13% 91%;
--ring: 271 81% 56%;
--radius: 0.375rem;
--radius: 0.75rem;
/* Sidebar colors - Enhanced purple theme */
--sidebar-background: 271 81% 96%;
+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']);
-2
View File
@@ -122,7 +122,6 @@ export class GitCheckoutCommand implements GitSubcommand {
await this.git.checkout({
dir: cwd,
ref: branchName,
force: true,
});
return createSuccessResult(`Switched to branch '${branchName}'\n`);
@@ -165,7 +164,6 @@ export class GitCheckoutCommand implements GitSubcommand {
await this.git.checkout({
dir: cwd,
ref: branchName,
force: true,
});
return createSuccessResult(`Switched to a new branch '${branchName}'\n`);
+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) {
-1
View File
@@ -1244,7 +1244,6 @@ export class Git {
fs: this.fs,
dir: options.dir,
ref: expectedBranch,
force: true,
});
} catch (checkoutError) {
console.warn(`Failed to checkout branch ${expectedBranch}:`, checkoutError);
+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;
}
+70 -55
View File
@@ -2,72 +2,87 @@ import { Bot, GitBranch, Database, Wifi, Settings2, Info, Settings, Rocket } fro
export interface SettingsItem {
id: string;
title: string;
description: string;
icon: React.ComponentType<{ className?: string }>;
title: string;
href: string;
}
export interface SettingsCategory {
id: string;
title: string;
items: SettingsItem[];
}
/**
* Get the list of settings items with translations
* Get the categorized list of settings items with translations
* @param t - Translation function from useTranslation hook
* @returns Array of settings items
* @returns Array of settings categories with translated items
*/
export const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [
export const getSettingsCategories = (t: (key: string) => string): SettingsCategory[] => [
{
id: 'preferences',
title: t('preferences'),
description: t('preferencesDescription'),
icon: Settings2,
href: '/settings/preferences',
id: 'general',
title: t('general'),
items: [
{
id: 'preferences',
icon: Settings2,
title: t('preferences'),
href: '/settings/preferences',
},
],
},
{
id: 'ai',
title: t('aiSettings'),
description: t('aiSettingsDescription'),
icon: Bot,
href: '/settings/ai',
id: 'integrations',
title: t('integrations'),
items: [
{
id: 'ai',
icon: Bot,
title: t('aiSettings'),
href: '/settings/ai',
},
{
id: 'git',
icon: GitBranch,
title: t('gitSettings'),
href: '/settings/git',
},
{
id: 'nostr',
icon: Wifi,
title: t('nostrSettings'),
href: '/settings/nostr',
},
{
id: 'deploy',
icon: Rocket,
title: t('deploySettings'),
href: '/settings/deploy',
},
],
},
{
id: 'git',
title: t('gitSettings'),
description: t('gitSettingsDescription'),
icon: GitBranch,
href: '/settings/git',
},
{
id: 'deploy',
title: t('deploySettings'),
description: t('deploySettingsDescription'),
icon: Rocket,
href: '/settings/deploy',
},
{
id: 'nostr',
title: t('nostrSettings'),
description: t('nostrSettingsDescription'),
icon: Wifi,
href: '/settings/nostr',
},
{
id: 'storage',
title: t('storageSettings'),
description: t('storageSettingsDescription'),
icon: Database,
href: '/settings/storage',
},
{
id: 'system',
title: t('systemSettings'),
description: t('systemSettingsDescription'),
icon: Settings,
href: '/settings/system',
},
{
id: 'about',
title: t('aboutShakespeare'),
description: t('aboutShakespeareDescription'),
icon: Info,
href: '/settings/about',
id: 'advanced',
title: t('advanced'),
items: [
{
id: 'storage',
icon: Database,
title: t('storageSettings'),
href: '/settings/storage',
},
{
id: 'system',
icon: Settings,
title: t('systemSettings'),
href: '/settings/system',
},
{
id: 'about',
icon: Info,
title: t('aboutShakespeare'),
href: '/settings/about',
},
],
},
];
+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)**');
});
});
});
+36 -16
View File
@@ -19,6 +19,7 @@ export interface MakeSystemPromptOpts {
metadata?: NostrMetadata;
repositoryUrl?: string;
template?: string;
projectTemplate?: { name: string; description: string; url: string };
}
/**
@@ -29,16 +30,19 @@ export const defaultSystemPrompt = `{% if mode === "init" %}You are Shakespeare,
# Your Environment
You are operating within **Shakespeare**, an AI-powered Nostr website builder that allows users to create custom Nostr applications through natural language conversation.
You are operating within **Shakespeare**, an AI-powered website builder that allows users to create custom applications through natural language conversation.
- **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
Shakespeare is a web-based development environment where users can build Nostr websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
Shakespeare is a web-based development environment where users can build websites and applications by chatting with an AI assistant (you). The platform combines the power of AI-driven development with a user-friendly interface that requires no coding knowledge from the user.
**Important Architecture Notes:**
@@ -64,7 +68,7 @@ Shakespeare is a web-based development environment where users can build Nostr w
- **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
@@ -140,22 +144,33 @@ Shakespeare operates on a browser-based virtual filesystem (VFS) that persists a
As the AI assistant in Shakespeare, you help users by:
- Understanding their requirements through natural conversation
- Writing and modifying code files to build their Nostr applications
- Writing and modifying code files to build their applications
- Explaining technical concepts in accessible terms
- Providing suggestions and best practices
- Troubleshooting issues and implementing fixes
- Building complete, functional Nostr websites and applications
- Building complete, functional websites and applications
- Learning from existing projects in the VFS to provide better solutions
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.
**Always commit your code changes** after completing work on a feature, fix, or meaningful set of changes.{% 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
+54
View File
@@ -185,4 +185,58 @@ describe('GitCommitTool', () => {
expect(result).toContain('✅ Successfully committed');
});
it('should error when HEAD is detached (currentBranch returns null)', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state - currentBranch returns null
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(null);
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Cannot commit: Git is in a detached HEAD state');
// Verify commit was never called
expect(mockGitInstance.commit).not.toHaveBeenCalled();
});
it('should error when HEAD is detached (currentBranch returns undefined)', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state - currentBranch returns undefined
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(undefined);
await expect(tool.execute({ message: 'Test commit' })).rejects.toThrow('❌ Cannot commit: Git is in a detached HEAD state');
// Verify commit was never called
expect(mockGitInstance.commit).not.toHaveBeenCalled();
});
it('should provide helpful instructions when HEAD is detached', async () => {
// Mock .git directory exists
vi.mocked(mockFS.stat).mockResolvedValue({
isDirectory: () => true,
isFile: () => false,
});
// Mock detached HEAD state
vi.mocked(mockGitInstance.currentBranch).mockResolvedValue(null);
try {
await tool.execute({ message: 'Test commit' });
expect.fail('Should have thrown an error');
} catch (error) {
const errorMessage = (error as Error).message;
// Verify the error message contains safe instructions that preserve changes
expect(errorMessage).toContain('git checkout -b temp-branch');
expect(errorMessage).toContain('try the commit again');
expect(errorMessage).toContain('preserving all changes');
}
});
});
+20 -10
View File
@@ -41,6 +41,26 @@ export class GitCommitTool implements Tool<GitCommitParams> {
throw new Error(`❌ Commit message cannot be empty.`);
}
// Check for detached HEAD state before doing any work
// currentBranch returns null when HEAD is detached
const currentBranch = await this.git.currentBranch({
dir: this.cwd,
});
if (currentBranch === null || currentBranch === undefined) {
throw new Error(
`❌ Cannot commit: Git is in a detached HEAD state.\n\n` +
`This usually happens after checking out a specific commit. ` +
`Your changes need to be on a branch before committing.\n\n` +
`To fix this and preserve your staged changes:\n` +
` 1. Run: git checkout -b temp-branch\n` +
` (This creates a new branch from your current state, preserving all changes)\n` +
` 2. Then try the commit again\n` +
` 3. After committing, you can merge to main with:\n` +
` git checkout main && git merge temp-branch`
);
}
// Get git status to see what files have changed
const statusMatrix = await this.git.statusMatrix({
dir: this.cwd,
@@ -79,16 +99,6 @@ export class GitCommitTool implements Tool<GitCommitParams> {
}
}
// Get current branch name
let currentBranch = 'main';
try {
currentBranch = await this.git.currentBranch({
dir: this.cwd,
}) || 'main';
} catch {
// Default to 'main' if we can't get the current branch
}
// Commit the changes (author/committer will be set automatically by Git class)
const commitSha = await this.git.commit({
dir: this.cwd,
+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}
+33 -10
View File
@@ -3,6 +3,9 @@
"settings": "Settings",
"backToSettings": "Back to Settings",
"help": "Help",
"general": "General",
"integrations": "Integrations",
"advanced": "Advanced",
"anonymous": "Anonymous",
"logIn": "Log in",
"signUp": "Sign up",
@@ -15,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",
@@ -60,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",
@@ -88,20 +91,19 @@
"remove": "Remove",
"retry": "Retry",
"name": "Name",
"id": "ID",
"email": "Email",
"buildNostrApps": "Build apps with AI",
"whatToBuild": "What would you like to build?",
"chooseModel": "Choose a model...",
"selectModelToDescribe": "Please select a model below, then describe what you'd like to build...",
"examplePrompt": "e.g., Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies...",
"settingsDescription": "Manage your application settings and preferences.",
"aiSettings": "AI",
"aiSettingsDescription": "Configure AI providers and API keys",
"gitSettings": "Git",
"gitSettingsDescription": "Configure Git credentials for HTTP authentication",
"deploySettings": "Deployment",
"deploySettingsDescription": "Configure deployment providers",
"deploySettingsDescriptionLong": "Configure deployment providers to deploy your projects to various hosting platforms.",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "Configure relay connections and Nostr preferences",
"storageSettings": "Storage",
@@ -112,6 +114,9 @@
"importRepository": "Import Repository",
"noProjectsYet": "No projects yet",
"createFirstProject": "Create your first project to get started",
"searchProjects": "Search projects...",
"noProjectsFound": "No projects found",
"tryDifferentSearch": "Try a different search term",
"closeSidebar": "Close sidebar",
"collapseSidebar": "Collapse sidebar",
"welcomeToShakespeare": "Welcome to Shakespeare",
@@ -179,7 +184,6 @@
"pushFailed": "Push failed",
"pullSuccessful": "Pull successful",
"pullFailed": "Pull failed",
"aiSettingsDescriptionLong": "Configure AI providers by adding your API keys. Settings are automatically saved and stored locally in your browser.",
"configuredProviders": "Configured Providers",
"addProvider": "Add Provider",
"getApiKey": "Get API key",
@@ -205,7 +209,6 @@
"shakespeareDeployNostrAuth": "This provider uses Nostr authentication. Make sure you are logged in to deploy.",
"providerType": "Provider Type",
"selectProviderType": "Select a provider type",
"gitSettingsDescriptionLong": "Configure Git credentials for HTTP authentication. Settings are automatically saved and stored locally in your browser.",
"configuredCredentials": "Configured Credentials",
"origin": "Origin",
"username": "Username",
@@ -226,7 +229,6 @@
"license": "License",
"loadingLicense": "Loading license...",
"failedToLoadLicense": "Failed to load license",
"dataSettingsDescriptionLong": "Export files and manage local data.",
"offlineCache": "Offline Cache",
"offlineCacheDescription": "Shakespeare caches files locally to enable offline functionality. Clear the cache to free up space or troubleshoot issues.",
"cacheSize": "Cache size",
@@ -294,7 +296,6 @@
"untracked": "untracked",
"toggleSidebar": "Toggle sidebar",
"openSidebar": "Open sidebar",
"nostrSettingsDescriptionLong": "Configure your Nostr connection settings and relay preferences.",
"nostrAccounts": "Nostr Accounts",
"noAccountsLoggedIn": "No accounts logged in. Add an account to get started.",
"createAccount": "Create Account",
@@ -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"
}
+20 -5
View File
@@ -3,6 +3,9 @@
"settings": "Saitunan",
"backToSettings": "Koma zuwa Saitunan",
"help": "Taimako",
"general": "Gabaɗaya",
"integrations": "Haɗin Kai",
"advanced": "Ci Gaba",
"anonymous": "Maras Suna",
"logIn": "Shiga",
"signUp": "Yi Rajista",
@@ -84,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?",
@@ -105,6 +109,9 @@
"importRepository": "Shigo da Repository",
"noProjectsYet": "Babu ayyuka har yanzu",
"createFirstProject": "Ƙirƙiri aikin farko don farawa",
"searchProjects": "Nemo ayyuka...",
"noProjectsFound": "Ba a sami ayyuka ba",
"tryDifferentSearch": "Gwada kalmar nema daban",
"closeSidebar": "Rufe gefen mashigi",
"collapseSidebar": "Rufe gefen mashigi",
"welcomeToShakespeare": "Maraba da Shakespeare",
@@ -172,7 +179,6 @@
"pushFailed": "Turawa ta gaza",
"pullSuccessful": "Ja ya yi nasara",
"pullFailed": "Ja ya gaza",
"aiSettingsDescriptionLong": "Saita masu samar da AI ta hanyar ƙara maɓallan API. Saitunan ana ajiye su kai tsaye kuma ana adana su a cikin burauzar ku.",
"configuredProviders": "Masu Samarwa da aka Saita",
"addProvider": "Ƙara Mai Samarwa",
"getApiKey": "Sami maɓallin API",
@@ -198,7 +204,6 @@
"shakespeareDeployNostrAuth": "Wannan mai samarwa yana amfani da tabbatar da Nostr. Tabbatar cewa kun shiga don tura.",
"providerType": "Nau'in Mai Samarwa",
"selectProviderType": "Zaɓi nau'in mai samarwa",
"gitSettingsDescriptionLong": "Saita bayanan shaidar Git don tabbatar da HTTP. Saitunan ana ajiye su kai tsaye kuma ana adana su a cikin burauzar ku.",
"configuredCredentials": "Bayanan Shaidar da aka Saita",
"origin": "Asali",
"username": "Sunan mai amfani",
@@ -210,7 +215,6 @@
"gitEmail": "Imel Git",
"coAuthoredByShakespeare": "Haɗin marubuta da Shakespeare",
"gitIdentityDescription": "Idan an saita suna da imel, za a yi amfani da su azaman marubucin aikin. In ba haka ba, za a yi amfani da shakespeare.diy. Lokacin da aka kunna haɗin marubuta, za a ƙara Shakespeare azaman haɗin marubuta.",
"dataSettingsDescriptionLong": "Fitar da fayiloli da sarrafa bayanan gida.",
"exportFiles": "Fitar da Fayiloli",
"exportFilesDescription": "Sauke duk ayyukanku da fayiloli azaman ajiyar ZIP. Wannan ya haɗa da duk fayilolin aikin, saitunan, da bayanan da aka adana a gida.",
"exportAllFiles": "Fitar da Duk Fayiloli",
@@ -280,7 +284,6 @@
"untracked": "ba a bi ba",
"toggleSidebar": "Juya gefen mashigi",
"openSidebar": "Buɗe gefen mashigi",
"nostrSettingsDescriptionLong": "Saita saitunan haɗin Nostr da zaɓuɓɓukan relay.",
"nostrAccounts": "Asusun Nostr",
"noAccountsLoggedIn": "Babu asusun da aka shiga. Ƙara asusu don farawa.",
"createAccount": "Ƙirƙiri Asusu",
@@ -428,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"
}
+20 -5
View File
@@ -3,6 +3,9 @@
"settings": "Ntọala",
"backToSettings": "Laghachi na Ntọala",
"help": "Enyemaka",
"general": "Izugbe",
"integrations": "Njikọta",
"advanced": "Dị elu",
"anonymous": "Onye na-amaghị aha",
"logIn": "Banye",
"signUp": "Debanye aha",
@@ -84,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?",
@@ -105,6 +109,9 @@
"importRepository": "Bubata Repository",
"noProjectsYet": "Enwebeghị ọrụ ọ bụla",
"createFirstProject": "Mepụta ọrụ mbụ gị iji malite",
"searchProjects": "Chọọ ọrụ...",
"noProjectsFound": "Achọtaghị ọrụ ọ bụla",
"tryDifferentSearch": "Nwalee okwu ọchụchọ dị iche",
"closeSidebar": "Mechie sidebar",
"collapseSidebar": "Gbakọọ sidebar",
"welcomeToShakespeare": "Nnọọ na Shakespeare",
@@ -172,7 +179,6 @@
"pushFailed": "Nkwanye dara",
"pullSuccessful": "Ndọta gara nke ọma",
"pullFailed": "Ndọta dara",
"aiSettingsDescriptionLong": "Hazie ndị na-enye AI site na ịtinye igodo API gị. Ntọala na-echekwa onwe ya ma chekwaa ya na mpaghara na browser gị.",
"configuredProviders": "Ndị Na-enye Ahaziri",
"addProvider": "Tinye Onye Na-enye",
"getApiKey": "Nweta igodo API",
@@ -198,7 +204,6 @@
"shakespeareDeployNostrAuth": "Onye na-enye a na-eji nkwenye Nostr. Jide n'aka na ị banyere iji bufee.",
"providerType": "Ụdị Onye Na-enye",
"selectProviderType": "Họrọ ụdị onye na-enye",
"gitSettingsDescriptionLong": "Hazie nzere Git maka nkwenye HTTP. Ntọala na-echekwa onwe ya ma chekwaa ya na mpaghara na browser gị.",
"configuredCredentials": "Nzere Ahaziri",
"origin": "Mmalite",
"username": "Aha onye ọrụ",
@@ -210,7 +215,6 @@
"gitEmail": "Ozi-eletrọniki Git",
"coAuthoredByShakespeare": "Ndekọ ọnụ na Shakespeare",
"gitIdentityDescription": "Ọ bụrụ na ahaziri aha na ozi-eletrọniki, a ga-eji ha dị ka onye dere ya. Ma ọ bụghị, a ga-eji shakespeare.diy. Mgbe emere ndekọ ọnụ, a ga-etinye Shakespeare dị ka ndekọ ọnụ.",
"dataSettingsDescriptionLong": "Bupụta faịlụ ma jikwaa data mpaghara.",
"exportFiles": "Bupụta Faịlụ",
"exportFilesDescription": "Budata ọrụ gị niile na faịlụ dị ka mkpokọta ZIP. Nke a gụnyere faịlụ ọrụ niile, ntọala, na data echekwara na mpaghara.",
"exportAllFiles": "Bupụta Faịlụ Niile",
@@ -277,7 +281,6 @@
"untracked": "na-esoghị",
"toggleSidebar": "Gbanwee sidebar",
"openSidebar": "Meghee sidebar",
"nostrSettingsDescriptionLong": "Hazie ntọala njikọ Nostr gị na nhọrọ relay.",
"nostrAccounts": "Akaụntụ Nostr",
"noAccountsLoggedIn": "Enweghị akaụntụ banyere. Tinye akaụntụ iji malite.",
"createAccount": "Mepụta Akaụntụ",
@@ -425,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"
}
+20 -6
View File
@@ -3,6 +3,9 @@
"settings": "Configurações",
"backToSettings": "Voltar às Configurações",
"help": "Ajuda",
"general": "Geral",
"integrations": "Integrações",
"advanced": "Avançado",
"anonymous": "Anônimo",
"logIn": "Entrar",
"signUp": "Cadastrar",
@@ -84,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?",
@@ -97,7 +101,6 @@
"gitSettingsDescription": "Configure credenciais do Git para autenticação HTTP",
"deploySettings": "Implantação",
"deploySettingsDescription": "Configure provedores de implantação",
"deploySettingsDescriptionLong": "Configure provedores de implantação para implantar seus projetos em várias plataformas de hospedagem.",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "Configure conexões de relay e preferências do Nostr",
"storageSettings": "Armazenamento",
@@ -108,6 +111,9 @@
"importRepository": "Importar Repositório",
"noProjectsYet": "Nenhum projeto ainda",
"createFirstProject": "Crie seu primeiro projeto para começar",
"searchProjects": "Pesquisar projetos...",
"noProjectsFound": "Nenhum projeto encontrado",
"tryDifferentSearch": "Tente um termo de pesquisa diferente",
"closeSidebar": "Fechar barra lateral",
"collapseSidebar": "Recolher barra lateral",
"welcomeToShakespeare": "Bem-vindo ao Shakespeare",
@@ -175,7 +181,6 @@
"pushFailed": "Push falhou",
"pullSuccessful": "Pull realizado com sucesso",
"pullFailed": "Pull falhou",
"aiSettingsDescriptionLong": "Configure provedores de IA adicionando suas chaves de API. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.",
"configuredProviders": "Provedores Configurados",
"addProvider": "Adicionar Provedor",
"getApiKey": "Obter chave de API",
@@ -201,7 +206,6 @@
"shakespeareDeployNostrAuth": "Este provedor usa autenticação Nostr. Certifique-se de estar logado para implantar.",
"providerType": "Tipo de Provedor",
"selectProviderType": "Selecione um tipo de provedor",
"gitSettingsDescriptionLong": "Configure credenciais do Git para autenticação HTTP. As configurações são salvas automaticamente e armazenadas localmente em seu navegador.",
"configuredCredentials": "Credenciais Configuradas",
"origin": "Origem",
"username": "Nome de usuário",
@@ -213,7 +217,6 @@
"gitEmail": "Email Git",
"coAuthoredByShakespeare": "Co-autoria de Shakespeare",
"gitIdentityDescription": "Se nome e email estiverem configurados, eles serão usados como autor do commit. Caso contrário, shakespeare.diy será usado. Quando co-autoria estiver ativada, Shakespeare será adicionado como co-autor.",
"dataSettingsDescriptionLong": "Exporte arquivos e gerencie dados locais.",
"offlineCache": "Cache Offline",
"offlineCacheDescription": "O Shakespeare armazena arquivos localmente para permitir funcionalidade offline. Limpe o cache para liberar espaço ou solucionar problemas.",
"cacheSize": "Tamanho do cache",
@@ -290,7 +293,6 @@
"untracked": "não rastreado",
"toggleSidebar": "Alternar barra lateral",
"openSidebar": "Abrir barra lateral",
"nostrSettingsDescriptionLong": "Configure suas configurações de conexão Nostr e preferências de relay.",
"nostrAccounts": "Contas Nostr",
"noAccountsLoggedIn": "Nenhuma conta logada. Adicione uma conta para começar.",
"createAccount": "Criar Conta",
@@ -438,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"
}
+20 -5
View File
@@ -3,6 +3,9 @@
"settings": "Awọn eto",
"backToSettings": "Pada si Awọn eto",
"help": "Iranlọwọ",
"general": "Gbogbogbo",
"integrations": "Awọn isopọ",
"advanced": "To siwaju",
"anonymous": "Alainidamọ",
"logIn": "Wọle",
"signUp": "Forukọsilẹ",
@@ -84,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ọ?",
@@ -105,6 +109,9 @@
"importRepository": "Gbe Repository wọle",
"noProjectsYet": "Ko si awọn iṣẹ akanṣe sibẹsibẹ",
"createFirstProject": "Ṣẹda iṣẹ akanṣe akọkọ rẹ lati bẹrẹ",
"searchProjects": "Wa awọn iṣẹ akanṣe...",
"noProjectsFound": "Ko ri awọn iṣẹ akanṣe",
"tryDifferentSearch": "Gbiyanju ọrọ wiwa miiran",
"closeSidebar": "Ti ẹgbẹ sidebar",
"collapseSidebar": "Subu sidebar",
"welcomeToShakespeare": "Kaabo si Shakespeare",
@@ -172,7 +179,6 @@
"pushFailed": "Titari kuna",
"pullSuccessful": "Fifa ni aṣeyọri",
"pullFailed": "Fifa kuna",
"aiSettingsDescriptionLong": "Tunto awọn olupese AI nipa fifi awọn bọtini API rẹ kun. Awọn eto ni a fi pamọ laifọwọyi ati pe a tọju wọn ni agbegbe ninu awọn aṣawakiri rẹ.",
"configuredProviders": "Awọn Olupese Ti a Tunto",
"addProvider": "Fi Olupese kun",
"getApiKey": "Gba bọtini API",
@@ -198,7 +204,6 @@
"shakespeareDeployNostrAuth": "Olupese yii nlo ijẹrisi Nostr. Rii daju pe o ti wọle lati gbe jade.",
"providerType": "Iru Olupese",
"selectProviderType": "Yan iru olupese kan",
"gitSettingsDescriptionLong": "Tunto awọn ẹri Git fun ijẹrisi HTTP. Awọn eto ni a fi pamọ laifọwọyi ati pe a tọju wọn ni agbegbe ninu awọn aṣawakiri rẹ.",
"configuredCredentials": "Awọn Ẹri Ti a Tunto",
"origin": "Ipilẹṣẹ",
"username": "Orukọ olumulo",
@@ -210,7 +215,6 @@
"gitEmail": "Imeeli Git",
"coAuthoredByShakespeare": "Ajọpọ onkọwe pẹlu Shakespeare",
"gitIdentityDescription": "Ti a ba tunto orukọ ati imeeli, wọn yoo jẹ lilo bi onkọwe. Bibẹẹkọ, shakespeare.diy yoo jẹ lilo. Nigbati a ba mu ajọpọ onkọwe ṣiṣẹ, Shakespeare yoo jẹ fifikun bi ajọpọ onkọwe.",
"dataSettingsDescriptionLong": "Gbe awọn faili jade ati ṣakoso data agbegbe.",
"exportFiles": "Gbe Awọn faili jade",
"exportFilesDescription": "Gba gbogbo awọn iṣẹ akanṣe ati awọn faili rẹ gẹgẹbi apo ZIP. Eyi pẹlu gbogbo awọn faili iṣẹ akanṣe, awọn eto, ati data ti a tọju ni agbegbe.",
"exportAllFiles": "Gbe Gbogbo Awọn faili jade",
@@ -277,7 +281,6 @@
"untracked": "ti a ko tọpa",
"toggleSidebar": "Yipada sidebar",
"openSidebar": "Ṣi sidebar",
"nostrSettingsDescriptionLong": "Tunto awọn eto asopọ Nostr rẹ ati awọn ayanfẹ relay.",
"nostrAccounts": "Awọn Akọọlẹ Nostr",
"noAccountsLoggedIn": "Ko si awọn akọọlẹ ti o wọle. Fi akọọlẹ kun lati bẹrẹ.",
"createAccount": "Ṣẹda Akọọlẹ",
@@ -425,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ọ"
}
+20 -6
View File
@@ -3,6 +3,9 @@
"settings": "设置",
"backToSettings": "返回设置",
"help": "帮助",
"general": "常规",
"integrations": "集成",
"advanced": "高级",
"anonymous": "匿名",
"logIn": "登录",
"signUp": "注册",
@@ -84,6 +87,7 @@
"remove": "移除",
"retry": "重试",
"name": "名称",
"id": "ID",
"email": "邮箱",
"buildNostrApps": "使用AI构建应用",
"whatToBuild": "您想构建什么?",
@@ -97,7 +101,6 @@
"gitSettingsDescription": "配置HTTP身份验证的Git凭据",
"deploySettings": "部署",
"deploySettingsDescription": "配置部署提供商",
"deploySettingsDescriptionLong": "配置部署提供商以将您的项目部署到各种托管平台。",
"nostrSettings": "Nostr",
"nostrSettingsDescription": "配置中继连接和Nostr偏好",
"storageSettings": "存储",
@@ -108,6 +111,9 @@
"importRepository": "导入仓库",
"noProjectsYet": "还没有项目",
"createFirstProject": "创建您的第一个项目开始使用",
"searchProjects": "搜索项目...",
"noProjectsFound": "未找到项目",
"tryDifferentSearch": "尝试不同的搜索词",
"closeSidebar": "关闭侧边栏",
"collapseSidebar": "折叠侧边栏",
"welcomeToShakespeare": "欢迎使用Shakespeare",
@@ -175,7 +181,6 @@
"pushFailed": "推送失败",
"pullSuccessful": "拉取成功",
"pullFailed": "拉取失败",
"aiSettingsDescriptionLong": "通过添加您的API密钥来配置AI提供商。设置会自动保存并存储在您的浏览器本地。",
"configuredProviders": "已配置的提供商",
"addProvider": "添加提供商",
"getApiKey": "获取API密钥",
@@ -201,7 +206,6 @@
"shakespeareDeployNostrAuth": "此提供商使用Nostr身份验证。请确保您已登录以进行部署。",
"providerType": "提供商类型",
"selectProviderType": "选择提供商类型",
"gitSettingsDescriptionLong": "配置HTTP身份验证的Git凭据。设置会自动保存并存储在您的浏览器本地。",
"configuredCredentials": "已配置的凭据",
"origin": "源",
"username": "用户名",
@@ -213,7 +217,6 @@
"gitEmail": "Git邮箱",
"coAuthoredByShakespeare": "Shakespeare共同作者",
"gitIdentityDescription": "如果配置了名称和邮箱,它们将用作提交作者。否则,将使用shakespeare.diy。启用共同作者时,Shakespeare将被添加为共同作者。",
"dataSettingsDescriptionLong": "导出文件和管理本地数据。",
"offlineCache": "离线缓存",
"offlineCacheDescription": "Shakespeare在本地缓存文件以启用离线功能。清除缓存以释放空间或解决问题。",
"cacheSize": "缓存大小",
@@ -290,7 +293,6 @@
"untracked": "未跟踪",
"toggleSidebar": "切换侧边栏",
"openSidebar": "打开侧边栏",
"nostrSettingsDescriptionLong": "配置您的Nostr连接设置和中继偏好。",
"nostrAccounts": "Nostr账户",
"noAccountsLoggedIn": "没有账户登录。添加账户开始使用。",
"createAccount": "创建账户",
@@ -438,5 +440,17 @@
"modified": "已修改",
"restoreToDefault": "恢复默认值",
"restoredToDefault": "已恢复默认值",
"terminal": "终端"
"terminal": "终端",
"globalChat": "聊天",
"globalChatWelcome": "你好! 👋",
"globalChatDescription": "随便问我什么。我在这里帮助回答问题、提供想法和进行对话。",
"clearChat": "清除聊天",
"popOutChat": "弹出窗口",
"minimizeChat": "最小化",
"typeMessage": "输入消息...",
"configureAIFirst": "请先配置AI提供商",
"globalChatEnabled": "浮动聊天按钮",
"globalChatEnabledDescription": "显示浮动聊天按钮以便快速AI对话",
"globalChatSystemPrompt": "聊天系统提示",
"globalChatSystemPromptDescription": "浮动聊天助手的自定义系统提示"
}
+286 -123
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,19 +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;
@@ -93,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
@@ -106,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"
@@ -171,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');
@@ -185,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),
@@ -201,6 +247,7 @@ export function AISettings() {
const newProvider: AIProvider = {
id: preset.id,
name: preset.name,
baseURL: preset.baseURL,
};
@@ -229,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,
@@ -243,6 +291,8 @@ export function AISettings() {
setProvider(newProvider);
setCustomProviderName('');
setCustomProviderId('');
setCustomIdManuallyEdited(false);
setCustomBaseURL('');
setCustomApiKey('');
setCustomAuthMethod('api-key');
@@ -285,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
@@ -303,7 +353,7 @@ export function AISettings() {
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
{t('aiSettingsDescriptionLong')}
{t('aiSettingsDescription')}
</p>
</div>
</div>
@@ -316,7 +366,7 @@ export function AISettings() {
{t('aiSettings')}
</h1>
<p className="text-muted-foreground">
{t('aiSettingsDescriptionLong')}
{t('aiSettingsDescription')}
</p>
</div>
)}
@@ -368,108 +418,110 @@ export function AISettings() {
const showNostrLoginRequired = isNostrPreset && !isLoggedIntoNostr;
return (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
{showNostrLoginRequired ? (
<div className="space-y-2">
<p className="text-sm text-muted-foreground">
{t('loginToNostrRequired')}
</p>
<Button
asChild
className="w-full"
>
<Link to="/settings/nostr">
{t('goToNostrSettings')}
</Link>
</Button>
</div>
) : (
<div className="space-y-2">
<div className="flex gap-2">
{!preset.nostr && (
<PasswordInput
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
className="flex-1"
value={presetApiKeys[preset.id] || ''}
onChange={(e) => setPresetApiKeys(prev => ({
...prev,
[preset.id]: e.target.value,
}))}
onKeyDown={(e) => {
if (e.key === 'Enter' &&
presetApiKeys[preset.id]?.trim() &&
presetTermsAgreements[preset.id]) {
handleAddPresetProvider(preset);
}
}}
/>
)}
<Button
onClick={() => handleAddPresetProvider(preset)}
disabled={
!presetTermsAgreements[preset.id] ||
(!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim())
}
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.baseURL}
size={16}
fallback={<Bot size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{(preset.apiKeysURL && preset.id !== "routstr") && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeysURL, '_blank')}
>
{t('add')}
{t('getApiKey')}
</button>
)}
</div>
{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>
{/* 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="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);
}
}}
/>
)}
</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>
)}
</div>
)}
</CardContent>
</Card>
);
})}
</div>
@@ -479,23 +531,54 @@ export function AISettings() {
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider" className="border rounded-lg">
<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"
@@ -548,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>
@@ -567,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 */}
+23 -18
View File
@@ -5,6 +5,7 @@ import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code, Globe } fr
import { Button } from '@/components/ui/button';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Alert, AlertDescription } from '@/components/ui/alert';
import { Card, CardContent } from '@/components/ui/card';
import { useIsMobile } from '@/hooks/useIsMobile';
import { EmailSubscription } from '@/components/EmailSubscription';
@@ -85,10 +86,10 @@ export function AboutSettings() {
<div className="space-y-3">
{/* Mirrors */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="mirrors" className="border rounded-lg">
<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>
@@ -102,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
@@ -112,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
@@ -122,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>
@@ -131,24 +132,28 @@ export function AboutSettings() {
</Accordion>
{/* Project Information */}
<Button
variant="outline"
className="w-full h-12 flex items-center gap-2 justify-start text-base"
asChild
>
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
<Code className="!size-5" />
{t('sourceCode')}
<ExternalLink className="ml-auto" />
</a>
</Button>
<Card>
<CardContent className="p-0">
<Button
variant="ghost"
className="w-full h-12 flex items-center gap-2 justify-start text-base"
asChild
>
<a href="https://gitlab.com/soapbox-pub/shakespeare" target="_blank">
<Code className="!size-5 text-muted-foreground" />
{t('sourceCode')}
<ExternalLink className="ml-auto" />
</a>
</Button>
</CardContent>
</Card>
{/* License */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="license-text" className="border rounded-lg">
<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>
+135
View File
@@ -10,6 +10,14 @@ import { useToast } from '@/hooks/useToast';
import { ZipImportDialog } from '@/components/ZipImportDialog';
import { useSeoMeta } from '@unhead/react';
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
import { useCurrentUser } from '@/hooks/useCurrentUser';
import { useUserRepositories } from '@/hooks/useUserRepositories';
import { useContacts } from '@/hooks/useContacts';
import { useFollowedRepositories } from '@/hooks/useFollowedRepositories';
import { RepositoryCard } from '@/components/RepositoryCard';
import { Skeleton } from '@/components/ui/skeleton';
import { Card, CardContent } from '@/components/ui/card';
import { Tabs, TabsList, TabsTrigger, TabsContent } from '@/components/ui/tabs';
export default function Clone() {
const { t } = useTranslation();
@@ -22,6 +30,11 @@ export default function Clone() {
const { toast } = useToast();
const autoCloneInitiatedRef = useRef(false);
const [isZipDialogOpen, setIsZipDialogOpen] = useState(false);
const { user } = useCurrentUser();
const { data: repositories = [], isLoading: isLoadingRepos } = useUserRepositories(user?.pubkey);
const { data: contacts = [] } = useContacts(user?.pubkey);
const { data: followedRepositories = [], isLoading: isLoadingFollowedRepos } = useFollowedRepositories(contacts);
const [activeTab, setActiveTab] = useState<'my-projects' | 'follows'>('my-projects');
useSeoMeta({
title: `${t('importRepository')} - Shakespeare`,
@@ -276,6 +289,128 @@ export default function Clone() {
open={isZipDialogOpen}
onOpenChange={setIsZipDialogOpen}
/>
{/* NIP-34 Repositories with Tabs */}
{user && (
<div className="mt-16 max-w-7xl mx-auto">
<Tabs value={activeTab} onValueChange={(value) => setActiveTab(value as 'my-projects' | 'follows')}>
<TabsList className="mb-6">
<TabsTrigger value="my-projects">
My Projects
</TabsTrigger>
<TabsTrigger value="follows">
Follows
</TabsTrigger>
</TabsList>
<TabsContent value="my-projects">
{isLoadingRepos ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 3 }).map((_, i) => (
<Card key={i} className="h-full flex flex-col">
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start gap-3 mb-4">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-4 w-24" />
</div>
</div>
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-9 flex-1" />
<Skeleton className="h-9 w-9" />
</div>
</CardContent>
</Card>
))}
</div>
) : repositories.length > 0 ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{repositories.map((repo) => (
<RepositoryCard key={repo.id} repo={repo} />
))}
</div>
) : (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
No repositories found. Publish your first repository to Nostr to see it here.
</p>
</div>
</CardContent>
</Card>
)}
</TabsContent>
<TabsContent value="follows">
{isLoadingFollowedRepos ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{Array.from({ length: 6 }).map((_, i) => (
<Card key={i} className="h-full flex flex-col">
<CardContent className="p-6 flex flex-col flex-1">
<div className="flex items-start gap-3 mb-4">
<Skeleton className="w-12 h-12 rounded-lg" />
<div className="flex-1 space-y-2">
<Skeleton className="h-5 w-32" />
<Skeleton className="h-4 w-24" />
</div>
</div>
<div className="space-y-2 mb-4">
<Skeleton className="h-4 w-full" />
<Skeleton className="h-4 w-4/5" />
</div>
<div className="flex gap-1 mb-4">
<Skeleton className="h-5 w-16" />
<Skeleton className="h-5 w-20" />
</div>
<div className="mt-auto flex gap-2">
<Skeleton className="h-9 flex-1" />
<Skeleton className="h-9 w-9" />
</div>
</CardContent>
</Card>
))}
</div>
) : followedRepositories.length > 0 ? (
<div className="grid md:grid-cols-2 lg:grid-cols-3 gap-6">
{followedRepositories.map((repo) => (
<RepositoryCard key={repo.id} repo={repo} />
))}
</div>
) : contacts.length > 0 ? (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
None of the people you follow have published repositories yet.
</p>
</div>
</CardContent>
</Card>
) : (
<Card className="border-dashed">
<CardContent className="py-12 px-8 text-center">
<div className="max-w-sm mx-auto space-y-4">
<p className="text-muted-foreground">
You're not following anyone yet. Follow people on Nostr to see their repositories here.
</p>
</div>
</CardContent>
</Card>
)}
</TabsContent>
</Tabs>
</div>
)}
</AppLayout>
);
}
+159 -142
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,
@@ -32,6 +32,7 @@ import { Input } from '@/components/ui/input';
import { PasswordInput } from '@/components/ui/password-input';
import { Label } from '@/components/ui/label';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Card, CardContent } from '@/components/ui/card';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select';
import { useDeploySettings } from '@/hooks/useDeploySettings';
import { useNetlifyOAuth } from '@/hooks/useNetlifyOAuth';
@@ -83,7 +84,6 @@ function SortableProviderItem({ provider, index, preset, onRemove, onUpdate, sho
ref={setNodeRef}
style={style}
value={String(index)}
className="border rounded-lg"
>
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
@@ -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`}
@@ -519,7 +527,7 @@ export function DeploySettings() {
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescriptionLong')}
{t('deploySettingsDescription')}
</p>
</div>
</div>
@@ -532,7 +540,7 @@ export function DeploySettings() {
{t('deploySettings')}
</h1>
<p className="text-muted-foreground">
{t('deploySettingsDescriptionLong')}
{t('deploySettingsDescription')}
</p>
</div>
)}
@@ -591,140 +599,142 @@ export function DeploySettings() {
const oauthError = oauthHook?.error ?? null;
return (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<Rocket size={16} />
);
})()}
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.apiKeyURL && !isOAuthConfigured && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</div>
<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...
</>
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
{(() => {
const url = getProviderUrl(preset);
return url ? (
<ExternalFavicon
url={url}
size={16}
fallback={<Rocket size={16} />}
/>
) : (
<>
{(() => {
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>
<Rocket size={16} />
);
})()}
<h5 className="font-medium">{preset.name}</h5>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
{preset.apiKeyURL && !isOAuthConfigured && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.apiKeyURL, '_blank')}
>
{t('getApiKey')}
</button>
)}
</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')}
<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>
</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>
);
})}
</div>
@@ -734,14 +744,19 @@ export function DeploySettings() {
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider" className="border rounded-lg">
<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') => {
@@ -771,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"
@@ -832,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"
+137 -116
View File
@@ -1,11 +1,12 @@
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';
import { Badge } from '@/components/ui/badge';
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
import { Card, CardContent } from '@/components/ui/card';
import { Switch } from '@/components/ui/switch';
import {
DropdownMenu,
@@ -126,7 +127,7 @@ export function GitSettings() {
{t('gitSettings')}
</h1>
<p className="text-muted-foreground">
{t('gitSettingsDescriptionLong')}
{t('gitSettingsDescription')}
</p>
</div>
</div>
@@ -139,7 +140,7 @@ export function GitSettings() {
{t('gitSettings')}
</h1>
<p className="text-muted-foreground">
{t('gitSettingsDescriptionLong')}
{t('gitSettingsDescription')}
</p>
</div>
)}
@@ -156,7 +157,7 @@ export function GitSettings() {
const isCustom = !preset;
return (
<AccordionItem key={origin} value={origin} className="border rounded-lg">
<AccordionItem key={origin} value={origin}>
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<ExternalFavicon
@@ -173,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"
@@ -183,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"
@@ -192,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')}
@@ -223,82 +230,109 @@ export function GitSettings() {
<h4 className="text-sm font-medium">{t('addProvider')}</h4>
<div className="grid grid-cols-1 md:grid-cols-2 gap-3">
{availablePresets.map((preset) => (
<div key={preset.id} className="border rounded-lg p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
{t('getToken')}
</button>
)}
</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>
</div>
{oauthError && (
<p className="text-sm text-destructive">
{oauthError}
</p>
)}
<Card key={preset.id}>
<CardContent className="p-4 space-y-3">
<div className="flex items-center justify-between">
<div className="flex items-center gap-2">
<ExternalFavicon
url={preset.origin}
size={16}
fallback={<GitBranch size={16} />}
/>
<h5 className="font-medium">{preset.name}</h5>
</div>
{preset.tokenURL && (preset.id !== 'github' || !isOAuthConfigured) && (
<button
type="button"
className="text-xs text-muted-foreground underline hover:text-foreground"
onClick={() => window.open(preset.tokenURL, '_blank')}
>
{t('getToken')}
</button>
)}
</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>
</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')}
@@ -322,34 +356,9 @@ 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>
)}
</div>
)}
</CardContent>
</Card>
))}
</div>
</div>
@@ -358,14 +367,19 @@ export function GitSettings() {
{/* Custom Provider */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="custom-provider" className="border rounded-lg">
<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"
@@ -374,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"
@@ -383,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')}
@@ -419,9 +437,12 @@ export function GitSettings() {
{/* Git Identity */}
<div className="space-y-3">
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="git-identity" className="border rounded-lg">
<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 />
+32 -36
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';
@@ -150,7 +150,7 @@ export function NostrSettings() {
{t('nostrSettings')}
</h1>
<p className="text-muted-foreground">
{t('nostrSettingsDescriptionLong')}
{t('nostrSettingsDescription')}
</p>
</div>
</div>
@@ -163,21 +163,19 @@ export function NostrSettings() {
{t('nostrSettings')}
</h1>
<p className="text-muted-foreground">
{t('nostrSettingsDescriptionLong')}
{t('nostrSettingsDescription')}
</p>
</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>
);
}
+2 -2
View File
@@ -199,7 +199,7 @@ export function ProjectView() {
onClick={() => setIsSidebarVisible(false)}
/>
{/* Sidebar - positioned above the backdrop */}
<div className="relative left-0 top-0 h-full w-80 max-w-[80vw] bg-background border-r shadow-lg z-10">
<div className="relative left-0 top-0 h-full w-72 max-w-[80vw] bg-background border-r shadow-lg z-10">
<ProjectSidebar
selectedProject={project}
onSelectProject={(selectedProject) => {
@@ -314,7 +314,7 @@ export function ProjectView() {
return (
<div className="h-screen flex bg-background">
{/* Fixed Sidebar */}
<div className={`w-80 border-r bg-sidebar duration-300 ${isSidebarVisible ? 'block' : 'hidden'}`}>
<div className={`w-72 border-r bg-sidebar duration-300 ${isSidebarVisible ? 'block' : 'hidden'}`}>
<ProjectSidebar
selectedProject={project}
onSelectProject={(selectedProject) => {
+24 -28
View File
@@ -1,42 +1,38 @@
import { useNavigate } from 'react-router-dom';
import { useTranslation } from 'react-i18next';
import { useIsMobile } from '@/hooks/useIsMobile';
import { getSettingsItems } from '@/lib/settingsItems';
import { getSettingsCategories } from '@/lib/settingsItems';
import { SettingsItemMobile } from '@/components/SettingsItemMobile';
export function Settings() {
const { t } = useTranslation();
const navigate = useNavigate();
const isMobile = useIsMobile();
const settingsItems = getSettingsItems(t);
const settingsCategories = getSettingsCategories(t);
if (isMobile) {
return (
<div className="p-6 space-y-4">
<div className="space-y-2">
<h2 className="text-xl font-bold">{t('settings')}</h2>
<p className="text-muted-foreground">
{t('settingsDescription')}
</p>
</div>
<div className="space-y-3">
{settingsItems.map((item) => {
const Icon = item.icon;
return (
<div
key={item.id}
className="flex items-center gap-3 p-4 rounded-lg border hover:border-primary/20 hover:bg-primary/5 cursor-pointer transition-colors"
onClick={() => navigate(item.href)}
>
<Icon className="h-5 w-5 text-primary flex-shrink-0" />
<div className="flex-1 min-w-0">
<div className="font-medium">{item.title}</div>
<div className="text-sm text-muted-foreground">{item.description}</div>
</div>
</div>
);
})}
</div>
<div className="p-4 space-y-8">
{settingsCategories.map((category) => (
<div key={category.id}>
<h3 className="text-xs font-semibold text-muted-foreground uppercase tracking-wider mb-2 px-2">
{category.title}
</h3>
<div className="overflow-hidden rounded-xl border border-border shadow-sm">
{category.items.map((item, index) => (
<SettingsItemMobile
key={item.id}
icon={item.icon}
title={item.title}
onClick={() => navigate(item.href)}
isFirst={index === 0}
isLast={index === category.items.length - 1}
/>
))}
</div>
</div>
))}
{import.meta.env.VERSION && (
<div className="text-center text-xs text-muted-foreground/60 pt-4">
v{import.meta.env.VERSION}
@@ -47,4 +43,4 @@ export function Settings() {
}
}
export default Settings;
export default Settings;
+1 -1
View File
@@ -15,7 +15,7 @@ describe('StorageSettings', () => {
expect(screen.getByText('Storage')).toBeInTheDocument();
// Check for description
expect(screen.getByText('Export files and manage local data.')).toBeInTheDocument();
expect(screen.getByText('Export files and manage local data')).toBeInTheDocument();
// Check for Persist Data section
expect(screen.getByText('Persist Data')).toBeInTheDocument();
+2 -2
View File
@@ -288,7 +288,7 @@ export function StorageSettings() {
{t('storageSettings')}
</h1>
<p className="text-muted-foreground">
{t('dataSettingsDescriptionLong')}
{t('storageSettingsDescription')}
</p>
</div>
</div>
@@ -301,7 +301,7 @@ export function StorageSettings() {
{t('storageSettings')}
</h1>
<p className="text-muted-foreground">
{t('dataSettingsDescriptionLong')}
{t('storageSettingsDescription')}
</p>
</div>
)}
+64 -108
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;
});
};
@@ -308,9 +302,12 @@ export function SystemSettings() {
<div className="space-y-3 max-w-xl">
{/* Service Worker Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="service-worker" className="border rounded-lg">
<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" className="border rounded-lg">
<AccordionTrigger className="px-4 py-3 hover:no-underline">
<div className="flex items-center gap-2">
<h4 className="text-sm font-medium">{t('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" className="border rounded-lg">
<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')} />
@@ -507,9 +457,10 @@ export function SystemSettings() {
{/* Favicon URL Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="favicon-url" className="border rounded-lg">
<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')} />
@@ -555,9 +506,10 @@ export function SystemSettings() {
{/* JavaScript CDN Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="esm-url" className="border rounded-lg">
<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')} />
@@ -604,9 +556,10 @@ export function SystemSettings() {
{/* Preview Domain Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="preview-domain" className="border rounded-lg">
<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')} />
@@ -652,9 +605,10 @@ export function SystemSettings() {
{/* Showcase Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="showcase" className="border rounded-lg">
<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')} />
@@ -746,9 +700,10 @@ export function SystemSettings() {
{/* Sentry DSN Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="sentry-dsn" className="border rounded-lg">
<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')} />
@@ -794,9 +749,10 @@ export function SystemSettings() {
{/* Filesystem Paths Configuration */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="filesystem-paths" className="border rounded-lg">
<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" className="border rounded-lg">
<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>
@@ -1063,9 +1018,10 @@ export function SystemSettings() {
{/* Terminal */}
<Accordion type="single" collapsible className="w-full">
<AccordionItem value="terminal" className="border rounded-lg">
<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',
+2 -1
View File
@@ -81,7 +81,8 @@ export default {
borderRadius: {
lg: 'var(--radius)',
md: 'calc(var(--radius) - 2px)',
sm: 'calc(var(--radius) - 4px)'
sm: 'calc(var(--radius) - 4px)',
xs: '2px'
},
keyframes: {
'accordion-down': {