From 009142b8547930b6c1b9c7449b3d84e30cb52f34 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 1 Dec 2025 13:20:25 -0600 Subject: [PATCH] Allow multiple project templates to be configured --- src/App.tsx | 8 +- src/components/AppProvider.tsx | 9 +- src/components/SentryProvider.test.tsx | 8 +- src/contexts/AppContext.ts | 13 +- src/hooks/useAIProjectId.test.ts | 526 ----------------------- src/hooks/useAIProjectId.ts | 96 ----- src/hooks/useGenerateProjectInfo.test.ts | 456 ++++++++++++++++++++ src/hooks/useGenerateProjectInfo.ts | 171 ++++++++ src/hooks/useGit.test.ts | 2 +- src/lib/SessionManager.test.ts | 2 +- src/lib/system.test.ts | 2 +- src/locales/en.json | 4 +- src/pages/Index.tsx | 24 +- src/pages/SystemSettings.tsx | 139 ++++-- src/test/TestApp.tsx | 8 +- 15 files changed, 792 insertions(+), 676 deletions(-) delete mode 100644 src/hooks/useAIProjectId.test.ts delete mode 100644 src/hooks/useAIProjectId.ts create mode 100644 src/hooks/useGenerateProjectInfo.test.ts create mode 100644 src/hooks/useGenerateProjectInfo.ts diff --git a/src/App.tsx b/src/App.tsx index 555c41fa..2610563f 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -106,7 +106,13 @@ const defaultConfig: 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.sh", corsProxy: "https://proxy.shakespeare.diy/?url={href}", faviconUrl: "https://favicon.shakespeare.diy/?url={href}", diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index c9f5a66b..40bdd2ba 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -22,11 +22,18 @@ const RelayMetadataSchema = z.object({ updatedAt: z.number(), }) satisfies z.ZodType; +// 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(), diff --git a/src/components/SentryProvider.test.tsx b/src/components/SentryProvider.test.tsx index d98f7c24..9af8c289 100644 --- a/src/components/SentryProvider.test.tsx +++ b/src/components/SentryProvider.test.tsx @@ -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}', diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index 8664e1cb..68ad6c78 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -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 */ diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts deleted file mode 100644 index 3443db42..00000000 --- a/src/hooks/useAIProjectId.test.ts +++ /dev/null @@ -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; - 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; - 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; - 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; - 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; - 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; - 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; - }); -}); \ No newline at end of file diff --git a/src/hooks/useAIProjectId.ts b/src/hooks/useAIProjectId.ts deleted file mode 100644 index 3a2ea9cb..00000000 --- a/src/hooks/useAIProjectId.ts +++ /dev/null @@ -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 => { - 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 - }; -} \ No newline at end of file diff --git a/src/hooks/useGenerateProjectInfo.test.ts b/src/hooks/useGenerateProjectInfo.test.ts new file mode 100644 index 00000000..e8e7325c --- /dev/null +++ b/src/hooks/useGenerateProjectInfo.test.ts @@ -0,0 +1,456 @@ +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" + } + ]; + + 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 + 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: { + 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; + 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', 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', 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', 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', + templateUrl: 'https://gitlab.com/soapbox-pub/mkstack.git' + }); + 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 first template when AI selects invalid template URL', async () => { + mockUseAISettings.mockReturnValue({ + settings: { + providers: [ + { id: '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; + mockCreateAIClient.mockReturnValue(mockOpenAI); + + const { result } = renderHook(() => useGenerateProjectInfo()); + + const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); + + expect(projectInfo.templateUrl).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); + expect(projectInfo.projectId).toBe('untitled'); + }); + + it('should fallback to untitled when project already exists', async () => { + mockUseAISettings.mockReturnValue({ + settings: { + providers: [ + { id: '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 getProject - first call returns project (exists), second returns null (untitled is available) + const mockGetProject = vi.fn() + .mockResolvedValueOnce({ id: 'test-project-name', name: 'Test Project', path: '/projects/test-project-name', lastModified: new Date() }) + .mockResolvedValueOnce(null); + + const mockProjectsManager = { + getProject: mockGetProject, + } as unknown as ProjectsManager; + mockUseProjectsManager.mockReturnValue(mockProjectsManager); + + const { result } = renderHook(() => useGenerateProjectInfo()); + + const projectInfo = await result.current.generateProjectInfo('openai/gpt-4', 'test prompt'); + + expect(projectInfo.projectId).toBe('untitled'); + expect(projectInfo.templateUrl).toBe('https://gitlab.com/soapbox-pub/mkstack.git'); + expect(mockGetProject).toHaveBeenCalledTimes(2); + }); + + it('should handle loading state correctly', async () => { + mockUseAISettings.mockReturnValue({ + settings: { + providers: [ + { id: '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', 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; + 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', + templateUrl: 'https://github.com/example/vanilla-template.git' + }); + }); +}); diff --git a/src/hooks/useGenerateProjectInfo.ts b/src/hooks/useGenerateProjectInfo.ts new file mode 100644 index 00000000..8d049ae6 --- /dev/null +++ b/src/hooks/useGenerateProjectInfo.ts @@ -0,0 +1,171 @@ +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; + templateUrl: 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 untitled project name + const fallbackWithUntitled = useCallback(async (templateUrl: string): Promise => { + 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 { + projectId: fallbackId, + templateUrl, + }; + }, [projectsManager]); + + const generateProjectInfo = useCallback(async (providerModel: string, prompt: string): Promise => { + 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`); + const fallbackTemplate = config.templates[0]; + return await fallbackWithUntitled(fallbackTemplate.url); + } + + // 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, + templateUrl: selectedTemplate.url, + }; + } + } + + // If we reach here, either the regex failed or the project already exists + // Fall back to "untitled" with number suffixes + return await fallbackWithUntitled(selectedTemplate.url); + } 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 fallbackWithUntitled(config.templates[0].url); + } finally { + setIsLoading(false); + } + }, [isConfigured, settings, onError, user, projectsManager, config.corsProxy, config.templates, fallbackWithUntitled]); + + return { + generateProjectInfo, + isLoading, + isConfigured + }; +} diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index 76d4b6f9..03c26442 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -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', diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index fff9818e..0c121368 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -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', diff --git a/src/lib/system.test.ts b/src/lib/system.test.ts index 237b7fbc..579ea5bb 100644 --- a/src/lib/system.test.ts +++ b/src/lib/system.test.ts @@ -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', diff --git a/src/locales/en.json b/src/locales/en.json index 081ddfc0..b5babca9 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -18,8 +18,8 @@ "systemSettingsDescription": "Configure system-level settings and advanced options.", "esmUrl": "Javascript CDN", "esmUrlDescription": "Javascript CDN URL for package imports.", - "projectTemplate": "Project Template", - "projectTemplateDescription": "Git repository URL to use as the starting template for new projects.", + "projectTemplates": "Project Templates", + "projectTemplatesDescription": "Configure multiple project templates. The AI will automatically select the most appropriate template based on the user's project description.", "previewDomain": "Preview Domain", "previewDomainDescription": "Domain used for iframe preview sandboxing.", "corsProxy": "CORS Proxy", diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 59216fca..dc7ec8b6 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -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, templateUrl } = 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, + templateUrl, projectId, () => { // Show a toast if template update fails (non-critical) @@ -335,7 +335,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 +356,7 @@ export default function Index() { onFileSelect={handleFileSelect} onFileRemove={handleFileRemove} selectedFiles={attachedFiles} - disabled={isCreating || isGeneratingId} + disabled={isCreating || isGeneratingInfo} multiple={true} /> @@ -366,7 +366,7 @@ export default function Index() { value={providerModel} onChange={setProviderModel} className="w-full" - disabled={isCreating || isGeneratingId} + disabled={isCreating || isGeneratingInfo} placeholder={t('chooseModel')} /> @@ -377,13 +377,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 ? (
) : ( diff --git a/src/pages/SystemSettings.tsx b/src/pages/SystemSettings.tsx index 88564ef8..391b1989 100644 --- a/src/pages/SystemSettings.tsx +++ b/src/pages/SystemSettings.tsx @@ -1,4 +1,4 @@ -import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw } from "lucide-react"; +import { Settings, ArrowLeft, RefreshCw, Trash2, XCircle, Loader2, RotateCcw, Plus } from "lucide-react"; import { useTranslation } from 'react-i18next'; import { useState, useEffect, useMemo } from "react"; import { Button } from "@/components/ui/button"; @@ -23,7 +23,7 @@ export function SystemSettings() { const { toast } = useToast(); const { serviceWorkerRegistration, updateServiceWorker, clearCache } = useOffline(); - const [projectTemplateInput, setProjectTemplateInput] = useState(config.projectTemplate); + const [templatesInput, setTemplatesInput] = useState(config.templates); const [esmUrlInput, setEsmUrlInput] = useState(config.esmUrl); const [corsProxyInput, setCorsProxyInput] = useState(config.corsProxy); const [faviconUrlInput, setFaviconUrlInput] = useState(config.faviconUrl); @@ -39,7 +39,7 @@ export function SystemSettings() { // Check which settings differ from defaults const isModified = useMemo(() => ({ - projectTemplate: config.projectTemplate !== defaultConfig.projectTemplate, + templates: JSON.stringify(config.templates) !== JSON.stringify(defaultConfig.templates), esmUrl: config.esmUrl !== defaultConfig.esmUrl, corsProxy: config.corsProxy !== defaultConfig.corsProxy, faviconUrl: config.faviconUrl !== defaultConfig.faviconUrl, @@ -56,11 +56,11 @@ export function SystemSettings() { }), [config, defaultConfig]); // Restore functions - clear the value from config to use the default - const restoreProjectTemplate = () => { - const defaultValue = defaultConfig.projectTemplate; - setProjectTemplateInput(defaultValue); + const restoreTemplates = () => { + const defaultValue = defaultConfig.templates; + setTemplatesInput(defaultValue); updateConfig((current) => { - const { projectTemplate, ...rest } = current; + const { templates, ...rest } = current; return rest; }); }; @@ -409,48 +409,131 @@ export function SystemSettings() { - {/* Project Template Configuration */} + {/* Project Templates Configuration */} - +
-

{t('projectTemplate')}

- {isModified.projectTemplate && ( +

{t('projectTemplates')}

+ {isModified.templates && (
)}
-
+
+ {templatesInput.map((template, index) => ( +
+
+
+ + { + const newTemplates = [...templatesInput]; + newTemplates[index] = { ...template, name: e.target.value }; + setTemplatesInput(newTemplates); + updateConfig((current) => ({ + ...current, + templates: newTemplates, + })); + }} + /> +
+
+ + { + const newTemplates = [...templatesInput]; + newTemplates[index] = { ...template, description: e.target.value }; + setTemplatesInput(newTemplates); + updateConfig((current) => ({ + ...current, + templates: newTemplates, + })); + }} + /> +
+
+ + { + const newTemplates = [...templatesInput]; + newTemplates[index] = { ...template, url: e.target.value }; + setTemplatesInput(newTemplates); + updateConfig((current) => ({ + ...current, + templates: newTemplates, + })); + }} + /> +
+ +
+
+ ))}
- { - const value = e.target.value; - setProjectTemplateInput(value); + + {isModified.templates && ( )}

- {t('projectTemplateDescription')} + {t('projectTemplatesDescription')}

diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index 1eb4e141..660418e4 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -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',