diff --git a/.gitlab-ci.yml b/.gitlab-ci.yml index 14b7efa7..4cc9481a 100644 --- a/.gitlab-ci.yml +++ b/.gitlab-ci.yml @@ -11,6 +11,8 @@ stages: test: stage: test script: + - npm run typecheck + - npm run build - npm run test pages: diff --git a/package-lock.json b/package-lock.json index 1edd0286..2d331915 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "mkstack", "version": "0.0.0", "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@fontsource-variable/inter": "^5.2.6", "@getalby/sdk": "^6.0.1", "@hookform/resolvers": "^3.9.0", @@ -77,6 +80,7 @@ "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", "turndown": "^7.2.1", + "uri-templates": "^0.2.0", "use-stick-to-bottom": "^1.1.1", "vaul": "^0.9.3", "webln": "^0.3.2", @@ -97,6 +101,7 @@ "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/turndown": "^5.0.5", + "@types/uri-templates": "^0.1.34", "@vitejs/plugin-react-swc": "^3.5.0", "autoprefixer": "^10.4.20", "eslint": "^9.9.0", @@ -347,6 +352,59 @@ "node": ">=18" } }, + "node_modules/@dnd-kit/accessibility": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", + "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/core": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", + "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", + "license": "MIT", + "dependencies": { + "@dnd-kit/accessibility": "^3.1.1", + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/sortable": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz", + "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==", + "license": "MIT", + "dependencies": { + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "@dnd-kit/core": "^6.3.0", + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/utilities": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz", + "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.5", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz", @@ -3793,6 +3851,13 @@ "integrity": "sha512-ko/gIFJRv177XgZsZcBwnqJN5x/Gien8qNOn0D5bQU/zAzVf9Zt3BlcUiLqhV9y4ARk0GbT3tnUiPNgnTXzc/Q==", "license": "MIT" }, + "node_modules/@types/uri-templates": { + "version": "0.1.34", + "resolved": "https://registry.npmjs.org/@types/uri-templates/-/uri-templates-0.1.34.tgz", + "integrity": "sha512-13v4r/Op3iEO1y6FvEHQjrUNnrNyO67SigdFC9n80sVfsrM2AWJRNYbE1pBs4/p87I7z1J979JGeLAo3rM1L/Q==", + "dev": true, + "license": "MIT" + }, "node_modules/@typescript-eslint/eslint-plugin": { "version": "8.31.1", "resolved": "https://registry.npmjs.org/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.31.1.tgz", @@ -10571,6 +10636,12 @@ "punycode": "^2.1.0" } }, + "node_modules/uri-templates": { + "version": "0.2.0", + "resolved": "https://registry.npmjs.org/uri-templates/-/uri-templates-0.2.0.tgz", + "integrity": "sha512-EWkjYEN0L6KOfEoOH6Wj4ghQqU7eBZMJqRHQnxQAq+dSEzRPClkWjf8557HkWQXF6BrAUoLSAyy9i3RVTliaNg==", + "license": "http://geraintluff.github.io/tv4/LICENSE.txt" + }, "node_modules/use-callback-ref": { "version": "1.3.3", "resolved": "https://registry.npmjs.org/use-callback-ref/-/use-callback-ref-1.3.3.tgz", diff --git a/package.json b/package.json index 267e0501..8761be75 100644 --- a/package.json +++ b/package.json @@ -6,10 +6,14 @@ "scripts": { "dev": "npm i --silent && vite", "build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'", - "test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'", + "typecheck": "npm i --silent && tsc --noEmit", + "test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'", "deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup" }, "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@fontsource-variable/inter": "^5.2.6", "@getalby/sdk": "^6.0.1", "@hookform/resolvers": "^3.9.0", @@ -79,6 +83,7 @@ "tailwind-merge": "^2.5.2", "tailwindcss-animate": "^1.0.7", "turndown": "^7.2.1", + "uri-templates": "^0.2.0", "use-stick-to-bottom": "^1.1.1", "vaul": "^0.9.3", "webln": "^0.3.2", @@ -99,6 +104,7 @@ "@types/react": "^18.3.1", "@types/react-dom": "^18.3.1", "@types/turndown": "^5.0.5", + "@types/uri-templates": "^0.1.34", "@vitejs/plugin-react-swc": "^3.5.0", "autoprefixer": "^10.4.20", "eslint": "^9.9.0", diff --git a/proxy.ts b/proxy.ts new file mode 100644 index 00000000..cc26d7c9 --- /dev/null +++ b/proxy.ts @@ -0,0 +1,40 @@ +export default { + async fetch(request: Request): Promise { + const url = new URL(request.url); + const target = url.searchParams.get("url"); + + if (!target) { + return new Response("Include a `url` query parameter", { status: 400 }); + } + + // Handle CORS preflight requests + if (request.method === "OPTIONS") { + return new Response(null, { + status: 200, + headers: { + "Access-Control-Allow-Origin": "*", + "Access-Control-Allow-Methods": "GET,HEAD,POST,OPTIONS", + "Access-Control-Allow-Headers": "*", // Or specify specific headers + "Access-Control-Max-Age": "86400", // Cache preflight for 24 hours + } + }); + } + + const headers = new Headers(request.headers); + headers.set('User-Agent', 'Shakespeare Proxy '); + + const targetResponse = await fetch(target, { + method: request.method, + headers: headers, + body: request.body, + }); + + const response = new Response(targetResponse.body, targetResponse); + + response.headers.set("Access-Control-Allow-Origin", "*"); + response.headers.set("Access-Control-Allow-Methods", "GET,HEAD,POST,OPTIONS"); + response.headers.set("Access-Control-Allow-Headers", "*"); + + return response; + } +}; \ No newline at end of file diff --git a/public/badge.svg b/public/badge.svg new file mode 100644 index 00000000..b51e3dc3 --- /dev/null +++ b/public/badge.svg @@ -0,0 +1,27 @@ + + 🎭 Edit with: Shakespeare + + + + + + + + + + + + + + + + + + + + + + 🎭 Edit with + Shakespeare + + diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index a80c5fea..c0d70908 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -11,6 +11,7 @@ import AISettings from "./pages/AISettings"; import GitSettings from "./pages/GitSettings"; import DataSettings from "./pages/DataSettings"; import AboutSettings from "./pages/AboutSettings"; +import EmailSettings from "./pages/EmailSettings"; import GitHubOAuth from "./pages/GitHubOAuth"; import { NIP19Page } from "./pages/NIP19Page"; import NotFound from "./pages/NotFound"; @@ -33,6 +34,7 @@ export function AppRouter() { } /> } /> } /> + } /> } /> } /> diff --git a/src/assets/quilly.svg b/src/assets/quilly.svg new file mode 100644 index 00000000..e26247fc --- /dev/null +++ b/src/assets/quilly.svg @@ -0,0 +1,114 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/components/AIMessageItem.tsx b/src/components/AIMessageItem.tsx index 3bd4a1ee..f850d900 100644 --- a/src/components/AIMessageItem.tsx +++ b/src/components/AIMessageItem.tsx @@ -16,14 +16,12 @@ interface AIMessageItemProps { message: AIMessage; isCurrentlyLoading?: boolean; toolCall?: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined; // Tool call data passed from the assistant message - reasoningContent?: string; // Reasoning content for streaming messages } export const AIMessageItem = memo(({ message, isCurrentlyLoading = false, toolCall, - reasoningContent }: AIMessageItemProps) => { const [isToolExpanded, setIsToolExpanded] = useState(false); const [isReasoningExpanded, setIsReasoningExpanded] = useState(false); @@ -186,6 +184,75 @@ export const AIMessageItem = memo(({ const toolInfo = getToolInfo(); const IconComponent = toolInfo.icon; + // Get tool call arguments for special rendering + let toolArgs: Record = {}; + let toolName = ''; + if (toolCall?.type === 'function') { + toolName = toolCall.function.name; + try { + toolArgs = JSON.parse(toolCall.function.arguments); + } catch { + toolArgs = {}; + } + } + + // Special rendering for tools + const renderSpecialContent = () => { + if (toolName === 'text_editor_write' && toolArgs.file_text) { + return ( +
+
+ {toolArgs.file_text as string} +
+
+ ); + } + + if (toolName === 'text_editor_str_replace' && toolArgs.old_str && toolArgs.new_str) { + const oldLines = (toolArgs.old_str as string).split('\n'); + const newLines = (toolArgs.new_str as string).split('\n'); + + return ( +
+
+ {/* Old content (removed) */} +
+ {oldLines.map((line, index) => ( +
+ - + + {line} + +
+ ))} +
+ + {/* New content (added) */} +
+ {newLines.map((line, index) => ( +
+ + + + {line} + +
+ ))} +
+
+
+ ); + } + + // Default rendering for other tools + return ( +
+
+ {content} +
+
+ ); + }; + // Regular tool message rendering return (
{/* -mt-2 to make it snug with the previous assistant message */} @@ -202,13 +269,7 @@ export const AIMessageItem = memo(({ - {isToolExpanded && ( -
-
- {content} -
-
- )} + {isToolExpanded && renderSpecialContent()}
); } @@ -233,16 +294,19 @@ export const AIMessageItem = memo(({ ); } + // If there's no reasoning content and the main content is empty, render nothing + if (!hasReasoningContent(message) && !getContent().trim()) { + return null; + } + // Assistant messages: left-aligned without avatar/name return (
-
+
{/* Reasoning content display */} - {((reasoningContent && reasoningContent.trim()) || - (hasReasoningContent(message) && message.reasoning_content.trim()) || - (reasoningContent !== undefined && !getContent().trim() && isCurrentlyLoading)) && ( -
+ {hasReasoningContent(message) && message.reasoning_content.trim() && ( +
- {isReasoningExpanded && (reasoningContent?.trim() || (hasReasoningContent(message) && message.reasoning_content.trim())) && ( + {isReasoningExpanded && (
- {reasoningContent || (hasReasoningContent(message) ? message.reasoning_content : '') || ''} + {message.reasoning_content}
@@ -276,15 +340,18 @@ export const AIMessageItem = memo(({
)} -
- - {getContent()} - -
+ {/* Main content display */} + {getContent().trim() && ( +
+ + {getContent()} + +
+ )} {/* Tool calls are now hidden from assistant messages */}
diff --git a/src/components/AISettingsProvider.test.tsx b/src/components/AISettingsProvider.test.tsx index 2ef9d26d..1e4949da 100644 --- a/src/components/AISettingsProvider.test.tsx +++ b/src/components/AISettingsProvider.test.tsx @@ -31,7 +31,7 @@ describe('AISettingsProvider', () => { // Mock the read function to return default settings const { readAISettings } = await import('@/lib/configUtils'); vi.mocked(readAISettings).mockResolvedValue({ - providers: {}, + providers: [], recentlyUsedModels: [], }); }); @@ -122,12 +122,13 @@ describe('AISettingsProvider', () => { it('should migrate old settings without recentlyUsedModels', async () => { const oldSettings = { - providers: { - openrouter: { + providers: [ + { + id: 'openrouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' } - }, + ], recentlyUsedModels: [] }; @@ -169,12 +170,13 @@ describe('AISettingsProvider', () => { act(() => { result.current.updateSettings({ - providers: { - 'test-provider': { + providers: [ + { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key' } - } + ] }); }); diff --git a/src/components/AISettingsProvider.tsx b/src/components/AISettingsProvider.tsx index 5788ba54..bececb67 100644 --- a/src/components/AISettingsProvider.tsx +++ b/src/components/AISettingsProvider.tsx @@ -1,6 +1,6 @@ import { useQueryClient } from '@tanstack/react-query'; import { ReactNode, useState, useEffect } from 'react'; -import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext'; +import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext'; import { useFS } from '@/hooks/useFS'; import { readAISettings, writeAISettings } from '@/lib/configUtils'; @@ -9,7 +9,7 @@ interface AISettingsProviderProps { } const DEFAULT_SETTINGS: AISettings = { - providers: {}, + providers: [], recentlyUsedModels: [], }; @@ -60,38 +60,40 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { } }; - const addProvider = (name: string, connection: AIConnection) => { - setSettings(prev => ({ - ...prev, - providers: { - ...prev.providers, - [name]: connection, - }, - })); - queryClient.invalidateQueries({ queryKey: ['provider-models'] }); - }; - - const removeProvider = (name: string) => { + const setProvider = (provider: AIProvider) => { setSettings(prev => { - const { [name]: removed, ...rest } = prev.providers; - return { - ...prev, - providers: rest, - }; + const existingIndex = prev.providers.findIndex(p => p.id === provider.id); + if (existingIndex >= 0) { + // Update existing provider + return { + ...prev, + providers: prev.providers.map(p => + p.id === provider.id ? provider : p + ), + }; + } else { + // Add new provider + return { + ...prev, + providers: [...prev.providers, provider], + }; + } }); queryClient.invalidateQueries({ queryKey: ['provider-models'] }); }; - const updateProvider = (name: string, connection: Partial) => { + const removeProvider = (id: string) => { setSettings(prev => ({ ...prev, - providers: { - ...prev.providers, - [name]: { - ...prev.providers[name], - ...connection, - }, - }, + providers: prev.providers.filter(provider => provider.id !== id), + })); + queryClient.invalidateQueries({ queryKey: ['provider-models'] }); + }; + + const setProviders = (providers: AIProvider[]) => { + setSettings(prev => ({ + ...prev, + providers, })); queryClient.invalidateQueries({ queryKey: ['provider-models'] }); }; @@ -120,14 +122,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { }); }; - const isConfigured = Object.entries(settings.providers).length > 0; + const isConfigured = settings.providers.length > 0; const contextValue: AISettingsContextType = { settings, updateSettings, - addProvider, + setProvider, removeProvider, - updateProvider, + setProviders, addRecentlyUsedModel, isConfigured, }; diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index e9c678b5..5a1c2913 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -4,193 +4,45 @@ import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, - DropdownMenuSeparator, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { - AlertDialog, - AlertDialogAction, - AlertDialogCancel, - AlertDialogContent, - AlertDialogDescription, - AlertDialogFooter, - AlertDialogHeader, - AlertDialogTitle, - AlertDialogTrigger, -} from '@/components/ui/alert-dialog'; -import { + GitBranch, MoreHorizontal, MessageSquarePlus, - Play, - CloudUpload, - Loader2, - GitBranch, - Download, - Trash2, - Settings, - GitMerge, + History, + Folder, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { GitDialog } from '@/components/GitDialog'; -import { AppSettingsDialog } from '@/components/AppSettingsDialog'; -import { useNavigate } from 'react-router-dom'; -import { useProjectsManager } from '@/hooks/useProjectsManager'; -import { useToast } from '@/hooks/useToast'; -import { useGit } from '@/hooks/useGit'; -import { useFS } from '@/hooks/useFS'; -import JSZip from 'jszip'; interface ActionsMenuProps { projectId: string; projectName: string; onNewChat: () => void; - onBuild: () => void; - onDeploy: () => void; + onProjectDetails?: () => void; isLoading?: boolean; isBuildLoading?: boolean; - isDeployLoading?: boolean; disabled?: boolean; onFirstInteraction?: () => void; - onProjectDeleted?: () => void; } export function ActionsMenu({ projectId, - projectName, + projectName: _projectName, onNewChat, - onBuild, - onDeploy, + onProjectDetails, isLoading = false, isBuildLoading = false, - isDeployLoading = false, disabled = false, - onFirstInteraction, - onProjectDeleted + onFirstInteraction: _onFirstInteraction, }: ActionsMenuProps) { const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [gitDialogOpen, setGitDialogOpen] = useState(false); - const [isDeleting, setIsDeleting] = useState(false); - const [isExporting, setIsExporting] = useState(false); - const navigate = useNavigate(); - const projectsManager = useProjectsManager(); - const { toast } = useToast(); - const git = useGit(); - const { fs } = useFS(); + const isAnyLoading = isLoading || isBuildLoading; - const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting; - const handleDeleteProject = async () => { - setIsDeleting(true); - try { - await projectsManager.deleteProject(projectId); - - toast({ - title: "Project deleted", - description: `"${projectName}" has been permanently deleted.`, - }); - - // Navigate back to home and notify parent - navigate('/'); - if (onProjectDeleted) { - onProjectDeleted(); - } - } catch (error) { - toast({ - title: "Failed to delete project", - description: error instanceof Error ? error.message : "An unexpected error occurred", - variant: "destructive", - }); - } finally { - setIsDeleting(false); - } - }; - - const handleExportProject = async () => { - setIsExporting(true); - try { - const zip = new JSZip(); - const projectPath = `/projects/${projectId}`; - - // Recursive function to add files and directories to zip from a specific project - const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => { - try { - const entries = await fs.readdir(dirPath, { withFileTypes: true }); - - for (const entry of entries) { - const fullPath = `${dirPath}/${entry.name}`; - - if (entry.isDirectory()) { - // Create folder in zip and recursively add its contents - const folder = zipFolder.folder(entry.name); - if (folder) { - await addProjectToZip(fullPath, folder); - } - } else if (entry.isFile()) { - // Add file to zip - try { - const fileContent = await fs.readFile(fullPath); - zipFolder.file(entry.name, fileContent); - } catch (error) { - console.warn(`Failed to read file ${fullPath}:`, error); - } - } - } - } catch (error) { - console.warn(`Failed to read directory ${dirPath}:`, error); - } - }; - - // Start from the project directory - await addProjectToZip(projectPath, zip); - - // Generate zip file - const content = await zip.generateAsync({ type: 'blob' }); - - // Create download link - const url = URL.createObjectURL(content); - const link = document.createElement('a'); - link.href = url; - - // Generate filename with commit hash - let filename = `${projectName}.zip`; - try { - // Get the current commit hash - const commits = await git.log({ - dir: projectPath, - depth: 1, - }); - - if (commits.length > 0) { - const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters - filename = `${projectName}-${commitHash}.zip`; - } - } catch (error) { - console.warn('Failed to get commit hash, using project name only:', error); - } - - link.download = filename; - - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); - - toast({ - title: "Project exported successfully", - description: `"${projectName}" has been downloaded as a zip file.`, - }); - } catch (error) { - console.error('Failed to export project:', error); - toast({ - title: "Failed to export project", - description: error instanceof Error ? error.message : "An unexpected error occurred", - variant: "destructive", - }); - } finally { - setIsExporting(false); - } - }; return ( <> @@ -216,118 +68,34 @@ export function ActionsMenu({ New Chat - setGitDialogOpen(true)} - disabled={isAnyLoading} - className="gap-2" - > - - Git Status - - setGitHistoryOpen(true)} disabled={isAnyLoading} className="gap-2" + > + + Rollback + + + setGitDialogOpen(true)} + disabled={isAnyLoading} + className="gap-2" > - Git History - - - - e.preventDefault()} - > - - Settings - - - - - {isExporting ? ( - - ) : ( - - )} - {isExporting ? 'Exporting...' : 'Export Project'} + Repository { - if (onFirstInteraction) onFirstInteraction(); - onBuild(); - }} + onClick={onProjectDetails} disabled={isAnyLoading} className="gap-2" > - {isBuildLoading ? ( - - ) : ( - - )} - {isBuildLoading ? 'Building...' : 'Build'} + + Project Details - { - if (onFirstInteraction) onFirstInteraction(); - onDeploy(); - }} - disabled={isAnyLoading} - className="gap-2" - > - {isDeployLoading ? ( - - ) : ( - - )} - {isDeployLoading ? 'Deploying...' : 'Deploy'} - - - - - - e.preventDefault()} - > - - Delete Project - - - - - Delete Project - - Are you sure you want to delete "{projectName}"? This action cannot be undone and will permanently delete all project data including files. - - - - Cancel - - {isDeleting ? ( - <> - - Deleting... - - ) : ( - 'Delete Project' - )} - - - - @@ -343,6 +111,8 @@ export function ActionsMenu({ open={gitHistoryOpen} onOpenChange={setGitHistoryOpen} /> + + ); } \ No newline at end of file diff --git a/src/components/AppSettingsDialog.tsx b/src/components/AppSettingsDialog.tsx deleted file mode 100644 index 3960d34f..00000000 --- a/src/components/AppSettingsDialog.tsx +++ /dev/null @@ -1,108 +0,0 @@ -import { useState } from 'react'; -import { Settings, Save } from 'lucide-react'; -import { Button } from '@/components/ui/button'; -import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { useAppContext } from '@/hooks/useAppContext'; -import { useToast } from '@/hooks/useToast'; - -interface AppSettingsDialogProps { - children?: React.ReactNode; -} - -export function AppSettingsDialog({ children }: AppSettingsDialogProps) { - const { config, updateConfig } = useAppContext(); - const { toast } = useToast(); - const [open, setOpen] = useState(false); - const [deployServer, setDeployServer] = useState(config.deployServer); - - const handleSave = () => { - // Validate deploy server - if (!deployServer.trim()) { - toast({ - title: "Invalid deploy server", - description: "Deploy server cannot be empty.", - variant: "destructive", - }); - return; - } - - // Remove protocol if present - const cleanDeployServer = deployServer.replace(/^https?:\/\//, ''); - - updateConfig((current) => ({ - ...current, - deployServer: cleanDeployServer, - })); - - toast({ - title: "Settings saved", - description: "Your deployment settings have been updated.", - }); - - setOpen(false); - }; - - const handleCancel = () => { - // Reset to current config - setDeployServer(config.deployServer); - setOpen(false); - }; - - return ( - - - {children || ( - - )} - - - - App Settings - - Configure your application preferences and deployment settings. - - - -
- - - Deployment - - -
- - setDeployServer(e.target.value)} - placeholder="shakespeare.wtf" - className="font-mono" - /> -

- Your projects will be deployed to subdomains of this server. - Example: yourproject.{deployServer || 'shakespeare.wtf'} -

-
-
-
-
- -
- - -
-
-
- ); -} \ No newline at end of file diff --git a/src/components/CreditsBadge.test.tsx b/src/components/CreditsBadge.test.tsx index 10a95b54..a8cb6e44 100644 --- a/src/components/CreditsBadge.test.tsx +++ b/src/components/CreditsBadge.test.tsx @@ -2,7 +2,6 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen, fireEvent } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; import { CreditsBadge } from './CreditsBadge'; -import type { AIConnection } from '@/contexts/AISettingsContext'; // Mock the useAICredits hook vi.mock('@/hooks/useAICredits', () => ({ @@ -16,7 +15,8 @@ vi.mock('@/hooks/useAICredits', () => ({ // Mock the fetch function global.fetch = vi.fn(); -const mockConnection: AIConnection = { +const mockProvider = { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key', }; @@ -25,10 +25,7 @@ describe('CreditsBadge', () => { it('renders the credits amount', () => { render( - + ); @@ -41,8 +38,7 @@ describe('CreditsBadge', () => { render( @@ -57,10 +53,7 @@ describe('CreditsBadge', () => { it('has proper styling for clickable badge', () => { render( - + ); @@ -72,10 +65,7 @@ describe('CreditsBadge', () => { it('does not render dialog directly', () => { render( - + ); diff --git a/src/components/CreditsBadge.tsx b/src/components/CreditsBadge.tsx index c12768d8..ee565159 100644 --- a/src/components/CreditsBadge.tsx +++ b/src/components/CreditsBadge.tsx @@ -1,10 +1,9 @@ import { Badge } from '@/components/ui/badge'; +import { AIProvider } from '@/contexts/AISettingsContext'; import { useAICredits } from '@/hooks/useAICredits'; -import type { AIConnection } from '@/contexts/AISettingsContext'; interface CreditsBadgeProps { - providerId: string; - connection: AIConnection; + provider: AIProvider; className?: string; onOpenDialog?: () => void; } @@ -12,8 +11,8 @@ interface CreditsBadgeProps { /** * Displays a clickable credits badge showing the remaining credits for an AI provider */ -export function CreditsBadge({ providerId, connection, className, onOpenDialog }: CreditsBadgeProps) { - const { data: credits, isLoading, error } = useAICredits(providerId, connection); +export function CreditsBadge({ provider, className, onOpenDialog }: CreditsBadgeProps) { + const { data: credits, isLoading, error } = useAICredits(provider); // Don't render anything if there's an error (provider doesn't support credits endpoint) if (error || isLoading) { diff --git a/src/components/CreditsDialog.test.tsx b/src/components/CreditsDialog.test.tsx index 061e0bd1..a30d3764 100644 --- a/src/components/CreditsDialog.test.tsx +++ b/src/components/CreditsDialog.test.tsx @@ -2,14 +2,16 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; import { CreditsDialog } from './CreditsDialog'; -import type { AIConnection } from '@/contexts/AISettingsContext'; +import type { AIProvider } from '@/contexts/AISettingsContext'; // Mock the fetch function global.fetch = vi.fn(); -const mockConnection: AIConnection = { +const mockProvider: AIProvider = { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key', + nostr: false, }; describe('CreditsDialog', () => { @@ -19,8 +21,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -36,8 +37,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -51,8 +51,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -67,8 +66,7 @@ describe('CreditsDialog', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -89,8 +87,7 @@ describe('CreditsDialog', () => { ); @@ -101,8 +98,7 @@ describe('CreditsDialog', () => { ); diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 7a45d96c..46b33e01 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -13,13 +13,12 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; -import type { AIConnection } from '@/contexts/AISettingsContext'; +import { AIProvider } from '@/contexts/AISettingsContext'; interface CreditsDialogProps { open: boolean; onOpenChange: (open: boolean) => void; - providerId: string; - connection: AIConnection; + provider: AIProvider; } interface Payment { @@ -182,7 +181,7 @@ function LightningPayment({ invoice, amount, onClose }: LightningPaymentProps) { ); } -export function CreditsDialog({ open, onOpenChange, providerId, connection }: CreditsDialogProps) { +export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogProps) { const { user } = useCurrentUser(); const { toast } = useToast(); const queryClient = useQueryClient(); @@ -194,9 +193,9 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Query for payment history const { data: payments, isLoading: isLoadingPayments } = useQuery({ - queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); const data = await ai.get('/credits/payments?limit=50') as PaymentsResponse; return data.data; }, @@ -208,7 +207,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Mutation for adding credits const addCreditsMutation = useMutation({ mutationFn: async (request: AddCreditsRequest): Promise => { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); return await ai.post('/credits/add', { body: request, }) as Payment; @@ -228,12 +227,12 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Refresh payments list queryClient.invalidateQueries({ - queryKey: ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); // Refresh credits balance queryClient.invalidateQueries({ - queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); }, onError: (error: Error) => { @@ -249,7 +248,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Mutation for checking payment status const checkPaymentMutation = useMutation({ mutationFn: async (paymentId: string): Promise => { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); return await ai.get(`/credits/payments/${paymentId}`) as Payment; }, onMutate: async (paymentId: string) => { @@ -266,7 +265,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // Update the specific payment in the cache instead of refetching queryClient.setQueryData( - ['ai-payments', connection.nostr ? user?.pubkey ?? '' : '', providerId], + ['ai-payments', provider.nostr ? user?.pubkey ?? '' : '', provider.id], (oldPayments) => { if (!oldPayments) return oldPayments; return oldPayments.map(payment => @@ -278,7 +277,7 @@ export function CreditsDialog({ open, onOpenChange, providerId, connection }: Cr // If payment completed, refresh credits balance if (updatedPayment.status === 'completed') { queryClient.invalidateQueries({ - queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], }); toast({ title: 'Payment completed!', diff --git a/src/components/DeployDialog.tsx b/src/components/DeployDialog.tsx new file mode 100644 index 00000000..87d1f94f --- /dev/null +++ b/src/components/DeployDialog.tsx @@ -0,0 +1,182 @@ +import { useState, useEffect } from 'react'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogFooter, +} from '@/components/ui/dialog'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useToast } from '@/hooks/useToast'; +import { useAppContext } from '@/hooks/useAppContext'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useMutation } from '@tanstack/react-query'; +import { deployProject } from '@/lib/deploy'; +import { useFS } from '@/hooks/useFS'; +import { + CloudUpload, + Loader2, +} from 'lucide-react'; + +interface DeployDialogProps { + projectId: string; + projectName: string; + open: boolean; + onOpenChange: (open: boolean) => void; + onFirstInteraction?: () => void; +} + +export function DeployDialog({ + projectId, + projectName, + open, + onOpenChange, + onFirstInteraction +}: DeployDialogProps) { + const { config } = useAppContext(); + const { user } = useCurrentUser(); + const { fs } = useFS(); + const { toast } = useToast(); + + // State for the deploy URL input + const [deployUrl, setDeployUrl] = useState(''); + + // Initialize deploy URL when dialog opens + useEffect(() => { + if (open) { + setDeployUrl(`${projectId}.${config.deployServer}`); + } + }, [open, projectId, config.deployServer]); + + const deployMutation = useMutation({ + mutationFn: async () => { + if (!user) { + throw new Error("You must be logged into Nostr to deploy a project"); + } + + // Parse the deploy URL to extract hostname and server + const hostname = deployUrl.trim(); + const parts = hostname.split('.'); + + if (parts.length < 2) { + throw new Error("Invalid deploy URL format. Please use format: subdomain.domain.com"); + } + + // Extract the deploy server (everything after the first dot) + const deployServer = parts.slice(1).join('.'); + + return await deployProject({ + fs, + projectId, // Keep the original projectId for file path + deployServer, + projectPath: `/projects/${projectId}`, + signer: user.signer, + customHostname: hostname, // Pass the custom hostname + }); + }, + onSuccess: (result) => { + toast({ + title: "Deployment successful!", + description: `Your project is now live at ${result.hostname}`, + }); + + // Open the deployed site in a new tab + window.open(result.url, '_blank'); + + // Close the dialog + onOpenChange(false); + }, + onError: (error) => { + toast({ + title: "Deployment failed", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + }, + }); + + const handleDeploy = () => { + if (onFirstInteraction) { + onFirstInteraction(); + } + deployMutation.mutate(); + }; + + const handleUrlChange = (value: string) => { + // Remove protocol if user enters it + const cleanValue = value.replace(/^https?:\/\//, ''); + setDeployUrl(cleanValue); + }; + + const isValidUrl = () => { + const trimmed = deployUrl.trim(); + return trimmed.length > 0 && trimmed.includes('.') && !trimmed.startsWith('.') && !trimmed.endsWith('.'); + }; + + return ( + + + + + + Deploy "{projectName}" + + + +
+
+ +
+ + https:// + + handleUrlChange(e.target.value)} + placeholder={`${projectId}.${config.deployServer}`} + className="pl-16" + disabled={deployMutation.isPending} + /> +
+

+ Your project will be deployed to this URL. You can customize the subdomain. +

+
+ + {!user && ( +
+

+ You must be logged into Nostr to deploy projects. +

+
+ )} +
+ + + + + +
+
+ ); +} \ No newline at end of file diff --git a/src/components/GitDialog.test.tsx b/src/components/GitDialog.test.tsx index faf4e17b..ab2a5081 100644 --- a/src/components/GitDialog.test.tsx +++ b/src/components/GitDialog.test.tsx @@ -43,17 +43,10 @@ vi.mock('@/hooks/useToast', () => ({ })), })); +const mockUseGitSettings = vi.fn(); + vi.mock('@/hooks/useGitSettings', () => ({ - useGitSettings: vi.fn(() => ({ - settings: { - credentials: { - 'https://github.com': { - username: 'git', - password: 'github-token', - }, - }, - }, - })), + useGitSettings: () => mockUseGitSettings(), })); describe('GitDialog', () => { @@ -62,9 +55,20 @@ describe('GitDialog', () => { data: baseGitStatus, refetch: mockRefetch, }); + + mockUseGitSettings.mockReturnValue({ + settings: { + credentials: { + 'https://github.com': { + username: 'git', + password: 'github-token', + }, + }, + }, + }); }); - it('renders git repository information', () => { + it('renders git dialog without repository information section', () => { render( {}}> @@ -73,11 +77,9 @@ describe('GitDialog', () => { ); - expect(screen.getByText('Git Repository Status')).toBeInTheDocument(); - expect(screen.getByText('Repository Information')).toBeInTheDocument(); - expect(screen.getByText('main')).toBeInTheDocument(); - expect(screen.getByText('5')).toBeInTheDocument(); - expect(screen.getAllByText('origin')).toHaveLength(2); // Appears in remotes and credentials sections + expect(screen.getByText('Repository')).toBeInTheDocument(); + expect(screen.queryByText('Repository Information')).not.toBeInTheDocument(); + expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed }); it('shows sync status', () => { @@ -145,7 +147,7 @@ describe('GitDialog', () => { expect(pushButton.closest('button')).toBeDisabled(); }); - it('shows configured credentials status', () => { + it('does not show credentials warning when credentials are configured', () => { render( {}}> @@ -154,8 +156,38 @@ describe('GitDialog', () => { ); - expect(screen.getByText('Authentication')).toBeInTheDocument(); - expect(screen.getByText('github.com')).toBeInTheDocument(); - expect(screen.getByText('Configured')).toBeInTheDocument(); + // Should not show warning when credentials are configured + expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument(); + expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed + }); + + it('shows credentials warning when no credentials are configured', () => { + // Mock git settings with no credentials and mock git status with an https remote + mockUseGitSettings.mockReturnValue({ + settings: { + credentials: {}, + }, + }); + + mockUseGitStatus.mockReturnValue({ + data: { + ...baseGitStatus, + remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }], + }, + refetch: mockRefetch, + }); + + render( + + {}}> + + + + ); + + // Should show warning when credentials are missing + expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument(); + expect(screen.getByText('log in')).toBeInTheDocument(); + expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed }); }); \ No newline at end of file diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 5b5b53a7..1aa22072 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -1,10 +1,9 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, - DialogDescription, DialogHeader, DialogTitle, DialogTrigger, @@ -19,6 +18,8 @@ import { import { Badge } from '@/components/ui/badge'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; import { GitBranch, Upload, @@ -31,16 +32,22 @@ import { Plus, Minus, Edit, - RefreshCw, - Settings, AlertTriangle, + Zap, + Save, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useGit } from '@/hooks/useGit'; import { useToast } from '@/hooks/useToast'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useNostr } from '@nostrify/react'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; import { cn } from '@/lib/utils'; -import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials'; +import { findCredentialsForRepo } from '@/lib/gitCredentials'; +import { nip19 } from 'nostr-tools'; + +const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"]; interface GitDialogProps { projectId: string; @@ -52,25 +59,286 @@ interface GitDialogProps { export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) { const [isPushing, setIsPushing] = useState(false); const [isPulling, setIsPulling] = useState(false); - const [pushResult, setPushResult] = useState(null); - const [pullResult, setPullResult] = useState(null); + const [isPushingToNostr, setIsPushingToNostr] = useState(false); + const [originUrl, setOriginUrl] = useState(''); + const [isSavingOrigin, setIsSavingOrigin] = useState(false); const navigate = useNavigate(); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); - const git = useGit(); + const { git } = useGit(); const { toast } = useToast(); + const { user } = useCurrentUser(); + const { nostr } = useNostr(); + const { mutateAsync: publishEvent } = useNostrPublish(); const projectPath = `/projects/${projectId}`; - // Get credentials for the current repository - const getCredentialsForCurrentRepo = () => { - if (!gitStatus?.remotes.length) return null; - const remoteUrl = gitStatus.remotes[0].url; // Use first remote (usually 'origin') - return findCredentialsForRepo(remoteUrl, settings.credentials); + // Initialize origin URL from git status + useEffect(() => { + if (gitStatus?.remotes) { + const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin'); + setOriginUrl(originRemote?.url || ''); + } + }, [gitStatus?.remotes]); + + const handleSaveOrigin = async () => { + if (!gitStatus?.isGitRepo) { + toast({ + title: "Cannot configure origin", + description: "Not a git repository", + variant: "destructive", + }); + return; + } + + setIsSavingOrigin(true); + + try { + // Remove existing origin if it exists + try { + await git.deleteRemote({ + dir: projectPath, + remote: 'origin', + }); + } catch { + // Ignore if origin doesn't exist + } + + // Add new origin if URL is provided + if (originUrl.trim()) { + await git.addRemote({ + dir: projectPath, + remote: 'origin', + url: originUrl.trim(), + }); + + toast({ + title: "Origin configured", + description: `Origin remote set to ${originUrl.trim()}`, + }); + } else { + toast({ + title: "Origin removed", + description: "Origin remote has been removed", + }); + } + + // Refresh git status after changing origin + await refetchGitStatus(); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + toast({ + title: "Failed to configure origin", + description: errorMessage, + variant: "destructive", + }); + } finally { + setIsSavingOrigin(false); + } }; - const currentCredentials = getCredentialsForCurrentRepo(); + const handlePushToNostr = async () => { + if (!user) { + toast({ + title: "Cannot push to Nostr", + description: "You must be logged in to push to Nostr", + variant: "destructive", + }); + return; + } + + if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { + toast({ + title: "Cannot push to Nostr", + description: "Not a git repository or no current branch", + variant: "destructive", + }); + return; + } + + setIsPushingToNostr(true); + + try { + // Check if repo announcement already exists + const existingRepoEvents = await nostr.query([{ + kinds: [30617], + authors: [user.pubkey], + '#d': [projectId], + limit: 1, + }], { signal: AbortSignal.timeout(5000) }); + + if (existingRepoEvents.length > 0) { + throw new Error(`Repository announcement already exists for project "${projectId}". Cannot create duplicate.`); + } + + // Create repo announcement event (NIP-34 kind 30617) + const cloneUrls = GRASP_SERVERS.map(server => + `https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git` + ); + const relayUrls = GRASP_SERVERS.map(server => `wss://${server}`); + + await publishEvent({ + kind: 30617, + content: "", + tags: [ + ["d", projectId], + ["clone", ...cloneUrls], + ["relays", ...relayUrls], + ], + }); + + // Get current repository state + const refTags: string[][] = []; + + // First check if we have any commits at all + try { + const log = await git.log({ dir: projectPath, depth: 1 }); + if (log.length === 0) { + throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.'); + } + console.log(`Repository has ${log.length} commit(s), latest: ${log[0].oid}`); + } catch (error) { + if (error instanceof Error && error.message.includes('no commits')) { + throw error; // Re-throw our custom error + } + throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.'); + } + + try { + // Get all refs using listRefs + const refs = await git.listRefs({ dir: projectPath }); + console.log('Found refs:', refs); + + for (const ref of refs) { + try { + const commitId = await git.resolveRef({ + dir: projectPath, + ref, + }); + if (ref.startsWith('refs/heads/') || ref.startsWith('refs/tags/')) { + refTags.push([ref, commitId]); + } + } catch (error) { + console.warn(`Failed to resolve ref ${ref}:`, error); + } + } + } catch (error) { + console.warn('Failed to list refs, trying alternative approach:', error); + } + + // If no refs found, try to get the current branch directly + if (refTags.length === 0) { + try { + const currentBranch = await git.currentBranch({ dir: projectPath }); + if (currentBranch) { + const currentCommit = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + refTags.push([`refs/heads/${currentBranch}`, currentCommit]); + console.log(`Added current branch: refs/heads/${currentBranch} -> ${currentCommit}`); + } else { + // Try to get HEAD directly even if no current branch + try { + const headCommit = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + refTags.push(['refs/heads/main', headCommit]); // Assume main branch + console.log(`Added assumed main branch: refs/heads/main -> ${headCommit}`); + } catch (headError) { + console.warn('Failed to resolve HEAD directly:', headError); + } + } + } catch (error) { + console.warn('Failed to get current branch:', error); + } + } + + if (refTags.length === 0) { + throw new Error('Could not determine repository state. The repository might not have any commits or branches.'); + } + + // Get HEAD reference + let headRef: string | undefined; + try { + const currentBranch = await git.currentBranch({ dir: projectPath }); + if (currentBranch) { + headRef = `ref: refs/heads/${currentBranch}`; + console.log(`HEAD points to: ${headRef}`); + } else { + // HEAD is detached, use the commit ID directly + const headValue = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + if (headValue) { + headRef = headValue; + console.log(`HEAD is detached at: ${headRef}`); + } + } + } catch (error) { + console.warn('Failed to resolve HEAD:', error); + } + + // Create repo state event (NIP-34 kind 30618) + await publishEvent({ + kind: 30618, + content: "", + tags: [ + ["d", projectId], + ...refTags, + ...(headRef ? [["HEAD", headRef]] : []), + ], + }); + + // Set origin remote to Nostr URL + const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/git.shakespeare.diy/${projectId}`; + + try { + // Remove existing origin if it exists + await git.deleteRemote({ + dir: projectPath, + remote: 'origin', + }); + } catch { + // Ignore if origin doesn't exist + } + + await git.addRemote({ + dir: projectPath, + remote: 'origin', + url: nostrUrl, + }); + + // Set nostr.repo config + await git.setConfig({ + dir: projectPath, + path: 'nostr.repo', + value: nip19.naddrEncode({ + kind: 30617, + pubkey: user.pubkey, + identifier: projectId, + }), + }); + + toast({ + title: "Repository published to Nostr", + description: "Waiting for GRASP servers to update...", + }); + + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + toast({ + title: "Push to Nostr failed", + description: errorMessage, + variant: "destructive", + }); + } finally { + setIsPushingToNostr(false); + } + }; const handlePush = async () => { if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { @@ -101,27 +369,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } setIsPushing(true); - setPushResult(null); try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') - // Prepare authentication if credentials are available - const authOptions = currentCredentials ? { - onAuth: () => ({ - username: currentCredentials.username, - password: currentCredentials.password - }), - } : {}; - await git.push({ dir: projectPath, remote: remote.name, ref: gitStatus.currentBranch, - ...authOptions, + onAuth: (url) => findCredentialsForRepo(url, settings.credentials), + signer: user?.signer, // For signing if pushing to Nostr }); - setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`); + toast({ title: "Push successful", description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`, @@ -131,7 +391,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog await refetchGitStatus(); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; - setPushResult(`❌ Push failed: ${errorMessage}`); toast({ title: "Push failed", description: errorMessage, @@ -162,19 +421,10 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } setIsPulling(true); - setPullResult(null); try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') - // Prepare authentication if credentials are available - const authOptions = currentCredentials ? { - onAuth: () => ({ - username: currentCredentials.username, - password: currentCredentials.password - }), - } : {}; - await git.pull({ dir: projectPath, ref: gitStatus.currentBranch, @@ -183,10 +433,10 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog name: 'shakespeare.diy', email: 'assistant@shakespeare.diy', }, - ...authOptions, + onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); - setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`); + toast({ title: "Pull successful", description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`, @@ -196,7 +446,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog await refetchGitStatus(); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; - setPullResult(`❌ Pull failed: ${errorMessage}`); toast({ title: "Pull failed", description: errorMessage, @@ -207,11 +456,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } }; - const handleRefresh = async () => { - await refetchGitStatus(); - setPushResult(null); - setPullResult(null); - }; + const getFileStatusIcon = (status: string) => { switch (status) { @@ -281,158 +526,131 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog return ( {children && {children}} - + e.preventDefault()}> - Git Repository Status + Repository - - View repository status and sync with remote repositories - + {/* URL Configuration */} + {gitStatus?.isGitRepo && ( + + + Git URL + + +
+
+ + setOriginUrl(e.target.value)} + disabled={isSavingOrigin} + /> +
+ +
+ + {/* Credentials Warning */} + {gitStatus.remotes.length > 0 && ( + (() => { + const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials)); + if (!remoteWithoutCredentials) return null; + + let protocol = ''; + let hostname = 'the remote host'; + try { + const url = new URL(remoteWithoutCredentials.url); + protocol = url.protocol; + hostname = url.hostname; + } catch { + // Invalid URL + return ( + + + + Invalid URL format. Enter an https URL. + + + ); + } + + // Check for unsupported protocols + if (protocol !== 'https:' && protocol !== 'nostr:') { + return ( + + + + The {protocol.replace(':', '')} URL type is not supported. Enter an https URL. + + + ); + } + + // For nostr protocol, only show warning if user is not logged in + if (protocol === 'nostr:' && !user) { + return ( + + + + You are not logged into Nostr. Push & pull might not work unless you{' '} + . + + + ); + } + + // For https protocol, show warning if no credentials + if (protocol === 'https:') { + return ( + + + + You are not logged into {hostname}. Push & pull might not work unless you{' '} + . + + + ); + } + + return null; + })() + )} +
+
+ )} +
- {/* Repository Info */} - - - - Repository Information - - - - - {gitStatus?.isGitRepo ? ( - <> -
- Current Branch: - - {gitStatus.currentBranch || 'unknown'} - -
- -
- Total Commits: - {gitStatus.totalCommits} -
- - {gitStatus.latestCommit && ( -
- Latest Commit: -
-
- {gitStatus.latestCommit.oid.substring(0, 7)} -
-
{gitStatus.latestCommit.message}
-
- - {new Date(gitStatus.latestCommit.author.timestamp * 1000).toLocaleString()} -
-
-
- )} - - {gitStatus.remotes.length > 0 && ( -
- Remotes: - {gitStatus.remotes.map((remote) => ( -
-
- {remote.name} - - {remote.url} - -
-
- ))} -
- )} - - ) : ( -
- -

Not a Git repository

-
- )} -
-
- - {/* Credentials Status */} - {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && ( - - - - Authentication - - - - Credentials for push/pull operations - - - - {gitStatus.remotes.map((remote) => { - const credentials = findCredentialsForRepo(remote.url, settings.credentials); - const originDisplayName = getOriginDisplayName(remote.url); - - return ( -
-
-
- {remote.name} - - {originDisplayName} - -
- {credentials ? ( -
- - Configured -
- ) : ( -
- - No credentials -
- )} -
- - {!credentials && ( - - - - No credentials configured for {originDisplayName}. - Push/pull operations may fail for private repositories.{' '} - - - - )} -
- ); - })} -
-
- )} {/* Sync Status */} {gitStatus?.isGitRepo && ( @@ -452,7 +670,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
)} + + )} diff --git a/src/components/GitSettingsProvider.test.tsx b/src/components/GitSettingsProvider.test.tsx index 96a201f3..2192aa12 100644 --- a/src/components/GitSettingsProvider.test.tsx +++ b/src/components/GitSettingsProvider.test.tsx @@ -179,7 +179,7 @@ describe('GitSettingsProvider', () => { password: 'test-token', } }, - corsProxy: 'https://cors.isomorphic-git.org' + corsProxy: 'https://proxy.shakespeare.diy/?url={href}' }) ); }); @@ -220,7 +220,7 @@ describe('GitSettingsProvider', () => { ); await waitFor(() => { - expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org'); + expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}'); }); }); @@ -232,7 +232,7 @@ describe('GitSettingsProvider', () => { ); await waitFor(() => { - expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://cors.isomorphic-git.org'); + expect(screen.getByTestId('cors-proxy')).toHaveTextContent('https://proxy.shakespeare.diy/?url={href}'); }); fireEvent.click(screen.getByText('Update CORS Proxy')); diff --git a/src/components/GitSettingsProvider.tsx b/src/components/GitSettingsProvider.tsx index 3f49fbf3..275a805f 100644 --- a/src/components/GitSettingsProvider.tsx +++ b/src/components/GitSettingsProvider.tsx @@ -9,7 +9,7 @@ interface GitSettingsProviderProps { const DEFAULT_SETTINGS: GitSettings = { credentials: {}, - corsProxy: 'https://cors.isomorphic-git.org', + corsProxy: 'https://proxy.shakespeare.diy/?url={href}', }; export function GitSettingsProvider({ children }: GitSettingsProviderProps) { @@ -22,6 +22,10 @@ export function GitSettingsProvider({ children }: GitSettingsProviderProps) { const initializeSettings = async () => { try { const settings = await readGitSettings(fs); + // Migrate old CORS proxy format + if (settings.corsProxy === 'https://cors.isomorphic-git.org') { + settings.corsProxy = DEFAULT_SETTINGS.corsProxy; + } setSettings(settings); } catch (error) { console.error('Failed to initialize Git settings:', error); diff --git a/src/components/LanguagePicker.tsx b/src/components/LanguagePicker.tsx index 6838115e..3ea6fdad 100644 --- a/src/components/LanguagePicker.tsx +++ b/src/components/LanguagePicker.tsx @@ -47,6 +47,24 @@ export function LanguagePicker({ className }: LanguagePickerProps) { {t('chinese')}
+ +
+ 🇳🇬 + {t('hausa')} +
+
+ +
+ 🇳🇬 + {t('yoruba')} +
+
+ +
+ 🇳🇬 + {t('igbo')} +
+
); diff --git a/src/components/LightningPayment.test.tsx b/src/components/LightningPayment.test.tsx index 05319747..1e17ef64 100644 --- a/src/components/LightningPayment.test.tsx +++ b/src/components/LightningPayment.test.tsx @@ -1,6 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { render, screen } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; +import type { AIProvider } from '@/contexts/AISettingsContext'; // Mock QRCode vi.mock('qrcode', () => ({ @@ -18,9 +19,11 @@ const mockWebLN = { // We need to import the component after mocking const { CreditsDialog } = await import('./CreditsDialog'); -const mockConnection = { +const mockProvider: AIProvider = { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key', + nostr: false, }; describe('Lightning Payment', () => { @@ -39,8 +42,7 @@ describe('Lightning Payment', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -61,8 +63,7 @@ describe('Lightning Payment', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); @@ -77,8 +78,7 @@ describe('Lightning Payment', () => { {}} - providerId="test-provider" - connection={mockConnection} + provider={mockProvider} /> ); diff --git a/src/components/ModelSelector.test.tsx b/src/components/ModelSelector.test.tsx index 2ce8e560..b5c7102b 100644 --- a/src/components/ModelSelector.test.tsx +++ b/src/components/ModelSelector.test.tsx @@ -34,13 +34,14 @@ describe('ModelSelector', () => { vi.clearAllMocks(); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels: [] }, + settings: { providers: [], recentlyUsedModels: [] }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); mockUseProviderModels.mockReturnValue({ @@ -69,13 +70,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels }, + settings: { providers: [], recentlyUsedModels }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( @@ -115,13 +117,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels }, + settings: { providers: [], recentlyUsedModels }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( @@ -163,13 +166,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels }, + settings: { providers: [], recentlyUsedModels }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( @@ -205,13 +209,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels: [] }, // No recently used models + settings: { providers: [], recentlyUsedModels: [] }, // No recently used models addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 420be9d9..590bca08 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -17,6 +17,8 @@ interface ModelSelectorProps { className?: string; disabled?: boolean; placeholder?: string; + open?: boolean; + onOpenChange?: (open: boolean) => void; } export function ModelSelector({ @@ -25,9 +27,16 @@ export function ModelSelector({ className, disabled = false, placeholder, + open: controlledOpen, + onOpenChange: setControlledOpen, }: ModelSelectorProps) { const { t } = useTranslation(); - const [open, setOpen] = useState(false); + const [uncontrolledOpen, setUncontrolledOpen] = useState(false); + + // Use controlled state if provided, otherwise use local state + const open = controlledOpen !== undefined ? controlledOpen : uncontrolledOpen; + const setOpen = setControlledOpen || setUncontrolledOpen; + const [isCustomInput, setIsCustomInput] = useState(false); const [customValue, setCustomValue] = useState(''); const { settings, addRecentlyUsedModel, isConfigured } = useAISettings(); @@ -140,23 +149,23 @@ export function ModelSelector({ return ( - - - + + + {isConfigured && } diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 6d745971..7b89ae81 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useRef } from 'react'; -import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify'; +import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify'; import { NostrContext } from '@nostrify/react'; import { useQueryClient } from '@tanstack/react-query'; import { useAppContext } from '@/hooks/useAppContext'; @@ -8,6 +8,19 @@ interface NostrProviderProps { children: React.ReactNode; } +const GIT_KINDS = [ + 30617, // NIP-34 Repository Announcement + 30618, // NIP-34 Commit Announcement + 1617, // NIP-34 Patch + 1621, // NIP-34 Issue +]; + +const GIT_RELAYS = [ + 'wss://git.shakespeare.diy/', + 'wss://relay.ngit.dev/', + 'wss://gitnostr.com/', +]; + const NostrProvider: React.FC = (props) => { const { children } = props; const { config, presetRelays } = useAppContext(); @@ -33,12 +46,28 @@ const NostrProvider: React.FC = (props) => { return new NRelay1(url); }, reqRouter(filters) { - return new Map([[relayUrl.current, filters]]); + const routes = new Map(); + routes.set(relayUrl.current, filters); + + if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) { + // If all filters are git-related, route to all git relays + for (const url of GIT_RELAYS) { + routes.set(url, filters); + } + } + return routes; }, - eventRouter(_event: NostrEvent) { + eventRouter(event: NostrEvent) { // Publish to the selected relay const allRelays = new Set([relayUrl.current]); + // If it's a git-related event, also publish to the git relays + if (GIT_KINDS.includes(event.kind)) { + for (const url of GIT_RELAYS) { + allRelays.add(url); + } + } + // Also publish to the preset relays, capped to 5 for (const { url } of (presetRelays ?? [])) { allRelays.add(url); diff --git a/src/components/OnboardingDialog.test.tsx b/src/components/OnboardingDialog.test.tsx index a668b254..cbf028e4 100644 --- a/src/components/OnboardingDialog.test.tsx +++ b/src/components/OnboardingDialog.test.tsx @@ -6,9 +6,14 @@ import { TestApp } from '@/test/TestApp'; // Mock the hooks vi.mock('@/hooks/useAISettings', () => ({ useAISettings: () => ({ - settings: { providers: {}, recentlyUsedModels: [] }, - addProvider: vi.fn(), + settings: { providers: [], recentlyUsedModels: [] }, + setProvider: vi.fn(), + removeProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), + updateSettings: vi.fn(), + isConfigured: false, }), })); diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 05225f69..4fa385a1 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -14,8 +14,6 @@ import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; -import type { AIConnection } from '@/contexts/AISettingsContext'; - interface OnboardingDialogProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -23,7 +21,8 @@ interface OnboardingDialogProps { type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion'; -const SHAKESPEARE_PROVIDER: AIConnection = { +const SHAKESPEARE_PROVIDER = { + id: "shakespeare", baseURL: "https://ai.shakespeare.diy/v1", nostr: true, }; @@ -34,7 +33,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const [isSettingUp, setIsSettingUp] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false); - const { addProvider, addRecentlyUsedModel } = useAISettings(); + const { setProvider, addRecentlyUsedModel } = useAISettings(); const { user } = useCurrentUser(); const login = useLoginActions(); const { models, isLoading: isLoadingModels } = useProviderModels(); @@ -54,7 +53,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) } // Add Shakespeare provider to their config - addProvider('shakespeare', SHAKESPEARE_PROVIDER); + setProvider(SHAKESPEARE_PROVIDER); // Move to model selection setStep('model-selection'); @@ -244,9 +243,16 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) >
- - {model.name ?? model.id} - +
+ + {model.description || model.name || model.id} + + {model.description && ( +

+ {model.name || model.id} +

+ )} +
{isFree && ( @@ -262,11 +268,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
- {model.description && ( -

- {model.description} -

- )}
{model.pricing && ( <> @@ -333,8 +334,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) handleCreditsDialogClose(); } }} - providerId="shakespeare" - connection={SHAKESPEARE_PROVIDER} + provider={SHAKESPEARE_PROVIDER} /> )} diff --git a/src/components/ProjectDetailsDialog.tsx b/src/components/ProjectDetailsDialog.tsx new file mode 100644 index 00000000..0ace47dc --- /dev/null +++ b/src/components/ProjectDetailsDialog.tsx @@ -0,0 +1,320 @@ +import { useState, useEffect } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { type Project } from '@/lib/ProjectsManager'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, +} from '@/components/ui/dialog'; +import { + AlertDialog, + AlertDialogAction, + AlertDialogCancel, + AlertDialogContent, + AlertDialogDescription, + AlertDialogFooter, + AlertDialogHeader, + AlertDialogTitle, + AlertDialogTrigger, +} from '@/components/ui/alert-dialog'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { useToast } from '@/hooks/useToast'; +import { useFS } from '@/hooks/useFS'; +import { useProjectsManager } from '@/hooks/useProjectsManager'; +import { useNavigate } from 'react-router-dom'; +import { + Calendar, + Folder, + Download, + Loader2, + Trash2, + Save, +} from 'lucide-react'; +import JSZip from 'jszip'; +import { Separator } from './ui/separator'; + +interface ProjectDetailsDialogProps { + project: Project; + open: boolean; + onOpenChange: (open: boolean) => void; + onProjectDeleted?: () => void; +} + +export function ProjectDetailsDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectDetailsDialogProps) { + const [isExporting, setIsExporting] = useState(false); + const [isDeleting, setIsDeleting] = useState(false); + const [isRenaming, setIsRenaming] = useState(false); + const [newProjectName, setNewProjectName] = useState(project.id); + const { toast } = useToast(); + const { fs } = useFS(); + const projectsManager = useProjectsManager(); + const navigate = useNavigate(); + const queryClient = useQueryClient(); + + // Reset state when project changes + useEffect(() => { + setNewProjectName(project.id); + setIsRenaming(false); + }, [project.id]); + + const formatDistanceToNow = (date: Date) => { + const now = new Date(); + const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000); + + if (diffInSeconds < 60) return 'just now'; + if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`; + if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`; + if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`; + if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} months ago`; + return `${Math.floor(diffInSeconds / 31536000)} years ago`; + }; + + const handleSaveProject = async () => { + if (!newProjectName.trim() || newProjectName === project.id) { + setNewProjectName(project.id); + return; + } + + setIsRenaming(true); + try { + await projectsManager.renameProject(project.id, newProjectName); + + // Invalidate the projects query to update the sidebar + await queryClient.invalidateQueries({ queryKey: ['projects'] }); + + toast({ + title: "Project renamed", + description: `Project renamed from "${project.id}" to "${newProjectName}".`, + }); + + // Close the dialog first + onOpenChange(false); + + // Navigate to the new URL + navigate(`/project/${newProjectName}`); + } catch (error) { + toast({ + title: "Failed to rename project", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + setNewProjectName(project.id); // Reset to original name + } finally { + setIsRenaming(false); + } + }; + + const handleDeleteProject = async () => { + setIsDeleting(true); + try { + await projectsManager.deleteProject(project.id); + + // Invalidate the projects query to update the sidebar + await queryClient.invalidateQueries({ queryKey: ['projects'] }); + + toast({ + title: "Project deleted", + description: `"${project.name}" has been permanently deleted.`, + }); + + // Close the dialog first + onOpenChange(false); + + // Navigate back to home and notify parent + navigate('/'); + if (onProjectDeleted) { + onProjectDeleted(); + } + } catch (error) { + toast({ + title: "Failed to delete project", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + } finally { + setIsDeleting(false); + } + }; + + const handleExportProject = async () => { + setIsExporting(true); + try { + const zip = new JSZip(); + const projectPath = `/projects/${project.id}`; + + // Recursive function to add files and directories to zip from a specific project + const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => { + try { + const entries = await fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = `${dirPath}/${entry.name}`; + + if (entry.isDirectory()) { + // Create folder in zip and recursively add its contents + const folder = zipFolder.folder(entry.name); + if (folder) { + await addFolderToZip(fullPath, folder); + } + } else if (entry.isFile()) { + // Add file to zip + try { + const fileContent = await fs.readFile(fullPath); + zipFolder.file(entry.name, fileContent); + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + }; + + // Start from the project directory + await addFolderToZip(projectPath, zip); + + // Generate zip file + const content = await zip.generateAsync({ type: 'blob' }); + + // Create download link + const url = URL.createObjectURL(content); + const link = document.createElement('a'); + link.href = url; + link.download = `${project.id}.zip`; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + + toast({ + title: "Project exported successfully", + description: `"${project.name}" has been downloaded as a zip file.`, + }); + } catch (error) { + console.error('Failed to export project:', error); + toast({ + title: "Failed to export project", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + } finally { + setIsExporting(false); + } + }; + + return ( + + + + + + {project.name} + + + +
+ {/* Last Modified */} +
+ + Last Modified: + {formatDistanceToNow(project.lastModified)} +
+ + {/* Project Name */} +
+ +
+ setNewProjectName(e.target.value)} + disabled={isRenaming} + onKeyDown={(e) => { + if (e.key === 'Enter') { + handleSaveProject(); + } else if (e.key === 'Escape') { + setNewProjectName(project.id); + } + }} + className="flex-1" + placeholder="Enter project name" + /> + +
+
+ + + + {/* Export Project Button */} + + + {/* Delete Project Button */} + + + + + + + Delete Project + + Are you sure you want to delete "{project.name}"? This action cannot be undone and will permanently delete all project data including files. + + + + Cancel + + {isDeleting ? ( + <> + + Deleting... + + ) : ( + 'Delete Project' + )} + + + + +
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/ProjectInfoDialog.tsx b/src/components/ProjectInfoDialog.tsx deleted file mode 100644 index 33fdf923..00000000 --- a/src/components/ProjectInfoDialog.tsx +++ /dev/null @@ -1,359 +0,0 @@ -import { useState, useEffect } from 'react'; -import { type Project } from '@/lib/ProjectsManager'; -import { useProjectsManager } from '@/hooks/useProjectsManager'; -import { useGitStatus } from '@/hooks/useGitStatus'; -import { - Dialog, - DialogContent, - DialogDescription, - DialogHeader, - DialogTitle, -} from '@/components/ui/dialog'; -import { Badge } from '@/components/ui/badge'; -import { Separator } from '@/components/ui/separator'; -import { Skeleton } from '@/components/ui/skeleton'; -import { - Calendar, - Folder, - GitBranch, - Package, - FileText, - GitCommit, - GitMerge, - Globe, - Clock, - User, - Hash, - AlertCircle, - CheckCircle, - Plus, - Minus, - Edit, - Eye -} from 'lucide-react'; - -interface ProjectInfoDialogProps { - project: Project; - open: boolean; - onOpenChange: (open: boolean) => void; -} - -interface ProjectMetadata { - description?: string; - version?: string; - nostrRepoAddress?: string; - fileCount?: number; -} - -export function ProjectInfoDialog({ project, open, onOpenChange }: ProjectInfoDialogProps) { - const [metadata, setMetadata] = useState({}); - const [isLoading, setIsLoading] = useState(false); - const projectsManager = useProjectsManager(); - const gitStatus = useGitStatus(project.id); - - useEffect(() => { - if (!open) return; - - const loadProjectMetadata = async () => { - setIsLoading(true); - try { - const meta: ProjectMetadata = {}; - - // Try to read package.json - try { - const packageJsonContent = await projectsManager.readFile(project.id, 'package.json'); - const packageJson = JSON.parse(packageJsonContent); - meta.description = packageJson.description; - meta.version = packageJson.version; - } catch { - // package.json doesn't exist or is invalid - } - - // Get Nostr repo address - try { - const repoAddress = await projectsManager.getNostrRepoAddress(project.id); - if (repoAddress) { - meta.nostrRepoAddress = repoAddress; - } - } catch { - // No Nostr repo configured - } - - // Calculate file count and size (simplified) - try { - const files = await projectsManager.listFiles(project.id); - meta.fileCount = files.length; - } catch { - // Can't read directory - } - - setMetadata(meta); - } catch (error) { - console.error('Failed to load project metadata:', error); - } finally { - setIsLoading(false); - } - }; - - loadProjectMetadata(); - }, [open, project.id, projectsManager]); - - const formatDate = (date: Date) => { - return new Intl.DateTimeFormat('en-US', { - year: 'numeric', - month: 'long', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', - }).format(date); - }; - - const formatDistanceToNow = (date: Date) => { - const now = new Date(); - const diffInSeconds = Math.floor((now.getTime() - date.getTime()) / 1000); - - if (diffInSeconds < 60) return 'just now'; - if (diffInSeconds < 3600) return `${Math.floor(diffInSeconds / 60)} minutes ago`; - if (diffInSeconds < 86400) return `${Math.floor(diffInSeconds / 3600)} hours ago`; - if (diffInSeconds < 2592000) return `${Math.floor(diffInSeconds / 86400)} days ago`; - if (diffInSeconds < 31536000) return `${Math.floor(diffInSeconds / 2592000)} months ago`; - return `${Math.floor(diffInSeconds / 31536000)} years ago`; - }; - - return ( - - - - - - {project.name} - - - Project information and metadata - - - - {isLoading ? ( -
-
-
-
-
-
- ) : ( -
- {/* Basic Information */} -
-

- Basic Information -

-
-
- - Project ID: - {project.id} -
-
- - Last Modified: - {formatDistanceToNow(project.lastModified)} -
- {metadata.version && ( -
- - Version: - {metadata.version} -
- )} - {metadata.fileCount !== undefined && ( -
- - Files: - {metadata.fileCount} -
- )} -
-
- Created: - {formatDate(project.lastModified)} -
- {metadata.description && ( -
- Description: -

{metadata.description}

-
- )} -
- - {/* Nostr Information */} - {metadata.nostrRepoAddress && ( - <> - -
-

- - Nostr Repository -

-
- Repository Address: - - {metadata.nostrRepoAddress} - -
-
- - )} - - {/* Git Status Information */} - -
-

- - Git Repository -

- - {gitStatus.isLoading ? ( -
- - - -
- ) : !gitStatus.data?.isGitRepo ? ( -
- - This project is not a Git repository -
- ) : ( -
- {/* Repository Status */} -
- {/* Current Branch */} -
- - Branch: - - {gitStatus.data?.currentBranch || 'unknown'} - -
- - {/* Uncommitted Changes */} -
- {gitStatus.data?.hasUncommittedChanges ? ( - <> - - Status: - - {gitStatus.data.changedFiles.length} uncommitted changes - - - ) : ( - <> - - Status: - - Clean working tree - - - )} -
- - {/* Total Commits */} -
- - Commits: - {gitStatus.data?.totalCommits || 0} -
- - {/* All Branches */} -
- - Branches: - {gitStatus.data?.branches.length || 0} -
-
- - {/* Latest Commit */} - {gitStatus.data?.latestCommit && ( -
-

- Latest Commit -

-
-
- -
-
- {gitStatus.data.latestCommit.message.split('\n')[0]} -
-
- {gitStatus.data.latestCommit.oid.substring(0, 7)} -
-
-
-
-
- - {gitStatus.data.latestCommit.author.name} -
-
- - {new Date(gitStatus.data.latestCommit.author.timestamp * 1000).toLocaleDateString()} -
-
-
-
- )} - - {/* Changed Files */} - {gitStatus.data?.hasUncommittedChanges && gitStatus.data.changedFiles.length > 0 && ( -
-

- Uncommitted Changes -

-
- {gitStatus.data.changedFiles.map((file, index) => ( -
- {file.status === 'added' && } - {file.status === 'modified' && } - {file.status === 'deleted' && } - {file.status === 'untracked' && } - {file.status === 'staged' && } - {file.status}: - - {file.filepath} - -
- ))} -
-
- )} - - {/* Remotes */} - {gitStatus.data?.remotes && gitStatus.data.remotes.length > 0 && ( -
-

- Remote Repositories -

-
- {gitStatus.data.remotes.map((remote, index) => ( -
- - {remote.name}: - - {remote.url} - -
- ))} -
-
- )} -
- )} -
- -
- )} -
-
- ); -} \ No newline at end of file diff --git a/src/components/SessionManagerProvider.tsx b/src/components/SessionManagerProvider.tsx index 173c250a..5030e015 100644 --- a/src/components/SessionManagerProvider.tsx +++ b/src/components/SessionManagerProvider.tsx @@ -17,13 +17,13 @@ export function SessionManagerProvider({ children }: SessionManagerProviderProps const { fs } = useFS(); const { settings } = useAISettings(); const { models } = useProviderModels(); - const { user } = useCurrentUser(); + const { user, metadata } = useCurrentUser(); const sessionManager = useMemo(() => { const getProviderModels = () => models; - const getCurrentUser = () => user; + const getCurrentUser = () => ({ user, metadata }); return new SessionManager(fs, settings, getProviderModels, getCurrentUser); - }, [fs, settings, models, user]); + }, [fs, settings, models, user, metadata]); // Cleanup on unmount useEffect(() => { diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 6cf9ea0c..200fff49 100644 --- a/src/components/SettingsLayout.tsx +++ b/src/components/SettingsLayout.tsx @@ -3,7 +3,7 @@ import { useNavigate, useLocation, Outlet } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; import { Button } from '@/components/ui/button'; import { ScrollArea } from '@/components/ui/scroll-area'; -import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; +import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -56,6 +56,13 @@ const getSettingsItems = (t: (key: string) => string): SettingsItem[] => [ icon: Database, href: '/settings/data', }, + { + id: 'email', + title: t('emailUpdates'), + description: t('emailUpdatesDescription'), + icon: Mail, + href: '/settings/email', + }, { id: 'about', title: t('aboutShakespeare'), diff --git a/src/components/Shakespeare/ChatPane.test.tsx b/src/components/Shakespeare/ChatPane.test.tsx index 259d0830..2345596b 100644 --- a/src/components/Shakespeare/ChatPane.test.tsx +++ b/src/components/Shakespeare/ChatPane.test.tsx @@ -8,10 +8,15 @@ vi.mock('@/hooks/useAISettings', () => ({ useAISettings: () => ({ isConfigured: true, settings: { - providers: {}, + providers: [], recentlyUsedModels: ['gpt-4'], }, + setProvider: vi.fn(), + removeProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), + updateSettings: vi.fn(), }), })); diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 86874a48..f9c987af 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -7,7 +7,8 @@ import { Skeleton } from '@/components/ui/skeleton'; import { CircularProgress } from '@/components/ui/circular-progress'; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger } from '@/components/ui/tooltip'; import { FileAttachment } from '@/components/ui/file-attachment'; -import { Square, Loader2, ChevronDown, ArrowUp } from 'lucide-react'; +import { OnboardingDialog } from '@/components/OnboardingDialog'; +import { Square, Loader2, ChevronDown, ArrowUp, X } from 'lucide-react'; import { useAISettings } from '@/hooks/useAISettings'; import { useFS } from '@/hooks/useFS'; import { useCurrentUser } from '@/hooks/useCurrentUser'; @@ -33,24 +34,67 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; -import { Git } from '@/lib/git'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; -import { makeSystemPrompt } from '@/lib/system'; -import { assistantContentEmpty } from '@/lib/ai-messages'; import { saveFileToTmp } from '@/lib/fileUtils'; +import { useGit } from '@/hooks/useGit'; +import { useConsoleErrorAlert, useAIModelErrorAlert } from '@/hooks/useErrorDetection'; +import { QuillySVG } from '@/components/ui/QuillySVG'; + + +function ChatIntervention({ + message, + onDismiss, + action, +}: { + message: string; + onDismiss: () => void; + action?: { label: string; onClick: () => void }; +}) { + return ( +
+
+ +
+
+

+ Pardon the interruption +

+

+ {message} + {' '} + {action && ( + + )} +

+
+
+ +
+
+ ); +} + +// Clean interfaces now handled by proper hooks interface ChatPaneProps { projectId: string; onNewChat?: () => void; onBuild?: () => void; - onDeploy?: () => void; onFirstInteraction?: () => void; onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; isBuildLoading?: boolean; - isDeployLoading?: boolean; } export interface ChatPaneRef { @@ -61,30 +105,31 @@ export const ChatPane = forwardRef(({ projectId, onNewChat: _onNewChat, onBuild: _onBuild, - onDeploy: _onDeploy, onFirstInteraction, onLoadingChange, isLoading: externalIsLoading, isBuildLoading: externalIsBuildLoading, - isDeployLoading: externalIsDeployLoading }, ref) => { const { t } = useTranslation(); const [input, setInput] = useState(''); - const [systemPrompt, setSystemPrompt] = useState(''); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [attachedFiles, setAttachedFiles] = useState([]); const [isDragOver, setIsDragOver] = useState(false); const [scrolledProjects] = useState(() => new Set()); + const [showOnboarding, setShowOnboarding] = useState(false); + const [isStuck, setIsStuck] = useState(false); // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; - const isDeployLoading = externalIsDeployLoading || false; const scrollAreaRef = useRef(null); const { isConfigured, settings, addRecentlyUsedModel } = useAISettings(); const [providerModel, setProviderModel] = useState(() => { // Initialize with first recently used model if available, otherwise empty return settings.recentlyUsedModels?.[0] || ''; }); + // State to control model selector dropdown + const [isModelSelectorOpen, setIsModelSelectorOpen] = useState(false); + const autostartedRef = useRef(false); useEffect(() => { if (!providerModel && settings.recentlyUsedModels?.length) { @@ -94,13 +139,13 @@ export const ChatPane = forwardRef(({ const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); - const { user, metadata } = useCurrentUser(); + const { git } = useGit(); + const { user } = useCurrentUser(); const { models } = useProviderModels(); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; const customTools = useMemo(() => { - const git = new Git(fs); const baseTools = { git_commit: new GitCommitTool(fs, cwd, git), text_editor_view: new TextEditorViewTool(fs, cwd), @@ -129,7 +174,7 @@ export const ChatPane = forwardRef(({ } return baseTools; - }, [fs, cwd, user, projectId]); + }, [fs, git, cwd, user, projectId]); // Convert tools to OpenAI format const tools = useMemo(() => { @@ -142,7 +187,7 @@ export const ChatPane = forwardRef(({ // Keep-alive functionality to prevent tab throttling during AI processing const { updateMetadata } = useKeepAlive({ - enabled: externalIsLoading || isBuildLoading || isDeployLoading, + enabled: externalIsLoading || isBuildLoading, title: 'Shakespeare', artist: `Working on ${projectId}...`, artwork: [ @@ -159,19 +204,6 @@ export const ChatPane = forwardRef(({ updateMetadata(title, description); }, [updateMetadata]); - useEffect(() => { - makeSystemPrompt({ - cwd, - fs, - mode: "agent", - name: "Shakespeare", - profession: "software extraordinaire", - tools: Object.values(tools), - user, - metadata, - }).then(setSystemPrompt) - }, [fs, cwd, tools, user, metadata]); - const { messages, streamingMessage, @@ -186,7 +218,6 @@ export const ChatPane = forwardRef(({ projectId, tools, customTools, - systemPrompt, onUpdateMetadata, }); @@ -211,8 +242,49 @@ export const ChatPane = forwardRef(({ } }, [internalIsLoading, onLoadingChange]); + // Timer to detect when AI appears stuck during tool generation + useEffect(() => { + // Start a 2-second timer + const timer = streamingMessage + ? setTimeout(() => setIsStuck(true), 2000) + : undefined; + + return () => { + setIsStuck(false); + clearTimeout(timer); + }; + }, [streamingMessage]); + + // Function to scroll to bottom + const scrollToBottom = useCallback(() => { + if (scrollAreaRef.current) { + scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; + } + }, []); + + // Function to open model selector dropdown + const openModelSelector = useCallback(() => { + setIsModelSelectorOpen(true); + }, []); + + // Function to suggest error fix + // Clean alert hooks with proper interfaces + const aiModelAlert = useAIModelErrorAlert(messages, _onNewChat, openModelSelector); + const consoleAlert = useConsoleErrorAlert(messages, isBuildLoading, internalIsLoading); + + // Scroll to bottom when alerts appear + useEffect(() => { + if (aiModelAlert.hasError || consoleAlert.hasError) { + setTimeout(() => { + scrollToBottom(); + }, 50); + } + }, [aiModelAlert.hasError, consoleAlert.hasError, scrollToBottom]); + // Check for autostart parameter and trigger AI generation useEffect(() => { + if (autostartedRef.current) return; + const autostart = searchParams.get('autostart'); const urlModel = searchParams.get('model'); @@ -235,18 +307,11 @@ export const ChatPane = forwardRef(({ // Start AI generation addRecentlyUsedModel(modelToUse); startGeneration(modelToUse); + autostartedRef.current = true; } } }, [addRecentlyUsedModel, isConfigured, providerModel, searchParams, setSearchParams, startGeneration]); - - // Function to scroll to bottom - const scrollToBottom = () => { - if (scrollAreaRef.current) { - scrollAreaRef.current.scrollTop = scrollAreaRef.current.scrollHeight; - } - }; - // Simple scroll event listener useEffect(() => { const container = scrollAreaRef.current; @@ -281,7 +346,6 @@ export const ChatPane = forwardRef(({ if (isNearBottom) { container.scrollTop = container.scrollHeight; } - } }, [messages, streamingMessage, isLoading]); @@ -296,7 +360,7 @@ export const ChatPane = forwardRef(({ return () => clearTimeout(timer); } - }, [projectId, scrolledProjects]); + }, [projectId, scrolledProjects, scrollToBottom]); const handleFileSelect = (file: File) => { setAttachedFiles(prev => [...prev, file]); @@ -349,8 +413,17 @@ export const ChatPane = forwardRef(({ setAttachedFiles(prev => [...prev, ...files]); }; - const handleSend = async () => { - if ((!input.trim() && attachedFiles.length === 0) || isLoading || !providerModel.trim()) return; + const send = useCallback(async (input: string, attachedFiles: File[]) => { + if ((!input.trim() && attachedFiles.length === 0) || isLoading) return; + + // If AI is not configured, show onboarding dialog + if (!isConfigured) { + setShowOnboarding(true); + return; + } + + // If configured but no model selected, don't proceed + if (!providerModel.trim()) return; const modelToUse = providerModel.trim(); @@ -400,9 +473,13 @@ export const ChatPane = forwardRef(({ await sendMessage(messageContent, modelToUse); } catch (error) { console.error('AI chat error:', error); - // Error handling is done in the useAIChat hook + // Error handling is done in the useAIChat hook and SessionManager } - }; + }, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage]); + + const handleSend = useCallback(async () => { + await send(input, attachedFiles); + }, [input, attachedFiles, send]); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !e.shiftKey) { @@ -440,6 +517,16 @@ export const ChatPane = forwardRef(({ } }; + // Handle textarea focus - show onboarding if not configured + const handleTextareaFocus = () => { + if (!isConfigured) { + setShowOnboarding(true); + } + if (onFirstInteraction) { + onFirstInteraction(); + } + }; + // Handle first user interaction to enable audio context const handleFirstInteraction = () => { // This will be handled automatically by the useKeepAlive hook @@ -456,28 +543,9 @@ export const ChatPane = forwardRef(({ } }), [internalStartNewSession]); - if (!isConfigured) { - return ( -
-
-
-
🤖
-
-

{t('aiNotConfigured')}

-

- {t('configureAI')} -

-

- {t('useMenuForAI')} -

-
-
-
-
- ); - } - - + const suggestErrorFix = useCallback(async (errorMessage: string) => { + await send(errorMessage, attachedFiles); + }, [send, attachedFiles]); return (
@@ -508,11 +576,6 @@ export const ChatPane = forwardRef(({ )} {messages.map((message, index) => { - // Skip assistant messages with no content - if (message.role === 'assistant' && assistantContentEmpty(message.content)) { - return null; - } - // Find the corresponding tool call for tool messages let toolCall: OpenAI.Chat.Completions.ChatCompletionMessageToolCall | undefined = undefined; if (message.role === 'tool') { @@ -536,12 +599,23 @@ export const ChatPane = forwardRef(({ })} {streamingMessage && ( streamingMessage.content || streamingMessage.reasoning_content ? ( - + <> + + {/* Show loading skeleton if AI appears stuck generating tools */} + {isStuck && ( +
+
+
+ +
+
+
+ )} + ) : ( !(streamingMessage?.tool_calls?.[0]?.type === 'function') && (
@@ -564,6 +638,28 @@ export const ChatPane = forwardRef(({
)} + + {/* AI Model Alert */} + {aiModelAlert.hasError && ( + + )} + + {/* Console Error Alert */} + {consoleAlert.hasError && ( + suggestErrorFix(consoleAlert.errorSummary || '') + }} + /> + )} +
@@ -584,9 +680,8 @@ export const ChatPane = forwardRef(({
{/* Chat Input Container */}
(({ onChange={(e) => setInput(e.target.value)} onKeyDown={handleKeyDown} onPaste={handlePaste} - onFocus={handleFirstInteraction} - placeholder={providerModel.trim() ? t('askToAddFeatures') : t('selectModelFirst')} + onFocus={handleTextareaFocus} + placeholder={ + !isConfigured + ? t('askToAddFeatures') + : providerModel.trim() + ? t('askToAddFeatures') + : t('selectModelFirst') + } className="flex-1 resize-none border-0 bg-transparent px-4 py-3 text-sm focus-visible:ring-0 focus-visible:ring-offset-0 placeholder:text-muted-foreground" - disabled={isLoading || !providerModel.trim()} + disabled={isLoading || (isConfigured && !providerModel.trim())} rows={1} aria-label="Chat message input" style={{ @@ -673,6 +774,8 @@ export const ChatPane = forwardRef(({ className="w-full" disabled={isLoading} placeholder={t('chooseModel')} + open={isModelSelectorOpen} + onOpenChange={setIsModelSelectorOpen} />
@@ -691,7 +794,7 @@ export const ChatPane = forwardRef(({
+ + {/* Onboarding Dialog */} +
); }); diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index dc3f3f3c..5fe9c644 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,21 +3,26 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; +import { useConsoleMessages, addConsoleMessage, clearConsoleMessages, type ConsoleMessage } from '@/hooks/useConsoleMessages'; +import { useBuildProject } from '@/hooks/useBuildProject'; import { Tabs, TabsContent } from '@/components/ui/tabs'; import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { Button } from '@/components/ui/button'; -import { FolderOpen, ArrowLeft, X, Bug, Copy, Check } from 'lucide-react'; +import { FolderOpen, ArrowLeft, X, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { BrowserAddressBar } from '@/components/ui/browser-address-bar'; import { DropdownMenu, DropdownMenuContent, + DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; import { FileTree } from './FileTree'; import { FileEditor } from './FileEditor'; +import { DeployDialog } from '@/components/DeployDialog'; +import { useSearchParams } from 'react-router-dom'; // Get iframe domain from environment variable const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.dev'; @@ -25,6 +30,10 @@ const IFRAME_DOMAIN = import.meta.env.VITE_IFRAME_DOMAIN || 'local-shakespeare.d interface PreviewPaneProps { projectId: string; activeTab: 'preview' | 'code'; + onToggleView?: () => void; + projectName?: string; + onFirstInteraction?: () => void; + isPreviewable?: boolean; } interface JSONRPCRequest { @@ -57,13 +66,8 @@ interface JSONRPCResponse { id: number; } -interface ConsoleMessage { - id: number; - level: 'log' | 'warn' | 'error' | 'info' | 'debug'; - message: string; -} -export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { +export function PreviewPane({ projectId, activeTab, onToggleView, projectName, onFirstInteraction, isPreviewable = true }: PreviewPaneProps) { const { t } = useTranslation(); const [selectedFile, setSelectedFile] = useState(null); const [fileContent, setFileContent] = useState(''); @@ -74,11 +78,44 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); - const [consoleMessages, setConsoleMessages] = useState([]); const [copiedMessageId, setCopiedMessageId] = useState(null); + const [deployDialogOpen, setDeployDialogOpen] = useState(false); const iframeRef = useRef(null); const { fs } = useFS(); const projectsManager = useProjectsManager(); + const { messages: consoleMessages } = useConsoleMessages(); + const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId); + + const [searchParams, setSearchParams] = useSearchParams(); + const [shouldBuild, setShouldBuild] = useState(false); + + const handleBuildProject = useCallback(() => { + buildProject(undefined, { + onError: (error) => { + console.error('Build failed:', error); + } + }); + }, [buildProject]); + + // Handle "build" URL parameter on initial load + useEffect(() => { + if (searchParams.has('build')) { + setShouldBuild(true); + + // Remove the build parameter from URL + const newSearchParams = new URLSearchParams(searchParams); + newSearchParams.delete('build'); + setSearchParams(newSearchParams, { replace: true }); + } + }, [searchParams, setSearchParams]); + + // Build automatically if "build" parameter was present + useEffect(() => { + if (shouldBuild && isPreviewable && !isBuildLoading) { + setShouldBuild(false); + handleBuildProject(); + } + }, [isBuildLoading, isPreviewable, handleBuildProject, shouldBuild]); const loadFileContent = useCallback(async (filePath: string) => { setIsLoading(true); @@ -133,16 +170,15 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const refreshIframeLegacy = useCallback(() => { if (iframeRef.current) { // Force reload the iframe by updating its src - const currentSrc = iframeRef.current.src; - iframeRef.current.src = ''; + iframeRef.current.src = '/'; // Use a small timeout to ensure the src is cleared before setting it back setTimeout(() => { if (iframeRef.current) { - iframeRef.current.src = currentSrc; + iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}${currentPath}`; } }, 10); } - }, []); + }, [currentPath, projectId]); const sendResponse = useCallback((message: JSONRPCResponse) => { if (iframeRef.current?.contentWindow) { @@ -175,13 +211,8 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { normalizedLevel = params.level as ConsoleMessage['level']; } - const newConsoleMessage: ConsoleMessage = { - id: Date.now(), - level: normalizedLevel, - message: params.message, - }; - - setConsoleMessages(prev => [...prev, newConsoleMessage]); + // Add to global console messages + addConsoleMessage(normalizedLevel, params.message); // Log to parent console for debugging with appropriate level console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); @@ -422,6 +453,13 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { } }, [selectedFile, loadFileContent]); + // Reset selected file when projectId changes + useEffect(() => { + setSelectedFile(null); + setFileContent(''); + setMobileCodeView('explorer'); + }, [projectId]); + useEffect(() => { checkForBuiltProject(); }, [checkForBuiltProject]); @@ -460,161 +498,244 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { }; const ConsoleDropdown = () => { - const getLevelColor = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return 'text-red-500'; - case 'warn': return 'text-yellow-500'; - case 'info': return 'text-blue-500'; - case 'debug': return 'text-gray-500'; - default: return 'text-gray-400'; - } - }; + const getLevelColor = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return 'text-red-500'; + case 'warn': return 'text-yellow-500'; + case 'info': return 'text-blue-500'; + case 'debug': return 'text-gray-500'; + default: return 'text-gray-400'; + } + }; - const getLevelIcon = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return '!'; - case 'warn': return '⚠'; - case 'info': return 'ℹ'; - case 'debug': return '🔍'; - default: return '•'; - } - }; + const getLevelIcon = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return '!'; + case 'warn': return '⚠'; + case 'info': return 'ℹ'; + case 'debug': return '🔍'; + default: return '•'; + } + }; - const clearConsole = () => { - setConsoleMessages([]); - }; + const clearConsole = () => { + clearConsoleMessages(); + }; - const copyMessageToClipboard = async (msg: ConsoleMessage) => { - try { - // Create a formatted string with all message details - const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`; + const copyMessageToClipboard = async (msg: ConsoleMessage) => { + try { + // Create a formatted string with all message details + const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`; - await navigator.clipboard.writeText(formattedMessage); - setCopiedMessageId(msg.id); + await navigator.clipboard.writeText(formattedMessage); + setCopiedMessageId(msg.id); - // Reset the copied state after 2 seconds - setTimeout(() => { - setCopiedMessageId(null); - }, 2000); - } catch (error) { - console.error('Failed to copy message to clipboard:', error); - } - }; + // Reset the copied state after 2 seconds + setTimeout(() => { + setCopiedMessageId(null); + }, 2000); + } catch (error) { + console.error('Failed to copy message to clipboard:', error); + } + }; - return ( - - - - - -
- Console Output ({consoleMessages.length}) - -
- -
- {consoleMessages.length === 0 ? ( -
- No console messages -
- ) : ( - consoleMessages.map((msg) => ( -
-
-
{getLevelIcon(msg.level)} {msg.message}
- -
-
- )) + return ( + + + + + +
+ Console Output ({consoleMessages.length}) +
- -
-
- ); -}; + +
+ {consoleMessages.length === 0 ? ( +
+ No console messages +
+ ) : ( + consoleMessages.map((msg) => ( +
+
+
{getLevelIcon(msg.level)} {msg.message}
+ +
+
+ )) + )} +
+
+ + + ); + }; + + const Menu = () => { + const isAnyLoading = isBuildLoading; + + return ( + + + + + + + {isBuildLoading ? ( + + ) : ( + + )} + {isBuildLoading ? 'Building...' : 'Build'} + + setDeployDialogOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + Deploy + + + + ); + }; return (
- - {hasBuiltProject ? ( -
-
- 0} - canGoForward={historyIndex < navigationHistory.length - 1} - extraContent={} - /> -
-