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/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/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 3e868305..5a1c2913 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -11,6 +11,7 @@ import { MoreHorizontal, MessageSquarePlus, History, + Folder, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { GitDialog } from '@/components/GitDialog'; @@ -19,6 +20,7 @@ interface ActionsMenuProps { projectId: string; projectName: string; onNewChat: () => void; + onProjectDetails?: () => void; isLoading?: boolean; isBuildLoading?: boolean; disabled?: boolean; @@ -29,6 +31,7 @@ export function ActionsMenu({ projectId, projectName: _projectName, onNewChat, + onProjectDetails, isLoading = false, isBuildLoading = false, disabled = false, @@ -65,6 +68,15 @@ export function ActionsMenu({ New Chat + setGitHistoryOpen(true)} + disabled={isAnyLoading} + className="gap-2" + > + + Rollback + + setGitDialogOpen(true)} disabled={isAnyLoading} @@ -75,12 +87,12 @@ export function ActionsMenu({ setGitHistoryOpen(true)} + onClick={onProjectDetails} disabled={isAnyLoading} className="gap-2" > - - Rollback + + Project Details diff --git a/src/components/CreditsBadge.test.tsx b/src/components/CreditsBadge.test.tsx index f5bcb70d..a8cb6e44 100644 --- a/src/components/CreditsBadge.test.tsx +++ b/src/components/CreditsBadge.test.tsx @@ -3,7 +3,6 @@ import { render, screen, fireEvent } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; import { CreditsBadge } from './CreditsBadge'; - // Mock the useAICredits hook vi.mock('@/hooks/useAICredits', () => ({ useAICredits: () => ({ @@ -16,7 +15,8 @@ vi.mock('@/hooks/useAICredits', () => ({ // Mock the fetch function global.fetch = vi.fn(); -const mockConnection = { +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 5bdc9695..ee565159 100644 --- a/src/components/CreditsBadge.tsx +++ b/src/components/CreditsBadge.tsx @@ -1,13 +1,9 @@ import { Badge } from '@/components/ui/badge'; +import { AIProvider } from '@/contexts/AISettingsContext'; import { useAICredits } from '@/hooks/useAICredits'; interface CreditsBadgeProps { - providerId: string; - connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; - }; + provider: AIProvider; className?: string; onOpenDialog?: () => void; } @@ -15,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 0983203e..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 { AIProvider } from '@/contexts/AISettingsContext'; // Mock the fetch function global.fetch = vi.fn(); -const mockConnection = { +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 89ae33af..46b33e01 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -13,15 +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 { AIProvider } from '@/contexts/AISettingsContext'; + interface CreditsDialogProps { open: boolean; onOpenChange: (open: boolean) => void; - providerId: string; - connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; - }; + provider: AIProvider; } interface Payment { @@ -184,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(); @@ -196,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; }, @@ -210,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; @@ -230,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) => { @@ -251,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) => { @@ -268,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 => @@ -280,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/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.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/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 361746f2..4fa385a1 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -334,8 +334,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) handleCreditsDialogClose(); } }} - providerId="shakespeare" - connection={SHAKESPEARE_PROVIDER} + provider={SHAKESPEARE_PROVIDER} /> )} diff --git a/src/components/ProjectInfoDialog.tsx b/src/components/ProjectDetailsDialog.tsx similarity index 69% rename from src/components/ProjectInfoDialog.tsx rename to src/components/ProjectDetailsDialog.tsx index 8460951a..0ace47dc 100644 --- a/src/components/ProjectInfoDialog.tsx +++ b/src/components/ProjectDetailsDialog.tsx @@ -1,4 +1,5 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; import { type Project } from '@/lib/ProjectsManager'; import { Dialog, @@ -18,6 +19,8 @@ import { 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'; @@ -28,23 +31,34 @@ import { Download, Loader2, Trash2, + Save, } from 'lucide-react'; import JSZip from 'jszip'; +import { Separator } from './ui/separator'; -interface ProjectInfoDialogProps { +interface ProjectDetailsDialogProps { project: Project; open: boolean; onOpenChange: (open: boolean) => void; onProjectDeleted?: () => void; } -export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDeleted }: ProjectInfoDialogProps) { +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(); @@ -58,11 +72,49 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete 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.`, @@ -172,10 +224,46 @@ export function ProjectInfoDialog({ project, open, onOpenChange, onProjectDelete {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 */} + )} +

+ + + + + + ); +} + +// Clean interfaces now handled by proper hooks interface ChatPaneProps { projectId: string; @@ -69,11 +116,11 @@ export const ChatPane = forwardRef(({ }, 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); // Use external state if provided, otherwise default to false const isBuildLoading = externalIsBuildLoading || false; @@ -83,6 +130,8 @@ export const ChatPane = forwardRef(({ // 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); useEffect(() => { if (!providerModel && settings.recentlyUsedModels?.length) { @@ -93,7 +142,7 @@ export const ChatPane = forwardRef(({ const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); const { git } = useGit(); - const { user, metadata } = useCurrentUser(); + const { user } = useCurrentUser(); const { models } = useProviderModels(); // Initialize AI chat with tools @@ -158,19 +207,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, @@ -185,7 +221,6 @@ export const ChatPane = forwardRef(({ projectId, tools, customTools, - systemPrompt, onUpdateMetadata, }); @@ -210,6 +245,32 @@ export const ChatPane = forwardRef(({ } }, [internalIsLoading, onLoadingChange]); + // 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(() => { const autostart = searchParams.get('autostart'); @@ -238,14 +299,6 @@ export const ChatPane = forwardRef(({ } }, [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; @@ -280,7 +333,6 @@ export const ChatPane = forwardRef(({ if (isNearBottom) { container.scrollTop = container.scrollHeight; } - } }, [messages, streamingMessage, isLoading]); @@ -295,7 +347,7 @@ export const ChatPane = forwardRef(({ return () => clearTimeout(timer); } - }, [projectId, scrolledProjects]); + }, [projectId, scrolledProjects, scrollToBottom]); const handleFileSelect = (file: File) => { setAttachedFiles(prev => [...prev, file]); @@ -348,8 +400,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(); @@ -399,9 +460,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) { @@ -439,6 +504,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 @@ -455,28 +530,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 (
@@ -557,6 +613,28 @@ export const ChatPane = forwardRef(({
)} + + {/* AI Model Alert */} + {aiModelAlert.hasError && ( + + )} + + {/* Console Error Alert */} + {consoleAlert.hasError && ( + suggestErrorFix(consoleAlert.errorSummary || '') + }} + /> + )} + @@ -577,9 +655,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={{ @@ -666,6 +749,8 @@ export const ChatPane = forwardRef(({ className="w-full" disabled={isLoading} placeholder={t('chooseModel')} + open={isModelSelectorOpen} + onOpenChange={setIsModelSelectorOpen} />
@@ -684,7 +769,7 @@ export const ChatPane = forwardRef(({
+ + {/* Onboarding Dialog */} + ); }); diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 53ebbf09..f8acca00 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,6 +3,7 @@ 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'; @@ -29,6 +30,7 @@ import { ConsoleMessage } from '@/types/console'; 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'; @@ -97,7 +99,7 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr const [currentPath, setCurrentPath] = useState('/'); const [navigationHistory, setNavigationHistory] = useState(['/']); const [historyIndex, setHistoryIndex] = useState(0); - +const [copiedMessageId, setCopiedMessageId] = useState(null); const [deployDialogOpen, setDeployDialogOpen] = useState(false); // Use external state if provided, otherwise use internal state @@ -107,15 +109,39 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr const iframeRef = useRef(null); const { fs } = useFS(); const projectsManager = useProjectsManager(); + const { messages: consoleMessages } = useConsoleMessages(); const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId); - const handleBuildProject = () => { + 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); @@ -255,17 +281,23 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr normalizedLevel = params.level as ConsoleMessage['level']; } - const newConsoleMessage: ConsoleMessage = { - id: Date.now(), - level: normalizedLevel, - message: params.message, - }; + // Add to global console messages + addConsoleMessage(normalizedLevel, params.message); - setConsoleMessages(prev => [...prev, newConsoleMessage]); + // Also update local state if provided (for external systems) + if (setConsoleMessages !== setInternalConsoleMessages) { + const newMessage: ConsoleMessage = { + id: Date.now() + Math.random(), + level: normalizedLevel, + message: params.message, + timestamp: Date.now(), + }; + setConsoleMessages(prev => [...prev, newMessage]); + } // Log to parent console for debugging with appropriate level console[normalizedLevel](`[IFRAME ${params.level.toUpperCase()}] ${params.message}`); - }, [setConsoleMessages]); + }, [setConsoleMessages, setInternalConsoleMessages]); const handleFetch = useCallback(async (request: JSONRPCRequest) => { const { params, id } = request; @@ -397,6 +429,13 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr } }, [selectedFile, loadFileContent]); + // Reset selected file when projectId changes + useEffect(() => { + setSelectedFile(null); + setFileContent(''); + setMobileCodeView('explorer'); + }, [projectId]); + useEffect(() => { checkForBuiltProject(); }, [checkForBuiltProject]); @@ -438,7 +477,30 @@ export function PreviewPane({ projectId, activeTab, config = {} }: PreviewPanePr const [isOpen, setIsOpen] = useState(false); const copiedMessageRef = useRef(null); const [_, setCopyUpdate] = useState(0); - + + 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 clearConsole = () => { + clearConsoleMessages(); + }; const copyMessageToClipboard = async (msg: ConsoleMessage) => { try { await navigator.clipboard.writeText(msg.message); diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index 2dc7f3fa..fe87aba2 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -1,4 +1,5 @@ import { useState, useEffect, useCallback } from 'react'; +import { useNavigate } from 'react-router-dom'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; @@ -7,6 +8,7 @@ import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } import { useGit } from '@/hooks/useGit'; import { useFS } from '@/hooks/useFS'; import { useToast } from '@/hooks/useToast'; +import { useGitStatus } from '@/hooks/useGitStatus'; interface GitCommit { oid: string; @@ -45,6 +47,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange const { fs } = useFS(); const { git } = useGit(); const { toast } = useToast(); + const navigate = useNavigate(); + const { data: gitStatus } = useGitStatus(projectId); const loadGitHistory = useCallback(async () => { setIsLoading(true); @@ -213,8 +217,9 @@ ${commitsToRevert.map(c => { description: `Reverted ${commitsToRevert.length} commit(s) back to ${targetCommit.oid.substring(0, 7)}`, }); - // Reload the git history to show the new commit - await loadGitHistory(); + // Close the dialog and navigate to project page with build query parameter + setIsOpen(false); + navigate(`/project/${projectId}?build`); } catch (err) { console.error('Failed to rollback:', err); @@ -226,7 +231,106 @@ ${commitsToRevert.map(c => { } finally { setIsRollingBack(null); } - }, [git, fs, projectId, toast, loadGitHistory]); + }, [git, fs, projectId, toast, navigate, setIsOpen]); + + const resetToHead = useCallback(async () => { + if (!fs) return; + + setIsRollingBack('HEAD'); + + try { + const projectPath = `/projects/${projectId}`; + + // Get the current HEAD commit + const headCommit = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + + // Get all files from HEAD + const headFiles = await git.listFiles({ + dir: projectPath, + ref: 'HEAD', + }); + + // Get current files in working directory + const currentFiles = await git.listFiles({ + dir: projectPath, + }); + + // Remove files that don't exist in HEAD (equivalent to git clean -fd for tracked files) + for (const filepath of currentFiles) { + if (!headFiles.includes(filepath)) { + try { + await fs.unlink(`${projectPath}/${filepath}`); + } catch (err) { + console.warn(`Could not remove ${filepath}:`, err); + } + } + } + + // Reset all files to HEAD state (equivalent to git reset --hard HEAD) + for (const filepath of headFiles) { + try { + const { blob } = await git.readBlob({ + dir: projectPath, + oid: headCommit, + filepath, + }); + + // Ensure directory exists + const dirPath = filepath.split('/').slice(0, -1).join('/'); + if (dirPath) { + await fs.mkdir(`${projectPath}/${dirPath}`, { recursive: true }); + } + + // Write the file + await fs.writeFile(`${projectPath}/${filepath}`, blob); + } catch (err) { + console.error(`Failed to reset ${filepath}:`, err); + } + } + + // Remove untracked files and directories (equivalent to git clean -fd) + // Get git status to find untracked files + const status = await git.statusMatrix({ + dir: projectPath, + }); + + const untrackedFiles = status + .filter(([, headStatus, workdirStatus, stageStatus]) => + headStatus === 0 && workdirStatus === 1 && stageStatus === 0 + ) + .map(([filepath]) => filepath); + + for (const filepath of untrackedFiles) { + try { + await fs.unlink(`${projectPath}/${filepath}`); + } catch (err) { + console.warn(`Could not remove untracked file ${filepath}:`, err); + } + } + + toast({ + title: "Reset successful", + description: "All changes have been discarded and working directory reset to HEAD", + }); + + // Close the dialog and navigate to project page with build query parameter + setIsOpen(false); + navigate(`/project/${projectId}?build`); + + } catch (err) { + console.error('Failed to reset:', err); + toast({ + title: "Reset failed", + description: err instanceof Error ? err.message : 'Failed to reset to HEAD', + variant: "destructive", + }); + } finally { + setIsRollingBack(null); + } + }, [git, fs, projectId, toast, navigate, setIsOpen]); useEffect(() => { if (isOpen) { @@ -372,15 +476,73 @@ ${commitsToRevert.map(c => {
{index === 0 ? ( - // Show "Current" for the most recent commit - + // Show "Current" or "Rollback" for the most recent commit + gitStatus?.hasUncommittedChanges ? ( + + + + + + + + + Discard All Changes + + +

+ This will discard all unstaged changes and reset your working directory to the current commit: +

+
+
{firstLine}
+
+ {commit.oid.substring(0, 7)} • {formatRelativeTime(commit.commit.author.timestamp)} +
+
+

+ This action cannot be undone. +

+
+
+ + Cancel + + {isRollingBack === 'HEAD' ? ( + <> +
+ Discarding... + + ) : ( + <> + + Discard Changes + + )} + + + + + ) : ( + + ) ) : ( // Show rollback button for older commits diff --git a/src/components/ui/QuillySVG.tsx b/src/components/ui/QuillySVG.tsx new file mode 100644 index 00000000..e3a8f31a --- /dev/null +++ b/src/components/ui/QuillySVG.tsx @@ -0,0 +1,63 @@ +import React from 'react'; + +interface QuillySVGProps extends React.SVGProps { + className?: string; + fillColor?: string; +} + +export function QuillySVG({ className = "w-4 h-4", fillColor = "currentColor", ...props }: QuillySVGProps) { + return ( + + {/* Main quill head/top part */} + + + {/* Main quill feather/plume part */} + + + {/* Body/torso part */} + + + {/* Additional body details */} + + + {/* Eyes */} + + + + {/* Extended body details */} + + + {/* Main body section */} + + + {/* Additional body details */} + + + {/* Body shading */} + + + {/* More body shading */} + + + {/* Lower body/legs area */} + + + {/* Extended body section */} + + + {/* Additional details */} + + + {/* Final details */} + + + {/* Bottom section */} + + + ); +} \ No newline at end of file diff --git a/src/components/ui/toast.tsx b/src/components/ui/toast.tsx index a8224775..38fdfa25 100644 --- a/src/components/ui/toast.tsx +++ b/src/components/ui/toast.tsx @@ -14,7 +14,7 @@ const ToastViewport = React.forwardRef< , React.ComponentPropsWithoutRef & - VariantProps + VariantProps >(({ className, variant, ...props }, ref) => { return ( ; customTools?: Record>; - systemPrompt?: string; maxSteps?: number; onUpdateMetadata?: (title: string, description: string) => void; } @@ -30,7 +29,6 @@ export function useAIChat({ projectId, tools = {}, customTools = {}, - systemPrompt, maxSteps = 50, onUpdateMetadata }: UseAIChatSessionOptions) { @@ -46,14 +44,14 @@ export function useAIChat({ const initSession = useCallback(async () => { // Load or update session - const session = await sessionManager.loadSession(projectId, tools, customTools, systemPrompt, maxSteps); + const session = await sessionManager.loadSession(projectId, tools, customTools, maxSteps); // Initialize individual state variables from existing session setMessages([...session.messages]); setStreamingMessage(session.streamingMessage ? { ...session.streamingMessage } : undefined); setIsLoading(session.isLoading); setTotalCost(session.totalCost || 0); setLastInputTokens(session.lastInputTokens || 0); - }, [sessionManager, projectId, tools, customTools, systemPrompt, maxSteps]); + }, [sessionManager, projectId, tools, customTools, maxSteps]); // Initialize session useEffect(() => { diff --git a/src/hooks/useAICredits.ts b/src/hooks/useAICredits.ts index 5d3d90ea..8a90ce6c 100644 --- a/src/hooks/useAICredits.ts +++ b/src/hooks/useAICredits.ts @@ -2,6 +2,7 @@ import { useQuery } from '@tanstack/react-query'; import { z } from 'zod'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { AIProvider } from '@/contexts/AISettingsContext'; // Zod schemas for the two possible response formats const creditsResponseV1Schema = z.object({ @@ -31,18 +32,14 @@ export interface CreditsResponse { * @param connection - The AI connection configuration * @returns Query result with credits information */ -export function useAICredits(providerId: string, connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; -}) { +export function useAICredits(provider: AIProvider) { const { user } = useCurrentUser(); return useQuery({ - queryKey: ['ai-credits', connection.nostr ? user?.pubkey ?? '' : '', providerId], + queryKey: ['ai-credits', provider.nostr ? user?.pubkey ?? '' : '', provider.id], queryFn: async (): Promise => { try { - const ai = createAIClient(connection, user); + const ai = createAIClient(provider, user); const data = await ai.get('/credits'); // Validate and normalize the response @@ -68,5 +65,6 @@ export function useAICredits(providerId: string, connection: { retry: false, // Don't retry as not all providers support this endpoint refetchOnWindowFocus: false, staleTime: 5 * 60 * 1000, // 5 minutes + enabled: provider.id === 'shakespeare' && !!user, }); } \ No newline at end of file diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 47e25658..cea562ec 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -42,9 +42,8 @@ describe('useAIProjectId', () => { // Mock parseProviderModel mockParseProviderModel.mockReturnValue({ - provider: 'openai', + provider: { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, model: 'gpt-4', - connection: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } }); // Mock createAIClient @@ -86,7 +85,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -110,7 +109,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -134,7 +133,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -157,7 +156,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -170,7 +169,7 @@ describe('useAIProjectId', () => { { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } ]); expect(mockCreateAIClient).toHaveBeenCalledWith( - { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, undefined ); }); @@ -188,7 +187,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -241,7 +240,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -296,7 +295,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -346,7 +345,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -396,7 +395,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); @@ -453,7 +452,7 @@ describe('useAIProjectId', () => { setProvider: vi.fn(), removeProvider: vi.fn(), setProviders: vi.fn(), - + addRecentlyUsedModel: vi.fn(), }); diff --git a/src/hooks/useAIProjectId.ts b/src/hooks/useAIProjectId.ts index 6fae5475..7c688c5e 100644 --- a/src/hooks/useAIProjectId.ts +++ b/src/hooks/useAIProjectId.ts @@ -28,8 +28,8 @@ export function useAIProjectId({ onError }: UseAIProjectIdOptions = {}) { try { // Initialize OpenAI client - const { model, connection } = parseProviderModel(providerModel, settings.providers); - const openai = createAIClient(connection, user); + const { model, provider } = parseProviderModel(providerModel, settings.providers); + const openai = createAIClient(provider, user); const systemPrompt = `You are a product expert. Given the user's project description, come up with a short, unique, and memorable name for their product or brand. Generate only the name without any additional text or punctuation. The name should be lowercase, use hyphens instead of spaces, and contain only alphanumeric characters and hyphens. Avoid using special characters or underscores.`; diff --git a/src/hooks/useConsoleMessages.ts b/src/hooks/useConsoleMessages.ts new file mode 100644 index 00000000..842196d6 --- /dev/null +++ b/src/hooks/useConsoleMessages.ts @@ -0,0 +1,79 @@ +import { useState, useCallback, useEffect } from 'react'; + +export interface ConsoleMessage { + id: number; + level: 'log' | 'warn' | 'error' | 'info' | 'debug'; + message: string; + timestamp: number; +} + +// Global state for console messages +let globalConsoleMessages: ConsoleMessage[] = []; +const listeners: Set<(messages: ConsoleMessage[]) => void> = new Set(); + +const notifyListeners = () => { + listeners.forEach(listener => listener([...globalConsoleMessages])); +}; + +export const useConsoleMessages = () => { + const [messages, setMessages] = useState(globalConsoleMessages); + + const addMessage = useCallback((level: ConsoleMessage['level'], message: string) => { + const newMessage: ConsoleMessage = { + id: Date.now() + Math.random(), // Ensure uniqueness + level, + message, + timestamp: Date.now(), + }; + + globalConsoleMessages = [...globalConsoleMessages, newMessage]; + notifyListeners(); + }, []); + + const clearMessages = useCallback(() => { + globalConsoleMessages = []; + notifyListeners(); + }, []); + + const getErrorsSince = useCallback((timestamp: number) => { + return globalConsoleMessages.filter( + msg => msg.level === 'error' && msg.timestamp > timestamp + ); + }, []); + + // Subscribe to global state changes + useEffect(() => { + const listener = (newMessages: ConsoleMessage[]) => { + setMessages(newMessages); + }; + listeners.add(listener); + return () => { + listeners.delete(listener); + }; + }, []); + + return { + messages, + addMessage, + clearMessages, + getErrorsSince, + }; +}; + +// Export functions for external use (like PreviewPane) +export const addConsoleMessage = (level: ConsoleMessage['level'], message: string) => { + const newMessage: ConsoleMessage = { + id: Date.now() + Math.random(), + level, + message, + timestamp: Date.now(), + }; + + globalConsoleMessages = [...globalConsoleMessages, newMessage]; + notifyListeners(); +}; + +export const clearConsoleMessages = () => { + globalConsoleMessages = []; + notifyListeners(); +}; diff --git a/src/hooks/useErrorDetection.ts b/src/hooks/useErrorDetection.ts new file mode 100644 index 00000000..9a100f85 --- /dev/null +++ b/src/hooks/useErrorDetection.ts @@ -0,0 +1,153 @@ +import { useState, useCallback, useMemo } from 'react'; +import type { AIMessage } from '@/lib/SessionManager'; +import { useConsoleMessages } from './useConsoleMessages'; + +export interface ConsoleErrorAlert { + hasError: boolean; + errorSummary: string | null; + errorCount: number; + dismiss: () => void; +} + +export const useConsoleErrorAlert = ( + aiMessages: AIMessage[], + isBuilding?: boolean, + isLoading?: boolean +): ConsoleErrorAlert => { + const { messages } = useConsoleMessages(); + const [dismissedErrorSummary, setDismissedErrorSummary] = useState(''); + + const { hasError, errorSummary, errorCount } = useMemo(() => { + // Don't show alerts while building or AI is working + if (isBuilding || isLoading) { + return { hasError: false, errorSummary: null, errorCount: 0 }; + } + + // Find the timestamp of the last AI assistant message + // Since AIMessage doesn't have timestamps, we'll use a different approach: + // Only show errors if there are any errors at all and no recent user activity + const lastMessage = aiMessages[aiMessages.length - 1]; + const isLastMessageFromAssistant = lastMessage?.role === 'assistant'; + + // Only show console errors if the last message was from assistant (AI just responded) + if (!isLastMessageFromAssistant) { + return { hasError: false, errorSummary: null, errorCount: 0 }; + } + + // Get recent errors (last 10 seconds worth to catch errors from recent AI actions) + const recentTimeThreshold = Date.now() - (10 * 1000); // 10 seconds ago + const recentErrors = messages.filter(msg => + msg.level === 'error' && + msg.timestamp > recentTimeThreshold + ); + + if (recentErrors.length === 0) { + return { hasError: false, errorSummary: null, errorCount: 0 }; + } + + // Just return the raw error messages, no formatting + const summary = recentErrors.slice(-3).map(e => e.message).join('\n'); + + return { + hasError: dismissedErrorSummary !== summary, + errorSummary: summary, + errorCount: recentErrors.length + }; + }, [messages, dismissedErrorSummary, aiMessages, isBuilding, isLoading]); + + const dismiss = useCallback(() => { + if (errorSummary) { + setDismissedErrorSummary(errorSummary); + } + }, [errorSummary]); + + return { + hasError, + errorSummary, + errorCount, + dismiss + }; +}; + +export interface AIModelErrorAlert { + hasError: boolean; + errorMessage: string | null; + errorType: 'warn' | 'error' | null; + action?: { label: string; onClick: () => void }; + dismiss: () => void; +} + +export const useAIModelErrorAlert = ( + messages: AIMessage[], + onNewChat?: () => void, + onChangeModel?: () => void +): AIModelErrorAlert => { + const [dismissedAlertKey, setDismissedAlertKey] = useState(''); + + const { hasError, errorMessage, errorType, action } = useMemo(() => { + const lastMessage = messages[messages.length - 1]; + + // Only show AI model alerts if the last message is from the assistant + // This ensures we don't show stale alerts when user continues the conversation + if (!lastMessage || lastMessage.role !== 'assistant') { + return { hasError: false, errorMessage: null, errorType: null, action: undefined }; + } + + const content = typeof lastMessage.content === 'string' ? lastMessage.content : ''; + + // Define error patterns with actions + const errorPatterns = [ + { + test: (content: string) => /AI service error: 422/.test(content) || /Provider returned error/.test(content), + type: 'error' as const, + message: 'The AI model encountered an issue. Try switching to a different model or starting a new chat.', + action: onChangeModel ? { label: 'Change model', onClick: onChangeModel } : undefined + }, + { + test: (content: string) => /maximum context length is \d+ tokens/.test(content) || /context length/.test(content), + type: 'warn' as const, + message: 'Your conversation is too long for this model. Try starting a new chat or switching to a model with a larger context window.', + action: onNewChat ? { label: 'New chat', onClick: onNewChat } : undefined + }, + { + test: (content: string) => /rate limit/i.test(content) || /too many requests/i.test(content), + type: 'warn' as const, + message: 'You\'re sending requests too quickly. Please wait a moment before trying again.' + } + ]; + + for (const pattern of errorPatterns) { + if (pattern.test(content)) { + const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content); + const alertKey = `${pattern.message}_${messageContent.slice(0, 50)}_${Date.now()}`; + + return { + hasError: dismissedAlertKey !== alertKey, + errorMessage: pattern.message, + errorType: pattern.type, + action: pattern.action, + alertKey + }; + } + } + + return { hasError: false, errorMessage: null, errorType: null, action: undefined }; + }, [messages, dismissedAlertKey, onNewChat, onChangeModel]); + + const dismiss = useCallback(() => { + const lastMessage = messages[messages.length - 1]; + if (errorMessage && lastMessage) { + const messageContent = typeof lastMessage.content === 'string' ? lastMessage.content : JSON.stringify(lastMessage.content); + const alertKey = `${errorMessage}_${messageContent.slice(0, 50)}_${Date.now()}`; + setDismissedAlertKey(alertKey); + } + }, [errorMessage, messages]); + + return { + hasError, + errorMessage, + errorType, + action, + dismiss + }; +}; diff --git a/src/hooks/useGitHubOAuth.ts b/src/hooks/useGitHubOAuth.ts index b0458404..aa685ed6 100644 --- a/src/hooks/useGitHubOAuth.ts +++ b/src/hooks/useGitHubOAuth.ts @@ -72,7 +72,7 @@ export function useGitHubOAuth() { const params = new URLSearchParams({ client_id: clientId, redirect_uri: window.location.origin + '/oauth/github', - scope: 'repo', + scope: 'repo workflow', state: state, code_challenge: codeChallenge, code_challenge_method: 'S256', diff --git a/src/hooks/useProviderModels.ts b/src/hooks/useProviderModels.ts index 86b2e9a9..84a5e437 100644 --- a/src/hooks/useProviderModels.ts +++ b/src/hooks/useProviderModels.ts @@ -45,9 +45,8 @@ export function useProviderModels(): ModelFetchResult { // Fetch models from each configured provider in parallel const providerPromises = settings.providers.map(async (provider) => { - const { id: providerKey, ...connection } = provider; try { - const openai = createAIClient(connection, user); + const openai = createAIClient(provider, user); // Fetch models with timeout try { @@ -59,8 +58,8 @@ export function useProviderModels(): ModelFetchResult { const providerModels = response.data.map((model) => { const providerModel: ProviderModel = { id: model.id, - provider: providerKey, - fullId: `${providerKey}/${model.id}`, + provider: provider.id, + fullId: `${provider.id}/${model.id}`, }; if ('name' in model && typeof model.name === 'string') { @@ -95,16 +94,16 @@ export function useProviderModels(): ModelFetchResult { return providerModels; } catch (fetchError) { if (fetchError instanceof Error && fetchError.name === 'AbortError') { - errors.push(`${providerKey}: Request timeout`); + errors.push(`${provider.id}: Request timeout`); } else { throw fetchError; } return []; } } catch (providerError) { - console.warn(`Failed to fetch models from ${providerKey}:`, providerError); + console.warn(`Failed to fetch models from ${provider.id}:`, providerError); errors.push( - `${providerKey}: ${ + `${provider.id}: ${ providerError instanceof Error ? providerError.message : 'Unknown error' }` ); diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index f5d6a5fc..4d401518 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -59,7 +59,7 @@ class MockFS implements JSRuntimeFS { error.code = 'ENOENT'; throw error; } - + const entries: string[] = []; // Find subdirectories @@ -125,6 +125,63 @@ class MockFS implements JSRuntimeFS { async rmdir(path: string): Promise { this.dirs.delete(path); } + + async rename(oldPath: string, newPath: string): Promise { + // Handle both files and directories + if (this.files.has(oldPath)) { + const content = this.files.get(oldPath); + this.files.delete(oldPath); + this.files.set(newPath, content!); + } + + if (this.dirs.has(oldPath)) { + this.dirs.delete(oldPath); + this.dirs.add(newPath); + + // Also move all subdirectories and files + const itemsToMove: Array<{ oldPath: string; newPath: string; isDir: boolean }> = []; + + // Collect directories to move + for (const dir of this.dirs) { + if (dir.startsWith(oldPath + '/')) { + const relativePath = dir.slice(oldPath.length); + itemsToMove.push({ + oldPath: dir, + newPath: newPath + relativePath, + isDir: true + }); + } + } + + // Collect files to move + for (const file of this.files.keys()) { + if (file.startsWith(oldPath + '/')) { + const relativePath = file.slice(oldPath.length); + itemsToMove.push({ + oldPath: file, + newPath: newPath + relativePath, + isDir: false + }); + } + } + + // Move all items + for (const item of itemsToMove) { + if (item.isDir) { + this.dirs.delete(item.oldPath); + this.dirs.add(item.newPath); + } else { + const content = this.files.get(item.oldPath); + this.files.delete(item.oldPath); + this.files.set(item.newPath, content!); + } + } + } + } + + async lstat(path: string): Promise<{ isDirectory(): boolean; isFile(): boolean; mtimeMs?: number }> { + return this.stat(path); + } } describe('ProjectsManager', () => { @@ -211,4 +268,68 @@ describe('ProjectsManager', () => { expect(project).toBeNull(); }); }); + + describe('renameProject', () => { + it('should rename a project directory', async () => { + await projectsManager.init(); + + // Create a project + await fs.mkdir('/projects/old-name'); + await fs.writeFile('/projects/old-name/package.json', '{}'); + + // Verify the project exists + const originalProject = await projectsManager.getProject('old-name'); + expect(originalProject).not.toBeNull(); + + // Rename the project + const renamedProject = await projectsManager.renameProject('old-name', 'new-name'); + + // Verify the renamed project + expect(renamedProject.id).toBe('new-name'); + expect(renamedProject.name).toBe('new-name'); + expect(renamedProject.path).toBe('/projects/new-name'); + + // Verify old project no longer exists + const oldProject = await projectsManager.getProject('old-name'); + expect(oldProject).toBeNull(); + + // Verify new project exists + const newProject = await projectsManager.getProject('new-name'); + expect(newProject).not.toBeNull(); + expect(newProject?.id).toBe('new-name'); + }); + + it('should throw error when old project does not exist', async () => { + await projectsManager.init(); + + await expect(projectsManager.renameProject('non-existent', 'new-name')) + .rejects.toThrow('Project with ID "non-existent" does not exist'); + }); + + it('should throw error when new project name already exists', async () => { + await projectsManager.init(); + + // Create two projects + await fs.mkdir('/projects/project-1'); + await fs.mkdir('/projects/project-2'); + + await expect(projectsManager.renameProject('project-1', 'project-2')) + .rejects.toThrow('Project with ID "project-2" already exists'); + }); + + it('should validate and normalize project names', async () => { + await projectsManager.init(); + + // Create a project + await fs.mkdir('/projects/old-name'); + + // Try to rename with invalid characters + await expect(projectsManager.renameProject('old-name', 'New Name With Spaces')) + .rejects.toThrow('Project name must contain only lowercase letters, numbers, and hyphens'); + + // Try to rename with empty name + await expect(projectsManager.renameProject('old-name', '')) + .rejects.toThrow('Project name cannot be empty'); + }); + }); }); \ No newline at end of file diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 07dddad6..b16dc17a 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -264,6 +264,50 @@ export class ProjectsManager { await this.deleteDirectory(projectPath); } + async renameProject(oldId: string, newId: string): Promise { + // Validate that the old project exists + const oldProject = await this.getProject(oldId); + if (!oldProject) { + throw new Error(`Project with ID "${oldId}" does not exist`); + } + + // Validate that the new ID doesn't already exist + if (await this.projectExists(newId)) { + throw new Error(`Project with ID "${newId}" already exists`); + } + + // Validate the new ID format (same rules as generateUniqueProjectId) + const validatedNewId = newId + .toLowerCase() + .replace(/[^a-z0-9]+/g, '-') + .replace(/^-+|-+$/g, ''); + + if (validatedNewId !== newId) { + throw new Error(`Project name must contain only lowercase letters, numbers, and hyphens`); + } + + if (!validatedNewId) { + throw new Error(`Project name cannot be empty`); + } + + const oldPath = `${this.dir}/${oldId}`; + const newPath = `${this.dir}/${newId}`; + + // Rename the directory + await this.fs.rename(oldPath, newPath); + + // Return the updated project object + const stats = await this.fs.stat(newPath); + const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date(); + + return { + id: newId, + name: this.formatProjectName(newId), + path: newPath, + lastModified: timestamp, + }; + } + private async deleteDirectory(dirPath: string): Promise { const files = await this.fs.readdir(dirPath); diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index 6288c2a0..e90f285a 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -6,6 +6,8 @@ import { createAIClient } from './ai-client'; import type { Tool } from './tools/Tool'; import type { NUser } from '@nostrify/react/login'; import type { AIProvider } from '@/contexts/AISettingsContext'; +import { makeSystemPrompt } from './system'; +import { NostrMetadata } from '@nostrify/nostrify'; export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | { role: 'assistant'; @@ -18,7 +20,6 @@ export interface SessionState { projectId: string; tools: Record; customTools: Record>; - systemPrompt?: string; maxSteps?: number; messages: AIMessage[]; streamingMessage?: { @@ -55,13 +56,13 @@ export class SessionManager { private fs: JSRuntimeFS; private aiSettings: { providers: AIProvider[] }; private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>; - private getCurrentUser?: () => NUser | undefined; + private getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }; constructor( fs: JSRuntimeFS, aiSettings: { providers: AIProvider[] }, getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>, - getCurrentUser?: () => NUser | undefined + getCurrentUser?: () => { user?: NUser; metadata?: NostrMetadata }, ) { this.fs = fs; this.aiSettings = aiSettings; @@ -76,7 +77,6 @@ export class SessionManager { projectId: string, tools: Record, customTools: Record>, - systemPrompt?: string, maxSteps?: number ): Promise { let messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = []; @@ -98,7 +98,6 @@ export class SessionManager { projectId, tools, customTools, - systemPrompt, maxSteps, isLoading: false, lastActivity: new Date(), @@ -114,7 +113,6 @@ export class SessionManager { session.tools = tools; session.customTools = customTools; - session.systemPrompt = systemPrompt; session.maxSteps = maxSteps; this.sessions.set(projectId, session); @@ -203,12 +201,12 @@ export class SessionManager { try { // Parse provider and model const parsed = parseProviderModel(providerModel, this.aiSettings.providers); - const connectionConfig = parsed.connection; - const modelName = parsed.model; + const provider = parsed.provider; + const model = parsed.model; // Initialize OpenAI client - const currentUser = this.getCurrentUser?.(); - const openai = createAIClient(connectionConfig, currentUser); + const { user, metadata } = this.getCurrentUser?.() ?? {}; + const openai = createAIClient(provider, user); let stepCount = 0; const maxSteps = session.maxSteps || 50; @@ -230,14 +228,25 @@ export class SessionManager { tool_calls: undefined }; + const systemPrompt = await makeSystemPrompt({ + cwd: `/projects/${projectId}`, + fs: this.fs, + mode: "agent", + name: "Shakespeare", + profession: "software extraordinaire", + tools: Object.values(session.tools), + user, + metadata, + }); + // Prepare messages for AI - const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = session.systemPrompt - ? [{ role: 'system', content: session.systemPrompt }, ...session.messages] + const messages: OpenAI.Chat.Completions.ChatCompletionMessageParam[] = systemPrompt + ? [{ role: 'system', content: systemPrompt }, ...session.messages] : session.messages; // Prepare completion options const completionOptions: OpenAI.Chat.Completions.ChatCompletionCreateParams = { - model: modelName, + 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, @@ -258,7 +267,7 @@ export class SessionManager { let finishReason: string | null = null; // Process the stream - let usage: { prompt_tokens: number; completion_tokens: number } | undefined; + let usage: { prompt_tokens: number; completion_tokens: number; cost?: number } | undefined; for await (const chunk of stream) { // Check if session was cancelled if (!session.isLoading) break; @@ -319,13 +328,25 @@ export class SessionManager { // Capture usage data if available (some providers include it in the final chunk) if (chunk.usage) { + const cost = 'cost' in chunk.usage && typeof chunk.usage.cost === 'number' + ? chunk.usage.cost + : undefined; + usage = { prompt_tokens: chunk.usage.prompt_tokens || 0, - completion_tokens: chunk.usage.completion_tokens || 0 + completion_tokens: chunk.usage.completion_tokens || 0, + cost, }; } } + // Fix tool calls with empty arguments + for (const toolCall of accumulatedToolCalls) { + if (toolCall.type === 'function') { + toolCall.function.arguments = toolCall.function.arguments || '{}'; + } + } + // Create final assistant message const assistantMessage: AIMessage = { role: 'assistant', @@ -461,20 +482,28 @@ export class SessionManager { /** * Update session cost and context usage based on usage data */ - private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number }, providerModel: string): void { + private updateSessionCost(projectId: string, usage: { prompt_tokens: number; completion_tokens: number; cost?: number }, providerModel: string): void { if (!this.getProviderModels) return; const session = this.sessions.get(projectId); if (!session) return; + // If provider gives direct cost, use it + if (typeof usage.cost === 'number') { + session.totalCost = (session.totalCost || 0) + usage.cost; + this.emit('costUpdated', projectId, session.totalCost); + return; + } + + // Otherwise, get the cost from the models endpoint try { const parsed = parseProviderModel(providerModel, this.aiSettings.providers); const modelName = parsed.model; - const providerName = parsed.provider; + const provider = parsed.provider; // Find the model in provider models to get pricing and context length const models = this.getProviderModels(); - const model = models.find(m => m.id === modelName && m.provider === providerName); + const model = models.find(m => m.id === modelName && m.provider === provider.id); // Update input tokens for context usage tracking session.lastInputTokens = usage.prompt_tokens; @@ -491,7 +520,6 @@ export class SessionManager { // Update session total cost session.totalCost = (session.totalCost || 0) + requestCost; - this.emit('costUpdated', projectId, session.totalCost); } catch (error) { console.warn('Failed to calculate session cost:', error); diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.ts index 8b2405e8..897006f1 100644 --- a/src/lib/ai-client.ts +++ b/src/lib/ai-client.ts @@ -1,33 +1,52 @@ import OpenAI from 'openai'; import { NIP98Client } from '@nostrify/nostrify'; import type { NUser } from '@nostrify/react/login'; +import type { AIProvider } from '@/contexts/AISettingsContext'; /** * Create an OpenAI client instance with the appropriate configuration. * If the connection requires Nostr authentication (NIP-98), it will use * the NIP98Client for authenticated requests. */ -export function createAIClient(connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; -}, user?: NUser): OpenAI { +export function createAIClient(provider: AIProvider, user?: NUser): OpenAI { const baseConfig: ConstructorParameters[0] = { - baseURL: connection.baseURL, - apiKey: connection.apiKey ?? '', + baseURL: provider.baseURL, + apiKey: provider.apiKey ?? '', dangerouslyAllowBrowser: true, + defaultHeaders: { + // https://openrouter.ai/docs/app-attribution + 'HTTP-Referer': 'https://shakespeare.diy', + 'X-Title': 'Shakespeare', + }, }; + let openai: OpenAI; + // If Nostr authentication is required and we have a user, use NIP-98 - if (connection.nostr && user?.signer) { + if (provider.nostr && user?.signer) { const nip98Client = new NIP98Client({ signer: user.signer }); - return new OpenAI({ + openai = new OpenAI({ ...baseConfig, fetch: (input, init) => nip98Client.fetch(input, init), }); + } else { + // Standard OpenAI client + openai = new OpenAI(baseConfig); } - // Standard OpenAI client - return new OpenAI(baseConfig); + const createCompletion: typeof openai.chat.completions.create + = openai.chat.completions.create.bind(openai.chat.completions); + + openai.chat.completions.create = ((...[body, options]: Parameters) => { + // OpenRouter usage accounting + // https://openrouter.ai/docs/use-cases/usage-accounting + if (provider.id === 'openrouter') { + (body as { usage?: { include?: boolean } }).usage = { include: true }; + } + + return createCompletion(body, options); + }) as typeof createCompletion; + + return openai; } \ No newline at end of file diff --git a/src/lib/commands/hexdump.test.ts b/src/lib/commands/hexdump.test.ts new file mode 100644 index 00000000..5b5b9f46 --- /dev/null +++ b/src/lib/commands/hexdump.test.ts @@ -0,0 +1,229 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { HexdumpCommand } from './hexdump'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + mkdir: vi.fn(), + stat: vi.fn(), + lstat: vi.fn(), + unlink: vi.fn(), + rmdir: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}); + +describe('HexdumpCommand', () => { + let mockFS: JSRuntimeFS; + let command: HexdumpCommand; + const testCwd = '/test/dir'; + + beforeEach(() => { + mockFS = createMockFS(); + command = new HexdumpCommand(mockFS); + }); + + it('should have correct name and description', () => { + expect(command.name).toBe('hexdump'); + expect(command.description).toBe('Display file contents in hexadecimal format'); + expect(command.usage).toBe('hexdump [-C] [-n length] [-s skip] [file...]'); + }); + + it('should show error when no file is specified', async () => { + const result = await command.execute([], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing file operand'); + }); + + it('should show error for non-existent file', async () => { + vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory')); + + const result = await command.execute(['nonexistent.txt'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should show error for directory', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await command.execute(['testdir'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should display hexdump in default format', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('0000000'); + expect(result.stdout).toContain('000000e'); // Final offset + }); + + it('should display hexdump in canonical format with -C', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('|Hello, World!'); + expect(result.stdout).toContain('|'); // Should have ASCII representation + }); + + it('should handle -n length option', async () => { + const content = 'Hello, World!\nThis is a longer line.'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-n', '5', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('|Hello|'); + expect(result.stdout).not.toContain('World'); + }); + + it('should handle -s skip option', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-s', '7', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000007'); + expect(result.stdout).toContain('|World!'); + expect(result.stdout).not.toContain('Hello'); + }); + + it('should handle -n and -s together', async () => { + const content = 'Hello, World!\n'; + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from(content)); + + const result = await command.execute(['-C', '-s', '7', '-n', '5', 'test.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000007'); + expect(result.stdout).toContain('|World|'); + expect(result.stdout).not.toContain('Hello'); + expect(result.stdout).not.toContain('!'); + }); + + it('should show error for invalid -n value', async () => { + const result = await command.execute(['-n', 'invalid'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid length'); + }); + + it('should show error for invalid -s value', async () => { + const result = await command.execute(['-s', 'invalid'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid skip offset'); + }); + + it('should show error for missing -n argument', async () => { + const result = await command.execute(['-n'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('option requires an argument -- n'); + }); + + it('should show error for missing -s argument', async () => { + const result = await command.execute(['-s'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('option requires an argument -- s'); + }); + + it('should show error for invalid option', async () => { + const result = await command.execute(['-x'], testCwd); + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('invalid option -- x'); + }); + + it('should handle multiple files', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile) + .mockResolvedValueOnce(Buffer.from('ABC')) + .mockResolvedValueOnce(Buffer.from('XYZ')); + + const result = await command.execute(['-C', 'file1.txt', 'file2.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('==> file1.txt <=='); + expect(result.stdout).toContain('==> file2.txt <=='); + expect(result.stdout).toContain('|ABC|'); + expect(result.stdout).toContain('|XYZ|'); + }); + + it('should handle piped input', async () => { + const input = 'Hello, World!'; + const result = await command.execute(['-C'], testCwd, input); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('|Hello, World!|'); + }); + + it('should handle binary data correctly', async () => { + // Create binary data with non-printable characters + const binaryData = Buffer.from([0x00, 0x01, 0x02, 0x7F, 0x80, 0xFF, 0x41, 0x42, 0x43]); + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(binaryData); + + const result = await command.execute(['-C', 'binary.dat'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('00000000'); + expect(result.stdout).toContain('00 01 02 7f 80 ff 41 42 43'); + expect(result.stdout).toContain('|......ABC|'); // Non-printable chars shown as dots + }); + + it('should handle empty file', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('')); + + const result = await command.execute(['-C', 'empty.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // No output for empty file + }); + + it('should handle skip beyond file length', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(Buffer.from('Hi')); + + const result = await command.execute(['-C', '-s', '10', 'short.txt'], testCwd); + expect(result.exitCode).toBe(0); + expect(result.stdout).toBe(''); // No output since skip is beyond file + }); +}); \ No newline at end of file diff --git a/src/lib/commands/hexdump.ts b/src/lib/commands/hexdump.ts new file mode 100644 index 00000000..b275a7e5 --- /dev/null +++ b/src/lib/commands/hexdump.ts @@ -0,0 +1,272 @@ +import { join } from "path-browserify"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'hexdump' command + * Display file contents in hexadecimal format + */ +export class HexdumpCommand implements ShellCommand { + name = 'hexdump'; + description = 'Display file contents in hexadecimal format'; + usage = 'hexdump [-C] [-n length] [-s skip] [file...]'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string, input?: string): Promise { + // Parse command line options + const options = this.parseOptions(args); + + if (options.error) { + return createErrorResult(options.error); + } + + // If input is provided (from pipe), process it + if (input !== undefined) { + const buffer = Buffer.from(input, 'utf8'); + const output = this.formatHexdump(buffer, options); + return createSuccessResult(output); + } + + // If no files specified, show usage + if (options.files.length === 0) { + return createErrorResult(`${this.name}: missing file operand\nUsage: ${this.usage}`); + } + + try { + const outputs: string[] = []; + + for (const filePath of options.files) { + try { + // Handle both absolute and relative paths + let absolutePath: string; + + if (filePath.startsWith('/') || filePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(filePath)) { + // It's an absolute path - use it directly + absolutePath = filePath; + } else { + // It's a relative path - resolve it relative to the current working directory + absolutePath = join(cwd, filePath); + } + + // Check if path exists and is a file + const stats = await this.fs.stat(absolutePath); + + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${filePath}: Is a directory`); + } + + // Read file content as binary + const content = await this.fs.readFile(absolutePath); + const buffer = Buffer.from(content); + + // Format the hexdump + const hexOutput = this.formatHexdump(buffer, options); + + // Add filename header if multiple files + if (options.files.length > 1) { + outputs.push(`==> ${filePath} <==`); + outputs.push(hexOutput); + } else { + outputs.push(hexOutput); + } + + } catch (error) { + // Handle file not found or permission errors + if (error instanceof Error) { + if (error.message.includes('ENOENT') || error.message.includes('not found')) { + return createErrorResult(`${this.name}: ${filePath}: No such file or directory`); + } else if (error.message.includes('EACCES') || error.message.includes('permission')) { + return createErrorResult(`${this.name}: ${filePath}: Permission denied`); + } else { + return createErrorResult(`${this.name}: ${filePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${filePath}: Unknown error`); + } + } + } + + const result = outputs.join('\n'); + return createSuccessResult(result); + + } catch (error) { + return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + /** + * Parse command line options + */ + private parseOptions(args: string[]): { + canonical: boolean; + length?: number; + skip: number; + files: string[]; + error?: string; + } { + const options = { + canonical: false, + length: undefined as number | undefined, + skip: 0, + files: [] as string[], + }; + + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-C') { + options.canonical = true; + } else if (arg === '-n') { + // Next argument should be the length + if (i + 1 >= args.length) { + return { ...options, error: `${this.name}: option requires an argument -- n` }; + } + const lengthStr = args[++i]; + const length = parseInt(lengthStr, 10); + if (isNaN(length) || length < 0) { + return { ...options, error: `${this.name}: invalid length: ${lengthStr}` }; + } + options.length = length; + } else if (arg === '-s') { + // Next argument should be the skip offset + if (i + 1 >= args.length) { + return { ...options, error: `${this.name}: option requires an argument -- s` }; + } + const skipStr = args[++i]; + const skip = parseInt(skipStr, 10); + if (isNaN(skip) || skip < 0) { + return { ...options, error: `${this.name}: invalid skip offset: ${skipStr}` }; + } + options.skip = skip; + } else if (arg.startsWith('-')) { + return { ...options, error: `${this.name}: invalid option -- ${arg.slice(1)}` }; + } else { + // It's a filename + options.files.push(arg); + } + } + + return options; + } + + /** + * Format buffer content as hexdump + */ + private formatHexdump(buffer: Buffer, options: { + canonical: boolean; + length?: number; + skip: number; + }): string { + const lines: string[] = []; + const bytesPerLine = 16; + + // Apply skip offset + const startOffset = options.skip; + if (startOffset >= buffer.length) { + return ''; // Nothing to display + } + + // Apply length limit + let endOffset = buffer.length; + if (options.length !== undefined) { + endOffset = Math.min(startOffset + options.length, buffer.length); + } + + for (let offset = startOffset; offset < endOffset; offset += bytesPerLine) { + const lineEnd = Math.min(offset + bytesPerLine, endOffset); + const lineBytes = buffer.subarray(offset, lineEnd); + + if (options.canonical) { + // Canonical format (-C): address, hex bytes, ASCII + lines.push(this.formatCanonicalLine(offset, lineBytes)); + } else { + // Default format: address followed by 16-bit words in hex + lines.push(this.formatDefaultLine(offset, lineBytes)); + } + } + + // Add final offset line if we have data + if (endOffset > startOffset) { + const finalOffset = endOffset; + lines.push(this.formatOffsetLine(finalOffset)); + } + + return lines.join('\n'); + } + + /** + * Format a line in canonical format (-C option) + */ + private formatCanonicalLine(offset: number, bytes: Buffer): string { + const addressStr = offset.toString(16).padStart(8, '0'); + + // Format hex bytes (2 groups of 8 bytes each) + const group1: string[] = []; + const group2: string[] = []; + + for (let i = 0; i < 16; i++) { + const hexByte = i < bytes.length + ? bytes[i].toString(16).padStart(2, '0') + : ' '; + + if (i < 8) { + group1.push(hexByte); + } else { + group2.push(hexByte); + } + } + + const hexStr = group1.join(' ') + ' ' + group2.join(' '); + + // Format ASCII representation + let asciiStr = ''; + for (let i = 0; i < bytes.length; i++) { + const byte = bytes[i]; + if (byte >= 32 && byte <= 126) { + // Printable ASCII character + asciiStr += String.fromCharCode(byte); + } else { + // Non-printable character + asciiStr += '.'; + } + } + + return `${addressStr} ${hexStr} |${asciiStr}|`; + } + + /** + * Format a line in default format + */ + private formatDefaultLine(offset: number, bytes: Buffer): string { + const addressStr = offset.toString(16).padStart(7, '0'); + + // Group bytes into 16-bit words (little-endian) + const words: string[] = []; + for (let i = 0; i < bytes.length; i += 2) { + if (i + 1 < bytes.length) { + // Full 16-bit word (little-endian) + const word = (bytes[i + 1] << 8) | bytes[i]; + words.push(word.toString(16).padStart(4, '0')); + } else { + // Partial word (only one byte) + const word = bytes[i]; + words.push(word.toString(16).padStart(2, '0') + ' '); + } + } + + return `${addressStr} ${words.join(' ')}`; + } + + /** + * Format the final offset line + */ + private formatOffsetLine(offset: number): string { + return offset.toString(16).padStart(7, '0'); + } +} \ No newline at end of file diff --git a/src/lib/commands/index.ts b/src/lib/commands/index.ts index a5da02d3..4d7d68d4 100644 --- a/src/lib/commands/index.ts +++ b/src/lib/commands/index.ts @@ -13,6 +13,7 @@ export { FindCommand } from './find'; export { GitCommand } from './git'; export { GrepCommand } from './grep'; export { HeadCommand } from './head'; +export { HexdumpCommand } from './hexdump'; export { LsCommand } from './ls'; export { MkdirCommand } from './mkdir'; export { MvCommand } from './mv'; @@ -25,4 +26,5 @@ export { TrCommand } from './tr'; export { UniqCommand } from './uniq'; export { WcCommand } from './wc'; export { WhoamiCommand } from './whoami'; -export { WhichCommand } from './which'; \ No newline at end of file +export { WhichCommand } from './which'; +export { UnzipCommand } from './unzip'; \ No newline at end of file diff --git a/src/lib/commands/unzip.test.ts b/src/lib/commands/unzip.test.ts new file mode 100644 index 00000000..8e073139 --- /dev/null +++ b/src/lib/commands/unzip.test.ts @@ -0,0 +1,303 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import JSZip from 'jszip'; +import { UnzipCommand } from './unzip'; +import type { JSRuntimeFS } from '../JSRuntime'; + +// Mock filesystem +const createMockFS = (): JSRuntimeFS => ({ + readFile: vi.fn(), + writeFile: vi.fn(), + readdir: vi.fn(), + mkdir: vi.fn(), + stat: vi.fn(), + lstat: vi.fn(), + unlink: vi.fn(), + rmdir: vi.fn(), + rename: vi.fn(), + readlink: vi.fn(), + symlink: vi.fn(), +}); + +describe('UnzipCommand', () => { + let mockFS: JSRuntimeFS; + let command: UnzipCommand; + + beforeEach(() => { + mockFS = createMockFS(); + command = new UnzipCommand(mockFS); + }); + + const createTestZip = async (files: Record): Promise => { + const zip = new JSZip(); + + for (const [path, content] of Object.entries(files)) { + if (path.endsWith('/')) { + zip.folder(path.slice(0, -1)); + } else { + zip.file(path, content); + } + } + + return zip.generateAsync({ type: 'uint8array' }); + }; + + it('should show usage when no arguments provided', async () => { + const result = await command.execute([], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('missing archive operand'); + expect(result.stderr).toContain('Usage:'); + }); + + it('should show error for invalid options', async () => { + const result = await command.execute(['-x', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("invalid option '-x'"); + }); + + it('should show error for non-existent archive', async () => { + vi.mocked(mockFS.stat).mockRejectedValue(new Error('ENOENT: no such file or directory')); + + const result = await command.execute(['nonexistent.zip'], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('No such file or directory'); + }); + + it('should show error when trying to unzip a directory', async () => { + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => true, + isFile: () => false, + }); + + const result = await command.execute(['testdir'], '/home'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Is a directory'); + }); + + it('should list archive contents with -l option', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World', + 'dir1/': '', + 'dir1/file2.txt': 'Test content' + }); + + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + + const result = await command.execute(['-l', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Archive: test.zip'); + expect(result.stdout).toContain('file1.txt'); + expect(result.stdout).toContain('dir1/'); + expect(result.stdout).toContain('dir1/file2.txt'); + }); + + it('should extract files to current directory', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + // Mock file operations - keep it simple + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await command.execute(['test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('Archive: test.zip'); + expect(result.stdout).toContain('inflating: file1.txt'); + + // Verify writeFile was called for extracted files + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array)); + }); + + it('should handle command line options correctly', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + // Test -d option + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await command.execute(['-d', 'extract', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('inflating: file1.txt'); + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/extract/file1.txt', expect.any(Uint8Array)); + }); + + it('should handle overwrite option', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'New content' + }); + + // Mock file exists scenario + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + // Without -o option, should fail + const resultWithoutOverwrite = await command.execute(['test.zip'], '/home'); + expect(resultWithoutOverwrite.exitCode).toBe(1); + expect(resultWithoutOverwrite.stderr).toContain('File exists (use -o to overwrite)'); + + // Reset mocks + vi.clearAllMocks(); + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }); // file exists + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + // With -o option, should succeed + const resultWithOverwrite = await command.execute(['-o', 'test.zip'], '/home'); + expect(resultWithOverwrite.exitCode).toBe(0); + expect(resultWithOverwrite.stdout).toContain('inflating: file1.txt'); + }); + + it('should prevent extraction outside allowed directories', async () => { + // Since JSZip normalizes paths during creation, we'll test the security logic + // by mocking the internal zip.files object to simulate a malicious ZIP + const zipData = await createTestZip({ + 'normal.txt': 'safe content' + }); + + // Mock the zip loading to return a ZIP with malicious paths + const originalLoadAsync = JSZip.loadAsync; + vi.spyOn(JSZip, 'loadAsync').mockImplementation(async () => { + const zip = new JSZip(); + // Simulate malicious ZIP file entries that would escape the directory + (zip as unknown as { files: Record Promise }> }).files = { + '../../../etc/passwd': { + name: '../../../etc/passwd', + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3])), + }, + '../../outside.txt': { + name: '../../outside.txt', + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6])), + }, + 'normal.txt': { + name: 'normal.txt', + dir: false, + async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9])), + } + }; + return zip; + }); + + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + + const result = await command.execute(['test.zip'], '/home/user'); + + // Should return error because some files were skipped + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain('Path is outside allowed directories'); + expect(result.stderr).toContain('../../../etc/passwd'); + expect(result.stderr).toContain('../../outside.txt'); + + // Should only extract the safe file + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/user/normal.txt', expect.any(Uint8Array)); + expect(mockFS.writeFile).toHaveBeenCalledTimes(1); + + // Restore the original method + JSZip.loadAsync = originalLoadAsync; + }); + + it('should allow extraction to /tmp directory', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockRejectedValueOnce(new Error('ENOENT')) // extraction dir doesn't exist + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + + const result = await command.execute(['-d', '/tmp', 'test.zip'], '/home/user'); + + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain('inflating: file1.txt'); + expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/file1.txt', expect.any(Uint8Array)); + }); + + it('should reject extraction directory outside allowed paths', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World' + }); + + // Mock that the archive exists and provide zip data + vi.mocked(mockFS.stat).mockResolvedValue({ + isDirectory: () => false, + isFile: () => true, + }); + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + + const result = await command.execute(['-d', '/etc', 'test.zip'], '/home/user'); + + expect(result.exitCode).toBe(1); + expect(result.stderr).toContain("extraction directory '/etc' is outside allowed paths"); + }); + + it('should support quiet mode with -q flag', async () => { + const zipData = await createTestZip({ + 'file1.txt': 'Hello World', + 'dir1/': '', + 'dir1/file2.txt': 'Test content' + }); + + vi.mocked(mockFS.stat) + .mockResolvedValueOnce({ isDirectory: () => false, isFile: () => true }) // archive exists + .mockResolvedValueOnce({ isDirectory: () => true, isFile: () => false }) // extraction dir exists + .mockRejectedValue(new Error('ENOENT')); // files don't exist (for overwrite check) + + vi.mocked(mockFS.readFile).mockResolvedValue(zipData); + vi.mocked(mockFS.writeFile).mockResolvedValue(undefined); + vi.mocked(mockFS.mkdir).mockResolvedValue(undefined); + + const result = await command.execute(['-q', 'test.zip'], '/home'); + + expect(result.exitCode).toBe(0); + // In quiet mode, should not show archive header or extraction messages + expect(result.stdout).toBe(''); + + // But files should still be extracted + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/file1.txt', expect.any(Uint8Array)); + expect(mockFS.writeFile).toHaveBeenCalledWith('/home/dir1/file2.txt', expect.any(Uint8Array)); + }); +}); \ No newline at end of file diff --git a/src/lib/commands/unzip.ts b/src/lib/commands/unzip.ts new file mode 100644 index 00000000..d6ddb449 --- /dev/null +++ b/src/lib/commands/unzip.ts @@ -0,0 +1,220 @@ +import { join, dirname, normalize } from "path-browserify"; +import JSZip from "jszip"; +import type { JSRuntimeFS } from "../JSRuntime"; +import type { ShellCommand, ShellCommandResult } from "./ShellCommand"; +import { createSuccessResult, createErrorResult } from "./ShellCommand"; + +/** + * Implementation of the 'unzip' command + * Extract files from ZIP archives + */ +export class UnzipCommand implements ShellCommand { + name = 'unzip'; + description = 'Extract files from ZIP archives'; + usage = 'unzip [-d directory] [-o] [-l] [-q] archive.zip'; + + private fs: JSRuntimeFS; + + constructor(fs: JSRuntimeFS) { + this.fs = fs; + } + + async execute(args: string[], cwd: string): Promise { + if (args.length === 0) { + return createErrorResult(`${this.name}: missing archive operand\nUsage: ${this.usage}`); + } + + let archivePath = ''; + let extractDir = cwd; + let overwrite = false; + let listOnly = false; + let quiet = false; + + // Parse command line options + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + + if (arg === '-d' && i + 1 < args.length) { + // Extract to specific directory + extractDir = args[i + 1]; + i++; // Skip next argument + } else if (arg === '-o') { + // Overwrite existing files + overwrite = true; + } else if (arg === '-l') { + // List archive contents only + listOnly = true; + } else if (arg === '-q') { + // Quiet mode - suppress output + quiet = true; + } else if (arg.startsWith('-')) { + return createErrorResult(`${this.name}: invalid option '${arg}'\nUsage: ${this.usage}`); + } else { + // This should be the archive path + archivePath = arg; + } + } + + if (!archivePath) { + return createErrorResult(`${this.name}: no archive specified\nUsage: ${this.usage}`); + } + + try { + // Resolve archive path + let absoluteArchivePath: string; + if (archivePath.startsWith('/') || archivePath.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(archivePath)) { + absoluteArchivePath = archivePath; + } else { + absoluteArchivePath = join(cwd, archivePath); + } + + // Check if archive exists + try { + const stats = await this.fs.stat(absoluteArchivePath); + if (stats.isDirectory()) { + return createErrorResult(`${this.name}: ${archivePath}: Is a directory`); + } + } catch { + return createErrorResult(`${this.name}: ${archivePath}: No such file or directory`); + } + + // Read the ZIP file + const zipData = await this.fs.readFile(absoluteArchivePath); + const zip = await JSZip.loadAsync(zipData); + + // Resolve extraction directory + let absoluteExtractDir: string; + if (extractDir.startsWith('/') || extractDir.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(extractDir)) { + absoluteExtractDir = extractDir; + } else { + absoluteExtractDir = join(cwd, extractDir); + } + + // Security check: ensure extraction directory is within allowed paths + if (!this.isPathAllowed(absoluteExtractDir, cwd)) { + return createErrorResult(`${this.name}: extraction directory '${extractDir}' is outside allowed paths (cwd or /tmp)`); + } + + if (listOnly) { + // List contents only + const entries: string[] = []; + zip.forEach((relativePath, file) => { + const date = file.date || new Date(); + const type = file.dir ? 'd' : '-'; + const sizeStr = file.dir ? '0' : '?'; + + entries.push(`${type}rw-r--r-- 1 user user ${sizeStr.padStart(8)} ${date.toISOString().slice(0, 19).replace('T', ' ')} ${relativePath}`); + }); + + return createSuccessResult(`Archive: ${archivePath}\n${entries.join('\n')}`); + } + + // Create extraction directory if it doesn't exist + try { + await this.fs.stat(absoluteExtractDir); + } catch { + await this.fs.mkdir(absoluteExtractDir, { recursive: true }); + } + + const extractedFiles: string[] = []; + const errors: string[] = []; + + // Extract all files + for (const [relativePath, file] of Object.entries(zip.files)) { + const extractPath = join(absoluteExtractDir, relativePath); + + // Security check: ensure each file path is within allowed directories + if (!this.isPathAllowed(extractPath, cwd)) { + errors.push(`${this.name}: ${relativePath}: Path is outside allowed directories (skipped for security)`); + continue; + } + + try { + if (file.dir) { + // Create directory + await this.fs.mkdir(extractPath, { recursive: true }); + if (!quiet) { + extractedFiles.push(` creating: ${relativePath}`); + } + } else { + // Check if file exists and handle overwrite + if (!overwrite) { + try { + await this.fs.stat(extractPath); + errors.push(`${this.name}: ${relativePath}: File exists (use -o to overwrite)`); + continue; + } catch { + // File doesn't exist, proceed with extraction + } + } + + // Create parent directories if needed + const parentDir = dirname(extractPath); + try { + await this.fs.stat(parentDir); + } catch { + await this.fs.mkdir(parentDir, { recursive: true }); + } + + // Extract file content + const content = await file.async('uint8array'); + await this.fs.writeFile(extractPath, content); + if (!quiet) { + extractedFiles.push(` inflating: ${relativePath}`); + } + } + } catch (error) { + errors.push(`${this.name}: ${relativePath}: ${error instanceof Error ? error.message : 'Unknown error'}`); + } + } + + let output = ''; + if (!quiet) { + output = `Archive: ${archivePath}\n`; + if (extractedFiles.length > 0) { + output += extractedFiles.join('\n'); + } + } + + if (errors.length > 0) { + if (!quiet && extractedFiles.length > 0) { + output += '\n'; + } + return createErrorResult(output + '\n' + errors.join('\n')); + } + + return createSuccessResult(output); + + } catch (error) { + if (error instanceof Error) { + if (error.message.includes('corrupted') || error.message.includes('invalid')) { + return createErrorResult(`${this.name}: ${archivePath}: Archive is corrupted or invalid`); + } else { + return createErrorResult(`${this.name}: ${archivePath}: ${error.message}`); + } + } else { + return createErrorResult(`${this.name}: ${archivePath}: Unknown error`); + } + } + } + + /** + * Check if a path is within allowed extraction directories (cwd or /tmp and their subdirectories) + */ + private isPathAllowed(extractPath: string, cwd: string): boolean { + // Normalize the paths without using resolve() since we're in browser environment + const normalizedPath = normalize(extractPath); + const normalizedCwd = normalize(cwd); + const tmpPath = '/tmp'; + + // Ensure paths are absolute for comparison + const absolutePath = normalizedPath.startsWith('/') ? normalizedPath : normalize(join(normalizedCwd, normalizedPath)); + const absoluteCwd = normalizedCwd.startsWith('/') ? normalizedCwd : '/' + normalizedCwd; + + // Check if path is within cwd or /tmp + return absolutePath.startsWith(absoluteCwd + '/') || + absolutePath === absoluteCwd || + absolutePath.startsWith(tmpPath + '/') || + absolutePath === tmpPath; + } +} \ No newline at end of file diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index 886217e5..8e1b1296 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -98,8 +98,6 @@ const resources = { getHelp: '🔧 Get help with debugging and optimization', buildDeploy: '🚀 Build and deploy your project', aiNotConfigured: 'AI Assistant Not Configured', - configureAI: 'Please configure your AI settings to start building with AI assistance.', - useMenuForAI: 'Use the menu in the top bar to access AI Settings.', askToAddFeatures: 'Ask me to add features, edit files, or build your project...', selectModelFirst: 'Please select a model to start chatting...', sendMessage: 'Send message', @@ -256,6 +254,11 @@ const resources = { recentlyUsed: 'Recently Used', errorLoadingModels: 'Error Loading Models', + // API Authentication Errors + apiAuthenticationFailed: 'API Authentication Failed', + invalidApiKey: 'Invalid API key for {{provider}}. Please check your API key in Settings.', + checkApiKeySettings: 'Check API Key Settings', + // Context and Cost contextUsage: 'Context usage: {{tokens}} / {{total}} tokens ({{percentage}}%)', totalCostSession: 'Total cost for this chat session', @@ -394,8 +397,6 @@ const resources = { getHelp: '🔧 Obtenha ajuda com depuração e otimização', buildDeploy: '🚀 Construa e implante seu projeto', aiNotConfigured: 'Assistente de IA Não Configurado', - configureAI: 'Configure suas configurações de IA para começar a construir com assistência de IA.', - useMenuForAI: 'Use o menu na barra superior para acessar as Configurações de IA.', askToAddFeatures: 'Peça para adicionar recursos, editar arquivos ou construir seu projeto...', selectModelFirst: 'Selecione um modelo para começar a conversar...', sendMessage: 'Enviar mensagem', @@ -552,6 +553,11 @@ const resources = { recentlyUsed: 'Usados Recentemente', errorLoadingModels: 'Erro ao Carregar Modelos', + // API Authentication Errors + apiAuthenticationFailed: 'Falha na Autenticação da API', + invalidApiKey: 'Chave de API inválida para {{provider}}. Verifique sua chave de API nas Configurações.', + checkApiKeySettings: 'Verificar Configurações da Chave de API', + // Context and Cost contextUsage: 'Uso de contexto: {{tokens}} / {{total}} tokens ({{percentage}}%)', totalCostSession: 'Custo total para esta sessão de chat', @@ -690,8 +696,6 @@ const resources = { getHelp: '🔧 获得调试和优化帮助', buildDeploy: '🚀 构建和部署您的项目', aiNotConfigured: 'AI助手未配置', - configureAI: '请配置您的AI设置以开始使用AI助手构建。', - useMenuForAI: '使用顶部栏中的菜单访问AI设置。', askToAddFeatures: '请我添加功能、编辑文件或构建您的项目...', selectModelFirst: '请先选择一个模型开始聊天...', sendMessage: '发送消息', @@ -848,6 +852,11 @@ const resources = { recentlyUsed: '最近使用', errorLoadingModels: '加载模型时出错', + // API Authentication Errors + apiAuthenticationFailed: 'API身份验证失败', + invalidApiKey: '{{provider}}的API密钥无效。请在设置中检查您的API密钥。', + checkApiKeySettings: '检查API密钥设置', + // Context and Cost contextUsage: '上下文使用:{{tokens}} / {{total}} 令牌 ({{percentage}}%)', totalCostSession: '此聊天会话的总费用', @@ -986,8 +995,6 @@ const resources = { getHelp: '🔧 Sami taimako da gyara kuskure da haɓakawa', buildDeploy: '🚀 Gina da tura aikinku', aiNotConfigured: 'Mataimakin AI Ba a Saita ba', - configureAI: 'Da fatan za a saita saitunan AI don farawa ginawa da taimakon AI.', - useMenuForAI: 'Yi amfani da menu a saman mashigi don shiga Saitunan AI.', askToAddFeatures: 'Roƙe ni in ƙara fasaloli, gyara fayiloli, ko gina aikinku...', selectModelFirst: 'Da fatan za a zaɓi samfuri don farawa hira...', sendMessage: 'Aika saƙo', @@ -1144,6 +1151,11 @@ const resources = { recentlyUsed: 'An yi amfani da su kwanan nan', errorLoadingModels: 'Kuskure wajen Lodin Samfura', + // API Authentication Errors + apiAuthenticationFailed: 'Gazawar Tabbatarwar API', + invalidApiKey: 'Maɓallin API na {{provider}} ba daidai ba ne. Da fatan za a duba maɓallin API a cikin Saitunan.', + checkApiKeySettings: 'Duba Saitunan Maɓallin API', + // Context and Cost contextUsage: 'Amfanin mahallin: {{tokens}} / {{total}} alamomi ({{percentage}}%)', totalCostSession: 'Jimlar farashi don wannan zaman hira', @@ -1282,8 +1294,6 @@ const resources = { getHelp: '🔧 Gba iranlọwọ pẹlu atunṣe ati imudara', buildDeploy: '🚀 Kọ ati gbe iṣẹ akanṣe rẹ lọ', aiNotConfigured: 'Oluranlọwọ AI Ko Tunto', - configureAI: 'Jọwọ tunto awọn eto AI rẹ lati bẹrẹ kikọ pẹlu iranlọwọ AI.', - useMenuForAI: 'Lo akojọ aṣayan ni oke ọpa lati wọle si Awọn eto AI.', askToAddFeatures: 'Beere mi lati fi awọn ẹya kun, ṣatunkọ awọn faili, tabi kọ iṣẹ akanṣe rẹ...', selectModelFirst: 'Jọwọ yan awoṣe lati bẹrẹ ibaraẹnisọrọ...', sendMessage: 'Fi ifiranṣẹ ranṣẹ', @@ -1578,8 +1588,6 @@ const resources = { getHelp: '🔧 Nweta enyemaka na debugging na optimization', buildDeploy: '🚀 Wuo ma bufee ọrụ gị', aiNotConfigured: 'Onye Enyemaka AI Ahazighị', - configureAI: 'Biko hazie ntọala AI gị iji malite iwu na enyemaka AI.', - useMenuForAI: 'Jiri menu dị n\'elu okporo iji nweta Ntọala AI.', askToAddFeatures: 'Rịọ m ka m tinye atụmatụ, dezie faịlụ, ma ọ bụ wuo ọrụ gị...', selectModelFirst: 'Biko họrọ ụdịdị iji malite ikwu okwu...', sendMessage: 'Ziga ozi', diff --git a/src/lib/parseProviderModel.test.ts b/src/lib/parseProviderModel.test.ts index 5065c819..24c64ab4 100644 --- a/src/lib/parseProviderModel.test.ts +++ b/src/lib/parseProviderModel.test.ts @@ -29,9 +29,9 @@ describe('parseProviderModel', () => { it('should parse simple provider/model format', () => { const result = parseProviderModel('openai/gpt-4o', mockProviders); - expect(result.provider).toBe('openai'); expect(result.model).toBe('gpt-4o'); - expect(result.connection).toEqual({ + expect(result.provider).toEqual({ + id: 'openai', baseURL: mockProviders[0].baseURL, apiKey: mockProviders[0].apiKey, nostr: mockProviders[0].nostr, @@ -41,9 +41,9 @@ describe('parseProviderModel', () => { it('should parse complex model names with slashes', () => { const result = parseProviderModel('openrouter/anthropic/claude-sonnet-4', mockProviders); - expect(result.provider).toBe('openrouter'); expect(result.model).toBe('anthropic/claude-sonnet-4'); - expect(result.connection).toEqual({ + expect(result.provider).toEqual({ + id: 'openrouter', baseURL: mockProviders[1].baseURL, apiKey: mockProviders[1].apiKey, nostr: mockProviders[1].nostr, @@ -53,9 +53,9 @@ describe('parseProviderModel', () => { it('should handle model names with multiple slashes', () => { const result = parseProviderModel('openrouter/meta/llama-3.1-405b-instruct', mockProviders); - expect(result.provider).toBe('openrouter'); expect(result.model).toBe('meta/llama-3.1-405b-instruct'); - expect(result.connection).toEqual({ + expect(result.provider).toEqual({ + id: 'openrouter', baseURL: mockProviders[1].baseURL, apiKey: mockProviders[1].apiKey, nostr: mockProviders[1].nostr, diff --git a/src/lib/parseProviderModel.ts b/src/lib/parseProviderModel.ts index 06ed9015..a3a49b9b 100644 --- a/src/lib/parseProviderModel.ts +++ b/src/lib/parseProviderModel.ts @@ -1,13 +1,8 @@ import type { AIProvider } from '@/contexts/AISettingsContext'; export interface ParsedProviderModel { - provider: string; model: string; - connection: { - baseURL: string; - apiKey?: string; - nostr?: boolean; - }; + provider: AIProvider; } /** @@ -25,25 +20,20 @@ export function parseProviderModel( throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")'); } - const provider = providerModelString.substring(0, firstSlashIndex); + const providerId = providerModelString.substring(0, firstSlashIndex); const model = providerModelString.substring(firstSlashIndex + 1); - if (!provider || !model) { + if (!providerId || !model) { throw new Error('Invalid format. Both provider and model must be specified'); } - const providerObj = providers.find(p => p.id === provider); - if (!providerObj) { - throw new Error(`Provider "${provider}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`); + const provider = providers.find(p => p.id === providerId); + if (!provider) { + throw new Error(`Provider "${providerId}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`); } return { - provider, model, - connection: { - baseURL: providerObj.baseURL, - apiKey: providerObj.apiKey, - nostr: providerObj.nostr, - }, + provider, }; } \ No newline at end of file diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index ba5d4e65..e3d50167 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -44,7 +44,7 @@ describe('ShellTool', () => { }); it('should have correct tool properties', () => { - expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators'); + expect(shellTool.description).toBe('Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators'); expect(shellTool.inputSchema).toBeDefined(); }); diff --git a/src/lib/tools/ShellTool.ts b/src/lib/tools/ShellTool.ts index d722ccf4..78d1a24e 100644 --- a/src/lib/tools/ShellTool.ts +++ b/src/lib/tools/ShellTool.ts @@ -18,6 +18,7 @@ import { GitCommand, GrepCommand, HeadCommand, + HexdumpCommand, LsCommand, MkdirCommand, MvCommand, @@ -28,6 +29,7 @@ import { TouchCommand, TrCommand, UniqCommand, + UnzipCommand, WcCommand, WhoamiCommand, WhichCommand @@ -46,7 +48,7 @@ export class ShellTool implements Tool { private git: Git; private commands: Map; - readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl. Supports compound commands with &&, ||, ;, and | operators"; + readonly description = "Execute shell commands like cat, ls, cd, pwd, rm, cp, mv, echo, head, tail, grep, find, wc, touch, mkdir, sort, uniq, cut, tr, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators"; readonly inputSchema = z.object({ command: z.string().describe( @@ -75,6 +77,7 @@ export class ShellTool implements Tool { this.registerCommand(new GitCommand({ git: this.git, fs, cwd: this.cwd })); this.registerCommand(new GrepCommand(fs)); this.registerCommand(new HeadCommand(fs)); + this.registerCommand(new HexdumpCommand(fs)); this.registerCommand(new LsCommand(fs)); this.registerCommand(new MkdirCommand(fs)); this.registerCommand(new MvCommand(fs)); @@ -85,6 +88,7 @@ export class ShellTool implements Tool { this.registerCommand(new TouchCommand(fs)); this.registerCommand(new TrCommand(fs)); this.registerCommand(new UniqCommand(fs)); + this.registerCommand(new UnzipCommand(fs)); this.registerCommand(new WcCommand(fs)); this.registerCommand(new WhoamiCommand()); diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index b9fd172c..5f44f3d9 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -144,8 +144,7 @@ function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpe
onOpenCreditsDialog(provider.id)} /> @@ -178,6 +197,7 @@ export function ProjectView() { projectId={project.id} projectName={project.name} onNewChat={handleNewChat} + onProjectDetails={() => setIsProjectDetailsOpen(true)} isLoading={isAILoading} isBuildLoading={build.isPending} onFirstInteraction={handleFirstInteraction} @@ -303,12 +323,12 @@ export function ProjectView() {
- {/* Project Info Dialog */} + {/* Project Details Dialog */} {project && ( - )} @@ -365,7 +385,7 @@ export function ProjectView() { @@ -388,6 +408,7 @@ export function ProjectView() { projectId={project.id} projectName={project.name} onNewChat={handleNewChat} + onProjectDetails={() => setIsProjectDetailsOpen(true)} isLoading={isAILoading} isBuildLoading={build.isPending} onFirstInteraction={handleFirstInteraction} @@ -460,12 +481,12 @@ export function ProjectView() { - {/* Project Info Dialog */} + {/* Project Details Dialog */} {project && ( - )}