diff --git a/index.html b/index.html index 752478ff..61806719 100644 --- a/index.html +++ b/index.html @@ -9,7 +9,7 @@ - + diff --git a/public/manifest.webmanifest b/public/manifest.webmanifest index f30b2c96..ed0d3952 100644 --- a/public/manifest.webmanifest +++ b/public/manifest.webmanifest @@ -8,12 +8,12 @@ "theme_color": "#000000", "icons": [ { - "src": "/favicon.png", + "src": "/shakespeare.png", "sizes": "192x192", "type": "image/png" }, { - "src": "/favicon.png", + "src": "/shakespeare.png", "sizes": "512x512", "type": "image/png" } diff --git a/public/favicon.png b/public/shakespeare.png similarity index 100% rename from public/favicon.png rename to public/shakespeare.png diff --git a/public/shakespeare.svg b/public/shakespeare.svg new file mode 100644 index 00000000..7eba08b6 --- /dev/null +++ b/public/shakespeare.svg @@ -0,0 +1,63 @@ + + + + + + + + + + + + + + + + + + + + + + diff --git a/src/App.tsx b/src/App.tsx index b3944f7d..45c68be2 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -38,7 +38,7 @@ const queryClient = new QueryClient({ }); const defaultConfig: AppConfig = { - theme: "light", + theme: "system", relayUrl: "wss://relay.primal.net", deployServer: "shakespeare.wtf", }; diff --git a/src/AppRouter.tsx b/src/AppRouter.tsx index c0d70908..5558d2db 100644 --- a/src/AppRouter.tsx +++ b/src/AppRouter.tsx @@ -11,7 +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"; @@ -34,7 +34,6 @@ export function AppRouter() { } /> } /> } /> - } /> } /> } /> diff --git a/src/components/AppLayout.tsx b/src/components/AppLayout.tsx index f58455e0..cc9552ed 100644 --- a/src/components/AppLayout.tsx +++ b/src/components/AppLayout.tsx @@ -18,7 +18,6 @@ interface AppLayoutProps { export function AppLayout({ children, selectedProject = null, - title = "Shakespeare", showSidebar = true, headerContent }: AppLayoutProps) { @@ -85,9 +84,6 @@ export function AppLayout({ )} -

- {title} -

{headerContent} diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 64dd1f30..4b33517c 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -399,7 +399,7 @@ export function CreditsDialog({ open, onOpenChange, provider }: CreditsDialogPro return ( - + e.preventDefault()} className="max-w-lg w-full max-h-[75vh] overflow-hidden flex flex-col sm:max-w-lg sm:max-h-[75vh] max-sm:w-full max-sm:h-full max-sm:max-w-none max-sm:max-h-none max-sm:m-0 max-sm:rounded-none"> {lightningInvoice ? ( diff --git a/src/components/EmailSubscription.tsx b/src/components/EmailSubscription.tsx new file mode 100644 index 00000000..3337864a --- /dev/null +++ b/src/components/EmailSubscription.tsx @@ -0,0 +1,204 @@ +import { useState, useEffect } from 'react'; +import { Mail, CheckCircle } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; +import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useToast } from '@/hooks/useToast'; +import { nip19 } from 'nostr-tools'; + +export function EmailSubscription() { + const { t } = useTranslation(); + const { user } = useCurrentUser(); + const { toast } = useToast(); + + const [email, setEmail] = useState(''); + const [isSubmitting, setIsSubmitting] = useState(false); + const [isSubmitted, setIsSubmitted] = useState(false); + + const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0'); + const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`; + const tag = '8982396'; + + // Check localStorage on component mount + useEffect(() => { + const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed'); + if (hasSubscribed === 'true') { + setIsSubmitted(true); + } + }, []); + + const handleSubmit = async (e: React.FormEvent) => { + e.preventDefault(); + + if (!email.trim()) { + toast({ + title: "Email required", + description: "Please enter your email address", + variant: "destructive", + }); + return; + } + + // Basic email validation + const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; + if (!emailRegex.test(email)) { + toast({ + title: "Invalid email", + description: "Please enter a valid email address", + variant: "destructive", + }); + return; + } + + setIsSubmitting(true); + + try { + // Submit to Mailchimp + const form = document.createElement('form'); + form.method = 'POST'; + form.action = url.href; + form.target = '_blank'; // Open in new tab + form.style.display = 'none'; + + // Add email field + const emailInput = document.createElement('input'); + emailInput.type = 'email'; + emailInput.name = 'EMAIL'; + emailInput.value = email.trim(); + form.appendChild(emailInput); + + // Add tag field with the new Shakespeare tag ID + const tagInput = document.createElement('input'); + tagInput.type = 'hidden'; + tagInput.name = 'tags'; + tagInput.value = tag; + form.appendChild(tagInput); + + // Add npub if available + if (user?.pubkey) { + const npubInput = document.createElement('input'); + npubInput.type = 'text'; + npubInput.name = 'NPUB'; + npubInput.value = nip19.npubEncode(user.pubkey); + npubInput.style.display = 'none'; + form.appendChild(npubInput); + } + + // Add honeypot field + const honeypotInput = document.createElement('input'); + honeypotInput.type = 'text'; + honeypotInput.name = honeypot; + honeypotInput.tabIndex = -1; + honeypotInput.style.position = 'absolute'; + honeypotInput.style.left = '-5000px'; + form.appendChild(honeypotInput); + + // Add form to document and submit + document.body.appendChild(form); + form.submit(); + + // Clean up after a short delay + setTimeout(() => { + document.body.removeChild(form); + }, 1000); + + // Save subscription status to localStorage + localStorage.setItem('shakespeare-email-subscribed', 'true'); + + setIsSubmitted(true); + toast({ + title: "Successfully subscribed!", + description: "You'll receive Shakespeare updates and resources occasionally.", + }); + } catch (error) { + console.error('Email signup error:', error); + toast({ + title: "Subscription failed", + description: "There was an error subscribing you to updates. Please try again.", + variant: "destructive", + }); + } finally { + setIsSubmitting(false); + } + }; + + if (isSubmitted) { + return ( + + +
+ +
+

+ Thanks for subscribing! +

+

+ You can opt out at any time using the unsubscribe link in our emails. +

+
+ +
+
+
+ ); + } + + return ( + + + + + {t('emailUpdates')} + + + {t('emailUpdatesDescription')} + + + +
+
+ + setEmail(e.target.value)} + disabled={isSubmitting} + required + /> +
+ +
+ + +

+ You can opt out at any time using the unsubscribe link in our emails. +

+
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 1aa22072..08f76ce4 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -1,5 +1,5 @@ import { useState, useEffect } from 'react'; -import { useNavigate } from 'react-router-dom'; +import { useNavigate, useSearchParams } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Dialog, @@ -47,7 +47,7 @@ import { cn } from '@/lib/utils'; import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { nip19 } from 'nostr-tools'; -const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"]; +const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev"]; interface GitDialogProps { projectId: string; @@ -62,6 +62,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const [isPushingToNostr, setIsPushingToNostr] = useState(false); const [originUrl, setOriginUrl] = useState(''); const [isSavingOrigin, setIsSavingOrigin] = useState(false); + const [searchParams, setSearchParams] = useSearchParams(); const navigate = useNavigate(); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); @@ -334,6 +335,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Push to Nostr failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPushingToNostr(false); @@ -395,6 +397,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog title: "Push failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPushing(false); @@ -425,6 +428,12 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') + // Get the current HEAD commit before pulling + const beforeCommit = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + await git.pull({ dir: projectPath, ref: gitStatus.currentBranch, @@ -436,20 +445,38 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); + // Get the current HEAD commit after pulling + const afterCommit = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + + // Check if the repository actually changed + const repoChanged = beforeCommit !== afterCommit; toast({ title: "Pull successful", - description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`, + description: repoChanged + ? `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}` + : `Already up to date with ${remote.name}/${gitStatus.currentBranch}`, }); // Refresh git status after pull await refetchGitStatus(); + + // Only trigger build if the repository actually changed + if (repoChanged) { + const newSearchParams = new URLSearchParams(searchParams); + newSearchParams.set('build', ''); + setSearchParams(newSearchParams); + } } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; toast({ title: "Pull failed", description: errorMessage, variant: "destructive", + duration: Infinity, }); } finally { setIsPulling(false); diff --git a/src/components/ModelSelector.tsx b/src/components/ModelSelector.tsx index 590bca08..767f510c 100644 --- a/src/components/ModelSelector.tsx +++ b/src/components/ModelSelector.tsx @@ -168,7 +168,9 @@ export function ModelSelector({ - {isConfigured && } + {(isConfigured && models.length >= 5) && ( + + )}
diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 7b89ae81..b902f297 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -18,7 +18,6 @@ const GIT_KINDS = [ const GIT_RELAYS = [ 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', ]; const NostrProvider: React.FC = (props) => { diff --git a/src/components/OnboardingDialog.test.tsx b/src/components/OnboardingDialog.test.tsx index cbf028e4..79bd7d2c 100644 --- a/src/components/OnboardingDialog.test.tsx +++ b/src/components/OnboardingDialog.test.tsx @@ -42,7 +42,7 @@ describe('OnboardingDialog', () => { ); - expect(screen.getAllByText('Welcome to Shakespeare!')).toHaveLength(2); // Title and heading + expect(screen.getByText('Welcome to Shakespeare!')).toBeInTheDocument(); // Only in dialog title now expect(screen.getByText(/Your AI-powered development assistant/)).toBeInTheDocument(); expect(screen.getByRole('button', { name: /Get Started/i })).toBeInTheDocument(); }); diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 4fa385a1..e1d2ae0c 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -8,12 +8,13 @@ import { Button } from '@/components/ui/button'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Badge } from '@/components/ui/badge'; import { Skeleton } from '@/components/ui/skeleton'; -import { ScrollArea } from '@/components/ui/scroll-area'; import { useAISettings } from '@/hooks/useAISettings'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; + interface OnboardingDialogProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -119,8 +120,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) return ( <> - - + + {step === 'model-selection' && ( )} + {step === 'conclusion' && ( + + )} - {step === 'welcome' && 'Welcome to Shakespeare!'} {step === 'model-selection' && 'Choose Your AI Model'} - {step === 'conclusion' && "You're All Set!"} -
+
{step === 'welcome' && (
-
🎭
+
+ +

Welcome to Shakespeare! @@ -191,15 +202,8 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) )} {step === 'model-selection' && ( -
-
-

- Choose an AI model to power your development experience. - Different models offer various capabilities and pricing. -

-
- - +
+
{isLoadingModels ? ( <> @@ -232,6 +236,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) shakespeareModels.map((model) => { const isSelected = selectedModel === model.fullId; const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0); + const isPremium = !isFree; return (
- - {model.description || model.name || model.id} + + { model.name || model.description || model.id} {model.description && (

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

)}
@@ -259,6 +264,11 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) Free )} + {isPremium && ( + + Premium + + )} {isSelected && (
@@ -268,12 +278,12 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
-
+
{model.pricing && ( - <> - Input: {formatPrice(model.pricing.prompt)} - Output: {formatPrice(model.pricing.completion)} - +
+
Input: {formatPrice(model.pricing.prompt)}
+
Output: {formatPrice(model.pricing.completion)}
+
)} {model.contextLength && ( Context: {model.contextLength.toLocaleString()} tokens @@ -285,9 +295,9 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) }) )}
- +
-
+
-
-

- "Create a farming equipment marketplace for local farmers to buy and sell tractors, tools, and supplies..." -

-
@@ -292,14 +249,6 @@ export function ProjectSidebar({
- - {/* ZIP Import Dialog */} -
); } \ No newline at end of file diff --git a/src/components/SettingsLayout.tsx b/src/components/SettingsLayout.tsx index 200fff49..6cf9ea0c 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, Mail } from 'lucide-react'; +import { Menu, Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; import { ProjectSidebar } from '@/components/ProjectSidebar'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -56,13 +56,6 @@ 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.tsx b/src/components/Shakespeare/ChatPane.tsx index f9d724c0..02721a19 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -34,13 +34,14 @@ 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 { ReadConsoleMessagesTool, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool'; +import { ReadConsoleMessagesTool, ProjectPreviewConsoleError } from '@/lib/tools/ReadConsoleMessagesTool'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { saveFileToTmp } from '@/lib/fileUtils'; import { useGit } from '@/hooks/useGit'; import { Quilly } from '@/components/Quilly'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; // Clean interfaces now handled by proper hooks @@ -51,6 +52,8 @@ interface ChatPaneProps { onLoadingChange?: (isLoading: boolean) => void; isLoading?: boolean; isBuildLoading?: boolean; + consoleError?: ProjectPreviewConsoleError | null; + onDismissConsoleError?: () => void; } export interface ChatPaneRef { @@ -64,6 +67,8 @@ export const ChatPane = forwardRef(({ onLoadingChange, isLoading: externalIsLoading, isBuildLoading: externalIsBuildLoading, + consoleError, + onDismissConsoleError, }, ref) => { const { t } = useTranslation(); const [searchParams, setSearchParams] = useSearchParams(); @@ -80,18 +85,8 @@ export const ChatPane = forwardRef(({ const [isStuck, setIsStuck] = useState(false); const [aiError, setAIError] = useState(null); - // Console error handling - useEffect(() => { - const handleConsoleError = (error: ProjectPreviewConsoleError) => { - // Only show console errors if there's no existing AI error - if (!aiError) { - setAIError(error); - } - }; - - addErrorListener(handleConsoleError); - return () => removeErrorListener(handleConsoleError); - }, [aiError]); + // Determine which error to show - console error takes priority over AI errors + const displayError = consoleError || aiError; // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; @@ -185,7 +180,7 @@ export const ChatPane = forwardRef(({ artist: `Working on ${projectId}...`, artwork: [ { - src: '/favicon.png', + src: '/shakespeare.png', sizes: '512x512', type: 'image/png' } @@ -225,6 +220,15 @@ export const ChatPane = forwardRef(({ sendMessage('Read the console messages and fix any errors present.', providerModel); }, [sendMessage, providerModel]); + // Handle error dismissal + const handleErrorDismiss = useCallback(() => { + if (consoleError && onDismissConsoleError) { + onDismissConsoleError(); + } else { + setAIError(null); + } + }, [consoleError, onDismissConsoleError]); + // Use external loading state if provided, otherwise use internal state const isLoading = externalIsLoading !== undefined ? externalIsLoading : internalIsLoading; @@ -525,7 +529,9 @@ export const ChatPane = forwardRef(({ {messages.length === 0 && !streamingMessage && !isLoading && (
-
🎭
+
+ +

{t('welcomeToShakespeare')} @@ -608,11 +614,11 @@ export const ChatPane = forwardRef(({

)} - {/* AI Error Alert */} - {aiError && ( + {/* Error Alert (Console or AI) */} + {displayError && ( setAIError(null)} + error={displayError} + onDismiss={handleErrorDismiss} onNewChat={onNewChat} onOpenModelSelector={openModelSelector} onRequestConsoleErrorHelp={handleConsoleErrorHelp} diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 2736683a..03783f08 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -8,7 +8,7 @@ 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, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X } from 'lucide-react'; +import { FolderOpen, ArrowLeft, Bug, Copy, Check, Play, Loader2, MenuIcon, Code, CloudUpload, X, Terminal } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { BrowserAddressBar } from '@/components/ui/browser-address-bar'; @@ -27,6 +27,7 @@ import { cn } from '@/lib/utils'; import { FileTree } from './FileTree'; import { FileEditor } from './FileEditor'; import { DeployDialog } from '@/components/DeployDialog'; +import { Terminal as TerminalComponent } from '@/components/Terminal'; import { useSearchParams } from 'react-router-dom'; // Get iframe domain from environment variable @@ -76,7 +77,8 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o const [selectedFile, setSelectedFile] = useState(null); const [fileContent, setFileContent] = useState(''); const [isLoading, setIsLoading] = useState(false); - const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor'>('explorer'); + const [mobileCodeView, setMobileCodeView] = useState<'explorer' | 'editor' | 'terminal'>('explorer'); + const [desktopCodeView, setDesktopCodeView] = useState<'files' | 'terminal'>('files'); const isMobile = useIsMobile(); const [hasBuiltProject, setHasBuiltProject] = useState(false); const [currentPath, setCurrentPath] = useState('/'); @@ -455,6 +457,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o setSelectedFile(null); setFileContent(''); setMobileCodeView('explorer'); + setDesktopCodeView('files'); // Reset navigation history and state setCurrentPath('/'); @@ -729,18 +732,48 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o {isMobile ? ( -
+
{mobileCodeView === 'explorer' ? ( - - -
- +
+ + +
+ +
+
+ {/* Floating Terminal Button */} + +
+ ) : mobileCodeView === 'terminal' ? ( + <> +
+ +

+ Terminal +

- +
+ +
+ ) : ( <>
@@ -803,50 +836,73 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o {t('backToPreview')}
- +
)} {/* Code view header without back button for non-previewable projects */} {!isMobile && !isPreviewable && (
+
)}
-
- - -
- + {desktopCodeView === 'terminal' ? ( +
+ +
+ ) : ( + <> +
+ + +
+ +
+
- -
-
- {selectedFile ? ( - - ) : ( -
-
-

- {t('selectFileFromExplorer')} -

-
+
+ {selectedFile ? ( + + ) : ( +
+
+

+ {t('selectFileFromExplorer')} +

+
+
+ )}
- )} -
+ + )}
)} diff --git a/src/components/ShakespeareLogo.tsx b/src/components/ShakespeareLogo.tsx new file mode 100644 index 00000000..44230c1a --- /dev/null +++ b/src/components/ShakespeareLogo.tsx @@ -0,0 +1,13 @@ +export interface ShakespeareLogoProps { + className?: string; +} + +export function ShakespeareLogo({ className }: ShakespeareLogoProps) { + return ( + Shakespeare + ); +} \ No newline at end of file diff --git a/src/components/Terminal.tsx b/src/components/Terminal.tsx new file mode 100644 index 00000000..2dde2550 --- /dev/null +++ b/src/components/Terminal.tsx @@ -0,0 +1,235 @@ +import { useState, useRef, useEffect, useCallback } from 'react'; +import { ScrollArea } from '@/components/ui/scroll-area'; +import { Button } from '@/components/ui/button'; +import { Copy } from 'lucide-react'; +import { cn } from '@/lib/utils'; +import { ShellTool } from '@/lib/tools/ShellTool'; +import { useFS } from '@/hooks/useFS'; +import { useGit } from '@/hooks/useGit'; + +interface TerminalProps { + projectId: string; + className?: string; +} + +interface TerminalLine { + id: string; + type: 'input' | 'output' | 'error'; + content: string; + timestamp: Date; +} + +export function Terminal({ projectId, className }: TerminalProps) { + const [lines, setLines] = useState([]); + const [currentInput, setCurrentInput] = useState(''); + const [isExecuting, setIsExecuting] = useState(false); + const [commandHistory, setCommandHistory] = useState([]); + const [historyIndex, setHistoryIndex] = useState(-1); + + const inputRef = useRef(null); + const scrollRef = useRef(null); + const shellToolRef = useRef(null); + + const { fs } = useFS(); + const { git } = useGit(); + + // Initialize ShellTool + useEffect(() => { + shellToolRef.current = new ShellTool(fs, `/projects/${projectId}`, git); + + // Add welcome message + setLines([{ + id: Date.now().toString(), + type: 'output', + content: `Welcome to Shakespeare Terminal\nType 'help' to see available commands.`, + timestamp: new Date() + }]); + }, [projectId, fs, git]); + + // Auto-scroll to bottom when new lines are added or execution state changes + useEffect(() => { + if (scrollRef.current) { + scrollRef.current.scrollTop = scrollRef.current.scrollHeight; + } + }, [lines, isExecuting]); + + // Focus input when component mounts + useEffect(() => { + if (inputRef.current) { + inputRef.current.focus(); + } + }, []); + + // Refocus input after command execution + useEffect(() => { + if (!isExecuting && inputRef.current) { + inputRef.current.focus(); + } + }, [isExecuting]); + + const addLine = useCallback((type: TerminalLine['type'], content: string) => { + const newLine: TerminalLine = { + id: Date.now().toString() + Math.random(), + type, + content, + timestamp: new Date() + }; + setLines(prev => [...prev, newLine]); + }, []); + + const executeCommand = useCallback(async (command: string) => { + if (!shellToolRef.current || !command.trim()) return; + + // Add command to history + if (command.trim() && !commandHistory.includes(command.trim())) { + setCommandHistory(prev => [...prev, command.trim()]); + } + setHistoryIndex(-1); + + // Add input line + addLine('input', command); + + setIsExecuting(true); + + try { + // Handle special help command + if (command.trim() === 'help') { + const availableCommands = shellToolRef.current.getAvailableCommands(); + const helpText = `Available commands:\n\n${availableCommands.map(cmd => + `${cmd.name.padEnd(12)} - ${cmd.description}` + ).join('\n')}\n\nUse 'which ' for more details about a specific command.`; + addLine('output', helpText); + } else if (command.trim() === 'clear') { + setLines([]); + } else { + const result = await shellToolRef.current.execute({ command }); + + // Add output + if (result && result.trim()) { + addLine('output', result); + } + } + } catch (error) { + addLine('error', `Error: ${error instanceof Error ? error.message : 'Unknown error'}`); + } finally { + setIsExecuting(false); + } + }, [addLine, commandHistory]); + + const handleSubmit = useCallback((e: React.FormEvent) => { + e.preventDefault(); + if (currentInput.trim() && !isExecuting) { + executeCommand(currentInput); + setCurrentInput(''); + } + }, [currentInput, isExecuting, executeCommand]); + + const handleKeyDown = useCallback((e: React.KeyboardEvent) => { + if (e.key === 'ArrowUp') { + e.preventDefault(); + if (commandHistory.length > 0) { + const newIndex = historyIndex === -1 ? commandHistory.length - 1 : Math.max(0, historyIndex - 1); + setHistoryIndex(newIndex); + setCurrentInput(commandHistory[newIndex]); + } + } else if (e.key === 'ArrowDown') { + e.preventDefault(); + if (historyIndex >= 0) { + const newIndex = historyIndex + 1; + if (newIndex >= commandHistory.length) { + setHistoryIndex(-1); + setCurrentInput(''); + } else { + setHistoryIndex(newIndex); + setCurrentInput(commandHistory[newIndex]); + } + } + } else if (e.key === 'Tab') { + e.preventDefault(); + // Basic tab completion could be added here + } + }, [commandHistory, historyIndex]); + + const copyToClipboard = useCallback(async (content: string) => { + try { + await navigator.clipboard.writeText(content); + } catch (error) { + console.error('Failed to copy to clipboard:', error); + } + }, []); + + // Focus input when clicking anywhere in the terminal + const handleTerminalClick = useCallback(() => { + if (inputRef.current) { + inputRef.current.focus(); + } + }, []); + + return ( +
+ {/* Terminal Content */} +
+ +
+ {lines.map((line) => ( +
+
+                  {line.type === 'input' ? (
+                    
+                      ${' '}
+                    
+                  ) : null}
+                  {line.content}
+                
+ +
+ ))} + + {/* Current Command Input - inline with content */} + {!isExecuting && ( +
+ + $ + +
+ setCurrentInput(e.target.value)} + onKeyDown={handleKeyDown} + disabled={isExecuting} + className="w-full bg-transparent border-none outline-none text-white font-mono placeholder-gray-500 caret-white leading-relaxed" + placeholder="" + autoComplete="off" + spellCheck="false" + autoCapitalize="off" + autoCorrect="off" + /> +
+
+ )} +
+
+
+
+ ); +} \ No newline at end of file diff --git a/src/index.css b/src/index.css index aaa90c5b..b09c5aa2 100644 --- a/src/index.css +++ b/src/index.css @@ -110,11 +110,13 @@ @layer base { * { - @apply border-border; + border-color: hsl(var(--border)); } body { - @apply bg-background text-foreground font-sans; + background-color: hsl(var(--background)); + color: hsl(var(--foreground)); + font-family: 'Inter Variable', 'Inter', 'system-ui', 'sans-serif'; font-feature-settings: "rlig" 1, "calt" 1; } @@ -138,8 +140,10 @@ } /* GitHub-style focus rings */ - .focus-ring { - @apply focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2; + .focus-ring:focus-visible { + outline: none; + box-shadow: 0 0 0 2px hsl(var(--ring)); + outline-offset: 2px; } /* Smooth transitions for theme switching */ @@ -256,6 +260,10 @@ padding-top: env(safe-area-inset-top); } + .bottom-safe-nav { + bottom: calc(env(safe-area-inset-bottom) + 3.75rem); + } + /* Mobile navigation button styles - text/icon highlighting only */ .mobile-nav-button, .mobile-nav-button:hover, diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 19978226..fde41dd3 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -250,7 +250,6 @@ export class SessionManager { model, messages, tools: session.tools && Object.keys(session.tools).length > 0 ? Object.values(session.tools) : undefined, - tool_choice: session.tools && Object.keys(session.tools).length > 0 ? 'auto' : undefined, stream: true, stream_options: { include_usage: true, @@ -301,9 +300,9 @@ export class SessionManager { } if (delta?.tool_calls) { - for (const toolCallDelta of delta.tool_calls) { - const index = toolCallDelta.index; - if (index === undefined) continue; + for (let i = 0; i < delta.tool_calls.length; i++) { + const toolCallDelta = delta.tool_calls[i]; + const index = toolCallDelta.index ?? i; // Fix for Gemini models accumulatedToolCalls[index] ??= { id: '', diff --git a/src/lib/build/esmPlugin.ts b/src/lib/build/esmPlugin.ts index ce95e7c0..d41f50de 100644 --- a/src/lib/build/esmPlugin.ts +++ b/src/lib/build/esmPlugin.ts @@ -5,6 +5,7 @@ interface PackageLock { [key: string]: { name?: string; version: string; + peerDependencies?: { [key: string]: string }; } | undefined; }; } @@ -61,6 +62,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { } }); + // Legacy (Internet Explorer) "behavior" syntax + build.onResolve({ filter: /^#default#/, namespace: "esm" }, (args) => { + return { + path: args.path, + external: true, + }; + }); + // Handle bare imports like "react" build.onResolve({ filter: /^[^./].*/ }, (args) => { const packageName = args.path.startsWith("@") @@ -69,8 +78,13 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { // Handle transitive dependency versions const keys: string[] = []; + let importerPackage: string | undefined; try { - const importerPackage = extractPackageName(args.importer); + const { pathname } = new URL(args.importer); + if (/\.css$/.test(pathname)) { + return; // CSS imports don't have external dependencies + } + importerPackage = extractPackageName(args.importer); keys.push( `node_modules/${importerPackage}/node_modules/${packageName}`, ); @@ -89,12 +103,13 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { .find((info) => info); const packagePath = args.path.slice(packageName.length); - const version = packageInfo?.version; + const version = packageInfo?.version + || packageLock.packages[`node_modules/${importerPackage}`]?.peerDependencies?.[packageName]; - if (!version) return; - - const name = packageInfo.name ?? packageName; - const specifier = `${name}@${version}${packagePath}`; + const name = packageInfo?.name ?? packageName; + const specifier = version + ? `${name}@${version}${packagePath}` + : `${name}${packagePath}`; const url = new URL(`https://esm.sh/*${specifier}`); @@ -131,6 +146,14 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin { } } + // Skip static assets + if (/\.(woff2?|ttf|otf|eot)$/.test(fullURL.pathname)) { + return { + path: fullURL.toString(), + external: true, + }; + } + return { path: fullURL.toString(), namespace: "esm", diff --git a/src/lib/build/fsPlugin.ts b/src/lib/build/fsPlugin.ts index 5e914752..cb53dd4e 100644 --- a/src/lib/build/fsPlugin.ts +++ b/src/lib/build/fsPlugin.ts @@ -1,4 +1,4 @@ -import path from "path-browserify"; +import { join, dirname, extname } from "path-browserify"; import type { Loader, Plugin } from "esbuild-wasm"; import type { JSRuntimeFS } from '@/lib/JSRuntime'; @@ -8,27 +8,37 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { name: "fs", setup(build) { + build.onResolve({ filter: /^data:/ }, (args) => { + return { + path: args.path, + external: true, + }; + }); + build.onResolve({ filter: /.*/ }, async (args) => { let resolved: string; if (args.path.startsWith("@/")) { - resolved = path.join(cwd, args.path.slice(2)); + resolved = join(cwd, args.path.slice(2)); } else if (args.kind === "entry-point") { - resolved = path.join(cwd, args.path); + resolved = join(cwd, args.path); } else if (args.importer) { - resolved = path.join(path.dirname(args.importer), args.path); + resolved = join(dirname(args.importer), args.path); } else { return; } + // Vite query parameters https://vite.dev/guide/assets + const [cleaned, query] = resolved.split("?"); + try { - resolved = await tryFileVariants(fs, resolved); + resolved = await tryFileVariants(fs, cleaned); } catch { return; // Let other plugins handle this } return { - path: resolved, + path: resolved + (typeof query === "string" ? "?" + query : ""), namespace: "fs", }; }); @@ -36,14 +46,25 @@ export function fsPlugin(fs: JSRuntimeFS, cwd: string): Plugin { build.onLoad( { filter: /.*/, namespace: "fs" }, async (args) => { - const ext = path.extname(args.path).slice(1); + const [path, query] = args.path.split("?"); + const params = new URLSearchParams(query); - if (!["ts", "tsx", "js", "jsx", "css"].includes(ext)) { + // https://vite.dev/guide/assets.html#importing-asset-as-string + if (params.has("raw")) { + return { + contents: await fs.readFile(path, "utf8"), + loader: "text", + }; + } + + const ext = extname(path).slice(1); + + if (!["ts", "tsx", "js", "jsx", "css", "json"].includes(ext)) { return; } return { - contents: await fs.readFile(args.path, "utf8"), + contents: await fs.readFile(path, "utf8"), loader: ext as Loader, }; }, @@ -67,7 +88,7 @@ async function tryFileVariants( // If it's a directory, try index files if (stat.isDirectory()) { for (const ext of extensions) { - const indexFile = path.join(basePath, "index" + ext); + const indexFile = join(basePath, "index" + ext); const indexStat = await statSafe(fs, indexFile); if (indexStat.isFile()) { return indexFile; diff --git a/src/lib/build/index.ts b/src/lib/build/index.ts index fc9dbd1c..6817bcb2 100644 --- a/src/lib/build/index.ts +++ b/src/lib/build/index.ts @@ -1,6 +1,7 @@ import { getEsbuild } from "@/lib/esbuild"; import { copyFiles } from "@/lib/copyFiles"; +import { shakespearePlugin } from "./shakespearePlugin"; import { esmPlugin } from "./esmPlugin"; import { fsPlugin } from "./fsPlugin"; @@ -49,6 +50,7 @@ async function bundle( outdir: "/", jsx: "automatic", plugins: [ + shakespearePlugin(), // Takes precedence over esmPlugin fsPlugin(fs, `${projectPath}/src`), esmPlugin(JSON.parse(packageLockText), target), ], @@ -71,7 +73,7 @@ async function bundle( } // Update index.html with proper script and link tags - updateIndexHtml(doc); + updateIndexHtml(doc, dist); const updatedHtml = "\n" + doc.documentElement.outerHTML; dist["index.html"] = new TextEncoder().encode(updatedHtml); @@ -154,7 +156,7 @@ export async function buildProject(options: BuildProjectOptions): Promise<{ }; } -function updateIndexHtml(doc: Document): void { +function updateIndexHtml(doc: Document, dist: Record): void { const entrypoint = doc.querySelector('script[src="/src/main.tsx"]'); if (!entrypoint) { @@ -163,8 +165,11 @@ function updateIndexHtml(doc: Document): void { entrypoint.setAttribute("src", "/main.js"); - const style = doc.createElement("link"); - style.setAttribute("rel", "stylesheet"); - style.setAttribute("href", "/main.css"); - doc.head.appendChild(style); + const css = dist["main.css"]; + if (css) { + const style = doc.createElement("style"); + style.setAttribute("type", "text/tailwindcss"); + style.textContent = new TextDecoder().decode(css); + doc.head.appendChild(style); + } } \ No newline at end of file diff --git a/src/lib/build/shakespearePlugin.ts b/src/lib/build/shakespearePlugin.ts new file mode 100644 index 00000000..c315be66 --- /dev/null +++ b/src/lib/build/shakespearePlugin.ts @@ -0,0 +1,168 @@ +import type { Plugin } from "esbuild-wasm"; + +/** + * Shakespeare plugin for dependency polyfills and workarounds. + * This plugin handles specific dependencies that need custom implementations + * or dummy APIs to work correctly in the browser environment. + */ +export function shakespearePlugin(): Plugin { + return { + name: "shakespeare", + + setup(build) { + // Handle "sonner" imports with a dummy API + build.onResolve({ filter: /^sonner$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-sonner", + }; + }); + + // Provide dummy sonner implementation + build.onLoad({ filter: /.*/, namespace: "shakespeare-sonner" }, () => { + return { + contents: ` + // Dummy implementation of sonner toast library + + // Toast function that does nothing + const toast = (message, options) => { + console.log('[Shakespeare Sonner Mock]:', message, options); + return { id: Math.random().toString(36) }; + }; + + // Add common toast methods + toast.success = (message, options) => { + console.log('[Shakespeare Sonner Mock] Success:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.error = (message, options) => { + console.log('[Shakespeare Sonner Mock] Error:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.info = (message, options) => { + console.log('[Shakespeare Sonner Mock] Info:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.warning = (message, options) => { + console.log('[Shakespeare Sonner Mock] Warning:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.loading = (message, options) => { + console.log('[Shakespeare Sonner Mock] Loading:', message, options); + return { id: Math.random().toString(36) }; + }; + + toast.promise = (promise, options) => { + console.log('[Shakespeare Sonner Mock] Promise:', promise, options); + return promise; + }; + + toast.dismiss = (id) => { + console.log('[Shakespeare Sonner Mock] Dismiss:', id); + }; + + // Toaster component (dummy React component) + const Toaster = (props) => { + console.log('[Shakespeare Sonner Mock] Toaster component rendered:', props); + return null; + }; + + // Export both named and default exports to match sonner API + export { toast, Toaster }; + export default toast; + `, + loader: "js", + }; + }); + + // Handle "next-themes" imports with a dummy API + build.onResolve({ filter: /^next-themes$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-next-themes", + }; + }); + + // Provide dummy next-themes implementation + build.onLoad({ filter: /.*/, namespace: "shakespeare-next-themes" }, () => { + return { + contents: ` + // Dummy implementation of next-themes + + // useTheme hook that returns system theme + const useTheme = () => { + return { theme: "system" }; + }; + + // ThemeProvider component (dummy React component) + const ThemeProvider = ({ children, ...props }) => { + console.log('[Shakespeare next-themes Mock] ThemeProvider rendered:', props); + return children; + }; + + // Export both named and default exports to match next-themes API + export { useTheme, ThemeProvider }; + `, + loader: "js", + }; + }); + + // Handle "virtual:pwa-register/react" imports with a dummy API + build.onResolve({ filter: /^virtual:pwa-register\/react$/ }, (args) => { + return { + path: args.path, + namespace: "shakespeare-pwa-register", + }; + }); + + // Provide dummy PWA register implementation + build.onLoad({ filter: /.*/, namespace: "shakespeare-pwa-register" }, () => { + return { + contents: ` + // Dummy implementation of virtual:pwa-register/react + + // useRegisterSW hook that returns dummy functions + const useRegisterSW = (options = {}) => { + console.log('[Shakespeare PWA Mock] useRegisterSW called:', options); + + return { + needRefresh: [false, () => {}], + offlineReady: [false, () => {}], + updateServiceWorker: (reloadPage) => { + console.log('[Shakespeare PWA Mock] updateServiceWorker called:', reloadPage); + if (reloadPage) { + window.location.reload(); + } + }, + }; + }; + + // Export the hook + export { useRegisterSW }; + `, + loader: "js", + }; + }); + + // Add more dependency polyfills here as needed + // Example structure for future dependencies: + // build.onResolve({ filter: /^some-other-package$/ }, (args) => { + // return { + // path: args.path, + // namespace: "shakespeare-other-package", + // }; + // }); + // + // build.onLoad({ filter: /.*/, namespace: "shakespeare-other-package" }, () => { + // return { + // contents: `// Custom implementation for some-other-package`, + // loader: "js", + // }; + // }); + }, + }; +} \ No newline at end of file diff --git a/src/lib/commands/git/add.test.ts b/src/lib/commands/git/add.test.ts new file mode 100644 index 00000000..61df2b44 --- /dev/null +++ b/src/lib/commands/git/add.test.ts @@ -0,0 +1,275 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitAddCommand } from './add'; +import type { JSRuntimeFS } from '../../JSRuntime'; +import type { Git } from '../../git'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn().mockResolvedValue('mock content'), + writeFile: vi.fn().mockResolvedValue(undefined), + readdir: vi.fn().mockResolvedValue([]), + mkdir: vi.fn().mockResolvedValue(undefined), + stat: vi.fn().mockImplementation((path: string) => { + if (path.endsWith('/.git')) { + return Promise.resolve({ + isDirectory: () => true, + isFile: () => false, + size: 0, + mtimeMs: Date.now(), + }); + } + return Promise.resolve({ + isDirectory: () => false, + isFile: () => true, + size: 100, + mtimeMs: Date.now(), + }); + }), + lstat: vi.fn().mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + size: 100, + mtimeMs: Date.now(), + }), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + rename: vi.fn().mockResolvedValue(undefined), + readlink: vi.fn().mockResolvedValue('mock link'), + symlink: vi.fn().mockResolvedValue(undefined), +}); + +// Mock Git +const createMockGit = (): Git => ({ + statusMatrix: vi.fn(), + add: vi.fn(), + remove: vi.fn(), +} as unknown as Git); + +describe('GitAddCommand', () => { + let addCommand: GitAddCommand; + let mockFS: JSRuntimeFS; + let mockGit: Git; + const testCwd = '/test'; + + beforeEach(() => { + mockFS = createMockFS(); + mockGit = createMockGit(); + addCommand = new GitAddCommand({ + git: mockGit, + fs: mockFS, + pwd: testCwd, + }); + }); + + it('should have correct command properties', () => { + expect(addCommand.name).toBe('add'); + expect(addCommand.description).toBe('Add file contents to the index'); + expect(addCommand.usage).toBe('git add [--all | -A] [--] [...]'); + }); + + it('should return error when not in a git repository', async () => { + // Mock stat to throw error for .git directory + vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT')); + + const result = await addCommand.execute(['file.txt']); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('fatal: not a git repository'); + }); + + it('should return error when no files specified', async () => { + const result = await addCommand.execute([]); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Nothing specified, nothing added'); + expect(result.stderr).toContain('Maybe you wanted to say \'git add .\'?'); + }); + + it('should add all modified files with --all flag', async () => { + // Mock status matrix with modified and untracked files + // [filepath, headStatus, workdirStatus, stageStatus] + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['modified.txt', 1, 2, 1], // Modified file (not staged) + ['untracked.txt', 0, 2, 0], // Untracked file + ['unchanged.txt', 1, 1, 1], // Unchanged file + ['staged.txt', 1, 2, 2], // Already staged file + ]); + + const result = await addCommand.execute(['--all']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // Git add is silent on success + + // Should add modified and untracked files, but not unchanged or already staged + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'modified.txt', + }); + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'untracked.txt', + }); + expect(mockGit.add).toHaveBeenCalledTimes(2); + }); + + it('should handle deleted files with --all flag', async () => { + // Mock status matrix with deleted file + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['deleted.txt', 1, 0, 1], // Deleted file (not staged) + ]); + + const result = await addCommand.execute(['--all']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + + // Should remove the deleted file + expect(mockGit.remove).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'deleted.txt', + }); + expect(mockGit.remove).toHaveBeenCalledTimes(1); + }); + + it('should add specific file', async () => { + const result = await addCommand.execute(['file.txt']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'file.txt', + }); + }); + + it('should handle git add . (current directory)', async () => { + // Mock status matrix with various files + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['file1.txt', 1, 2, 1], // Modified file + ['file2.txt', 0, 2, 0], // Untracked file + ['deleted.txt', 1, 0, 1], // Deleted file + ]); + + const result = await addCommand.execute(['.']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + + // Should add modified and untracked files + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'file1.txt', + }); + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'file2.txt', + }); + + // Should remove deleted file + expect(mockGit.remove).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'deleted.txt', + }); + }); + + it('should reject absolute paths', async () => { + const result = await addCommand.execute(['/absolute/path/file.txt']); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('absolute paths are not supported'); + }); + + it('should handle non-existent files', async () => { + // Mock stat to throw error for non-existent file + vi.mocked(mockFS.stat).mockImplementation((path: string) => { + if (path.endsWith('/.git')) { + return Promise.resolve({ + isDirectory: () => true, + isFile: () => false, + size: 0, + mtimeMs: Date.now(), + }); + } + if (path.includes('nonexistent')) { + throw new Error('ENOENT'); + } + return Promise.resolve({ + isDirectory: () => false, + isFile: () => true, + size: 100, + mtimeMs: Date.now(), + }); + }); + + // Mock git.remove to also throw error (file doesn't exist in git either) + vi.mocked(mockGit.remove).mockRejectedValueOnce(new Error('File not found')); + + const result = await addCommand.execute(['nonexistent.txt']); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('pathspec \'nonexistent.txt\' did not match any files'); + }); + + it('should handle -A flag (same as --all)', async () => { + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['modified.txt', 1, 2, 1], // Modified file + ]); + + const result = await addCommand.execute(['-A']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'modified.txt', + }); + }); + + it('should handle mixed options and paths', async () => { + // Mock status matrix for --all to work + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['modified.txt', 1, 2, 1], // Modified file + ]); + + const result = await addCommand.execute(['--all', 'specific.txt']); + + expect(result.exitCode).toBe(0); + + // When --all is specified, it should ignore specific paths and add all files + expect(mockGit.statusMatrix).toHaveBeenCalled(); + }); + + it('should handle double dash separator', async () => { + const result = await addCommand.execute(['--', 'file.txt']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); + + expect(mockGit.add).toHaveBeenCalledWith({ + dir: testCwd, + filepath: 'file.txt', + }); + }); + + it('should continue with other files if one fails', async () => { + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['good.txt', 1, 2, 1], // This should succeed + ['bad.txt', 1, 2, 1], // This will fail + ]); + + // Mock git.add to fail for bad.txt but succeed for good.txt + vi.mocked(mockGit.add).mockImplementation(({ filepath }) => { + if (filepath === 'bad.txt') { + throw new Error('Permission denied'); + } + return Promise.resolve(); + }); + + const result = await addCommand.execute(['--all']); + + expect(result.exitCode).toBe(0); // Should still succeed overall + expect(mockGit.add).toHaveBeenCalledTimes(2); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/git/add.ts b/src/lib/commands/git/add.ts index c7d55a5a..5829bf4d 100644 --- a/src/lib/commands/git/add.ts +++ b/src/lib/commands/git/add.ts @@ -77,27 +77,22 @@ export class GitAddCommand implements GitSubcommand { dir: this.pwd, }); - let addedCount = 0; - let removedCount = 0; - - for (const [filepath, headStatus, workdirStatus] of statusMatrix) { + for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { try { if (workdirStatus === 0 && headStatus === 1) { - // File was deleted + // File was deleted in working directory await this.git.remove({ - + dir: this.pwd, filepath, }); - removedCount++; - } else if (workdirStatus === 1) { - // File exists (new or modified) + } else if (workdirStatus === 2 && stageStatus !== 2) { + // File exists and has changes that aren't staged yet await this.git.add({ - + dir: this.pwd, filepath, }); - addedCount++; } } catch { // Continue with other files if one fails @@ -105,19 +100,8 @@ export class GitAddCommand implements GitSubcommand { } } - const messages: string[] = []; - if (addedCount > 0) { - messages.push(`Added ${addedCount} file${addedCount !== 1 ? 's' : ''}`); - } - if (removedCount > 0) { - messages.push(`Removed ${removedCount} file${removedCount !== 1 ? 's' : ''}`); - } - - if (messages.length === 0) { - return createSuccessResult(''); - } - - return createSuccessResult(messages.join(', ') + '\n'); + // Git add is typically silent on success, like real git + return createSuccessResult(''); } catch (error) { return createErrorResult(`Failed to add all files: ${error instanceof Error ? error.message : 'Unknown error'}`); @@ -133,24 +117,24 @@ export class GitAddCommand implements GitSubcommand { if (path === '.') { // Add current directory (all files in it) const statusMatrix = await this.git.statusMatrix({ - + dir: this.pwd, }); - for (const [filepath, headStatus, workdirStatus] of statusMatrix) { + for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { try { if (workdirStatus === 0 && headStatus === 1) { - // File was deleted + // File was deleted in working directory await this.git.remove({ - + dir: this.pwd, filepath, }); addedFiles.push(filepath); - } else if (workdirStatus === 1) { - // File exists + } else if (workdirStatus === 2 && stageStatus !== 2) { + // File exists and has changes that aren't staged yet await this.git.add({ - + dir: this.pwd, filepath, }); @@ -179,7 +163,7 @@ export class GitAddCommand implements GitSubcommand { } else { // Add single file await this.git.add({ - + dir: this.pwd, filepath: path, }); @@ -189,7 +173,7 @@ export class GitAddCommand implements GitSubcommand { // Check if it's a deleted file try { await this.git.remove({ - + dir: this.pwd, filepath: path, }); @@ -208,11 +192,8 @@ export class GitAddCommand implements GitSubcommand { return createErrorResult(errors.join('\n')); } - if (addedFiles.length === 0) { - return createSuccessResult(''); - } - - return createSuccessResult(`Added ${addedFiles.length} file${addedFiles.length !== 1 ? 's' : ''}\n`); + // Git add is typically silent on success, like real git + return createSuccessResult(''); } private async addDirectory(dirPath: string, addedFiles: string[]): Promise { @@ -231,7 +212,7 @@ export class GitAddCommand implements GitSubcommand { } else { try { await this.git.add({ - + dir: this.pwd, filepath: entryPath, }); diff --git a/src/lib/commands/git/status.test.ts b/src/lib/commands/git/status.test.ts new file mode 100644 index 00000000..4132e906 --- /dev/null +++ b/src/lib/commands/git/status.test.ts @@ -0,0 +1,218 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { GitStatusCommand } from './status'; +import type { JSRuntimeFS } from '../../JSRuntime'; +import type { Git } from '../../git'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn().mockResolvedValue('mock content'), + writeFile: vi.fn().mockResolvedValue(undefined), + readdir: vi.fn().mockResolvedValue([]), + mkdir: vi.fn().mockResolvedValue(undefined), + stat: vi.fn().mockImplementation((path: string) => { + if (path.endsWith('/.git')) { + return Promise.resolve({ + isDirectory: () => true, + isFile: () => false, + size: 0, + mtimeMs: Date.now(), + }); + } + throw new Error('ENOENT: no such file or directory'); + }), + lstat: vi.fn().mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + size: 0, + mtimeMs: Date.now(), + }), + unlink: vi.fn().mockResolvedValue(undefined), + rmdir: vi.fn().mockResolvedValue(undefined), + rename: vi.fn().mockResolvedValue(undefined), + readlink: vi.fn().mockResolvedValue('mock link'), + symlink: vi.fn().mockResolvedValue(undefined), +}); + +// Mock Git +const createMockGit = (): Git => ({ + statusMatrix: vi.fn(), + currentBranch: vi.fn(), + stat: vi.fn(), +} as unknown as Git); + +describe('GitStatusCommand', () => { + let statusCommand: GitStatusCommand; + let mockFS: JSRuntimeFS; + let mockGit: Git; + const testCwd = '/test'; + + beforeEach(() => { + mockFS = createMockFS(); + mockGit = createMockGit(); + statusCommand = new GitStatusCommand({ + git: mockGit, + fs: mockFS, + pwd: testCwd, + }); + }); + + it('should have correct command properties', () => { + expect(statusCommand.name).toBe('status'); + expect(statusCommand.description).toBe('Show the working tree status'); + expect(statusCommand.usage).toBe('git status [--porcelain] [--short]'); + }); + + it('should return error when not in a git repository', async () => { + // Mock stat to throw error for .git directory + vi.mocked(mockFS.stat).mockRejectedValueOnce(new Error('ENOENT')); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('fatal: not a git repository'); + }); + + it('should show clean status when no changes', async () => { + // Mock git status matrix with no changes + vi.mocked(mockGit.statusMatrix).mockResolvedValue([]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('On branch main'); + expect(result.stdout).toContain('nothing to commit, working tree clean'); + }); + + it('should show untracked files correctly', async () => { + // Mock git status matrix with untracked file + // [filepath, headStatus, workdirStatus, stageStatus] + // Untracked: headStatus=0, stageStatus=0, workdirStatus=2 + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['newfile.txt', 0, 2, 0] + ]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('On branch main'); + expect(result.stdout).toContain('Untracked files:'); + expect(result.stdout).toContain('newfile.txt'); + }); + + it('should show staged files correctly', async () => { + // Mock git status matrix with staged file + // Staged new file: headStatus=0, stageStatus=2, workdirStatus=2 + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['newfile.txt', 0, 2, 2] + ]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('On branch main'); + expect(result.stdout).toContain('Changes to be committed:'); + expect(result.stdout).toContain('new file: newfile.txt'); + }); + + it('should show modified files correctly', async () => { + // Mock git status matrix with modified file + // Modified file: headStatus=1, stageStatus=1, workdirStatus=2 + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['existing.txt', 1, 2, 1] + ]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('On branch main'); + expect(result.stdout).toContain('Changes not staged for commit:'); + expect(result.stdout).toContain('modified: existing.txt'); + }); + + it('should show deleted files correctly', async () => { + // Mock git status matrix with deleted file + // Deleted file: headStatus=1, stageStatus=1, workdirStatus=0 + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['deleted.txt', 1, 0, 1] + ]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('On branch main'); + expect(result.stdout).toContain('Changes not staged for commit:'); + expect(result.stdout).toContain('deleted: deleted.txt'); + }); + + it('should format porcelain output correctly', async () => { + // Mock git status matrix with various changes + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['untracked.txt', 0, 2, 0], // Untracked + ['staged.txt', 0, 2, 2], // Staged new file + ['modified.txt', 1, 2, 1], // Modified + ['deleted.txt', 1, 0, 1], // Deleted + ]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); + + const result = await statusCommand.execute(['--porcelain']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('?? untracked.txt'); + expect(result.stdout).toContain('A staged.txt'); + expect(result.stdout).toContain(' M modified.txt'); + expect(result.stdout).toContain(' D deleted.txt'); + }); + + it('should handle short format', async () => { + // Mock git status matrix with changes + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['untracked.txt', 0, 2, 0], // Untracked + ]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('main'); + + const result = await statusCommand.execute(['--short']); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('?? untracked.txt'); + }); + + it('should handle complex status matrix correctly', async () => { + // Mock git status matrix with a complex scenario + vi.mocked(mockGit.statusMatrix).mockResolvedValue([ + ['file1.txt', 1, 2, 2], // Modified and staged + ['file2.txt', 0, 2, 0], // Untracked + ['file3.txt', 1, 0, 0], // Deleted (staged) + ['file4.txt', 1, 2, 1], // Modified (not staged) + ]); + vi.mocked(mockGit.currentBranch).mockResolvedValue('feature-branch'); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('On branch feature-branch'); + expect(result.stdout).toContain('Changes to be committed:'); + expect(result.stdout).toContain('modified: file1.txt'); + expect(result.stdout).toContain('deleted: file3.txt'); + expect(result.stdout).toContain('Untracked files:'); + expect(result.stdout).toContain('file2.txt'); + expect(result.stdout).toContain('Changes not staged for commit:'); + expect(result.stdout).toContain('modified: file4.txt'); + }); + + it('should handle detached HEAD state', async () => { + // Mock git status matrix with no current branch + vi.mocked(mockGit.statusMatrix).mockResolvedValue([]); + vi.mocked(mockGit.currentBranch).mockResolvedValue(undefined); + + const result = await statusCommand.execute([]); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('HEAD detached at unknown'); + expect(result.stdout).toContain('nothing to commit, working tree clean'); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/git/status.ts b/src/lib/commands/git/status.ts index d1618c26..39bff1b3 100644 --- a/src/lib/commands/git/status.ts +++ b/src/lib/commands/git/status.ts @@ -39,7 +39,6 @@ export class GitStatusCommand implements GitSubcommand { let currentBranch: string | null = null; try { currentBranch = await this.git.currentBranch({ - dir: this.pwd, }) || null; } catch { @@ -78,22 +77,26 @@ export class GitStatusCommand implements GitSubcommand { let indexStatus = ' '; let workingStatus = ' '; - // Determine index status (staged changes) - if (headStatus === 0 && stageStatus === 1) { - indexStatus = 'A'; // Added + // Determine index status (staged changes - comparing HEAD to stage) + if (headStatus === 0 && stageStatus === 2) { + indexStatus = 'A'; // Added to stage } else if (headStatus === 1 && stageStatus === 0) { - indexStatus = 'D'; // Deleted - } else if (headStatus === 1 && stageStatus === 1 && headStatus !== stageStatus) { - indexStatus = 'M'; // Modified + indexStatus = 'D'; // Deleted from stage + } else if (headStatus === 1 && stageStatus === 2) { + indexStatus = 'M'; // Modified in stage } - // Determine working directory status - if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) { - workingStatus = '?'; // Untracked + // Determine working directory status (comparing stage to working dir) + if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) { + // Untracked files show as ?? in porcelain format + indexStatus = '?'; + workingStatus = '?'; + } else if (stageStatus === 2 && workdirStatus === 0) { + workingStatus = 'D'; // Deleted in working dir } else if (stageStatus === 1 && workdirStatus === 0) { - workingStatus = 'D'; // Deleted - } else if (stageStatus !== workdirStatus) { - workingStatus = 'M'; // Modified + workingStatus = 'D'; // Deleted in working dir (was same as HEAD) + } else if (stageStatus !== workdirStatus && workdirStatus === 2) { + workingStatus = 'M'; // Modified in working dir } // Only show files with changes @@ -112,7 +115,7 @@ export class GitStatusCommand implements GitSubcommand { if (currentBranch) { lines.push(`On branch ${currentBranch}`); } else { - lines.push('On branch main'); + lines.push('HEAD detached at unknown'); } // Categorize changes @@ -122,24 +125,26 @@ export class GitStatusCommand implements GitSubcommand { const deleted: string[] = []; for (const [filepath, headStatus, workdirStatus, stageStatus] of statusMatrix) { - // Staged changes (index differs from HEAD) - if (headStatus === 0 && stageStatus === 1) { + // Staged changes (stage differs from HEAD) + if (headStatus === 0 && stageStatus === 2) { staged.push(`\tnew file: ${filepath}`); } else if (headStatus === 1 && stageStatus === 0) { staged.push(`\tdeleted: ${filepath}`); - } else if (headStatus !== stageStatus && headStatus === 1 && stageStatus === 1) { + } else if (headStatus === 1 && stageStatus === 2) { staged.push(`\tmodified: ${filepath}`); } - // Working directory changes (working dir differs from index) - if (stageStatus === 1 && workdirStatus === 0) { + // Working directory changes (working dir differs from stage) + if (stageStatus === 2 && workdirStatus === 0) { deleted.push(`\tdeleted: ${filepath}`); - } else if (stageStatus !== workdirStatus && stageStatus === 1 && workdirStatus === 1) { + } else if (stageStatus === 1 && workdirStatus === 0) { + deleted.push(`\tdeleted: ${filepath}`); + } else if (stageStatus !== workdirStatus && workdirStatus === 2) { modified.push(`\tmodified: ${filepath}`); } - // Untracked files - if (headStatus === 0 && stageStatus === 0 && workdirStatus === 1) { + // Untracked files (not in HEAD, not in stage, but in working dir) + if (headStatus === 0 && stageStatus === 0 && workdirStatus === 2) { untracked.push(`\t${filepath}`); } } @@ -148,7 +153,7 @@ export class GitStatusCommand implements GitSubcommand { if (staged.length > 0) { lines.push(''); lines.push('Changes to be committed:'); - lines.push(' (use "git reset HEAD ..." to unstage)'); + lines.push(' (use "git restore --staged ..." to unstage)'); lines.push(''); lines.push(...staged); } @@ -158,7 +163,7 @@ export class GitStatusCommand implements GitSubcommand { lines.push(''); lines.push('Changes not staged for commit:'); lines.push(' (use "git add ..." to update what will be committed)'); - lines.push(' (use "git checkout -- ..." to discard changes in working directory)'); + lines.push(' (use "git restore ..." to discard changes in working directory)'); lines.push(''); lines.push(...modified); lines.push(...deleted); diff --git a/src/lib/git.ts b/src/lib/git.ts index e19666e2..2504755a 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -911,7 +911,6 @@ export class Git { const gitRelays = new Set([ 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', 'wss://relay.nostr.band/', // General purpose relay as fallback ]); @@ -1313,6 +1312,7 @@ export class Git { dir: options.dir, ref: `refs/heads/${currentBranch}`, value: upstreamCommit, + force: true, }); // Update the working directory @@ -1395,7 +1395,6 @@ export class Git { relayUrls.push( 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', 'wss://relay.nostr.band/' ); } diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index d4b00446..e2ff3198 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -81,9 +81,6 @@ const resources = { dataSettingsDescription: 'Export files and manage local data', emailUpdates: 'Email Updates', emailUpdatesDescription: 'Subscribe to Shakespeare updates and resources', - emailUpdatesDescriptionLong: 'Stay updated with the latest Shakespeare features, tutorials, and resources.', - aboutShakespeareSettings: 'About Shakespeare', - aboutShakespeareSettingsDescription: 'Information about Shakespeare', // Project Sidebar newProject: 'New Project', @@ -207,7 +204,6 @@ const resources = { aboutShakespeare: 'About Shakespeare', aboutShakespeareDescription: 'Information about Shakespeare', sourceCode: 'Source Code', - viewOnGitLab: 'View on GitLab', description: 'Description', license: 'License', loadingLicense: 'Loading license...', @@ -396,9 +392,6 @@ const resources = { dataSettingsDescription: 'Exporte arquivos e gerencie dados locais', emailUpdates: 'Atualizações por Email', emailUpdatesDescription: 'Inscreva-se para receber atualizações e recursos do Shakespeare', - emailUpdatesDescriptionLong: 'Mantenha-se atualizado com os recursos mais recentes do Shakespeare, tutoriais e recursos. Enviamos apenas atualizações ocasionais e você pode cancelar a inscrição a qualquer momento.', - aboutShakespeareSettings: 'Sobre o Shakespeare', - aboutShakespeareSettingsDescription: 'Informações sobre o Shakespeare', // Project Sidebar newProject: 'Novo Projeto', @@ -565,7 +558,6 @@ const resources = { aboutShakespeare: 'Sobre o Shakespeare', aboutShakespeareDescription: 'Informações sobre o Shakespeare.', sourceCode: 'Código-fonte', - viewOnGitLab: 'Ver no GitLab', description: 'Descrição', license: 'Licença', loadingLicense: 'Carregando licença...', @@ -711,9 +703,6 @@ const resources = { dataSettingsDescription: '导出文件和管理本地数据', emailUpdates: '邮件更新', emailUpdatesDescription: '订阅Shakespeare更新和资源', - emailUpdatesDescriptionLong: '及时了解最新的Shakespeare功能、教程和资源。我们只会偶尔发送更新,您可以随时取消订阅。', - aboutShakespeareSettings: '关于Shakespeare', - aboutShakespeareSettingsDescription: '关于Shakespeare的信息', // Project Sidebar newProject: '新项目', @@ -880,7 +869,6 @@ const resources = { aboutShakespeare: '关于Shakespeare', aboutShakespeareDescription: '关于Shakespeare的信息。', sourceCode: '源代码', - viewOnGitLab: '在GitLab上查看', description: '描述', license: '许可证', loadingLicense: '加载许可证中...', @@ -1026,9 +1014,6 @@ const resources = { dataSettingsDescription: 'Fitar da fayiloli da sarrafa bayanan gida', emailUpdates: 'Sabuntawar Imel', emailUpdatesDescription: 'Yi rajista don karbar sabuntawar Shakespeare da albarkatu', - emailUpdatesDescriptionLong: 'Kasance da sabuntawa game da sabbin fasalolin Shakespeare, koyarwa, da albarkatu. Muna aika sabuntawa lokaci-lokaci kawai kuma kuna iya dakatar da rajista koyaushe.', - aboutShakespeareSettings: 'Game da Shakespeare', - aboutShakespeareSettingsDescription: 'Bayani game da Shakespeare', // Project Sidebar newProject: 'Sabon Aikin', @@ -1194,7 +1179,6 @@ const resources = { aboutShakespeare: 'Game da Shakespeare', aboutShakespeareDescription: 'Bayani game da Shakespeare.', sourceCode: 'Lambar Tushe', - viewOnGitLab: 'Duba akan GitLab', description: 'Bayanin', license: 'Lasisi', loadingLicense: 'Ana lodin lasisi...', @@ -1340,9 +1324,6 @@ const resources = { dataSettingsDescription: 'Gbe awọn faili jade ati ṣakoso data agbegbe', emailUpdates: 'Awọn Imudojuiwọn Imeeli', emailUpdatesDescription: 'Forukọsilẹ fun awọn imudojuiwọn Shakespeare ati awọn ohun elo', - emailUpdatesDescriptionLong: 'Wa pẹlu imudojuiwọn pẹlu awọn ẹya Shakespeare tuntun, awọn ikẹkọ, ati awọn ohun elo. A nfi awọn imudojuiwọn lọọrọọ nikan ranṣẹ ati pe o le da forukọsilẹ duro nigbakugba.', - aboutShakespeareSettings: 'Nipa Shakespeare', - aboutShakespeareSettingsDescription: 'Alaye nipa Shakespeare', // Project Sidebar newProject: 'Iṣẹ akanṣe Tuntun', @@ -1508,7 +1489,6 @@ const resources = { aboutShakespeare: 'Nipa Shakespeare', aboutShakespeareDescription: 'Alaye nipa Shakespeare.', sourceCode: 'Koodu Orisun', - viewOnGitLab: 'Wo lori GitLab', description: 'Apejuwe', license: 'Iwe-aṣẹ', loadingLicense: 'N gbe iwe-aṣẹ...', @@ -1649,9 +1629,6 @@ const resources = { dataSettingsDescription: 'Bupụta faịlụ na jikwaa data mpaghara', emailUpdates: 'Nmelite Email', emailUpdatesDescription: 'Debanye aha maka nmelite Shakespeare na akụrụngwa', - emailUpdatesDescriptionLong: 'Nọrọ na-emelite na atụmatụ Shakespeare ọhụrụ, nkuzi, na akụrụngwa. Anyị na-eziga naanị nmelite mgbe ụfọdụ ma ị nwere ike ịkwụsị ndebanye aha mgbe ọ bụla.', - aboutShakespeareSettings: 'Gbasara Shakespeare', - aboutShakespeareSettingsDescription: 'Ozi gbasara Shakespeare', // Project Sidebar newProject: 'Ọrụ Ọhụrụ', @@ -1817,7 +1794,6 @@ const resources = { aboutShakespeare: 'Gbasara Shakespeare', aboutShakespeareDescription: 'Ozi gbasara Shakespeare.', sourceCode: 'Koodu Isi', - viewOnGitLab: 'Lee na GitLab', description: 'Nkọwa', license: 'Ikike', loadingLicense: 'Na-ebu ikike...', diff --git a/src/lib/tools/NpmAddPackageTool.test.ts b/src/lib/tools/NpmAddPackageTool.test.ts index 65ddd3c6..0e4a8917 100644 --- a/src/lib/tools/NpmAddPackageTool.test.ts +++ b/src/lib/tools/NpmAddPackageTool.test.ts @@ -195,6 +195,25 @@ describe('NpmAddPackageTool', () => { } }; + vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2)); + + const result = await tool.execute({ name: 'lodash' }); + + // Should not fetch from registry when no version specified and package already installed + expect(mockFetch).not.toHaveBeenCalled(); + expect(mockFS.writeFile).not.toHaveBeenCalled(); + expect(result).toContain('ℹ️ Package lodash is already installed in dependencies with version ^4.17.21.'); + }); + + it('should handle package already installed with specific version', async () => { + const packageJson = { + name: 'test-project', + version: '1.0.0', + dependencies: { + 'lodash': '^4.17.21' + } + }; + vi.mocked(mockFS.readFile).mockResolvedValue(JSON.stringify(packageJson, null, 2)); mockFetch.mockResolvedValue({ ok: true, @@ -208,10 +227,10 @@ describe('NpmAddPackageTool', () => { }) }); - const result = await tool.execute({ name: 'lodash' }); + const result = await tool.execute({ name: 'lodash', version: '4.17.21' }); expect(mockFS.writeFile).not.toHaveBeenCalled(); - expect(result).toContain('ℹ️ Package lodash@4.17.21 is already installed'); + expect(result).toContain('ℹ️ Package lodash@4.17.21 is already installed in dependencies.'); }); it('should handle missing package.json', async () => { diff --git a/src/lib/tools/NpmAddPackageTool.ts b/src/lib/tools/NpmAddPackageTool.ts index d29865c8..a911d657 100644 --- a/src/lib/tools/NpmAddPackageTool.ts +++ b/src/lib/tools/NpmAddPackageTool.ts @@ -88,6 +88,16 @@ export class NpmAddPackageTool implements Tool { throw new Error(`❌ Invalid package.json format. Could not parse JSON.`); } + // Check if package already exists + const dependencyKey = dev ? 'devDependencies' : 'dependencies'; + const otherKey = dev ? 'dependencies' : 'devDependencies'; + + // If no version is specified and package is already installed, it's a no-op + if (!version && packageJson[dependencyKey]?.[name]) { + const currentVersion = packageJson[dependencyKey][name]; + return `ℹ️ Package ${name} is already installed in ${dependencyKey} with version ${currentVersion}.`; + } + // Determine version to use and fetch package metadata let targetVersion = version; let packageMetadata: NpmRegistryResponse; @@ -107,10 +117,7 @@ export class NpmAddPackageTool implements Tool { } } - // Check if package already exists - const dependencyKey = dev ? 'devDependencies' : 'dependencies'; - const otherKey = dev ? 'dependencies' : 'devDependencies'; - + // Check if package already exists with the specific version if (packageJson[dependencyKey]?.[name]) { const currentVersion = packageJson[dependencyKey][name]; if (currentVersion === `^${targetVersion}`) { diff --git a/src/pages/AboutSettings.tsx b/src/pages/AboutSettings.tsx index c42dd692..8e5e86dd 100644 --- a/src/pages/AboutSettings.tsx +++ b/src/pages/AboutSettings.tsx @@ -1,12 +1,12 @@ import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft } from 'lucide-react'; +import { Info, ExternalLink, Loader2, AlertTriangle, ArrowLeft, Code } from 'lucide-react'; import { Button } from '@/components/ui/button'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'; import { Alert, AlertDescription } from '@/components/ui/alert'; import { useIsMobile } from '@/hooks/useIsMobile'; +import { EmailSubscription } from '@/components/EmailSubscription'; export function AboutSettings() { const { t } = useTranslation(); @@ -78,64 +78,56 @@ export function AboutSettings() {
)} -
- {/* Project Information */} - - - - - {t('sourceCode')} - - - - - - +
+ {/* Email Updates */} + - {/* License */} - - - -
- - {t('license')} -
-
- - {isLoading ? ( -
- - {t('loadingLicense')} +
+ {/* Project Information */} + + + {/* License */} + + + +
+ + {t('license')}
- ) : error ? ( - - - - {t('failedToLoadLicense')}: {error} - - - ) : license ? ( -
- ) : null} - - - + + + {isLoading ? ( +
+ + {t('loadingLicense')} +
+ ) : error ? ( + + + + {t('failedToLoadLicense')}: {error} + + + ) : license ? ( +
+ ) : null} + + + +
); diff --git a/src/pages/Clone.tsx b/src/pages/Clone.tsx index 01ec43ca..ac4b54e6 100644 --- a/src/pages/Clone.tsx +++ b/src/pages/Clone.tsx @@ -4,11 +4,12 @@ import { useTranslation } from 'react-i18next'; import { AppLayout } from '@/components/AppLayout'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; -import { GitBranch, Loader2, AlertCircle } from 'lucide-react'; +import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; - +import { ZipImportDialog } from '@/components/ZipImportDialog'; import { useSeoMeta } from '@unhead/react'; +import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu'; export default function Clone() { const { t } = useTranslation(); @@ -20,6 +21,7 @@ export default function Clone() { const projectsManager = useProjectsManager(); const { toast } = useToast(); const autoCloneInitiatedRef = useRef(false); + const [isZipDialogOpen, setIsZipDialogOpen] = useState(false); useSeoMeta({ title: `${t('importRepository')} - Shakespeare`, @@ -171,6 +173,25 @@ export default function Clone() { } }, [handleClone, searchParams]); + const handleImportZip = async (file: File, overwrite = false, projectId?: string) => { + try { + // Import project from zip file + const project = await projectsManager.importProjectFromZip(file, projectId, overwrite); + + // Show success toast + toast({ + title: overwrite ? "Project Overwritten Successfully" : "Project Imported Successfully", + description: `"${project.name}" has been ${overwrite ? 'overwritten' : 'imported'} and is ready to use.`, + }); + + // Navigate to the imported project + navigate(`/project/${project.id}`); + } catch (error) { + console.error('Failed to import project:', error); + throw error; // Re-throw to let the dialog handle the error display + } + }; + return (
@@ -226,7 +247,35 @@ export default function Clone() { )}
+ + {/* Import ZIP File Link */} +
+ + + + + + setIsZipDialogOpen(true)} + > + + Import ZIP File + + + +
+ + {/* ZIP Import Dialog */} + ); } \ No newline at end of file diff --git a/src/pages/EmailSettings.tsx b/src/pages/EmailSettings.tsx deleted file mode 100644 index efff3f35..00000000 --- a/src/pages/EmailSettings.tsx +++ /dev/null @@ -1,292 +0,0 @@ -import { useState, useEffect } from 'react'; -import { ArrowLeft, Mail, CheckCircle } from 'lucide-react'; -import { useTranslation } from 'react-i18next'; -import { Button } from '@/components/ui/button'; -import { Input } from '@/components/ui/input'; -import { Label } from '@/components/ui/label'; -import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; -import { useIsMobile } from '@/hooks/useIsMobile'; -import { useNavigate } from 'react-router-dom'; -import { useCurrentUser } from '@/hooks/useCurrentUser'; -import { useToast } from '@/hooks/useToast'; -import { nip19 } from 'nostr-tools'; - -export function EmailSettings() { - const { t } = useTranslation(); - const isMobile = useIsMobile(); - const navigate = useNavigate(); - const { user } = useCurrentUser(); - const { toast } = useToast(); - - const [email, setEmail] = useState(''); - const [isSubmitting, setIsSubmitting] = useState(false); - const [isSubmitted, setIsSubmitted] = useState(false); - - const url = new URL('https://pub.us7.list-manage.com/subscribe/post?u=f1f718a93795f42a604d558d8&id=f7271442a0&f_id=00ffa3e4f0'); - const honeypot = `b_${url.searchParams.get('u')}_${url.searchParams.get('id')}`; - const tag = '8982396'; - - // Check localStorage on component mount - useEffect(() => { - const hasSubscribed = localStorage.getItem('shakespeare-email-subscribed'); - if (hasSubscribed === 'true') { - setIsSubmitted(true); - } - }, []); - - const handleSubmit = async (e: React.FormEvent) => { - e.preventDefault(); - - if (!email.trim()) { - toast({ - title: "Email required", - description: "Please enter your email address", - variant: "destructive", - }); - return; - } - - // Basic email validation - const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; - if (!emailRegex.test(email)) { - toast({ - title: "Invalid email", - description: "Please enter a valid email address", - variant: "destructive", - }); - return; - } - - setIsSubmitting(true); - - try { - // Submit to Mailchimp - const form = document.createElement('form'); - form.method = 'POST'; - form.action = url.href; - form.target = '_blank'; // Open in new tab - form.style.display = 'none'; - - // Add email field - const emailInput = document.createElement('input'); - emailInput.type = 'email'; - emailInput.name = 'EMAIL'; - emailInput.value = email.trim(); - form.appendChild(emailInput); - - // Add tag field with the new Shakespeare tag ID - const tagInput = document.createElement('input'); - tagInput.type = 'hidden'; - tagInput.name = 'tags'; - tagInput.value = tag; - form.appendChild(tagInput); - - // Add npub if available - if (user?.pubkey) { - const npubInput = document.createElement('input'); - npubInput.type = 'text'; - npubInput.name = 'NPUB'; - npubInput.value = nip19.npubEncode(user.pubkey); - npubInput.style.display = 'none'; - form.appendChild(npubInput); - } - - // Add honeypot field - const honeypotInput = document.createElement('input'); - honeypotInput.type = 'text'; - honeypotInput.name = honeypot; - honeypotInput.tabIndex = -1; - honeypotInput.style.position = 'absolute'; - honeypotInput.style.left = '-5000px'; - form.appendChild(honeypotInput); - - // Add form to document and submit - document.body.appendChild(form); - form.submit(); - - // Clean up after a short delay - setTimeout(() => { - document.body.removeChild(form); - }, 1000); - - // Save subscription status to localStorage - localStorage.setItem('shakespeare-email-subscribed', 'true'); - - setIsSubmitted(true); - toast({ - title: "Successfully subscribed!", - description: "You'll receive Shakespeare updates and resources occasionally.", - }); - } catch (error) { - console.error('Email signup error:', error); - toast({ - title: "Subscription failed", - description: "There was an error subscribing you to updates. Please try again.", - variant: "destructive", - }); - } finally { - setIsSubmitting(false); - } - }; - - if (isSubmitted) { - return ( -
- {isMobile && ( -
- -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
-
- )} - - {!isMobile && ( -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
- )} - -
- - -
- -
-

- Thanks for subscribing! -

-

- You can opt out at any time using the unsubscribe link in our emails. -

-
-
- - -
-
-
-
-
-
- ); - } - - return ( -
- {isMobile && ( -
- -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
-
- )} - - {!isMobile && ( -
-

- - {t('emailUpdates')} -

-

- {t('emailUpdatesDescriptionLong')} -

-
- )} - -
- - - - Stay Updated with Shakespeare - - - -
-
- - setEmail(e.target.value)} - disabled={isSubmitting} - required - /> -
- -
- - -

- You can opt out at any time using the unsubscribe link in our emails. -

-
-
-
-
-
-
- ); -} - -export default EmailSettings; \ No newline at end of file diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index c0c1c0b0..2803d804 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -21,6 +21,7 @@ import { ModelSelector } from '@/components/ModelSelector'; import { FileAttachment } from '@/components/ui/file-attachment'; import { Plus } from 'lucide-react'; import { useSeoMeta } from '@unhead/react'; +import { ShakespeareLogo } from '@/components/ShakespeareLogo'; export default function Index() { const { t } = useTranslation(); @@ -267,7 +268,9 @@ export default function Index() {
-
🎭
+
+ +

{t('buildNostrApps')}

diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index cf8112a9..41de533e 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -92,15 +92,13 @@ export function NostrSettings() { {isLoading ? (
{/* Loading skeleton for accounts */} - {[...Array(2)].map((_, i) => ( -
- -
- -
- +
+ +
+
- ))} + +
{/* Add account button skeleton */}
diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 8dd43d1c..f73f3a3b 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -18,7 +18,7 @@ import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { StarButton } from '@/components/StarButton'; import { useBuildProject } from '@/hooks/useBuildProject'; import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable'; -import { clearConsoleMessages } from '@/lib/tools/ReadConsoleMessagesTool'; +import { clearConsoleMessages, ProjectPreviewConsoleError, addErrorListener, removeErrorListener } from '@/lib/tools/ReadConsoleMessagesTool'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -29,6 +29,7 @@ export function ProjectView() { const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); const [isAILoading, setIsAILoading] = useState(false); const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false); + const [consoleError, setConsoleError] = useState(null); const projectsManager = useProjectsManager(); const chatPaneRef = useRef(null); @@ -46,8 +47,9 @@ export function ProjectView() { try { const projectData = await projectsManager.getProject(projectId); setProject(projectData); - // Clear console messages when switching projects + // Clear console messages and error state when switching projects clearConsoleMessages(); + setConsoleError(null); } catch (error) { console.error('Failed to load project:', error); } finally { @@ -79,6 +81,16 @@ export function ProjectView() { } }, [isPreviewable, mobileView, activeTab]); + // Global console error listener (always active regardless of current tab) + useEffect(() => { + const handleConsoleError = (error: ProjectPreviewConsoleError) => { + setConsoleError(error); + }; + + addErrorListener(handleConsoleError); + return () => removeErrorListener(handleConsoleError); + }, []); + const handleNewChat = () => { // Reset to chat view on mobile when starting new chat if (isMobile) { @@ -100,6 +112,10 @@ export function ProjectView() { // when isAILoading becomes true after user interaction }; + const handleDismissConsoleError = () => { + setConsoleError(null); + }; + const handleProjectDeleted = async () => { setProject(null); navigate('/'); @@ -212,6 +228,8 @@ export function ProjectView() { onLoadingChange={handleAILoadingChange} isLoading={isAILoading} isBuildLoading={build.isPending} + consoleError={consoleError} + onDismissConsoleError={handleDismissConsoleError} /> ) : (
diff --git a/src/pages/Settings.tsx b/src/pages/Settings.tsx index ecb29350..cf978600 100644 --- a/src/pages/Settings.tsx +++ b/src/pages/Settings.tsx @@ -1,6 +1,6 @@ import { useNavigate } from 'react-router-dom'; import { useTranslation } from 'react-i18next'; -import { Bot, GitBranch, Database, Wifi, Settings2, Info, Mail } from 'lucide-react'; +import { Bot, GitBranch, Database, Wifi, Settings2, Info } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; interface SettingsItem { @@ -48,13 +48,6 @@ 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'),