mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-03 07:57:22 +00:00
Compare commits
10
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
898c6a8286 | ||
|
|
7f14194ae4 | ||
|
|
2ea05addcc | ||
|
|
9507177aaa | ||
|
|
669bbb8a1f | ||
|
|
15567ee4cf | ||
|
|
2d163e8fed | ||
|
|
f6f9a0038b | ||
|
|
c26f447072 | ||
|
|
3253b198c7 |
No files matched your search
@@ -1,6 +1,6 @@
|
||||
import { memo, useState } from 'react';
|
||||
import { Streamdown } from 'streamdown';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2, Logs } from 'lucide-react';
|
||||
import { Wrench, Eye, FileText, Edit, Package, PackageMinus, GitCommit, BookOpen, Download, Hash, Tag, Network, List, Plus, Terminal, Globe, CheckCircle, Lightbulb, Loader2 } from 'lucide-react';
|
||||
import type { AIMessage } from '@/lib/SessionManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { UserMessage } from '@/components/UserMessage';
|
||||
@@ -150,11 +150,6 @@ export const AIMessageItem = memo(({
|
||||
icon: CheckCircle,
|
||||
title: 'TypeScript'
|
||||
};
|
||||
case 'read_console_messages':
|
||||
return {
|
||||
icon: Logs,
|
||||
title: 'Read Console'
|
||||
};
|
||||
default:
|
||||
return {
|
||||
icon: Wrench,
|
||||
|
||||
@@ -5,9 +5,9 @@ import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
|
||||
// import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
// import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||
|
||||
interface Act1DialogProps {
|
||||
open: boolean;
|
||||
@@ -22,39 +22,44 @@ const SHAKESPEARE_PROVIDER = {
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
// const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
|
||||
const MKSTACK_NSP_ADDR = '31999:4bcaa7b5606e3c14df05cd497e588f5d3fe559b4e9a425e8b418a43af1ffb015:mkstack';
|
||||
|
||||
export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
const [step, setStep] = useState<DialogStep>('welcome');
|
||||
// const { setProvider, updateSettings } = useAISettings();
|
||||
const [isSettingUp, setIsSettingUp] = useState(false);
|
||||
const { setProvider, updateSettings } = useAISettings();
|
||||
|
||||
// // Get the selectedNSPAddr from localStorage
|
||||
// const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
|
||||
// Get the selectedNSPAddr from localStorage
|
||||
const [selectedNSPAddr] = useLocalStorage<string | null>('selectedNSPAddr', null);
|
||||
|
||||
// Get user's credits
|
||||
const { data: creditsData } = useAICredits(SHAKESPEARE_PROVIDER);
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
setIsSettingUp(true);
|
||||
|
||||
try {
|
||||
// // Add Shakespeare provider to their config
|
||||
// setProvider(SHAKESPEARE_PROVIDER);
|
||||
// Add Shakespeare provider to their config
|
||||
setProvider(SHAKESPEARE_PROVIDER);
|
||||
|
||||
// // Configure recently used models based on credits or NSP
|
||||
// const hasCredits = creditsData?.amount && creditsData.amount > 0;
|
||||
// const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
|
||||
// Configure recently used models based on credits or NSP
|
||||
const hasCredits = creditsData?.amount && creditsData.amount > 0;
|
||||
const hasMKStackNSP = selectedNSPAddr === MKSTACK_NSP_ADDR;
|
||||
|
||||
// if (hasCredits || hasMKStackNSP) {
|
||||
// // User has credits or MKStack NSP - set to shakespeare model
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
|
||||
// } else {
|
||||
// // No credits - set to tybalt model (free)
|
||||
// updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
|
||||
// }
|
||||
if (hasCredits || hasMKStackNSP) {
|
||||
// User has credits or MKStack NSP - set to shakespeare model
|
||||
updateSettings({ recentlyUsedModels: ['shakespeare/shakespeare'] });
|
||||
} else {
|
||||
// No credits - set to tybalt model (free)
|
||||
updateSettings({ recentlyUsedModels: ['shakespeare/tybalt'] });
|
||||
}
|
||||
|
||||
// Move to migration step
|
||||
setStep('migration');
|
||||
} catch (error) {
|
||||
console.error('Failed to configure Shakespeare provider:', error);
|
||||
} finally {
|
||||
setIsSettingUp(false);
|
||||
}
|
||||
};
|
||||
|
||||
@@ -82,6 +87,7 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('welcome');
|
||||
setIsSettingUp(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
@@ -120,6 +126,12 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
<span className="text-xl">
|
||||
{step === 'welcome' && 'Welcome to Shakespeare: Act 2! 🎭'}
|
||||
{step === 'migration' && 'Migrating Your Projects'}
|
||||
{step === 'credits' && 'Your Credits'}
|
||||
{step === 'conclusion' && "You're All Set!"}
|
||||
</span>
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
@@ -185,10 +197,21 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
|
||||
<Button
|
||||
onClick={handleGetStarted}
|
||||
disabled={isSettingUp}
|
||||
size="lg"
|
||||
className="gap-2"
|
||||
>
|
||||
Next
|
||||
{isSettingUp ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
|
||||
Setting up...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Sparkles className="h-4 w-4" />
|
||||
Configure Act 2
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
@@ -320,7 +343,14 @@ export function Act1Dialog({ open, onOpenChange }: Act1DialogProps) {
|
||||
<div className="space-y-3">
|
||||
<h2 className="text-2xl font-bold">Welcome to the Future!</h2>
|
||||
<p className="text-lg text-muted-foreground max-w-md mx-auto">
|
||||
You're all up to speed with Act 2! Get ready to build amazing Nostr applications.
|
||||
You're all set up with Act 2! Your AI assistant is configured
|
||||
and ready to help you build amazing Nostr applications.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="bg-muted/50 rounded-lg p-4 max-w-md mx-auto">
|
||||
<p className="text-sm text-muted-foreground italic">
|
||||
"Create a decentralized social media app with custom feeds and real-time messaging..."
|
||||
</p>
|
||||
</div>
|
||||
|
||||
|
||||
@@ -1,103 +0,0 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { render, screen } from '@testing-library/react';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
import { OnboardingCreditsBadge } from './OnboardingCreditsBadge';
|
||||
import type { UseQueryResult } from '@tanstack/react-query';
|
||||
import type { CreditsResponse } from '@/hooks/useAICredits';
|
||||
|
||||
// Mock the useAICredits hook
|
||||
vi.mock('@/hooks/useAICredits', () => ({
|
||||
useAICredits: vi.fn(),
|
||||
}));
|
||||
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
|
||||
const mockUseAICredits = vi.mocked(useAICredits);
|
||||
|
||||
describe('OnboardingCreditsBadge', () => {
|
||||
const mockProvider = {
|
||||
id: 'shakespeare',
|
||||
baseURL: 'https://ai.shakespeare.diy/v1',
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
it('renders credits badge when data is available', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: { object: 'credits', amount: 25.50 },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('$25.50')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('does not render when loading', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: true,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render when there is an error', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
error: new Error('Provider does not support credits'),
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render when no credits data is available', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: undefined,
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
|
||||
it('does not render when credits amount is 0', () => {
|
||||
mockUseAICredits.mockReturnValue({
|
||||
data: { object: 'credits', amount: 0 },
|
||||
isLoading: false,
|
||||
error: null,
|
||||
} as UseQueryResult<CreditsResponse, Error>);
|
||||
|
||||
const { container } = render(
|
||||
<TestApp>
|
||||
<OnboardingCreditsBadge provider={mockProvider} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(container.firstChild).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -1,42 +0,0 @@
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { useAICredits } from '@/hooks/useAICredits';
|
||||
|
||||
interface OnboardingCreditsBadgeProps {
|
||||
provider: AIProvider;
|
||||
className?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Displays a non-clickable credits badge for onboarding showing the remaining credits for an AI provider
|
||||
*/
|
||||
export function OnboardingCreditsBadge({ provider, className }: OnboardingCreditsBadgeProps) {
|
||||
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) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Don't render if no credits data is available or if amount is 0
|
||||
if (!credits || credits.amount === 0) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Format the amount as currency
|
||||
const formattedAmount = new Intl.NumberFormat('en-US', {
|
||||
style: 'currency',
|
||||
currency: 'USD',
|
||||
minimumFractionDigits: 2,
|
||||
maximumFractionDigits: 2,
|
||||
}).format(credits.amount);
|
||||
|
||||
return (
|
||||
<Badge
|
||||
variant="secondary"
|
||||
className={`text-xs ${className}`}
|
||||
>
|
||||
{formattedAmount}
|
||||
</Badge>
|
||||
);
|
||||
}
|
||||
@@ -1,100 +1,60 @@
|
||||
import { Decimal } from 'decimal.js';
|
||||
import { useState, useEffect, useRef } from 'react';
|
||||
import { useState, useEffect } from 'react';
|
||||
import { generateSecretKey } from 'nostr-tools';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft, ExternalLink } from 'lucide-react';
|
||||
import { Bot, Check, Sparkles, ArrowRight, ArrowLeft } from 'lucide-react';
|
||||
import { Dialog, DialogContent, DialogHeader, DialogTitle } from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { Badge } from '@/components/ui/badge';
|
||||
import { Skeleton } from '@/components/ui/skeleton';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { useAISettings } from '@/hooks/useAISettings';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useLoginActions } from '@/hooks/useLoginActions';
|
||||
import { useProviderModels } from '@/hooks/useProviderModels';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
import { OnboardingCreditsBadge } from '@/components/OnboardingCreditsBadge';
|
||||
import { ShakespeareLogo } from '@/components/ShakespeareLogo';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface OnboardingDialogProps {
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
}
|
||||
|
||||
type OnboardingStep = 'welcome' | 'open-source' | 'provider-selection' | 'model-selection' | 'conclusion';
|
||||
type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion';
|
||||
|
||||
const SHAKESPEARE_PROVIDER = {
|
||||
id: "shakespeare",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
};
|
||||
|
||||
export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) {
|
||||
const [step, setStep] = useState<OnboardingStep>('welcome');
|
||||
const [selectedProvider, setSelectedProvider] = useState<PresetProvider | null>(null);
|
||||
const [providerApiKey, setProviderApiKey] = useState<string>('');
|
||||
const [selectedModel, setSelectedModel] = useState<string>('');
|
||||
const [isSettingUp, setIsSettingUp] = useState(false);
|
||||
const [showCreditsDialog, setShowCreditsDialog] = useState(false);
|
||||
const [agreedToTerms, setAgreedToTerms] = useState(false);
|
||||
const [agreedToProviderTerms, setAgreedToProviderTerms] = useState(false);
|
||||
|
||||
// Ref for the scrollable content area
|
||||
const scrollableContentRef = useRef<HTMLDivElement>(null);
|
||||
|
||||
const { setProvider, addRecentlyUsedModel } = useAISettings();
|
||||
const { user } = useCurrentUser();
|
||||
const login = useLoginActions();
|
||||
const { models, isLoading: isLoadingModels } = useProviderModels();
|
||||
|
||||
// Filter models to only show selected provider models
|
||||
const providerModels = selectedProvider
|
||||
? models.filter(model => model.provider === selectedProvider.id)
|
||||
: [];
|
||||
|
||||
const handleGetStarted = () => {
|
||||
setStep('open-source');
|
||||
};
|
||||
|
||||
const handleContinueFromOpenSource = () => {
|
||||
if (!agreedToTerms) return;
|
||||
setStep('provider-selection');
|
||||
};
|
||||
|
||||
const handleProviderSelect = (provider: PresetProvider) => {
|
||||
setSelectedProvider(provider);
|
||||
// Clear API key when switching providers
|
||||
setProviderApiKey('');
|
||||
// Reset provider terms agreement when switching providers
|
||||
setAgreedToProviderTerms(false);
|
||||
};
|
||||
|
||||
const handleContinueFromProviderSelection = async () => {
|
||||
if (!selectedProvider) return;
|
||||
|
||||
// Check if user agreed to provider terms
|
||||
if (!agreedToProviderTerms) return;
|
||||
|
||||
// Check if provider requires API key and if it's provided
|
||||
const requiresApiKey = selectedProvider.apiKeysURL && !selectedProvider.nostr;
|
||||
if (requiresApiKey && !providerApiKey.trim()) return;
|
||||
// Filter models to only show Shakespeare provider models
|
||||
const shakespeareModels = models.filter(model => model.provider === 'shakespeare');
|
||||
|
||||
const handleGetStarted = async () => {
|
||||
setIsSettingUp(true);
|
||||
|
||||
try {
|
||||
// If user is not logged in and provider uses Nostr auth, generate and login with secret key
|
||||
if (!user && selectedProvider.nostr) {
|
||||
// If user is not logged in, generate and login with secret key
|
||||
if (!user) {
|
||||
const secretKey = generateSecretKey();
|
||||
const nsec = nip19.nsecEncode(secretKey);
|
||||
login.nsec(nsec);
|
||||
}
|
||||
|
||||
// Add selected provider to their config
|
||||
const providerConfig = {
|
||||
id: selectedProvider.id,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
apiKey: requiresApiKey ? providerApiKey.trim() : undefined,
|
||||
};
|
||||
setProvider(providerConfig);
|
||||
// Add Shakespeare provider to their config
|
||||
setProvider(SHAKESPEARE_PROVIDER);
|
||||
|
||||
// Move to model selection
|
||||
setStep('model-selection');
|
||||
@@ -116,7 +76,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
addRecentlyUsedModel(selectedModel);
|
||||
|
||||
// Find the selected model to check if it's free
|
||||
const model = providerModels.find(m => m.fullId === selectedModel);
|
||||
const model = shakespeareModels.find(m => m.fullId === selectedModel);
|
||||
const isFreeModel = !model?.pricing || (
|
||||
model.pricing.prompt.equals(0) && model.pricing.completion.equals(0)
|
||||
);
|
||||
@@ -151,54 +111,23 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
useEffect(() => {
|
||||
if (open) {
|
||||
setStep('welcome');
|
||||
setSelectedProvider(null);
|
||||
setProviderApiKey('');
|
||||
setSelectedModel('');
|
||||
setIsSettingUp(false);
|
||||
setShowCreditsDialog(false);
|
||||
setAgreedToTerms(false);
|
||||
setAgreedToProviderTerms(false);
|
||||
}
|
||||
}, [open]);
|
||||
|
||||
// Scroll to top when step changes
|
||||
useEffect(() => {
|
||||
if (scrollableContentRef.current) {
|
||||
scrollableContentRef.current.scrollTop = 0;
|
||||
}
|
||||
}, [step]);
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="max-w-2xl h-[100dvh] sm:h-auto sm:max-h-[90vh] flex flex-col">
|
||||
<DialogContent className="max-w-2xl max-h-[90vh] sm:max-h-[80vh] flex flex-col">
|
||||
<DialogHeader className="flex-shrink-0">
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
{step === 'open-source' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('welcome')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'provider-selection' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('open-source')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
</Button>
|
||||
)}
|
||||
{step === 'model-selection' && (
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => setStep('provider-selection')}
|
||||
onClick={() => setStep('welcome')}
|
||||
className="mr-2 p-1 h-auto"
|
||||
>
|
||||
<ArrowLeft className="h-4 w-4" />
|
||||
@@ -220,7 +149,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</DialogTitle>
|
||||
</DialogHeader>
|
||||
|
||||
<div ref={scrollableContentRef} className="flex-1 overflow-y-auto min-h-0">
|
||||
<div className="flex-1 overflow-y-auto min-h-0">
|
||||
{step === 'welcome' && (
|
||||
<div className="text-center space-y-6 py-4">
|
||||
<div className="mb-4">
|
||||
@@ -272,210 +201,6 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'open-source' && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">Shakespeare is Open Source software that runs entirely in your web browser</h2>
|
||||
</div>
|
||||
|
||||
<div className="grid gap-1 max-w-md mx-auto">
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Your browser connects directly to third-party AI providers of your choice</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Your files are stored on your device in your browser</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Be careful not to delete your browser data or you may lose project files</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">You are responsible for taking backups or syncing to git</p>
|
||||
</div>
|
||||
<div className="flex items-start gap-3 p-3 rounded-lg bg-muted/50">
|
||||
<div className="h-2 w-2 rounded-full bg-primary mt-2 flex-shrink-0" />
|
||||
<p className="text-sm">Quality of output depends on quality of input and models used, and is not guaranteed</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<p className="text-xs text-muted-foreground max-w-xl mx-auto">
|
||||
Shakespeare is not a cloud service. It's Open Source software that runs in your web browser.
|
||||
You agree to the Terms of Service of AI providers you interact with.
|
||||
Shakespeare is provided "as is" without warranty of any kind.
|
||||
</p>
|
||||
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Checkbox
|
||||
id="agree-terms"
|
||||
checked={agreedToTerms}
|
||||
onCheckedChange={(checked) => setAgreedToTerms(checked === true)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
I agree
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleContinueFromOpenSource}
|
||||
disabled={!agreedToTerms}
|
||||
className="gap-2 rounded-full w-full max-w-md"
|
||||
>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'provider-selection' && (
|
||||
<div className="space-y-6 py-4">
|
||||
<div className="text-center space-y-4">
|
||||
<h2 className="text-2xl font-bold">Choose your AI provider</h2>
|
||||
<p className="text-muted-foreground max-w-md mx-auto">
|
||||
Select an AI provider to power your development assistant. You can add more providers later in settings.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 p-1 gap-3 max-w-4xl mx-auto">
|
||||
{AI_PROVIDER_PRESETS.map((provider) => {
|
||||
const isSelected = selectedProvider?.id === provider.id;
|
||||
const isShakespeare = provider.id === 'shakespeare';
|
||||
|
||||
return (
|
||||
<Card
|
||||
key={provider.id}
|
||||
className={cn('cursor-pointer transition-all hover:shadow-md', {
|
||||
'ring-2 ring-primary': isSelected,
|
||||
})}
|
||||
onClick={() => handleProviderSelect(provider)}
|
||||
>
|
||||
<div className="flex items-center justify-between p-3">
|
||||
<div className="flex-1">
|
||||
<CardTitle className={cn('text-lg font-semibold', {
|
||||
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isShakespeare,
|
||||
})}>
|
||||
{provider.name}
|
||||
</CardTitle>
|
||||
</div>
|
||||
<div className="flex items-center gap-2">
|
||||
<OnboardingCreditsBadge provider={provider} />
|
||||
{isSelected && (
|
||||
<div className="h-5 w-5 rounded-full bg-primary flex items-center justify-center">
|
||||
<Check className="h-3 w-3 text-primary-foreground" />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</div>
|
||||
|
||||
{/* API Key Input Section */}
|
||||
{selectedProvider && selectedProvider.apiKeysURL && !selectedProvider.nostr && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="text-center">
|
||||
<h3 className="text-lg font-semibold">
|
||||
{selectedProvider.id === 'routstr' ? 'Enter Cashu Token' : 'Enter API Key'}
|
||||
</h3>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedProvider.id === 'routstr' ? (
|
||||
<>{selectedProvider.name} requires a Cashu token</>
|
||||
) : (
|
||||
<>
|
||||
{selectedProvider.name} requires an {selectedProvider.apiKeysURL ? (
|
||||
<a className="text-foreground underline" href={selectedProvider.apiKeysURL} target="_blank">
|
||||
API key
|
||||
<ExternalLink className="inline-block h-4 w-4 ml-1" />
|
||||
</a>
|
||||
) : (
|
||||
<>API key</>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
</p>
|
||||
</div>
|
||||
<PasswordInput
|
||||
placeholder={selectedProvider.id === 'routstr' ? 'Enter a Cashu Token' : 'Enter your API key'}
|
||||
value={providerApiKey}
|
||||
onChange={(e) => setProviderApiKey(e.target.value)}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && providerApiKey.trim()) {
|
||||
handleContinueFromProviderSelection();
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
{selectedProvider && (
|
||||
<div className="space-y-3 max-w-md mx-auto">
|
||||
<div className="flex items-center justify-center gap-2">
|
||||
<Checkbox
|
||||
id="agree-provider-terms"
|
||||
checked={agreedToProviderTerms}
|
||||
onCheckedChange={(checked) => setAgreedToProviderTerms(checked === true)}
|
||||
/>
|
||||
<label
|
||||
htmlFor="agree-provider-terms"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
I agree to {selectedProvider.name}'s{' '}
|
||||
{selectedProvider.tosURL ? (
|
||||
<a
|
||||
href={selectedProvider.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-primary underline hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
Terms of Service
|
||||
</a>
|
||||
) : (
|
||||
'Terms of Service'
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="flex justify-center">
|
||||
<Button
|
||||
onClick={handleContinueFromProviderSelection}
|
||||
disabled={
|
||||
!selectedProvider ||
|
||||
isSettingUp ||
|
||||
!agreedToProviderTerms ||
|
||||
!!(selectedProvider?.apiKeysURL && !selectedProvider?.nostr && !providerApiKey.trim())
|
||||
}
|
||||
className="gap-2 rounded-full w-full max-w-md"
|
||||
>
|
||||
{isSettingUp ? (
|
||||
<>
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-white" />
|
||||
Setting up...
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
Continue
|
||||
<ArrowRight className="h-4 w-4" />
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{step === 'model-selection' && (
|
||||
<div className="flex flex-col h-full">
|
||||
<div className="flex-1 overflow-y-auto min-h-0 my-4">
|
||||
@@ -498,7 +223,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</Card>
|
||||
))}
|
||||
</>
|
||||
) : providerModels.length === 0 ? (
|
||||
) : shakespeareModels.length === 0 ? (
|
||||
<Card className="p-6 text-center">
|
||||
<div className="space-y-2">
|
||||
<Bot className="h-8 w-8 mx-auto text-muted-foreground" />
|
||||
@@ -508,11 +233,10 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</Card>
|
||||
) : (
|
||||
providerModels.map((model) => {
|
||||
shakespeareModels.map((model) => {
|
||||
const isSelected = selectedModel === model.fullId;
|
||||
const isFree = model.pricing?.prompt.equals(0) && model.pricing?.completion.equals(0);
|
||||
const isPremium = !!model.pricing && !isFree;
|
||||
const modelName = model.name || model.id;
|
||||
const isPremium = !isFree;
|
||||
|
||||
return (
|
||||
<Card
|
||||
@@ -522,19 +246,15 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
}`}
|
||||
onClick={() => handleModelSelect(model.fullId)}
|
||||
>
|
||||
<CardHeader>
|
||||
<CardHeader className="pb-3">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="flex-1">
|
||||
<CardTitle className={cn('text-xl font-semibold', {
|
||||
'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent': isPremium,
|
||||
})}>
|
||||
{modelName}
|
||||
<CardTitle className={`text-xl font-semibold ${isPremium ? 'bg-gradient-to-r from-primary to-accent bg-clip-text text-transparent' : ''}`}>
|
||||
{ model.name || model.description || model.id}
|
||||
</CardTitle>
|
||||
{model.description && (
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
{model.description.length > 70
|
||||
? model.description.slice(0, 70) + '...'
|
||||
: model.description}
|
||||
{model.description || model.id}
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
@@ -557,21 +277,19 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</div>
|
||||
</CardHeader>
|
||||
{(model.pricing || model.contextLength) && (
|
||||
<CardContent className="pt-0">
|
||||
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<div className="text-right">
|
||||
<div>Input: {formatPrice(model.pricing.prompt)}</div>
|
||||
<div>Output: {formatPrice(model.pricing.completion)}</div>
|
||||
</div>
|
||||
)}
|
||||
{model.contextLength && (
|
||||
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
)}
|
||||
<CardContent className="pt-0">
|
||||
<div className="flex items-end justify-end gap-4 text-xs text-muted-foreground">
|
||||
{model.pricing && (
|
||||
<div className="text-right">
|
||||
<div>Input: {formatPrice(model.pricing.prompt)}</div>
|
||||
<div>Output: {formatPrice(model.pricing.completion)}</div>
|
||||
</div>
|
||||
)}
|
||||
{model.contextLength && (
|
||||
<span>Context: {model.contextLength.toLocaleString()} tokens</span>
|
||||
)}
|
||||
</div>
|
||||
</CardContent>
|
||||
</Card>
|
||||
);
|
||||
})
|
||||
@@ -579,7 +297,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex justify-end gap-2 pt-4 flex-shrink-0">
|
||||
<div className="flex justify-end gap-2 pt-4 border-t flex-shrink-0">
|
||||
<Button
|
||||
onClick={handleContinue}
|
||||
disabled={!selectedModel}
|
||||
@@ -613,7 +331,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
</Dialog>
|
||||
|
||||
{/* Credits Dialog */}
|
||||
{showCreditsDialog && selectedModel && selectedProvider && (
|
||||
{showCreditsDialog && selectedModel && (
|
||||
<CreditsDialog
|
||||
open={showCreditsDialog}
|
||||
onOpenChange={(open) => {
|
||||
@@ -621,11 +339,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps)
|
||||
handleCreditsDialogClose();
|
||||
}
|
||||
}}
|
||||
provider={{
|
||||
id: selectedProvider.id,
|
||||
baseURL: selectedProvider.baseURL,
|
||||
nostr: selectedProvider.nostr || undefined,
|
||||
}}
|
||||
provider={SHAKESPEARE_PROVIDER}
|
||||
/>
|
||||
)}
|
||||
</>
|
||||
|
||||
@@ -0,0 +1,685 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { ScrollArea } from '@/components/ui/scroll-area';
|
||||
import { Upload, FileArchive, AlertCircle, FileText, Trash2, FolderOpen, CheckSquare, Square, AlertTriangle } from 'lucide-react';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { cn } from '@/lib/utils';
|
||||
import JSZip from 'jszip';
|
||||
|
||||
interface ProjectInfo {
|
||||
id: string;
|
||||
name: string;
|
||||
path: string;
|
||||
files: string[];
|
||||
isConflict: boolean;
|
||||
selected: boolean;
|
||||
}
|
||||
|
||||
interface ProjectImportDialogProps {
|
||||
mode?: 'single' | 'bulk';
|
||||
onImport: (data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] }, overwrite: boolean) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ProjectImportDialog({
|
||||
mode = 'single',
|
||||
onImport,
|
||||
disabled = false,
|
||||
className,
|
||||
open,
|
||||
onOpenChange
|
||||
}: ProjectImportDialogProps) {
|
||||
// Use controlled state if props are provided, otherwise use internal state
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(false);
|
||||
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [discoveredProjects, setDiscoveredProjects] = useState<ProjectInfo[]>([]);
|
||||
const [isAnalyzing, setIsAnalyzing] = useState(false);
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||
const [zipData, setZipData] = useState<JSZip | null>(null);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { data: existingProjects = [] } = useProjects();
|
||||
const projectsManager = useProjectsManager();
|
||||
|
||||
// Analyze ZIP for bulk import
|
||||
const analyzeZipForProjects = useCallback(async (zip: JSZip): Promise<ProjectInfo[]> => {
|
||||
const projects: ProjectInfo[] = [];
|
||||
const projectPaths = new Set<string>();
|
||||
|
||||
// Find all potential project directories
|
||||
for (const [path] of Object.entries(zip.files)) {
|
||||
const pathParts = path.split('/').filter(part => part !== '');
|
||||
|
||||
// Skip files in root directory - we're looking for project directories
|
||||
if (pathParts.length < 2) continue;
|
||||
|
||||
// Check if this looks like a project indicator file
|
||||
if (isProjectIndicator(path)) {
|
||||
let projectPath: string;
|
||||
|
||||
// If structure is projects/project-name/file, extract project-name
|
||||
if (pathParts[0] === 'projects' && pathParts.length >= 3) {
|
||||
projectPath = `projects/${pathParts[1]}`;
|
||||
} else {
|
||||
// Otherwise, assume first directory is the project
|
||||
projectPath = pathParts[0];
|
||||
}
|
||||
|
||||
projectPaths.add(projectPath);
|
||||
}
|
||||
}
|
||||
|
||||
// For each discovered project path, gather information
|
||||
for (const projectPath of projectPaths) {
|
||||
const files: string[] = [];
|
||||
|
||||
// Collect all files in this project directory
|
||||
for (const [path, zipEntry] of Object.entries(zip.files)) {
|
||||
if (path.startsWith(projectPath + '/') && !zipEntry.dir) {
|
||||
const relativePath = path.substring(projectPath.length + 1);
|
||||
files.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
// Generate project ID and name from directory path
|
||||
let id: string;
|
||||
let name: string;
|
||||
|
||||
if (projectPath.startsWith('projects/')) {
|
||||
const projectName = projectPath.substring('projects/'.length);
|
||||
id = projectName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
name = projectName;
|
||||
} else {
|
||||
id = projectPath
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
name = projectPath;
|
||||
}
|
||||
|
||||
// Skip if no files found (empty directory)
|
||||
if (files.length === 0) continue;
|
||||
|
||||
// Check if this project conflicts with existing projects
|
||||
const isConflict = existingProjects.some(existing => existing.id === id);
|
||||
|
||||
projects.push({
|
||||
id,
|
||||
name,
|
||||
path: projectPath,
|
||||
files,
|
||||
isConflict,
|
||||
selected: !isConflict, // Auto-select non-conflicting projects
|
||||
});
|
||||
}
|
||||
|
||||
return projects;
|
||||
}, [existingProjects]);
|
||||
|
||||
// Handle file selection
|
||||
const handleFileSelect = useCallback(async (file: File) => {
|
||||
// Only accept zip files
|
||||
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||
setError('Please select a ZIP file');
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setError(null);
|
||||
setGeneratedId('');
|
||||
|
||||
// Auto-generate ID from file name for single mode
|
||||
if (mode === 'single') {
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setGeneratedId(id);
|
||||
}
|
||||
|
||||
// For bulk mode, analyze the ZIP to discover projects
|
||||
if (mode === 'bulk') {
|
||||
setIsAnalyzing(true);
|
||||
setDiscoveredProjects([]);
|
||||
|
||||
try {
|
||||
const arrayBuffer = await file.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
setZipData(zip);
|
||||
|
||||
const projects = await analyzeZipForProjects(zip);
|
||||
setDiscoveredProjects(projects);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to analyze ZIP file');
|
||||
} finally {
|
||||
setIsAnalyzing(false);
|
||||
}
|
||||
}
|
||||
}, [mode, analyzeZipForProjects]);
|
||||
|
||||
|
||||
const isProjectIndicator = (path: string): boolean => {
|
||||
const indicators = [
|
||||
'package.json',
|
||||
'index.html',
|
||||
'src/',
|
||||
'public/',
|
||||
'tsconfig.json',
|
||||
'vite.config.',
|
||||
'webpack.config.',
|
||||
'README.md',
|
||||
'.git/',
|
||||
];
|
||||
|
||||
return indicators.some(indicator => path.includes('/' + indicator));
|
||||
};
|
||||
|
||||
// Check for existing project when generated ID changes (single mode)
|
||||
useEffect(() => {
|
||||
if (mode === 'single' && generatedId && existingProjects.length > 0) {
|
||||
const existing = existingProjects.find(project => project.id === generatedId);
|
||||
if (existing) {
|
||||
setError(`A project with ID "${generatedId}" already exists. You can choose to overwrite it.`);
|
||||
} else {
|
||||
setError(null);
|
||||
}
|
||||
}
|
||||
}, [generatedId, existingProjects, mode]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, [handleFileSelect]);
|
||||
|
||||
const handleClickUpload = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileRemove = () => {
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setDiscoveredProjects([]);
|
||||
setZipData(null);
|
||||
setError(null);
|
||||
};
|
||||
|
||||
// Bulk import project selection handlers
|
||||
const handleProjectToggle = (projectId: string, checked: boolean) => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project =>
|
||||
project.id === projectId ? { ...project, selected: checked } : project
|
||||
)
|
||||
);
|
||||
};
|
||||
|
||||
const handleSelectAll = () => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project => ({ ...project, selected: true }))
|
||||
);
|
||||
};
|
||||
|
||||
const handleDeselectAll = () => {
|
||||
setDiscoveredProjects(prev =>
|
||||
prev.map(project => ({ ...project, selected: false }))
|
||||
);
|
||||
};
|
||||
|
||||
const selectedProjects = discoveredProjects.filter(project => project.selected);
|
||||
const conflictingProjects = selectedProjects.filter(project => project.isConflict);
|
||||
|
||||
const handleImport = async (overwrite = false) => {
|
||||
if (!selectedFile) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
if (mode === 'single') {
|
||||
// Single project import
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||
}, 200);
|
||||
|
||||
await onImport({ file: selectedFile, projectId: generatedId }, overwrite);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
} else {
|
||||
// Bulk project import
|
||||
const projectsToImport = await Promise.all(
|
||||
selectedProjects.map(async (project) => {
|
||||
const files = await projectsManager.extractFilesFromZip(zipData!, project.path);
|
||||
return {
|
||||
id: project.id,
|
||||
files,
|
||||
};
|
||||
})
|
||||
);
|
||||
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 5, 90));
|
||||
}, 100);
|
||||
|
||||
await onImport({ projects: projectsToImport }, overwrite);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
}
|
||||
|
||||
// Close dialog and reset state immediately
|
||||
setIsOpen(false);
|
||||
handleFileRemove();
|
||||
setImportProgress(0);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import projects');
|
||||
setImportProgress(0);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
if (mode === 'single') {
|
||||
// For single mode, check if project exists
|
||||
const existingProject = existingProjects.find(project => project.id === generatedId);
|
||||
if (existingProject) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
} else {
|
||||
// For bulk mode, check for conflicts
|
||||
if (conflictingProjects.length > 0) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const confirmOverwrite = async () => {
|
||||
setShowOverwriteDialog(false);
|
||||
await handleImport(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isImporting && !isAnalyzing) {
|
||||
setIsOpen(false);
|
||||
handleFileRemove();
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||
|
||||
const canImport = mode === 'single'
|
||||
? selectedFile && generatedId
|
||||
: selectedProjects.length > 0;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn("gap-2", className)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
{mode === 'single' ? 'Import ZIP' : 'Import Projects'}
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent className={cn(
|
||||
"h-auto max-h-[90vh] flex flex-col",
|
||||
mode === 'single' ? "sm:max-w-md" : "sm:max-w-xl"
|
||||
)}>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
{mode === 'single' ? 'Import Project from ZIP' : 'Import Multiple Projects'}
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
{mode === 'single'
|
||||
? 'Upload a ZIP file containing your project source code to import it into Shakespeare.'
|
||||
: 'Upload a ZIP file containing multiple projects to import them into Shakespeare.'
|
||||
}
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex-1 flex flex-col overflow-hidden min-h-0 space-y-4">
|
||||
{!isImporting && !isAnalyzing && (
|
||||
<>
|
||||
{/* Drag and Drop Area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-4 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||
)}
|
||||
onClick={handleClickUpload}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}}
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
disabled={isImporting || isAnalyzing}
|
||||
/>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
<FileText className="h-6 w-6 text-green-600" />
|
||||
) : (
|
||||
<Upload className="h-6 w-6 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-green-600">
|
||||
{selectedFile.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop your ZIP file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{mode === 'single'
|
||||
? 'Supports ZIP files up to 50MB'
|
||||
: 'Supports ZIP files containing exported Shakespeare projects'
|
||||
}
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-amber-600 mb-4">
|
||||
<AlertTriangle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Project List (Bulk Mode Only) */}
|
||||
{mode === 'bulk' && discoveredProjects.length > 0 && (
|
||||
<div className="space-y-3 flex-1 flex flex-col min-h-0">
|
||||
<div className="flex items-center justify-between flex-shrink-0">
|
||||
<h3 className="text-sm font-medium">
|
||||
Found {discoveredProjects.length} project{discoveredProjects.length !== 1 ? 's' : ''}
|
||||
</h3>
|
||||
<div className="flex gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleSelectAll}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<CheckSquare className="h-3 w-3 mr-1" />
|
||||
Select All
|
||||
</Button>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleDeselectAll}
|
||||
className="h-8 text-xs"
|
||||
>
|
||||
<Square className="h-3 w-3 mr-1" />
|
||||
Deselect All
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="border rounded-lg overflow-hidden">
|
||||
<ScrollArea className="h-64">
|
||||
<div className="p-2 space-y-1">
|
||||
{discoveredProjects.map((project) => (
|
||||
<div
|
||||
key={project.id}
|
||||
className={cn(
|
||||
"flex items-start space-x-3 p-2 rounded-lg border transition-colors",
|
||||
project.selected ? "bg-primary/5 border-primary/20" : "bg-background",
|
||||
project.isConflict && "border-amber-200 bg-amber-50/50 dark:border-amber-800 dark:bg-amber-950/20"
|
||||
)}
|
||||
>
|
||||
<Checkbox
|
||||
id={`project-${project.id}`}
|
||||
checked={project.selected}
|
||||
onCheckedChange={(checked) => handleProjectToggle(project.id, checked as boolean)}
|
||||
className="mt-1"
|
||||
/>
|
||||
<div className="flex-1 min-w-0 space-y-1">
|
||||
<div className="flex items-center gap-2">
|
||||
<FolderOpen className="h-4 w-4 text-primary flex-shrink-0" />
|
||||
<span className="font-medium text-sm truncate">{project.name}</span>
|
||||
{project.isConflict && (
|
||||
<div className="hidden sm:flex items-center gap-1 text-amber-600 flex-shrink-0">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs">Conflict</span>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{project.isConflict && (
|
||||
<div className="sm:hidden flex items-center gap-1 text-amber-600">
|
||||
<AlertTriangle className="h-3 w-3" />
|
||||
<span className="text-xs font-medium">Conflict - Will overwrite existing project</span>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{project.files.length} file{project.files.length !== 1 ? 's' : ''}
|
||||
{project.isConflict && <span className="hidden sm:inline"> • Will overwrite existing project</span>}
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</ScrollArea>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
{selectedFile && (mode === 'single' || discoveredProjects.length > 0) && (
|
||||
<div className="flex justify-end gap-2 pt-3 border-t flex-shrink-0">
|
||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!canImport || isImporting}
|
||||
className={mode === 'single' && error ? "bg-amber-600 hover:bg-amber-700" : conflictingProjects.length > 0 ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{mode === 'single' ? (
|
||||
error ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Overwrite Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Project
|
||||
</>
|
||||
)
|
||||
) : (
|
||||
<>
|
||||
{conflictingProjects.length > 0 ? <Trash2 className="mr-2 h-4 w-4" /> : <Upload className="mr-2 h-4 w-4" />}
|
||||
{conflictingProjects.length > 0 ? 'Import & Overwrite' : 'Import Projects'} ({selectedProjects.length})
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Analysis Progress (Bulk Mode Only) */}
|
||||
{mode === 'bulk' && isAnalyzing && (
|
||||
<div className="space-y-2 py-6">
|
||||
<div className="flex items-center gap-2 text-sm justify-center">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||
Analyzing ZIP file...
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Discovering projects and checking for conflicts...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Progress */}
|
||||
{isImporting && (
|
||||
<div className="space-y-3 py-6">
|
||||
<div className="flex items-center gap-2 text-sm justify-center">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div >
|
||||
{mode === 'single' ? 'Importing project...' : `Importing ${selectedProjects.length} project${selectedProjects.length !== 1 ? 's' : ''}...`}
|
||||
</div>
|
||||
<Progress value={importProgress} className="w-full" />
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Extracting files and setting up projects...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success State */}
|
||||
{!isImporting && !isAnalyzing && importProgress === 100 && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600 justify-center py-3">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
{mode === 'single' ? 'Project imported successfully!' : 'Projects imported successfully!'}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Overwrite Confirmation Dialog */}
|
||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||
{mode === 'single' ? 'Overwrite Existing Project' : 'Overwrite Existing Projects'}
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-3">
|
||||
{mode === 'single' ? (
|
||||
<>
|
||||
<p>
|
||||
A project with ID "<strong>{generatedId}</strong>" already exists.
|
||||
Overwriting it will:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in project</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<p>
|
||||
You have selected <strong>{conflictingProjects.length}</strong> project{conflictingProjects.length !== 1 ? 's' : ''} that already exist:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2 max-h-32 overflow-y-auto">
|
||||
{conflictingProjects.map((project) => (
|
||||
<li key={project.id}>
|
||||
<strong>{project.name}</strong> (ID: {project.id})
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
<p>Overwriting will:</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in these projects</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
</>
|
||||
)}
|
||||
<p className="text-amber-600 font-medium">
|
||||
This action cannot be undone. Are you sure you want to continue?
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmOverwrite}
|
||||
className="bg-amber-600 hover:bg-amber-700"
|
||||
>
|
||||
Yes, {mode === 'single' ? 'Overwrite Project' : 'Overwrite Projects'}
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -118,8 +118,6 @@ export function ProjectSidebar({
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
}, [favorites, queryClient]);
|
||||
@@ -251,8 +249,6 @@ export function ProjectSidebar({
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -203,7 +203,6 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
isLoading: internalIsLoading,
|
||||
totalCost,
|
||||
lastInputTokens,
|
||||
addMessage,
|
||||
sendMessage,
|
||||
startGeneration,
|
||||
stopGeneration,
|
||||
@@ -217,33 +216,9 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
});
|
||||
|
||||
// Handle console error help requests
|
||||
const handleConsoleErrorHelp = useCallback(async () => {
|
||||
const tool = new ReadConsoleMessagesTool();
|
||||
const toolCallId = `call_${crypto.randomUUID().replace(/-/g, '')}`;
|
||||
|
||||
await addMessage({
|
||||
role: 'assistant',
|
||||
content: 'Let me take a look at the console messages to help diagnose the issue.',
|
||||
tool_calls: [
|
||||
{
|
||||
id: toolCallId,
|
||||
type: 'function',
|
||||
function: {
|
||||
name: 'read_console_messages',
|
||||
arguments: '{}',
|
||||
}
|
||||
}
|
||||
]
|
||||
});
|
||||
|
||||
await addMessage({
|
||||
role: 'tool',
|
||||
content: await tool.execute({ filter: 'error' }),
|
||||
tool_call_id: toolCallId,
|
||||
});
|
||||
|
||||
await startGeneration(providerModel);
|
||||
}, [addMessage, providerModel, startGeneration]);
|
||||
const handleConsoleErrorHelp = useCallback(() => {
|
||||
sendMessage('Read the console messages and fix any errors present.', providerModel);
|
||||
}, [sendMessage, providerModel]);
|
||||
|
||||
// Handle error dismissal
|
||||
const handleErrorDismiss = useCallback(() => {
|
||||
@@ -300,12 +275,10 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
setIsModelSelectorOpen(true);
|
||||
}, []);
|
||||
|
||||
// Scroll to bottom when any error occurs (AI error or console error)
|
||||
// Scroll to bottom when AI error occurs
|
||||
useEffect(() => {
|
||||
if (displayError) {
|
||||
scrollToBottom();
|
||||
}
|
||||
}, [displayError, scrollToBottom]);
|
||||
scrollToBottom();
|
||||
}, [aiError, scrollToBottom]);
|
||||
|
||||
// Check for autostart parameter and trigger AI generation
|
||||
useEffect(() => {
|
||||
|
||||
@@ -497,12 +497,6 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
try {
|
||||
await fs.writeFile(`/projects/${projectId}/${selectedFile}`, content);
|
||||
setFileContent(content);
|
||||
|
||||
// Automatically trigger a rebuild after saving a file
|
||||
if (isPreviewable) {
|
||||
console.log('File saved, triggering rebuild...');
|
||||
handleBuildProject();
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to save file:', error);
|
||||
}
|
||||
@@ -532,7 +526,7 @@ export function PreviewPane({ projectId, activeTab, onToggleView, projectName, o
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-8 w-8 p-0 relative"
|
||||
className="h-8 w-8 p-0 relative hover:bg-accent hover:text-accent-foreground transition-colors"
|
||||
>
|
||||
<Bug className="h-4 w-4" />
|
||||
{hasErrors && (
|
||||
|
||||
@@ -1,203 +0,0 @@
|
||||
import { describe, it, expect, vi, beforeEach } from 'vitest';
|
||||
import { render, screen, fireEvent, waitFor } from '@testing-library/react';
|
||||
import { ZipImportDialog } from './ZipImportDialog';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the useProjects hook
|
||||
const mockProjects = [
|
||||
{ id: 'test-project', name: 'Test Project', path: '/projects/test-project', lastModified: new Date() }
|
||||
];
|
||||
|
||||
vi.mock('@/hooks/useProjects', () => ({
|
||||
useProjects: () => ({
|
||||
data: mockProjects,
|
||||
isLoading: false,
|
||||
error: null
|
||||
})
|
||||
}));
|
||||
|
||||
describe('ZipImportDialog', () => {
|
||||
const mockOnImport = vi.fn();
|
||||
const defaultProps = {
|
||||
onImport: mockOnImport,
|
||||
disabled: false
|
||||
};
|
||||
|
||||
beforeEach(() => {
|
||||
mockOnImport.mockClear();
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
it('renders dialog trigger button', () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
expect(screen.getByText('Import ZIP')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
it('opens dialog when trigger is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Import Project from ZIP')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('processes file selection without displaying project ID', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'my-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
// Verify that the file name is displayed (from the file selection area)
|
||||
expect(screen.getByText('my-project.zip')).toBeInTheDocument();
|
||||
// Verify that Project ID label is not displayed
|
||||
expect(screen.queryByText('Project ID')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('shows overwrite warning when project ID already exists', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file that will generate an existing project ID
|
||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText(/A project with this ID already exists/)).toBeInTheDocument();
|
||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
|
||||
it('calls onImport with correct parameters when import button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file
|
||||
const file = new File(['test content'], 'new-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for file to be processed
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('new-project.zip')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click import button
|
||||
const importButton = screen.getByText('Import Project');
|
||||
fireEvent.click(importButton);
|
||||
|
||||
await waitFor(() => {
|
||||
expect(mockOnImport).toHaveBeenCalledWith(file, false, "new-project");
|
||||
});
|
||||
});
|
||||
|
||||
it('shows overwrite confirmation dialog when overwrite button is clicked', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Create a mock file that will generate an existing project ID
|
||||
const file = new File(['test content'], 'test-project.zip', { type: 'application/zip' });
|
||||
|
||||
// Find the hidden file input by ref
|
||||
const fileInput = document.querySelector('input[type="file"][accept=".zip"]');
|
||||
|
||||
if (fileInput) {
|
||||
fireEvent.change(fileInput, { target: { files: [file] } });
|
||||
}
|
||||
|
||||
// Wait for overwrite button to appear
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overwrite Project')).toBeInTheDocument();
|
||||
});
|
||||
|
||||
// Click overwrite button
|
||||
const overwriteButton = screen.getByText('Overwrite Project');
|
||||
fireEvent.click(overwriteButton);
|
||||
|
||||
// Check for overwrite confirmation dialog
|
||||
await waitFor(() => {
|
||||
expect(screen.getByText('Overwrite Existing Project')).toBeInTheDocument();
|
||||
// Use a more flexible matcher for the text that might be split across elements
|
||||
const dialogContent = screen.getByText('Overwrite Existing Project').closest('.AlertDialogContent');
|
||||
if (dialogContent) {
|
||||
expect(dialogContent.textContent).toContain('A project with the ID "test-project" already exists');
|
||||
}
|
||||
}, { timeout: 2000 });
|
||||
});
|
||||
|
||||
it('does not show project ID input field (simplified interface)', async () => {
|
||||
render(
|
||||
<TestApp>
|
||||
<ZipImportDialog {...defaultProps} />
|
||||
</TestApp>
|
||||
);
|
||||
|
||||
// Open dialog
|
||||
const triggerButton = screen.getByText('Import ZIP');
|
||||
fireEvent.click(triggerButton);
|
||||
|
||||
// Check that there's no input field for project ID
|
||||
expect(screen.queryByLabelText('Project ID')).not.toBeInTheDocument();
|
||||
expect(screen.queryByPlaceholderText('project-name')).not.toBeInTheDocument();
|
||||
});
|
||||
});
|
||||
@@ -1,397 +0,0 @@
|
||||
import React, { useState, useRef, useCallback, useEffect } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog';
|
||||
import { Progress } from '@/components/ui/progress';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle } from '@/components/ui/alert-dialog';
|
||||
import { Upload, FileArchive, AlertCircle, FileText, Trash2 } from 'lucide-react';
|
||||
import { useProjects } from '@/hooks/useProjects';
|
||||
import { cn } from '@/lib/utils';
|
||||
|
||||
interface ZipImportDialogProps {
|
||||
onImport: (file: File, overwrite?: boolean, projectId?: string) => Promise<void>;
|
||||
disabled?: boolean;
|
||||
className?: string;
|
||||
open?: boolean;
|
||||
onOpenChange?: (open: boolean) => void;
|
||||
}
|
||||
|
||||
export function ZipImportDialog({ onImport, disabled = false, className, open, onOpenChange }: ZipImportDialogProps) {
|
||||
// Use controlled state if props are provided, otherwise use internal state
|
||||
const [internalIsOpen, setInternalIsOpen] = useState(false);
|
||||
const isOpen = open !== undefined ? open : internalIsOpen;
|
||||
const setIsOpen = onOpenChange || setInternalIsOpen;
|
||||
const [selectedFile, setSelectedFile] = useState<File | null>(null);
|
||||
const [generatedId, setGeneratedId] = useState('');
|
||||
const [isImporting, setIsImporting] = useState(false);
|
||||
const [importProgress, setImportProgress] = useState(0);
|
||||
const [error, setError] = useState<string | null>(null);
|
||||
const [isDragOver, setIsDragOver] = useState(false);
|
||||
const [existingProject, setExistingProject] = useState<{ id: string; name: string } | null>(null);
|
||||
const [showOverwriteDialog, setShowOverwriteDialog] = useState(false);
|
||||
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||
const { data: projects = [] } = useProjects();
|
||||
|
||||
const handleFileSelect = (file: File) => {
|
||||
// Only accept zip files
|
||||
if (!file.name.toLowerCase().endsWith('.zip')) {
|
||||
setError('Please select a ZIP file');
|
||||
return;
|
||||
}
|
||||
|
||||
setSelectedFile(file);
|
||||
setError(null);
|
||||
|
||||
// Auto-generate ID from file name
|
||||
const baseName = file.name.replace(/\.zip$/i, '');
|
||||
const id = baseName
|
||||
.toLowerCase()
|
||||
.replace(/[^a-z0-9]+/g, '-')
|
||||
.replace(/^-+|-+$/g, '');
|
||||
setGeneratedId(id);
|
||||
};
|
||||
|
||||
// Check for existing project when generated ID changes
|
||||
useEffect(() => {
|
||||
if (generatedId && projects.length > 0) {
|
||||
const existing = projects.find(project => project.id === generatedId);
|
||||
setExistingProject(existing || null);
|
||||
} else {
|
||||
setExistingProject(null);
|
||||
}
|
||||
}, [generatedId, projects]);
|
||||
|
||||
// Drag and drop handlers
|
||||
const handleDragOver = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeave = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDrop = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleDragOverDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(true);
|
||||
}, []);
|
||||
|
||||
const handleDragLeaveDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
}, []);
|
||||
|
||||
const handleDropDialog = useCallback((e: React.DragEvent) => {
|
||||
e.preventDefault();
|
||||
e.stopPropagation();
|
||||
setIsDragOver(false);
|
||||
|
||||
const files = Array.from(e.dataTransfer.files);
|
||||
if (files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleClickUpload = () => {
|
||||
fileInputRef.current?.click();
|
||||
};
|
||||
|
||||
const handleFileRemove = () => {
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
};
|
||||
|
||||
const handleImport = async (overwrite = false) => {
|
||||
if (!selectedFile) return;
|
||||
|
||||
setIsImporting(true);
|
||||
setImportProgress(0);
|
||||
setError(null);
|
||||
|
||||
try {
|
||||
// Simulate progress for better UX
|
||||
const progressInterval = setInterval(() => {
|
||||
setImportProgress(prev => Math.min(prev + 10, 90));
|
||||
}, 200);
|
||||
|
||||
await onImport(selectedFile, overwrite, generatedId);
|
||||
|
||||
clearInterval(progressInterval);
|
||||
setImportProgress(100);
|
||||
|
||||
// Close dialog after a short delay
|
||||
setTimeout(() => {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setImportProgress(0);
|
||||
setExistingProject(null);
|
||||
}, 1000);
|
||||
} catch (err) {
|
||||
setError(err instanceof Error ? err.message : 'Failed to import project');
|
||||
setImportProgress(0);
|
||||
} finally {
|
||||
setIsImporting(false);
|
||||
}
|
||||
};
|
||||
|
||||
const handleImportWithOverwriteCheck = async () => {
|
||||
if (!selectedFile || !generatedId) return;
|
||||
|
||||
// Check if project with this ID already exists
|
||||
try {
|
||||
// This would ideally be passed as a prop or through context
|
||||
// For now, we'll assume the parent will handle the check and pass existing project info
|
||||
if (existingProject) {
|
||||
setShowOverwriteDialog(true);
|
||||
} else {
|
||||
await handleImport(false);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Error checking existing project:', error);
|
||||
await handleImport(false);
|
||||
}
|
||||
};
|
||||
|
||||
const confirmOverwrite = async () => {
|
||||
setShowOverwriteDialog(false);
|
||||
await handleImport(true);
|
||||
};
|
||||
|
||||
const handleClose = () => {
|
||||
if (!isImporting) {
|
||||
setIsOpen(false);
|
||||
setSelectedFile(null);
|
||||
setGeneratedId('');
|
||||
setError(null);
|
||||
setImportProgress(0);
|
||||
}
|
||||
};
|
||||
|
||||
// Only render DialogTrigger if this component is being used in uncontrolled mode
|
||||
// (no open/onOpenChange props provided)
|
||||
const isControlled = open !== undefined && onOpenChange !== undefined;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={isOpen} onOpenChange={setIsOpen}>
|
||||
{!isControlled && (
|
||||
<DialogTrigger asChild>
|
||||
<Button
|
||||
variant="outline"
|
||||
disabled={disabled}
|
||||
className={cn("gap-2", className)}
|
||||
>
|
||||
<FileArchive className="h-4 w-4" />
|
||||
Import ZIP
|
||||
</Button>
|
||||
</DialogTrigger>
|
||||
)}
|
||||
|
||||
<DialogContent
|
||||
className="sm:max-w-md"
|
||||
onDragOver={handleDragOverDialog}
|
||||
onDragLeave={handleDragLeaveDialog}
|
||||
onDrop={handleDropDialog}
|
||||
>
|
||||
<DialogHeader>
|
||||
<DialogTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Project from ZIP
|
||||
</DialogTitle>
|
||||
<DialogDescription>
|
||||
Upload a ZIP file containing your project source code to import it into Shakespeare.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="space-y-4">
|
||||
{!isImporting && (
|
||||
<>
|
||||
{/* Drag and Drop Area */}
|
||||
<div
|
||||
className={cn(
|
||||
"relative border-2 border-dashed rounded-lg p-8 text-center transition-colors cursor-pointer",
|
||||
isDragOver ? "border-primary bg-primary/5" : "border-muted-foreground/25 hover:border-primary/50 hover:bg-primary/5",
|
||||
selectedFile && "border-green-500/50 bg-green-500/5"
|
||||
)}
|
||||
onClick={handleClickUpload}
|
||||
onDragOver={handleDragOver}
|
||||
onDragLeave={handleDragLeave}
|
||||
onDrop={handleDrop}
|
||||
>
|
||||
<input
|
||||
ref={fileInputRef}
|
||||
type="file"
|
||||
onChange={(e) => {
|
||||
const files = e.target.files;
|
||||
if (files && files.length > 0) {
|
||||
handleFileSelect(files[0]);
|
||||
}
|
||||
}}
|
||||
accept=".zip"
|
||||
className="hidden"
|
||||
disabled={isImporting}
|
||||
/>
|
||||
|
||||
<div className="space-y-3">
|
||||
<div className="flex justify-center">
|
||||
{selectedFile ? (
|
||||
<FileText className="h-8 w-8 text-green-600" />
|
||||
) : (
|
||||
<Upload className="h-8 w-8 text-muted-foreground" />
|
||||
)}
|
||||
</div>
|
||||
|
||||
<div>
|
||||
{selectedFile ? (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium text-green-600">
|
||||
{selectedFile.name}
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
{(selectedFile.size / 1024 / 1024).toFixed(2)} MB
|
||||
</p>
|
||||
<button
|
||||
onClick={(e) => {
|
||||
e.stopPropagation();
|
||||
handleFileRemove();
|
||||
}}
|
||||
className="text-xs text-destructive hover:underline"
|
||||
>
|
||||
Remove file
|
||||
</button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-1">
|
||||
<p className="text-sm font-medium">
|
||||
Drop your ZIP file here or click to browse
|
||||
</p>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Supports ZIP files up to 50MB
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{/* Error Display */}
|
||||
{error && (
|
||||
<div className="flex items-center gap-2 text-sm text-destructive">
|
||||
<AlertCircle className="h-4 w-4" />
|
||||
{error}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Overwrite Warning */}
|
||||
{existingProject && (
|
||||
<div className="flex items-center gap-2 text-xs text-amber-600 bg-amber-50 dark:bg-amber-950/20 p-2 rounded">
|
||||
<AlertCircle className="h-3 w-3" />
|
||||
A project with this ID already exists. You can choose to overwrite it.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Import Button */}
|
||||
<div className="flex justify-end gap-2 pt-4">
|
||||
<Button variant="outline" onClick={handleClose} disabled={isImporting}>
|
||||
Cancel
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handleImportWithOverwriteCheck}
|
||||
disabled={!selectedFile || !generatedId || isImporting}
|
||||
className={existingProject ? "bg-amber-600 hover:bg-amber-700" : ""}
|
||||
>
|
||||
{existingProject ? (
|
||||
<>
|
||||
<Trash2 className="mr-2 h-4 w-4" />
|
||||
Overwrite Project
|
||||
</>
|
||||
) : (
|
||||
<>
|
||||
<Upload className="mr-2 h-4 w-4" />
|
||||
Import Project
|
||||
</>
|
||||
)}
|
||||
</Button>
|
||||
</div>
|
||||
</>
|
||||
)}
|
||||
|
||||
{/* Import Progress */}
|
||||
{isImporting && (
|
||||
<div className="space-y-3">
|
||||
<div className="flex items-center gap-2 text-sm">
|
||||
<div className="animate-spin rounded-full h-4 w-4 border-b-2 border-primary"></div>
|
||||
Importing project...
|
||||
</div>
|
||||
<Progress value={importProgress} className="w-full" />
|
||||
<p className="text-xs text-muted-foreground text-center">
|
||||
Extracting files and setting up project...
|
||||
</p>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Success State */}
|
||||
{!isImporting && importProgress === 100 && (
|
||||
<div className="flex items-center gap-2 text-sm text-green-600">
|
||||
<svg className="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
|
||||
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M5 13l4 4L19 7"></path>
|
||||
</svg>
|
||||
Project imported successfully!
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Overwrite Confirmation Dialog */}
|
||||
<AlertDialog open={showOverwriteDialog} onOpenChange={setShowOverwriteDialog}>
|
||||
<AlertDialogContent>
|
||||
<AlertDialogHeader>
|
||||
<AlertDialogTitle className="flex items-center gap-2">
|
||||
<AlertCircle className="h-5 w-5 text-amber-600" />
|
||||
Overwrite Existing Project
|
||||
</AlertDialogTitle>
|
||||
<AlertDialogDescription className="space-y-2">
|
||||
<p>
|
||||
A project with the ID "<strong>{generatedId}</strong>" already exists.
|
||||
Overwriting it will:
|
||||
</p>
|
||||
<ul className="list-disc list-inside text-sm space-y-1 ml-2">
|
||||
<li><strong>Delete all existing files</strong> in the project</li>
|
||||
<li><strong>Replace them with files</strong> from the ZIP archive</li>
|
||||
<li><strong>Preserve Git history</strong> if it exists</li>
|
||||
<li><strong>Keep AI chat history</strong> and session data</li>
|
||||
</ul>
|
||||
<p className="text-amber-600 font-medium">
|
||||
This action cannot be undone. Are you sure you want to continue?
|
||||
</p>
|
||||
</AlertDialogDescription>
|
||||
</AlertDialogHeader>
|
||||
<AlertDialogFooter>
|
||||
<AlertDialogCancel>Cancel</AlertDialogCancel>
|
||||
<AlertDialogAction
|
||||
onClick={confirmOverwrite}
|
||||
className="bg-amber-600 hover:bg-amber-700"
|
||||
>
|
||||
Yes, Overwrite Project
|
||||
</AlertDialogAction>
|
||||
</AlertDialogFooter>
|
||||
</AlertDialogContent>
|
||||
</AlertDialog>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -9,10 +9,10 @@ export const buttonVariants = cva(
|
||||
destructive:
|
||||
"bg-destructive text-destructive-foreground hover:bg-destructive/90",
|
||||
outline:
|
||||
"border border-input bg-background hover:bg-border/20 dark:hover:bg-border/50",
|
||||
"border border-input bg-background hover:bg-accent hover:text-accent-foreground",
|
||||
secondary:
|
||||
"bg-secondary text-secondary-foreground hover:bg-secondary/80",
|
||||
ghost: "",
|
||||
ghost: "hover:bg-accent hover:text-accent-foreground",
|
||||
link: "text-primary underline-offset-4 hover:underline",
|
||||
},
|
||||
size: {
|
||||
|
||||
@@ -36,6 +36,6 @@ export function useAICredits(provider: AIProvider) {
|
||||
retry: false, // Don't retry as not all providers support this endpoint
|
||||
refetchOnWindowFocus: false,
|
||||
staleTime: 5 * 60 * 1000, // 5 minutes
|
||||
enabled: !!provider.nostr && !!user,
|
||||
enabled: provider.id === 'shakespeare' && !!user,
|
||||
});
|
||||
}
|
||||
@@ -3,6 +3,7 @@ import { ProjectsManager } from './ProjectsManager';
|
||||
import { JSRuntimeFS } from './JSRuntime';
|
||||
import { Git } from './git';
|
||||
import type { NPool } from '@nostrify/nostrify';
|
||||
import type JSZip from 'jszip';
|
||||
|
||||
const createMockNostr = (): NPool => ({
|
||||
req: vi.fn(),
|
||||
@@ -438,65 +439,48 @@ describe('ProjectsManager', () => {
|
||||
vi.restoreAllMocks();
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('cloneProject', () => {
|
||||
it('should clean up project directory when clone fails', async () => {
|
||||
it('should prevent zip slip attacks during bulk file extraction', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Mock git.clone to fail
|
||||
const mockGit = {
|
||||
clone: vi.fn().mockRejectedValue(new Error('Clone failed')),
|
||||
} as Partial<import('./git').Git>;
|
||||
// Create a mock ZIP with malicious paths for bulk import
|
||||
const mockZip = {
|
||||
files: {
|
||||
'projects/project1/../../../etc/passwd': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([1, 2, 3]))
|
||||
},
|
||||
'projects/project1/../../outside.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([4, 5, 6]))
|
||||
},
|
||||
'projects/project1/safe-file.txt': {
|
||||
dir: false,
|
||||
async: vi.fn().mockResolvedValue(new Uint8Array([7, 8, 9]))
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Attempt to clone a project
|
||||
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
|
||||
.rejects.toThrow('Clone failed');
|
||||
|
||||
// Verify that the project directory was cleaned up
|
||||
const project = await projectsManager.getProject('test-project');
|
||||
expect(project).toBeNull();
|
||||
|
||||
// Verify directory doesn't exist in filesystem
|
||||
await expect(fs.stat('/projects/test-project')).rejects.toThrow('ENOENT');
|
||||
});
|
||||
|
||||
it('should handle cleanup errors gracefully', async () => {
|
||||
await projectsManager.init();
|
||||
|
||||
// Mock git.clone to fail
|
||||
const mockGit = {
|
||||
clone: vi.fn().mockRejectedValue(new Error('Clone failed')),
|
||||
} as Partial<import('./git').Git>;
|
||||
|
||||
// Replace git instance
|
||||
Object.assign(projectsManager, { git: mockGit });
|
||||
|
||||
// Spy on console.warn to check for cleanup warnings
|
||||
// Spy on console.warn to check for security warnings
|
||||
const consoleSpy = vi.spyOn(console, 'warn').mockImplementation(() => {});
|
||||
|
||||
// Mock fs.rmdir to fail (simulate cleanup error)
|
||||
const originalRmdir = fs.rmdir;
|
||||
fs.rmdir = vi.fn().mockRejectedValue(new Error('Cleanup failed'));
|
||||
|
||||
try {
|
||||
// Attempt to clone a project
|
||||
await expect(projectsManager.cloneProject('test-project', 'https://github.com/test/repo.git'))
|
||||
.rejects.toThrow('Clone failed');
|
||||
// Extract files from the malicious ZIP for bulk import
|
||||
const files = await projectsManager.extractFilesFromZip(mockZip as unknown as JSZip, 'projects/project1');
|
||||
|
||||
// Should have logged a cleanup warning
|
||||
// Should only contain safe files
|
||||
expect(Object.keys(files)).toEqual(['safe-file.txt']);
|
||||
expect(files['safe-file.txt']).toEqual(new Uint8Array([7, 8, 9]));
|
||||
|
||||
// Should have logged a security warning about skipped files
|
||||
expect(consoleSpy).toHaveBeenCalledWith(
|
||||
'Failed to clean up directory after clone failure:',
|
||||
expect.any(Error)
|
||||
expect.stringContaining('Skipped 2 files due to resolving to paths outside of project directory:'),
|
||||
['projects/project1/../../../etc/passwd', 'projects/project1/../../outside.txt']
|
||||
);
|
||||
|
||||
} finally {
|
||||
// Restore mocks
|
||||
consoleSpy.mockRestore();
|
||||
fs.rmdir = originalRmdir;
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
+422
-138
@@ -46,59 +46,259 @@ export class ProjectsManager {
|
||||
async createProject(name: string, customId?: string): Promise<Project> {
|
||||
const project = await this.cloneProject(name, GIT_TEMPLATE_URL, customId, { depth: 1 });
|
||||
|
||||
// Delete README.md if it exists
|
||||
// Delete README.md if it exists (template-specific cleanup)
|
||||
try {
|
||||
await this.fs.unlink(`${project.path}/README.md`);
|
||||
} catch {
|
||||
// README.md might not exist, ignore error
|
||||
}
|
||||
|
||||
// Delete .git directory and reinitialize
|
||||
try {
|
||||
await this.deleteDirectory(`${project.path}/.git`);
|
||||
} catch {
|
||||
// .git directory might not exist, ignore error
|
||||
}
|
||||
|
||||
// Initialize new git repository
|
||||
await this.git.init({
|
||||
dir: project.path,
|
||||
defaultBranch: 'main',
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(project.path, {
|
||||
isOverwrite: false,
|
||||
commitMessage: 'New project created with Shakespeare',
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
const files = await this.getAllFiles(project.path);
|
||||
for (const file of files) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: project.path,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: project.path,
|
||||
message: 'New project created with Shakespeare',
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
// Automatically request persistent storage after project creation
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project creation if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project creation:', error);
|
||||
}
|
||||
|
||||
return project;
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified method for setting up project infrastructure.
|
||||
* Handles git initialization/management, .ai directory creation, and persistent storage.
|
||||
*/
|
||||
private async setupProjectInfrastructure(
|
||||
projectPath: string,
|
||||
options: {
|
||||
isOverwrite?: boolean;
|
||||
commitMessage?: string;
|
||||
skipPersistentStorage?: boolean;
|
||||
} = {}
|
||||
): Promise<void> {
|
||||
const { isOverwrite = false, commitMessage = 'Project setup', skipPersistentStorage = false } = options;
|
||||
|
||||
// Initialize git repository if there's no .git directory
|
||||
try {
|
||||
await this.fs.stat(`${projectPath}/.git`);
|
||||
|
||||
// If git exists and we're overwriting, stage the new files
|
||||
if (isOverwrite) {
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
// Ignore git add errors for files that might be gitignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make commit for the overwrite
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: commitMessage,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// No .git directory found, initialize new repository
|
||||
await this.git.init({
|
||||
dir: projectPath,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git (excluding .ai directory)
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory and .ai directory
|
||||
if (!file.startsWith('.git/') && !file.startsWith('.ai/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: commitMessage,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
// Create .ai/history directory
|
||||
try {
|
||||
await this.fs.mkdir(`${projectPath}/.ai/history`, { recursive: true });
|
||||
} catch {
|
||||
// Directory might already exist
|
||||
}
|
||||
|
||||
// Automatically request persistent storage (unless skipped)
|
||||
if (!skipPersistentStorage) {
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project setup if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project setup:', error);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Unified project import method that handles both ZIP files and direct file objects
|
||||
*/
|
||||
async importProject(
|
||||
source: File | { files: { [path: string]: Uint8Array } },
|
||||
options: {
|
||||
projectId?: string;
|
||||
overwrite?: boolean;
|
||||
projectName?: string;
|
||||
} = {}
|
||||
): Promise<Project> {
|
||||
const { projectId, overwrite = false, projectName } = options;
|
||||
|
||||
let finalProjectId: string;
|
||||
let finalProjectName: string;
|
||||
let files: { [path: string]: Uint8Array };
|
||||
|
||||
if (source instanceof File) {
|
||||
// Handle ZIP file import
|
||||
finalProjectId = projectId || await this.generateUniqueProjectId(source.name.replace(/\.zip$/i, ''));
|
||||
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||
|
||||
// Extract files from ZIP
|
||||
const arrayBuffer = await source.arrayBuffer();
|
||||
const zip = await JSZip.loadAsync(arrayBuffer);
|
||||
|
||||
files = {};
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||
if (zipEntry.dir) continue;
|
||||
|
||||
// Validate extraction path is within project directory
|
||||
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
const content = await zipEntry.async('uint8array');
|
||||
files[relativePath] = content;
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||
}
|
||||
} else {
|
||||
// Handle direct files import
|
||||
finalProjectId = projectId || await this.generateUniqueProjectId('imported-project');
|
||||
finalProjectName = projectName || this.formatProjectName(finalProjectId);
|
||||
files = source.files;
|
||||
}
|
||||
|
||||
const projectPath = `${this.dir}/${finalProjectId}`;
|
||||
const projectExists = await this.projectExists(finalProjectId);
|
||||
|
||||
// Check if project with this ID already exists when not overwriting
|
||||
if (projectExists && !overwrite) {
|
||||
throw new Error(`Project with ID "${finalProjectId}" already exists`);
|
||||
}
|
||||
|
||||
try {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
// Ignore deletion errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract all files with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
// Validate extraction path is within project directory
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file (this will overwrite existing files)
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
extractedFiles.push(relativePath);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside of project directory:`, skippedFiles);
|
||||
}
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: source instanceof File
|
||||
? `Import project from ${source.name}`
|
||||
: `Import project from files`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id: finalProjectId,
|
||||
name: finalProjectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error (only if this was a new project creation)
|
||||
if (!projectExists) {
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
// Legacy method for backward compatibility
|
||||
async importProjectFromZip(zipFile: File, customId?: string, overwrite = false): Promise<Project> {
|
||||
// Generate a project ID based on the zip file name or use custom ID
|
||||
const baseName = zipFile.name.replace(/\.zip$/i, '');
|
||||
@@ -198,66 +398,12 @@ export class ProjectsManager {
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Initialize git repository if there's no .git directory
|
||||
try {
|
||||
await this.fs.stat(`${projectPath}/.git`);
|
||||
|
||||
// If git exists and we're overwriting, stage the new files
|
||||
if (overwrite) {
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
} catch {
|
||||
// Ignore git add errors for files that might be gitignored
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Make commit for the overwrite
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: `Overwrite project from ${zipFile.name}`,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
} catch {
|
||||
// No .git directory found, initialize new repository
|
||||
await this.git.init({
|
||||
dir: projectPath,
|
||||
defaultBranch: 'main',
|
||||
});
|
||||
|
||||
// Add all files to git
|
||||
const projectFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of projectFiles) {
|
||||
// Skip .git directory
|
||||
if (!file.startsWith('.git/')) {
|
||||
await this.git.add({
|
||||
dir: projectPath,
|
||||
filepath: file,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// Make initial commit
|
||||
await this.git.commit({
|
||||
dir: projectPath,
|
||||
message: `Import project from ${zipFile.name}`,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
}
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: `Import project from ${zipFile.name}`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id,
|
||||
@@ -278,6 +424,106 @@ export class ProjectsManager {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Import project directly from files object (bypasses ZIP creation)
|
||||
* Used by bulk import to avoid unnecessary ZIP repackaging
|
||||
*/
|
||||
async importProjectFromFiles(
|
||||
projectId: string,
|
||||
files: { [path: string]: Uint8Array },
|
||||
overwrite = false,
|
||||
projectName?: string
|
||||
): Promise<Project> {
|
||||
const projectPath = `${this.dir}/${projectId}`;
|
||||
const projectExists = await this.projectExists(projectId);
|
||||
|
||||
// Check if project with this ID already exists when not overwriting
|
||||
if (projectExists && !overwrite) {
|
||||
throw new Error(`Project with ID "${projectId}" already exists`);
|
||||
}
|
||||
|
||||
// Determine project name
|
||||
const finalProjectName = projectName || this.formatProjectName(projectId);
|
||||
|
||||
try {
|
||||
// Create project directory (or ensure it exists for overwrite)
|
||||
await this.fs.mkdir(projectPath, { recursive: true });
|
||||
|
||||
// If overwriting, delete existing files except .ai directory and .git directory
|
||||
if (projectExists && overwrite) {
|
||||
const existingFiles = await this.getAllFiles(projectPath);
|
||||
for (const file of existingFiles) {
|
||||
// Preserve .ai directory and .git directory
|
||||
if (!file.startsWith('.ai/') && !file.startsWith('.git/')) {
|
||||
try {
|
||||
await this.fs.unlink(`${projectPath}/${file}`);
|
||||
} catch {
|
||||
// Ignore deletion errors
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Extract all files with security validation
|
||||
const extractedFiles: string[] = [];
|
||||
const skippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, content] of Object.entries(files)) {
|
||||
// Validate the extraction path is within the project directory
|
||||
const extractPath = this.join(projectPath, relativePath);
|
||||
|
||||
if (!this.isPathWithinProject(extractPath, projectPath)) {
|
||||
skippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
// Ensure parent directory exists
|
||||
const dirPath = extractPath.split('/').slice(0, -1).join('/');
|
||||
if (dirPath) {
|
||||
await this.fs.mkdir(dirPath, { recursive: true });
|
||||
}
|
||||
|
||||
// Write the file (this will overwrite existing files)
|
||||
await this.fs.writeFile(extractPath, content);
|
||||
extractedFiles.push(relativePath);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to resolving to paths outside the project directory:`, skippedFiles);
|
||||
}
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Setup project infrastructure using unified method
|
||||
await this.setupProjectInfrastructure(projectPath, {
|
||||
isOverwrite: overwrite,
|
||||
commitMessage: `Import project from files`,
|
||||
skipPersistentStorage: false,
|
||||
});
|
||||
|
||||
return {
|
||||
id: projectId,
|
||||
name: finalProjectName,
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
} catch (error) {
|
||||
// Clean up on error (only if this was a new project creation)
|
||||
if (!projectExists) {
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch {
|
||||
// Ignore cleanup errors
|
||||
}
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
|
||||
async cloneProject(name: string, repoUrl: string, customId?: string, options?: { depth?: number }): Promise<Project> {
|
||||
const id = customId || await this.generateUniqueProjectId(name);
|
||||
|
||||
@@ -290,45 +536,33 @@ export class ProjectsManager {
|
||||
|
||||
await this.fs.mkdir(projectPath);
|
||||
|
||||
// Clone the repository (Git class now handles Nostr URIs automatically)
|
||||
await this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
singleBranch: true,
|
||||
depth: options?.depth, // Use depth if provided, otherwise clone full history
|
||||
});
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Automatically request persistent storage after project cloning
|
||||
try {
|
||||
// Clone the repository (Git class now handles Nostr URIs automatically)
|
||||
await this.git.clone({
|
||||
dir: projectPath,
|
||||
url: repoUrl,
|
||||
singleBranch: true,
|
||||
depth: options?.depth, // Use depth if provided, otherwise clone full history
|
||||
});
|
||||
|
||||
// Get filesystem stats for timestamps
|
||||
const stats = await this.fs.stat(projectPath);
|
||||
const timestamp = stats.mtimeMs ? new Date(stats.mtimeMs) : new Date();
|
||||
|
||||
// Automatically request persistent storage after project cloning
|
||||
try {
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Don't fail project cloning if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project cloning:', error);
|
||||
}
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
await ensurePersistentStorage();
|
||||
} catch (error) {
|
||||
// Clean up the directory that was created if cloning fails
|
||||
try {
|
||||
await this.deleteDirectory(projectPath);
|
||||
} catch (cleanupError) {
|
||||
// Log cleanup error but don't mask the original clone error
|
||||
console.warn('Failed to clean up directory after clone failure:', cleanupError);
|
||||
}
|
||||
// Re-throw the original clone error
|
||||
throw error;
|
||||
// Don't fail project cloning if persistent storage request fails
|
||||
console.warn('Failed to request persistent storage after project cloning:', error);
|
||||
}
|
||||
|
||||
// Return the full project object with dynamically generated properties
|
||||
return {
|
||||
id,
|
||||
name: this.formatProjectName(id), // Use formatted directory name
|
||||
path: projectPath,
|
||||
lastModified: timestamp,
|
||||
};
|
||||
}
|
||||
|
||||
async getProjects(): Promise<Project[]> {
|
||||
@@ -658,4 +892,54 @@ export class ProjectsManager {
|
||||
|
||||
return '/' + normalized.join('/');
|
||||
}
|
||||
|
||||
/**
|
||||
* Extract files from a ZIP archive for a specific project path
|
||||
* Used by bulk import to extract files from a specific directory within a ZIP
|
||||
*/
|
||||
async extractFilesFromZip(zip: JSZip, projectPath: string): Promise<{ [path: string]: Uint8Array }> {
|
||||
const files: { [path: string]: Uint8Array } = {};
|
||||
const skippedFiles: string[] = [];
|
||||
const securitySkippedFiles: string[] = [];
|
||||
|
||||
for (const [relativePath, zipEntry] of Object.entries(zip.files)) {
|
||||
if (zipEntry.dir) continue;
|
||||
|
||||
// Check if this file is within the specified project path
|
||||
if (!relativePath.startsWith(projectPath + '/')) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Get the relative path within the project
|
||||
const fileRelativePath = relativePath.substring(projectPath.length + 1);
|
||||
|
||||
// Skip empty paths (shouldn't happen due to the dir check above, but just in case)
|
||||
if (!fileRelativePath) continue;
|
||||
|
||||
// Validate extraction path is safe (zip slip protection)
|
||||
// Check for directory traversal attempts in the original path
|
||||
if (fileRelativePath.includes('../') || fileRelativePath.includes('..\\') || fileRelativePath.startsWith('/') || fileRelativePath.startsWith('\\')) {
|
||||
securitySkippedFiles.push(relativePath);
|
||||
continue;
|
||||
}
|
||||
|
||||
try {
|
||||
const content = await zipEntry.async('uint8array');
|
||||
files[fileRelativePath] = content;
|
||||
} catch (error) {
|
||||
console.warn(`Failed to extract file ${relativePath}:`, error);
|
||||
skippedFiles.push(relativePath);
|
||||
}
|
||||
}
|
||||
|
||||
if (securitySkippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${securitySkippedFiles.length} files due to resolving to paths outside of project directory:`, securitySkippedFiles);
|
||||
}
|
||||
|
||||
if (skippedFiles.length > 0) {
|
||||
console.warn(`Skipped ${skippedFiles.length} files due to extraction errors:`, skippedFiles);
|
||||
}
|
||||
|
||||
return files;
|
||||
}
|
||||
}
|
||||
@@ -188,6 +188,10 @@ export class SessionManager {
|
||||
throw new Error('No messages in session');
|
||||
}
|
||||
|
||||
// Check if last message is from user
|
||||
const lastMessage = session.messages[session.messages.length - 1];
|
||||
if (lastMessage.role !== 'user') return;
|
||||
|
||||
session.isLoading = true;
|
||||
session.abortController = new AbortController();
|
||||
session.lastActivity = new Date();
|
||||
|
||||
@@ -1,62 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { AI_PROVIDER_PRESETS, getPresetProvider, getShakespeareProvider } from './aiProviderPresets';
|
||||
|
||||
describe('AI Provider Presets', () => {
|
||||
it('should export preset providers array', () => {
|
||||
expect(AI_PROVIDER_PRESETS).toBeDefined();
|
||||
expect(Array.isArray(AI_PROVIDER_PRESETS)).toBe(true);
|
||||
expect(AI_PROVIDER_PRESETS.length).toBeGreaterThan(0);
|
||||
});
|
||||
|
||||
it('should include Shakespeare provider', () => {
|
||||
const shakespeare = AI_PROVIDER_PRESETS.find(p => p.id === 'shakespeare');
|
||||
expect(shakespeare).toBeDefined();
|
||||
expect(shakespeare?.name).toBe('Shakespeare AI');
|
||||
expect(shakespeare?.nostr).toBe(true);
|
||||
});
|
||||
|
||||
it('should include other major providers', () => {
|
||||
const providerIds = AI_PROVIDER_PRESETS.map(p => p.id);
|
||||
expect(providerIds).toContain('openai');
|
||||
expect(providerIds).toContain('anthropic');
|
||||
expect(providerIds).toContain('openrouter');
|
||||
});
|
||||
|
||||
it('should get preset provider by id', () => {
|
||||
const openai = getPresetProvider('openai');
|
||||
expect(openai).toBeDefined();
|
||||
expect(openai?.name).toBe('OpenAI');
|
||||
|
||||
const nonExistent = getPresetProvider('non-existent');
|
||||
expect(nonExistent).toBeUndefined();
|
||||
});
|
||||
|
||||
it('should get Shakespeare provider', () => {
|
||||
const shakespeare = getShakespeareProvider();
|
||||
expect(shakespeare).toBeDefined();
|
||||
expect(shakespeare.id).toBe('shakespeare');
|
||||
expect(shakespeare.name).toBe('Shakespeare AI');
|
||||
expect(shakespeare.nostr).toBe(true);
|
||||
});
|
||||
|
||||
it('should have valid preset structure', () => {
|
||||
AI_PROVIDER_PRESETS.forEach(preset => {
|
||||
expect(preset.id).toBeDefined();
|
||||
expect(typeof preset.id).toBe('string');
|
||||
expect(preset.name).toBeDefined();
|
||||
expect(typeof preset.name).toBe('string');
|
||||
expect(preset.baseURL).toBeDefined();
|
||||
expect(typeof preset.baseURL).toBe('string');
|
||||
expect(preset.baseURL).toMatch(/^https?:\/\//);
|
||||
|
||||
// Optional fields
|
||||
if (preset.apiKeysURL) {
|
||||
expect(typeof preset.apiKeysURL).toBe('string');
|
||||
expect(preset.apiKeysURL).toMatch(/^https?:\/\//);
|
||||
}
|
||||
if (preset.nostr !== undefined) {
|
||||
expect(typeof preset.nostr).toBe('boolean');
|
||||
}
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,81 +0,0 @@
|
||||
export interface PresetProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
baseURL: string;
|
||||
apiKeysURL?: string;
|
||||
nostr?: boolean;
|
||||
tosURL?: string;
|
||||
}
|
||||
|
||||
export const AI_PROVIDER_PRESETS: PresetProvider[] = [
|
||||
{
|
||||
id: "shakespeare",
|
||||
name: "Shakespeare AI",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
tosURL: "https://ai.shakespeare.diy/terms",
|
||||
nostr: true,
|
||||
},
|
||||
{
|
||||
id: "openrouter",
|
||||
name: "OpenRouter",
|
||||
baseURL: "https://openrouter.ai/api/v1",
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
tosURL: "https://openrouter.ai/terms",
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
baseURL: "https://api.ppq.ai",
|
||||
apiKeysURL: "https://ppq.ai/api-docs",
|
||||
tosURL: "https://ppq.ai/terms",
|
||||
},
|
||||
{
|
||||
id: "routstr",
|
||||
name: "Routstr",
|
||||
baseURL: "https://api.routstr.com/v1",
|
||||
apiKeysURL: "https://chat.routstr.com/",
|
||||
tosURL: "https://routstr.com/terms",
|
||||
},
|
||||
{
|
||||
id: "zai",
|
||||
name: "Z.ai",
|
||||
baseURL: "https://api.z.ai/api/paas/v4",
|
||||
apiKeysURL: "https://z.ai/manage-apikey/apikey-list",
|
||||
tosURL: "https://docs.z.ai/legal-agreement/terms-of-use",
|
||||
},
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
baseURL: "https://api.openai.com/v1",
|
||||
apiKeysURL: "https://platform.openai.com/api-keys",
|
||||
tosURL: "https://openai.com/policies/",
|
||||
},
|
||||
{
|
||||
id: "anthropic",
|
||||
name: "Anthropic",
|
||||
baseURL: "https://api.anthropic.com/v1",
|
||||
apiKeysURL: "https://console.anthropic.com/settings/keys",
|
||||
tosURL: "https://www.anthropic.com/legal/",
|
||||
},
|
||||
{
|
||||
id: "xai",
|
||||
name: "xAI",
|
||||
baseURL: "https://api.x.ai/v1",
|
||||
apiKeysURL: "https://console.x.ai",
|
||||
tosURL: "https://x.ai/legal",
|
||||
},
|
||||
];
|
||||
|
||||
// Helper function to get a specific preset by ID
|
||||
export function getPresetProvider(id: string): PresetProvider | undefined {
|
||||
return AI_PROVIDER_PRESETS.find(preset => preset.id === id);
|
||||
}
|
||||
|
||||
// Helper function to get the Shakespeare provider preset
|
||||
export function getShakespeareProvider(): PresetProvider {
|
||||
const shakespeare = getPresetProvider("shakespeare");
|
||||
if (!shakespeare) {
|
||||
throw new Error("Shakespeare provider preset not found");
|
||||
}
|
||||
return shakespeare;
|
||||
}
|
||||
@@ -78,18 +78,15 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
|
||||
// Handle transitive dependency versions
|
||||
const keys: string[] = [];
|
||||
let importerPkg: string | undefined;
|
||||
let importerVersion: string | undefined;
|
||||
let importerPackage: string | undefined;
|
||||
try {
|
||||
const { pathname } = new URL(args.importer);
|
||||
if (/\.css$/.test(pathname)) {
|
||||
return; // CSS imports don't have external dependencies
|
||||
}
|
||||
const result = extractPackageName(args.importer);
|
||||
importerPkg = result.pkg;
|
||||
importerVersion = result.version;
|
||||
importerPackage = extractPackageName(args.importer);
|
||||
keys.push(
|
||||
`node_modules/${importerPkg}/node_modules/${packageName}`,
|
||||
`node_modules/${importerPackage}/node_modules/${packageName}`,
|
||||
);
|
||||
} catch {
|
||||
// fallthrough
|
||||
@@ -106,15 +103,8 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
.find((info) => info);
|
||||
|
||||
const packagePath = args.path.slice(packageName.length);
|
||||
|
||||
let version: string | undefined;
|
||||
|
||||
if (importerPkg === packageName && importerVersion) {
|
||||
version = importerVersion;
|
||||
} else {
|
||||
version = packageInfo?.version
|
||||
|| packageLock.packages[`node_modules/${importerPkg}`]?.peerDependencies?.[packageName];
|
||||
}
|
||||
const version = packageInfo?.version
|
||||
|| packageLock.packages[`node_modules/${importerPackage}`]?.peerDependencies?.[packageName];
|
||||
|
||||
const name = packageInfo?.name ?? packageName;
|
||||
const specifier = version
|
||||
@@ -207,7 +197,7 @@ export function esmPlugin(packageLock: PackageLock, target?: string): Plugin {
|
||||
}
|
||||
|
||||
/** Extract package name from esm.sh-style URL */
|
||||
function extractPackageName(esmShURL: string): { pkg?: string; version?: string } {
|
||||
function extractPackageName(esmShURL: string): string {
|
||||
const full = new URL(esmShURL)
|
||||
.pathname
|
||||
.slice(1)
|
||||
@@ -217,15 +207,7 @@ function extractPackageName(esmShURL: string): { pkg?: string; version?: string
|
||||
? full.split("/").slice(0, 2).join("/")
|
||||
: full.split("/")[0];
|
||||
|
||||
const pkg = full.startsWith("@")
|
||||
return full.startsWith("@")
|
||||
? base.split("@").splice(0, 2).join("@")
|
||||
: base.split("@")[0];
|
||||
|
||||
let version: string | undefined;
|
||||
|
||||
if (full.slice(pkg.length).startsWith("@")) {
|
||||
version = full.slice(pkg.length + 1).split("/")[0];
|
||||
}
|
||||
|
||||
return { pkg, version };
|
||||
}
|
||||
@@ -14,7 +14,6 @@ import { GitCheckoutCommand } from "./git/checkout";
|
||||
import { GitRemoteCommand } from "./git/remote";
|
||||
import { GitPushCommand } from "./git/push";
|
||||
import { GitPullCommand } from "./git/pull";
|
||||
import { GitFetchCommand } from "./git/fetch";
|
||||
import { GitCloneCommand } from "./git/clone";
|
||||
import { GitConfigCommand } from "./git/config";
|
||||
import { GitResetCommand } from "./git/reset";
|
||||
@@ -78,7 +77,6 @@ export class GitCommand implements ShellCommand {
|
||||
this.registerSubcommand(new GitRemoteCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitPushCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitPullCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitFetchCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitCloneCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitConfigCommand(subcommandOptions));
|
||||
this.registerSubcommand(new GitResetCommand(subcommandOptions));
|
||||
@@ -146,7 +144,6 @@ grow, mark and tweak your common history
|
||||
tag Create, list, delete or verify a tag object
|
||||
|
||||
collaborate (see also: git help workflows)
|
||||
fetch Download objects and refs from another repository
|
||||
pull Fetch from and integrate with another repository or a local branch
|
||||
push Update remote refs along with associated objects
|
||||
remote Manage set of tracked repositories
|
||||
|
||||
@@ -1,202 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitDiffCommand } from './diff';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
statusMatrix: async () => [
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
['modified.txt', 1, 2, 1], // Modified in working dir
|
||||
['staged.txt', 1, 1, 2], // Modified in stage
|
||||
['new.txt', 0, 2, 0], // Untracked file
|
||||
['deleted.txt', 1, 0, 1], // Deleted in working dir
|
||||
],
|
||||
readBlob: async ({ filepath }: { filepath: string }) => {
|
||||
const content = {
|
||||
'modified.txt': 'original content\nline 2',
|
||||
'staged.txt': 'original staged content',
|
||||
'deleted.txt': 'deleted file content',
|
||||
}[filepath] || '';
|
||||
return { blob: new TextEncoder().encode(content) };
|
||||
},
|
||||
log: async () => [],
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
readFile: async (path: string) => {
|
||||
const filename = path.split('/').pop();
|
||||
const content = {
|
||||
'modified.txt': 'modified content\nline 2\nnew line',
|
||||
'staged.txt': 'staged content modified',
|
||||
'new.txt': 'this is a new file',
|
||||
// deleted.txt is not in working dir
|
||||
}[filename || ''];
|
||||
|
||||
if (!content) {
|
||||
throw new Error('File not found');
|
||||
}
|
||||
return content;
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitDiffCommand', () => {
|
||||
let command: GitDiffCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitDiffCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
type ParseArgsResult = {
|
||||
commits: string[];
|
||||
paths: string[];
|
||||
options: { cached: boolean; staged: boolean };
|
||||
};
|
||||
|
||||
it('should parse no arguments correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
commits: [],
|
||||
paths: [],
|
||||
options: { cached: false, staged: false },
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse --cached option', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--cached']);
|
||||
expect(result).toEqual({
|
||||
commits: [],
|
||||
paths: [],
|
||||
options: { cached: true, staged: true },
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse commits and paths', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD~1', 'HEAD', '--', 'file.txt']);
|
||||
expect(result).toEqual({
|
||||
commits: ['HEAD~1', 'HEAD'],
|
||||
paths: ['file.txt'],
|
||||
options: { cached: false, staged: false },
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should fail when not in a git repository', async () => {
|
||||
const commandWithoutGit = new GitDiffCommand({
|
||||
...mockOptions,
|
||||
fs: {
|
||||
stat: async () => {
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should show working directory diff for modified files', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||
expect(result.stdout).toContain('--- a/modified.txt');
|
||||
expect(result.stdout).toContain('+++ b/modified.txt');
|
||||
expect(result.stdout).toContain('-original content');
|
||||
expect(result.stdout).toContain('+modified content');
|
||||
expect(result.stdout).toContain('+new line');
|
||||
});
|
||||
|
||||
it('should NOT show untracked files in diff', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
// Untracked files should not appear in git diff output
|
||||
expect(result.stdout).not.toContain('diff --git a/new.txt b/new.txt');
|
||||
expect(result.stdout).not.toContain('new file mode 100644');
|
||||
expect(result.stdout).not.toContain('+this is a new file');
|
||||
});
|
||||
|
||||
it('should show deleted files in diff', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/deleted.txt b/deleted.txt');
|
||||
expect(result.stdout).toContain('deleted file mode 100644');
|
||||
expect(result.stdout).toContain('--- a/deleted.txt');
|
||||
expect(result.stdout).toContain('+++ /dev/null');
|
||||
expect(result.stdout).toContain('-deleted file content');
|
||||
});
|
||||
|
||||
it('should show staged diff with --cached option', async () => {
|
||||
const result = await command.execute(['--cached']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/staged.txt b/staged.txt');
|
||||
expect(result.stdout).toContain('--- a/staged.txt');
|
||||
expect(result.stdout).toContain('+++ b/staged.txt');
|
||||
});
|
||||
|
||||
it('should show newly added files in staged diff', async () => {
|
||||
// Test with a file that was added to the index (new file staged)
|
||||
const commandWithStagedNew = new GitDiffCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [
|
||||
['new-staged.txt', 0, 1, 2], // New file added to stage
|
||||
],
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithStagedNew.execute(['--cached']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/new-staged.txt b/new-staged.txt');
|
||||
expect(result.stdout).toContain('new file mode 100644');
|
||||
expect(result.stdout).toContain('--- /dev/null');
|
||||
expect(result.stdout).toContain('+++ b/new-staged.txt');
|
||||
});
|
||||
|
||||
it('should return empty output when no changes', async () => {
|
||||
const commandWithNoChanges = new GitDiffCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [],
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNoChanges.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should filter by path when specified', async () => {
|
||||
const result = await command.execute(['--', 'modified.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('diff --git a/modified.txt b/modified.txt');
|
||||
expect(result.stdout).not.toContain('new.txt');
|
||||
expect(result.stdout).not.toContain('deleted.txt');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -91,13 +91,10 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
// Filter for files with working directory changes
|
||||
// Status matrix: [filepath, headStatus, workdirStatus, stageStatus]
|
||||
// 0 = absent, 1 = same as previous stage, 2 = different from previous stage
|
||||
// 0 = absent, 1 = present, 2 = modified
|
||||
const changedFiles = statusMatrix.filter(([filepath, _headStatus, workdirStatus, stageStatus]) => {
|
||||
// Show files that have working directory changes (differ from index)
|
||||
// Exclude untracked files - git diff only shows changes to tracked files
|
||||
const hasWorkingDirChanges = (stageStatus !== workdirStatus && workdirStatus === 2 && stageStatus !== 0) ||
|
||||
(stageStatus === 2 && workdirStatus === 0) ||
|
||||
(stageStatus === 1 && workdirStatus === 0);
|
||||
// Show files that differ between index and working directory
|
||||
const hasWorkingDirChanges = stageStatus !== workdirStatus;
|
||||
|
||||
if (paths.length > 0) {
|
||||
return hasWorkingDirChanges && paths.some(path => filepath.includes(path));
|
||||
@@ -113,87 +110,79 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
for (const [filepath, _headStatus, workdirStatus, stageStatus] of changedFiles) {
|
||||
try {
|
||||
// Get staged/index content
|
||||
let indexContent = '';
|
||||
if (stageStatus === 1 || stageStatus === 2) {
|
||||
// Get staged content (index)
|
||||
let stagedContent = '';
|
||||
if (stageStatus === 1) {
|
||||
try {
|
||||
// For files in the index, read from HEAD as the baseline
|
||||
// This represents the last committed version for comparison
|
||||
// Try to read from HEAD first as a fallback for staged content
|
||||
const headBlob = await this.git.readBlob({
|
||||
dir: this.pwd,
|
||||
oid: 'HEAD',
|
||||
filepath,
|
||||
});
|
||||
indexContent = new TextDecoder().decode(headBlob.blob);
|
||||
stagedContent = new TextDecoder().decode(headBlob.blob);
|
||||
} catch {
|
||||
// File might be new or not in HEAD
|
||||
indexContent = '';
|
||||
// File might be new
|
||||
stagedContent = '';
|
||||
}
|
||||
}
|
||||
|
||||
// Get working directory content
|
||||
let workdirContent = '';
|
||||
if (workdirStatus === 2) {
|
||||
if (workdirStatus === 1) {
|
||||
try {
|
||||
workdirContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
// File might be deleted
|
||||
workdirContent = '';
|
||||
}
|
||||
} else if (workdirStatus === 0) {
|
||||
// File is deleted in working directory
|
||||
workdirContent = '';
|
||||
}
|
||||
|
||||
// Skip if contents are identical
|
||||
if (indexContent === workdirContent) {
|
||||
if (stagedContent === workdirContent) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Generate diff header
|
||||
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
|
||||
|
||||
if (workdirStatus === 0 && (stageStatus === 1 || stageStatus === 2)) {
|
||||
if (stageStatus === 0 && workdirStatus === 1) {
|
||||
// New untracked file
|
||||
diffLines.push('new file mode 100644');
|
||||
diffLines.push(`index 0000000..${this.getShortHash(workdirContent)}`);
|
||||
diffLines.push('--- /dev/null');
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
} else if (stageStatus === 1 && workdirStatus === 0) {
|
||||
// Deleted file
|
||||
diffLines.push('deleted file mode 100644');
|
||||
diffLines.push(`index ${this.getShortHash(indexContent)}..0000000`);
|
||||
diffLines.push(`index ${this.getShortHash(stagedContent)}..0000000`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push('+++ /dev/null');
|
||||
} else {
|
||||
// Modified file
|
||||
diffLines.push(`index ${this.getShortHash(indexContent)}..${this.getShortHash(workdirContent)} 100644`);
|
||||
diffLines.push(`index ${this.getShortHash(stagedContent)}..${this.getShortHash(workdirContent)} 100644`);
|
||||
diffLines.push(`--- a/${filepath}`);
|
||||
diffLines.push(`+++ b/${filepath}`);
|
||||
}
|
||||
|
||||
// Generate unified diff
|
||||
const indexLines = indexContent.split('\n');
|
||||
// Generate simple unified diff
|
||||
const stagedLines = stagedContent.split('\n');
|
||||
const workdirLines = workdirContent.split('\n');
|
||||
|
||||
// Simple hunk header
|
||||
diffLines.push(`@@ -1,${indexLines.length} +1,${workdirLines.length} @@`);
|
||||
diffLines.push(`@@ -1,${stagedLines.length} +1,${workdirLines.length} @@`);
|
||||
|
||||
// Simple line-by-line diff
|
||||
const maxLines = Math.max(indexLines.length, workdirLines.length);
|
||||
for (let i = 0; i < maxLines; i++) {
|
||||
const oldLine = indexLines[i];
|
||||
const newLine = workdirLines[i];
|
||||
// Show all old lines as removed
|
||||
for (const line of stagedLines) {
|
||||
if (line || stagedLines.length > 0) {
|
||||
diffLines.push(`-${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
if (oldLine !== undefined && newLine !== undefined) {
|
||||
if (oldLine === newLine) {
|
||||
// Unchanged line (show context)
|
||||
diffLines.push(` ${oldLine}`);
|
||||
} else {
|
||||
// Changed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
diffLines.push(`+${newLine}`);
|
||||
}
|
||||
} else if (oldLine !== undefined) {
|
||||
// Removed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
} else if (newLine !== undefined) {
|
||||
// Added line
|
||||
diffLines.push(`+${newLine}`);
|
||||
// Show all new lines as added
|
||||
for (const line of workdirLines) {
|
||||
if (line || workdirLines.length > 0) {
|
||||
diffLines.push(`+${line}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -259,9 +248,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
// Filter for files with staged changes (index differs from HEAD)
|
||||
const stagedFiles = statusMatrix.filter(([filepath, headStatus, _workdirStatus, stageStatus]) => {
|
||||
const hasStagedChanges = (headStatus === 0 && stageStatus === 2) || // Added to stage
|
||||
(headStatus === 1 && stageStatus === 0) || // Deleted from stage
|
||||
(headStatus === 1 && stageStatus === 2); // Modified in stage
|
||||
const hasStagedChanges = headStatus !== stageStatus;
|
||||
|
||||
if (paths.length > 0) {
|
||||
return hasStagedChanges && paths.some(path => filepath.includes(path));
|
||||
@@ -294,7 +281,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
// Get staged content (approximated by working directory for now)
|
||||
let stagedContent = '';
|
||||
if (stageStatus === 1 || stageStatus === 2) {
|
||||
if (stageStatus === 1) {
|
||||
try {
|
||||
stagedContent = await this.fs.readFile(`${this.pwd}/${filepath}`, 'utf8');
|
||||
} catch {
|
||||
@@ -305,7 +292,7 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
// Generate diff header
|
||||
diffLines.push(`diff --git a/${filepath} b/${filepath}`);
|
||||
|
||||
if (headStatus === 0 && stageStatus === 2) {
|
||||
if (headStatus === 0 && stageStatus === 1) {
|
||||
// New file staged
|
||||
diffLines.push('new file mode 100644');
|
||||
diffLines.push(`index 0000000..${this.getShortHash(stagedContent)}`);
|
||||
@@ -330,28 +317,14 @@ export class GitDiffCommand implements GitSubcommand {
|
||||
|
||||
diffLines.push(`@@ -1,${headLines.length} +1,${stagedLines.length} @@`);
|
||||
|
||||
// Simple line-by-line diff
|
||||
const maxLines = Math.max(headLines.length, stagedLines.length);
|
||||
for (let i = 0; i < maxLines; i++) {
|
||||
const oldLine = headLines[i];
|
||||
const newLine = stagedLines[i];
|
||||
// Show removed lines
|
||||
for (const line of headLines) {
|
||||
diffLines.push(`-${line}`);
|
||||
}
|
||||
|
||||
if (oldLine !== undefined && newLine !== undefined) {
|
||||
if (oldLine === newLine) {
|
||||
// Unchanged line (show context)
|
||||
diffLines.push(` ${oldLine}`);
|
||||
} else {
|
||||
// Changed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
diffLines.push(`+${newLine}`);
|
||||
}
|
||||
} else if (oldLine !== undefined) {
|
||||
// Removed line
|
||||
diffLines.push(`-${oldLine}`);
|
||||
} else if (newLine !== undefined) {
|
||||
// Added line
|
||||
diffLines.push(`+${newLine}`);
|
||||
}
|
||||
// Show added lines
|
||||
for (const line of stagedLines) {
|
||||
diffLines.push(`+${line}`);
|
||||
}
|
||||
|
||||
diffLines.push('');
|
||||
|
||||
@@ -1,227 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitFetchCommand } from './fetch';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
listRemotes: async () => [
|
||||
{ remote: 'origin', url: 'https://github.com/user/repo.git' },
|
||||
{ remote: 'upstream', url: 'https://github.com/upstream/repo.git' }
|
||||
],
|
||||
fetch: async () => {},
|
||||
resolveRef: async () => 'abc123def456',
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitFetchCommand', () => {
|
||||
let command: GitFetchCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitFetchCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
type ParseArgsResult = {
|
||||
remote: string;
|
||||
refs: string[];
|
||||
options: {
|
||||
all: boolean;
|
||||
tags: boolean;
|
||||
prune: boolean;
|
||||
verbose: boolean;
|
||||
};
|
||||
};
|
||||
|
||||
it('should parse no arguments correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: [],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote only', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['upstream']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
refs: [],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote and refs', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['origin', 'main', 'develop']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: ['main', 'develop'],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse options correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--all', '--tags', '--prune', '--verbose']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: [],
|
||||
options: {
|
||||
all: true,
|
||||
tags: true,
|
||||
prune: true,
|
||||
verbose: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse short options', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['-p', '-v']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
refs: [],
|
||||
options: {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: true,
|
||||
verbose: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse mixed arguments and options', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['upstream', '--verbose', 'main', '--tags']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
refs: ['main'],
|
||||
options: {
|
||||
all: false,
|
||||
tags: true,
|
||||
prune: false,
|
||||
verbose: true,
|
||||
},
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should fail when not in a git repository', async () => {
|
||||
const commandWithoutGit = new GitFetchCommand({
|
||||
...mockOptions,
|
||||
fs: {
|
||||
stat: async () => {
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should fail when remote does not exist', async () => {
|
||||
const result = await command.execute(['nonexistent']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("fatal: 'nonexistent' does not appear to be a git repository");
|
||||
});
|
||||
|
||||
it('should fetch from default remote successfully', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
expect(result.stdout).toContain('refs/heads/* -> refs/remotes/origin/*');
|
||||
});
|
||||
|
||||
it('should fetch from specific remote successfully', async () => {
|
||||
const result = await command.execute(['upstream']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/upstream/repo.git');
|
||||
expect(result.stdout).toContain('refs/heads/* -> refs/remotes/upstream/*');
|
||||
});
|
||||
|
||||
it('should fetch specific refs successfully', async () => {
|
||||
const result = await command.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
expect(result.stdout).toContain('* branch main -> origin/main');
|
||||
});
|
||||
|
||||
it('should fetch multiple specific refs successfully', async () => {
|
||||
const result = await command.execute(['origin', 'main', 'develop']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('From https://github.com/user/repo.git');
|
||||
expect(result.stdout).toContain('* branch main -> origin/main');
|
||||
expect(result.stdout).toContain('* branch develop -> origin/develop');
|
||||
});
|
||||
|
||||
it('should handle authentication errors', async () => {
|
||||
const commandWithAuthError = new GitFetchCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
fetch: async () => {
|
||||
throw new Error('authentication failed');
|
||||
},
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithAuthError.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: Authentication failed');
|
||||
});
|
||||
|
||||
it('should handle network errors', async () => {
|
||||
const commandWithNetworkError = new GitFetchCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
fetch: async () => {
|
||||
throw new Error('network error');
|
||||
},
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNetworkError.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: unable to access remote repository');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,173 +0,0 @@
|
||||
import type { JSRuntimeFS } from "../../JSRuntime";
|
||||
import type { ShellCommandResult } from "../ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "../ShellCommand";
|
||||
import type { GitSubcommand, GitSubcommandOptions } from "../git";
|
||||
import type { Git } from "../../git";
|
||||
|
||||
export class GitFetchCommand implements GitSubcommand {
|
||||
name = 'fetch';
|
||||
description = 'Download objects and refs from another repository';
|
||||
usage = 'git fetch [<remote>] [<refspec>...]';
|
||||
|
||||
private git: Git;
|
||||
private fs: JSRuntimeFS;
|
||||
private pwd: string;
|
||||
|
||||
constructor(options: GitSubcommandOptions) {
|
||||
this.git = options.git;
|
||||
this.fs = options.fs;
|
||||
this.pwd = options.pwd;
|
||||
}
|
||||
|
||||
async execute(args: string[]): Promise<ShellCommandResult> {
|
||||
try {
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await this.fs.stat(`${this.pwd}/.git`);
|
||||
} catch {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
|
||||
const { remote, refs } = this.parseArgs(args);
|
||||
|
||||
// Get remote URL
|
||||
let remoteUrl: string;
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const targetRemote = remotes.find(r => r.remote === remote);
|
||||
if (!targetRemote) {
|
||||
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
|
||||
}
|
||||
remoteUrl = targetRemote.url;
|
||||
} catch {
|
||||
return createErrorResult(`fatal: '${remote}' does not appear to be a git repository`);
|
||||
}
|
||||
|
||||
try {
|
||||
// If specific refs are provided, fetch them; otherwise fetch all refs
|
||||
if (refs.length > 0) {
|
||||
// Fetch specific refs
|
||||
for (const ref of refs) {
|
||||
await this.git.fetch({
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
ref: ref,
|
||||
});
|
||||
}
|
||||
} else {
|
||||
// Fetch all refs (default behavior)
|
||||
await this.git.fetch({
|
||||
dir: this.pwd,
|
||||
remote: remote,
|
||||
});
|
||||
}
|
||||
|
||||
// Build output message
|
||||
const lines: string[] = [];
|
||||
lines.push(`From ${remoteUrl}`);
|
||||
|
||||
if (refs.length > 0) {
|
||||
// Show specific refs that were fetched
|
||||
for (const ref of refs) {
|
||||
try {
|
||||
await this.git.resolveRef({
|
||||
dir: this.pwd,
|
||||
ref: `refs/remotes/${remote}/${ref}`,
|
||||
});
|
||||
lines.push(` * branch ${ref} -> ${remote}/${ref}`);
|
||||
} catch {
|
||||
// If we can't resolve the ref, it might be a tag or other ref type
|
||||
lines.push(` * [new ref] ${ref} -> ${remote}/${ref}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// For fetch without specific refs, we'll show a generic message
|
||||
lines.push(` * [new refs] refs/heads/* -> refs/remotes/${remote}/*`);
|
||||
}
|
||||
|
||||
return createSuccessResult(lines.join('\n') + '\n');
|
||||
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('authentication')) {
|
||||
return createErrorResult('fatal: Authentication failed. Please configure git credentials.');
|
||||
} else if (error.message.includes('network')) {
|
||||
return createErrorResult('fatal: unable to access remote repository. Please check your network connection.');
|
||||
} else if (error.message.includes('not found')) {
|
||||
return createErrorResult(`fatal: remote ref not found`);
|
||||
}
|
||||
}
|
||||
|
||||
return createErrorResult(`Failed to fetch: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`git fetch: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private parseArgs(args: string[]): {
|
||||
remote: string;
|
||||
refs: string[];
|
||||
options: {
|
||||
all: boolean;
|
||||
tags: boolean;
|
||||
prune: boolean;
|
||||
verbose: boolean;
|
||||
}
|
||||
} {
|
||||
let remote = 'origin'; // Default remote
|
||||
const refs: string[] = [];
|
||||
const options = {
|
||||
all: false,
|
||||
tags: false,
|
||||
prune: false,
|
||||
verbose: false,
|
||||
};
|
||||
|
||||
const nonOptionArgs: string[] = [];
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg.startsWith('-')) {
|
||||
// Handle options
|
||||
switch (arg) {
|
||||
case '--all':
|
||||
options.all = true;
|
||||
break;
|
||||
case '--tags':
|
||||
options.tags = true;
|
||||
break;
|
||||
case '--prune':
|
||||
case '-p':
|
||||
options.prune = true;
|
||||
break;
|
||||
case '--verbose':
|
||||
case '-v':
|
||||
options.verbose = true;
|
||||
break;
|
||||
default:
|
||||
// Ignore unknown options for now
|
||||
break;
|
||||
}
|
||||
} else {
|
||||
nonOptionArgs.push(arg);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse non-option arguments
|
||||
if (nonOptionArgs.length >= 1) {
|
||||
remote = nonOptionArgs[0];
|
||||
}
|
||||
if (nonOptionArgs.length >= 2) {
|
||||
// All remaining args are refs/refspecs
|
||||
refs.push(...nonOptionArgs.slice(1));
|
||||
}
|
||||
|
||||
return { remote, refs, options };
|
||||
}
|
||||
}
|
||||
@@ -1,123 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitPullCommand } from './pull';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
currentBranch: async () => 'main',
|
||||
listRemotes: async () => [{ remote: 'origin', url: 'https://github.com/user/repo.git' }],
|
||||
statusMatrix: async () => [],
|
||||
fetch: async () => {},
|
||||
resolveRef: async () => 'abc123',
|
||||
merge: async () => {},
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async () => ({ isDirectory: () => true }),
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitPullCommand', () => {
|
||||
let command: GitPullCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitPullCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
it('should parse no arguments correctly', () => {
|
||||
// Access the private method for testing
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote only', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['upstream']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
branch: undefined,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse remote and branch correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['origin', 'main']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: 'main',
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse different remote and branch', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['upstream', 'develop']);
|
||||
expect(result).toEqual({
|
||||
remote: 'upstream',
|
||||
branch: 'develop',
|
||||
});
|
||||
});
|
||||
|
||||
it('should ignore option flags', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['--rebase', 'origin', '--verbose', 'main']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: 'main',
|
||||
});
|
||||
});
|
||||
|
||||
it('should handle extra arguments beyond remote and branch', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => { remote: string; branch?: string } }).parseArgs(['origin', 'main', 'extra', 'args']);
|
||||
expect(result).toEqual({
|
||||
remote: 'origin',
|
||||
branch: 'main',
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should list modified files when there are uncommitted changes', async () => {
|
||||
// Mock statusMatrix to return some modified files
|
||||
const mockGitWithChanges = {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [
|
||||
['src/index.ts', 1, 2, 1], // Modified file
|
||||
['README.md', 1, 2, 2], // Modified and staged
|
||||
['package.json', 0, 2, 0], // Untracked file
|
||||
],
|
||||
} as unknown as Git;
|
||||
|
||||
// Mock FS to ensure .git directory exists
|
||||
const mockFSWithGit = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const commandWithChanges = new GitPullCommand({
|
||||
git: mockGitWithChanges,
|
||||
fs: mockFSWithGit,
|
||||
pwd: '/test/repo',
|
||||
});
|
||||
|
||||
const result = await commandWithChanges.execute(['origin', 'main']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('error: Your local changes to the following files would be overwritten by merge:');
|
||||
expect(result.stderr).toContain('\tsrc/index.ts');
|
||||
expect(result.stderr).toContain('\tREADME.md');
|
||||
expect(result.stderr).toContain('\tpackage.json');
|
||||
expect(result.stderr).toContain('Please commit your changes or stash them before you merge.');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -35,7 +35,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
currentBranch = await this.git.currentBranch({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
}) || null;
|
||||
if (!targetBranch) {
|
||||
@@ -51,7 +51,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remoteUrl: string;
|
||||
try {
|
||||
const remotes = await this.git.listRemotes({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
@@ -69,16 +69,12 @@ export class GitPullCommand implements GitSubcommand {
|
||||
dir: this.pwd,
|
||||
});
|
||||
|
||||
const modifiedFiles = statusMatrix
|
||||
.filter(([, headStatus, workdirStatus, stageStatus]) => {
|
||||
// Check for any uncommitted changes (modified, staged, or untracked)
|
||||
return headStatus !== workdirStatus || headStatus !== stageStatus;
|
||||
})
|
||||
.map(([filepath]) => filepath);
|
||||
const hasChanges = statusMatrix.some(([, headStatus, workdirStatus, stageStatus]) => {
|
||||
return headStatus !== workdirStatus || headStatus !== stageStatus;
|
||||
});
|
||||
|
||||
if (modifiedFiles.length > 0) {
|
||||
const fileList = modifiedFiles.map(file => `\t${file}`).join('\n');
|
||||
return createErrorResult(`error: Your local changes to the following files would be overwritten by merge:\n${fileList}\nPlease commit your changes or stash them before you merge.`);
|
||||
if (hasChanges) {
|
||||
return createErrorResult('error: Your local changes to the following files would be overwritten by merge:\nPlease commit your changes or stash them before you merge.');
|
||||
}
|
||||
|
||||
try {
|
||||
@@ -94,7 +90,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remoteOid: string;
|
||||
try {
|
||||
remoteOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: remoteRef,
|
||||
});
|
||||
@@ -106,14 +102,14 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let currentOid: string;
|
||||
try {
|
||||
currentOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
} catch {
|
||||
// Empty repository, just checkout the remote branch
|
||||
await this.git.checkout({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: targetBranch,
|
||||
});
|
||||
@@ -127,7 +123,7 @@ export class GitPullCommand implements GitSubcommand {
|
||||
|
||||
// Perform fast-forward merge (simplified)
|
||||
await this.git.merge({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ours: currentBranch || 'HEAD',
|
||||
theirs: remoteRef,
|
||||
@@ -161,13 +157,18 @@ export class GitPullCommand implements GitSubcommand {
|
||||
let remote = 'origin'; // Default remote
|
||||
let branch: string | undefined;
|
||||
|
||||
const nonOptionArgs = args.filter(arg => !arg.startsWith('-'));
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const arg = args[i];
|
||||
|
||||
if (nonOptionArgs.length >= 1) {
|
||||
remote = nonOptionArgs[0];
|
||||
}
|
||||
if (nonOptionArgs.length >= 2) {
|
||||
branch = nonOptionArgs[1];
|
||||
if (!arg.startsWith('-')) {
|
||||
if (remote === 'origin' && !branch) {
|
||||
// First non-option argument is remote
|
||||
remote = arg;
|
||||
} else if (!branch) {
|
||||
// Second non-option argument is branch
|
||||
branch = arg;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return { remote, branch };
|
||||
|
||||
@@ -1,245 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { GitResetCommand } from './reset';
|
||||
import type { GitSubcommandOptions } from '../git';
|
||||
import type { Git } from '../../git';
|
||||
import type { JSRuntimeFS } from '../../JSRuntime';
|
||||
|
||||
// Mock implementations
|
||||
const mockGit = {
|
||||
statusMatrix: async () => [
|
||||
// [filepath, headStatus, workdirStatus, stageStatus]
|
||||
['staged.txt', 1, 1, 2], // Modified in stage
|
||||
['new-staged.txt', 0, 1, 2], // New file staged
|
||||
['modified.txt', 1, 2, 1], // Modified in working dir (not staged)
|
||||
['unchanged.txt', 1, 1, 1], // No changes
|
||||
],
|
||||
resetIndex: async ({ filepath }: { filepath: string }) => {
|
||||
// Mock successful reset
|
||||
return { filepath };
|
||||
},
|
||||
resolveRef: async ({ ref }: { ref: string }) => {
|
||||
const refs = {
|
||||
'HEAD': 'abc123def456',
|
||||
'HEAD~1': 'def456abc123',
|
||||
};
|
||||
if (refs[ref as keyof typeof refs]) {
|
||||
return refs[ref as keyof typeof refs];
|
||||
}
|
||||
throw new Error(`Unknown ref: ${ref}`);
|
||||
},
|
||||
readCommit: async () => ({
|
||||
oid: 'abc123def456',
|
||||
commit: {
|
||||
message: 'Test commit',
|
||||
author: { name: 'Test', email: '[email protected]' },
|
||||
},
|
||||
}),
|
||||
writeRef: async () => {},
|
||||
checkout: async () => {},
|
||||
} as unknown as Git;
|
||||
|
||||
const mockFS = {
|
||||
stat: async (path: string) => {
|
||||
if (path.endsWith('/.git')) {
|
||||
return { isDirectory: () => true };
|
||||
}
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS;
|
||||
|
||||
const mockOptions: GitSubcommandOptions = {
|
||||
git: mockGit,
|
||||
fs: mockFS,
|
||||
pwd: '/test/repo',
|
||||
};
|
||||
|
||||
describe('GitResetCommand', () => {
|
||||
let command: GitResetCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
command = new GitResetCommand(mockOptions);
|
||||
});
|
||||
|
||||
describe('parseArgs', () => {
|
||||
type ParseArgsResult = {
|
||||
mode: 'soft' | 'mixed' | 'hard';
|
||||
target: string;
|
||||
files: string[];
|
||||
isFileReset: boolean;
|
||||
};
|
||||
|
||||
it('should parse no arguments as file reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs([]);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD',
|
||||
files: [],
|
||||
isFileReset: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse HEAD as file reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD',
|
||||
files: [],
|
||||
isFileReset: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse HEAD with files as file reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['HEAD', 'file1.txt', 'file2.txt']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD',
|
||||
files: ['file1.txt', 'file2.txt'],
|
||||
isFileReset: true,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse commit hash as commit reset', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['abc123def']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'abc123def',
|
||||
files: [],
|
||||
isFileReset: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse mode flags correctly', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--hard', 'HEAD~1']);
|
||||
expect(result).toEqual({
|
||||
mode: 'hard',
|
||||
target: 'HEAD~1',
|
||||
files: [],
|
||||
isFileReset: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('should parse mixed mode with commit', () => {
|
||||
const result = (command as unknown as { parseArgs: (args: string[]) => ParseArgsResult }).parseArgs(['--mixed', 'HEAD~1']);
|
||||
expect(result).toEqual({
|
||||
mode: 'mixed',
|
||||
target: 'HEAD~1',
|
||||
files: [],
|
||||
isFileReset: false,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('execute', () => {
|
||||
it('should fail when not in a git repository', async () => {
|
||||
const commandWithoutGit = new GitResetCommand({
|
||||
...mockOptions,
|
||||
fs: {
|
||||
stat: async () => {
|
||||
throw new Error('File not found');
|
||||
},
|
||||
} as unknown as JSRuntimeFS,
|
||||
});
|
||||
|
||||
const result = await commandWithoutGit.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('fatal: not a git repository');
|
||||
});
|
||||
|
||||
it('should unstage all files when called without arguments', async () => {
|
||||
const result = await command.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
expect(result.stdout).toContain('M\tstaged.txt');
|
||||
expect(result.stdout).toContain('M\tnew-staged.txt');
|
||||
// Should not include files that aren't staged
|
||||
expect(result.stdout).not.toContain('modified.txt');
|
||||
expect(result.stdout).not.toContain('unchanged.txt');
|
||||
});
|
||||
|
||||
it('should unstage all files when called with HEAD', async () => {
|
||||
const result = await command.execute(['HEAD']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
expect(result.stdout).toContain('M\tstaged.txt');
|
||||
expect(result.stdout).toContain('M\tnew-staged.txt');
|
||||
});
|
||||
|
||||
it('should unstage specific files when called with HEAD and file paths', async () => {
|
||||
const result = await command.execute(['HEAD', 'staged.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('Unstaged changes after reset:');
|
||||
expect(result.stdout).toContain('M\tstaged.txt');
|
||||
expect(result.stdout).not.toContain('new-staged.txt');
|
||||
});
|
||||
|
||||
it('should return empty output when no files are staged', async () => {
|
||||
const commandWithNoStaged = new GitResetCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
statusMatrix: async () => [
|
||||
['modified.txt', 1, 2, 1], // Modified in working dir only
|
||||
['unchanged.txt', 1, 1, 1], // No changes
|
||||
],
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithNoStaged.execute([]);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle errors when resetting specific files', async () => {
|
||||
const commandWithError = new GitResetCommand({
|
||||
...mockOptions,
|
||||
git: {
|
||||
...mockGit,
|
||||
resetIndex: async ({ filepath }: { filepath: string }) => {
|
||||
if (filepath === 'nonexistent.txt') {
|
||||
throw new Error('File not found');
|
||||
}
|
||||
return { filepath };
|
||||
},
|
||||
} as unknown as Git,
|
||||
});
|
||||
|
||||
const result = await commandWithError.execute(['HEAD', 'nonexistent.txt']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("error: pathspec 'nonexistent.txt' did not match any file(s) known to git");
|
||||
});
|
||||
|
||||
it('should handle commit reset with hard mode', async () => {
|
||||
const result = await command.execute(['--hard', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||
});
|
||||
|
||||
it('should handle commit reset with mixed mode', async () => {
|
||||
const result = await command.execute(['--mixed', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toContain('HEAD is now at def456a');
|
||||
});
|
||||
|
||||
it('should return error for soft reset (not implemented)', async () => {
|
||||
const result = await command.execute(['--soft', 'HEAD~1']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('--soft reset is not implemented');
|
||||
});
|
||||
|
||||
it('should handle invalid commit reference', async () => {
|
||||
const result = await command.execute(['abcdef12345']);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain("fatal: ambiguous argument 'abcdef12345'");
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -29,10 +29,10 @@ export class GitResetCommand implements GitSubcommand {
|
||||
return createErrorResult('fatal: not a git repository (or any of the parent directories): .git');
|
||||
}
|
||||
|
||||
const { mode, target, files, isFileReset } = this.parseArgs(args);
|
||||
const { mode, target, files } = this.parseArgs(args);
|
||||
|
||||
if (isFileReset) {
|
||||
// Reset specific files or all files (unstage)
|
||||
if (files.length > 0) {
|
||||
// Reset specific files (unstage)
|
||||
return await this.resetFiles(files);
|
||||
} else {
|
||||
// Reset to commit
|
||||
@@ -47,27 +47,22 @@ export class GitResetCommand implements GitSubcommand {
|
||||
private parseArgs(args: string[]): {
|
||||
mode: 'soft' | 'mixed' | 'hard';
|
||||
target: string;
|
||||
files: string[];
|
||||
isFileReset: boolean;
|
||||
files: string[]
|
||||
} {
|
||||
let mode: 'soft' | 'mixed' | 'hard' = 'mixed'; // Default mode
|
||||
let target = 'HEAD'; // Default target
|
||||
const files: string[] = [];
|
||||
let foundTarget = false;
|
||||
let hasMode = false;
|
||||
|
||||
for (const arg of args) {
|
||||
if (arg === '--soft') {
|
||||
mode = 'soft';
|
||||
hasMode = true;
|
||||
} else if (arg === '--mixed') {
|
||||
mode = 'mixed';
|
||||
hasMode = true;
|
||||
} else if (arg === '--hard') {
|
||||
mode = 'hard';
|
||||
hasMode = true;
|
||||
} else if (!arg.startsWith('-')) {
|
||||
if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/) || arg.match(/^HEAD[~^]\d*$/))) {
|
||||
if (!foundTarget && (arg === 'HEAD' || arg.match(/^[a-f0-9]{7,40}$/))) {
|
||||
target = arg;
|
||||
foundTarget = true;
|
||||
} else {
|
||||
@@ -76,17 +71,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
}
|
||||
}
|
||||
|
||||
// Determine if this is a file reset operation
|
||||
// git reset without arguments = unstage all files
|
||||
// git reset HEAD = unstage all files
|
||||
// git reset HEAD <files> = unstage specific files
|
||||
// git reset <commit> = reset to commit
|
||||
// git reset --mode <commit> = reset to commit with mode
|
||||
const isFileReset = (args.length === 0) ||
|
||||
(target === 'HEAD' && !hasMode && files.length === 0) ||
|
||||
(files.length > 0);
|
||||
|
||||
return { mode, target, files, isFileReset };
|
||||
return { mode, target, files };
|
||||
}
|
||||
|
||||
private async resetFiles(files: string[]): Promise<ShellCommandResult> {
|
||||
@@ -94,53 +79,17 @@ export class GitResetCommand implements GitSubcommand {
|
||||
const resetFiles: string[] = [];
|
||||
const errors: string[] = [];
|
||||
|
||||
if (files.length === 0) {
|
||||
// Reset all staged files (git reset or git reset HEAD)
|
||||
for (const file of files) {
|
||||
try {
|
||||
// Get the status matrix to find all staged files
|
||||
const statusMatrix = await this.git.statusMatrix({
|
||||
// Remove from staging area (reset to HEAD)
|
||||
await this.git.resetIndex({
|
||||
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
|
||||
// Find files that are staged (differ from HEAD)
|
||||
const stagedFiles = statusMatrix
|
||||
.filter(([, headStatus, , stageStatus]) => {
|
||||
return headStatus !== stageStatus;
|
||||
})
|
||||
.map(([filepath]) => filepath);
|
||||
|
||||
if (stagedFiles.length === 0) {
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
// Reset each staged file
|
||||
for (const file of stagedFiles) {
|
||||
try {
|
||||
await this.git.resetIndex({
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
resetFiles.push(file);
|
||||
} catch (error) {
|
||||
errors.push(`error: failed to reset '${file}': ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
return createErrorResult(`Failed to get repository status: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
} else {
|
||||
// Reset specific files
|
||||
for (const file of files) {
|
||||
try {
|
||||
// Remove from staging area (reset to HEAD)
|
||||
await this.git.resetIndex({
|
||||
dir: this.pwd,
|
||||
filepath: file,
|
||||
});
|
||||
resetFiles.push(file);
|
||||
} catch {
|
||||
errors.push(`error: pathspec '${file}' did not match any file(s) known to git`);
|
||||
}
|
||||
resetFiles.push(file);
|
||||
} catch {
|
||||
errors.push(`error: pathspec '${file}' did not match any file(s) known to git`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -165,7 +114,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
let targetOid: string;
|
||||
try {
|
||||
targetOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: target,
|
||||
});
|
||||
@@ -177,7 +126,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
let currentOid: string;
|
||||
try {
|
||||
currentOid = await this.git.resolveRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
});
|
||||
@@ -203,7 +152,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
// Reset the index to match the target commit
|
||||
try {
|
||||
await this.git.checkout({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: target,
|
||||
noCheckout: true, // Only update the index, not the working directory
|
||||
@@ -223,14 +172,14 @@ export class GitResetCommand implements GitSubcommand {
|
||||
|
||||
// Get the commit object to ensure it exists
|
||||
await this.git.readCommit({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
oid: targetOid,
|
||||
});
|
||||
|
||||
// Update HEAD to point to the target commit
|
||||
await this.git.writeRef({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: 'HEAD',
|
||||
value: targetOid,
|
||||
@@ -239,7 +188,7 @@ export class GitResetCommand implements GitSubcommand {
|
||||
// Reset the working directory by checking out all files from the target commit
|
||||
// Use force to overwrite any local changes
|
||||
await this.git.checkout({
|
||||
|
||||
|
||||
dir: this.pwd,
|
||||
ref: targetOid,
|
||||
force: true,
|
||||
|
||||
@@ -19,7 +19,6 @@ export { MkdirCommand } from './mkdir';
|
||||
export { MvCommand } from './mv';
|
||||
export { PwdCommand } from './pwd';
|
||||
export { RmCommand } from './rm';
|
||||
export { SedCommand } from './sed';
|
||||
export { SortCommand } from './sort';
|
||||
export { TailCommand } from './tail';
|
||||
export { TouchCommand } from './touch';
|
||||
|
||||
@@ -1,274 +0,0 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { SedCommand } from './sed';
|
||||
import type { JSRuntimeFS } from '../JSRuntime';
|
||||
|
||||
// Mock filesystem
|
||||
const mockFS: JSRuntimeFS = {
|
||||
readFile: ((path: string, encoding?: string) => {
|
||||
const files: Record<string, string> = {
|
||||
'/test/hello.txt': 'hello world\nfoo bar\nbaz qux\n',
|
||||
'/test/numbers.txt': '1\n2\n3\n4\n5\n',
|
||||
'/test/mixed.txt': 'apple\nbanana\ncherry\napple pie\n',
|
||||
};
|
||||
|
||||
if (path in files) {
|
||||
if (encoding === 'utf8' || (encoding && encoding !== undefined)) {
|
||||
return Promise.resolve(files[path]);
|
||||
} else {
|
||||
// No encoding specified, return Uint8Array
|
||||
return Promise.resolve(new TextEncoder().encode(files[path]));
|
||||
}
|
||||
}
|
||||
return Promise.reject(new Error('ENOENT: no such file or directory'));
|
||||
}) as JSRuntimeFS['readFile'],
|
||||
|
||||
writeFile: async (_path: string, _data: string | Uint8Array, _encoding?: string) => {
|
||||
// Mock write operation
|
||||
},
|
||||
|
||||
stat: async (_path: string) => ({
|
||||
isFile: () => true,
|
||||
isDirectory: () => false,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
|
||||
lstat: async (_path: string) => ({
|
||||
isFile: () => true,
|
||||
isDirectory: () => false,
|
||||
size: 100,
|
||||
mtimeMs: Date.now(),
|
||||
}),
|
||||
|
||||
readdir: (async (_path: string, _options?: { withFileTypes?: boolean }) => {
|
||||
if (_options?.withFileTypes) {
|
||||
return [];
|
||||
}
|
||||
return [];
|
||||
}) as JSRuntimeFS['readdir'],
|
||||
mkdir: async () => {},
|
||||
rmdir: async () => {},
|
||||
unlink: async () => {},
|
||||
rename: async () => {},
|
||||
readlink: async () => '',
|
||||
symlink: async () => {},
|
||||
};
|
||||
|
||||
describe('SedCommand', () => {
|
||||
let sedCommand: SedCommand;
|
||||
|
||||
beforeEach(() => {
|
||||
sedCommand = new SedCommand(mockFS);
|
||||
});
|
||||
|
||||
describe('basic functionality', () => {
|
||||
it('should have correct name and description', () => {
|
||||
expect(sedCommand.name).toBe('sed');
|
||||
expect(sedCommand.description).toBe('Stream editor for filtering and transforming text');
|
||||
});
|
||||
|
||||
it('should return error when no script provided', async () => {
|
||||
const result = await sedCommand.execute([], '/test');
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('missing script');
|
||||
});
|
||||
});
|
||||
|
||||
describe('substitute command', () => {
|
||||
it('should substitute text with s command', async () => {
|
||||
const input = 'hello world\nfoo bar\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi world\nfoo bar\n');
|
||||
});
|
||||
|
||||
it('should substitute globally with g flag', async () => {
|
||||
const input = 'hello hello world\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/g'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi hi world\n');
|
||||
});
|
||||
|
||||
it('should substitute case-insensitively with i flag', async () => {
|
||||
const input = 'Hello HELLO world\n';
|
||||
const result = await sedCommand.execute(['s/hello/hi/gi'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi hi world\n');
|
||||
});
|
||||
|
||||
it('should substitute with special characters', async () => {
|
||||
const input = 'test.txt\n';
|
||||
const result = await sedCommand.execute(['s/\\.txt/.bak/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('test.bak\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('delete command', () => {
|
||||
it('should delete all lines with d command', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('\n');
|
||||
});
|
||||
|
||||
it('should delete specific line with line number', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['2d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline3\n');
|
||||
});
|
||||
|
||||
it('should delete lines matching pattern', async () => {
|
||||
const input = 'keep this\ndelete this line\nkeep this too\n';
|
||||
const result = await sedCommand.execute(['/delete/d'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('keep this\nkeep this too\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('print command', () => {
|
||||
it('should print all lines normally without -n', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline1\nline2\nline2\n'); // Each line printed twice (normal + p command)
|
||||
});
|
||||
|
||||
it('should print only specified lines with -n', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['-n', '2p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('quit command', () => {
|
||||
it('should quit after processing specified line', async () => {
|
||||
const input = 'line1\nline2\nline3\nline4\n';
|
||||
const result = await sedCommand.execute(['2q'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nline2\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('append, insert, and change commands', () => {
|
||||
it('should append text after line', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['1a\\appended text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nappended text\nline2\n');
|
||||
});
|
||||
|
||||
it('should insert text before line', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['2i\\inserted text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\ninserted text\nline2\n');
|
||||
});
|
||||
|
||||
it('should change line', async () => {
|
||||
const input = 'line1\nline2\nline3\n';
|
||||
const result = await sedCommand.execute(['2c\\changed text'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('line1\nchanged text\nline3\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('file operations', () => {
|
||||
it('should process file content', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', undefined);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle file not found error', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/', 'nonexistent.txt'], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('No such file or directory');
|
||||
});
|
||||
|
||||
it('should reject absolute paths', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/', '/absolute/path.txt'], '/test');
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('absolute paths are not supported');
|
||||
});
|
||||
});
|
||||
|
||||
describe('option parsing', () => {
|
||||
it('should parse -n option', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['-n', 'p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should parse -e option', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['-e', 's/hello/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi world\n');
|
||||
});
|
||||
|
||||
it('should parse combined options', async () => {
|
||||
const input = 'line1\nline2\n';
|
||||
const result = await sedCommand.execute(['-ne', 'p'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
});
|
||||
|
||||
describe('multiple scripts', () => {
|
||||
it('should process multiple scripts in order', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['-e', 's/hello/hi/', '-e', 's/world/universe/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hi universe\n');
|
||||
});
|
||||
});
|
||||
|
||||
describe('edge cases', () => {
|
||||
it('should handle empty input', async () => {
|
||||
const result = await sedCommand.execute(['s/hello/hi/'], '/test', '');
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('');
|
||||
});
|
||||
|
||||
it('should handle invalid regex patterns gracefully', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['s/[/hi/'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(0);
|
||||
expect(result.stdout).toBe('hello world\n'); // Should return original
|
||||
});
|
||||
|
||||
it('should handle invalid script format', async () => {
|
||||
const input = 'hello world\n';
|
||||
const result = await sedCommand.execute(['invalid_script'], '/test', input);
|
||||
|
||||
expect(result.exitCode).toBe(1);
|
||||
expect(result.stderr).toContain('Invalid sed script');
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -1,375 +0,0 @@
|
||||
import { join } from "path-browserify";
|
||||
import type { JSRuntimeFS } from "../JSRuntime";
|
||||
import type { ShellCommand, ShellCommandResult } from "./ShellCommand";
|
||||
import { createSuccessResult, createErrorResult } from "./ShellCommand";
|
||||
|
||||
/**
|
||||
* Implementation of the 'sed' command
|
||||
* Stream editor for filtering and transforming text
|
||||
*/
|
||||
export class SedCommand implements ShellCommand {
|
||||
name = 'sed';
|
||||
description = 'Stream editor for filtering and transforming text';
|
||||
usage = 'sed [-i] [-n] [-e script] [script] [file...]';
|
||||
|
||||
private fs: JSRuntimeFS;
|
||||
|
||||
constructor(fs: JSRuntimeFS) {
|
||||
this.fs = fs;
|
||||
}
|
||||
|
||||
async execute(args: string[], cwd: string, input?: string): Promise<ShellCommandResult> {
|
||||
if (args.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing script\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
try {
|
||||
const { options, scripts, files } = this.parseArgs(args);
|
||||
|
||||
if (scripts.length === 0) {
|
||||
return createErrorResult(`${this.name}: missing script\nUsage: ${this.usage}`);
|
||||
}
|
||||
|
||||
let content = '';
|
||||
|
||||
// If input is provided (from pipe), use that input
|
||||
if (input !== undefined) {
|
||||
content = input;
|
||||
} else if (files.length === 0) {
|
||||
// Read from stdin (not implemented in this context, return empty)
|
||||
return createSuccessResult('');
|
||||
} else {
|
||||
// Read all files
|
||||
for (const file of files) {
|
||||
try {
|
||||
// Handle absolute paths
|
||||
if (file.startsWith('/') || file.startsWith('\\') || /^[A-Za-z]:[\\/]/.test(file)) {
|
||||
return createErrorResult(`${this.name}: absolute paths are not supported: ${file}`);
|
||||
}
|
||||
|
||||
const absolutePath = join(cwd, file);
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
return createErrorResult(`${this.name}: ${file}: Is a directory`);
|
||||
}
|
||||
|
||||
const fileContent = await this.fs.readFile(absolutePath, 'utf8');
|
||||
content += fileContent;
|
||||
} catch (error) {
|
||||
if (error instanceof Error) {
|
||||
if (error.message.includes('ENOENT') || error.message.includes('not found')) {
|
||||
return createErrorResult(`${this.name}: ${file}: No such file or directory`);
|
||||
} else if (error.message.includes('EACCES') || error.message.includes('permission')) {
|
||||
return createErrorResult(`${this.name}: ${file}: Permission denied`);
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${file}: ${error.message}`);
|
||||
}
|
||||
} else {
|
||||
return createErrorResult(`${this.name}: ${file}: Unknown error`);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Process content with sed scripts
|
||||
let result = content;
|
||||
for (const script of scripts) {
|
||||
result = await this.processScript(script, result, options);
|
||||
}
|
||||
|
||||
// Handle in-place editing
|
||||
if (options.inPlace && files.length > 0) {
|
||||
for (const file of files) {
|
||||
const absolutePath = join(cwd, file);
|
||||
await this.fs.writeFile(absolutePath, result, 'utf8');
|
||||
}
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
// Handle quiet mode
|
||||
if (options.quiet) {
|
||||
// In quiet mode, only explicitly printed lines are output
|
||||
// For now, we'll return empty unless there are 'p' commands
|
||||
return createSuccessResult('');
|
||||
}
|
||||
|
||||
return createSuccessResult(result);
|
||||
|
||||
} catch (error) {
|
||||
return createErrorResult(`${this.name}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
|
||||
private async processScript(script: string, content: string, options: { quiet: boolean; inPlace: boolean }): Promise<string> {
|
||||
// Track if original content ended with newline
|
||||
const originalEndsWithNewline = content.endsWith('\n');
|
||||
|
||||
// Split lines but handle the trailing newline properly
|
||||
let lines = content.split('\n');
|
||||
if (originalEndsWithNewline && lines[lines.length - 1] === '') {
|
||||
lines = lines.slice(0, -1); // Remove the empty line at the end
|
||||
}
|
||||
|
||||
const resultLines: string[] = [];
|
||||
|
||||
// Parse the sed script
|
||||
const command = this.parseScript(script);
|
||||
|
||||
if (!command) {
|
||||
throw new Error(`Invalid sed script: ${script}`);
|
||||
}
|
||||
|
||||
for (let i = 0; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
let processedLine = line;
|
||||
let shouldPrint = !options.quiet;
|
||||
|
||||
switch (command.type) {
|
||||
case 's': {// Substitute
|
||||
const substituted = this.substitute(line, command.pattern!, command.replacement!, command.flags!);
|
||||
processedLine = substituted;
|
||||
break;
|
||||
}
|
||||
|
||||
case 'd': // Delete
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
shouldPrint = false;
|
||||
continue;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'p': // Print
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
if (options.quiet) {
|
||||
shouldPrint = false;
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'q': // Quit
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
return this.formatOutput(resultLines, originalEndsWithNewline);
|
||||
}
|
||||
break;
|
||||
|
||||
case 'a': // Append
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(processedLine);
|
||||
resultLines.push(command.text || '');
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'i': // Insert
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(command.text || '');
|
||||
resultLines.push(processedLine);
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
|
||||
case 'c': // Change
|
||||
if (this.matchesAddress(i + 1, line, command.address ?? null)) {
|
||||
resultLines.push(command.text || '');
|
||||
shouldPrint = false;
|
||||
}
|
||||
break;
|
||||
}
|
||||
|
||||
if (shouldPrint) {
|
||||
resultLines.push(processedLine);
|
||||
}
|
||||
}
|
||||
|
||||
return this.formatOutput(resultLines, originalEndsWithNewline);
|
||||
}
|
||||
|
||||
private formatOutput(lines: string[], originalEndsWithNewline: boolean): string {
|
||||
if (lines.length === 0) {
|
||||
return originalEndsWithNewline ? '\n' : '';
|
||||
}
|
||||
|
||||
const result = lines.join('\n');
|
||||
|
||||
// Only add trailing newline if original content had one
|
||||
return originalEndsWithNewline ? result + '\n' : result;
|
||||
}
|
||||
|
||||
private parseScript(script: string): SedCommandSpec | null {
|
||||
// Handle substitute command: s/pattern/replacement/flags
|
||||
const substituteMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?s\/(.*)\/(.*)\/([gimx]*)$/);
|
||||
if (substituteMatch) {
|
||||
return {
|
||||
type: 's',
|
||||
address: substituteMatch[1] || null,
|
||||
pattern: substituteMatch[2],
|
||||
replacement: substituteMatch[3],
|
||||
flags: substituteMatch[4]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle delete command: d or address d
|
||||
const deleteMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?d$/);
|
||||
if (deleteMatch) {
|
||||
return {
|
||||
type: 'd',
|
||||
address: deleteMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle print command: p or address p
|
||||
const printMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?p$/);
|
||||
if (printMatch) {
|
||||
return {
|
||||
type: 'p',
|
||||
address: printMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle quit command: q or address q
|
||||
const quitMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?q$/);
|
||||
if (quitMatch) {
|
||||
return {
|
||||
type: 'q',
|
||||
address: quitMatch[1] || null
|
||||
};
|
||||
}
|
||||
|
||||
// Handle append command: a\text or address a\text
|
||||
const appendMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?a\\(.*)$/);
|
||||
if (appendMatch) {
|
||||
return {
|
||||
type: 'a',
|
||||
address: appendMatch[1] || null,
|
||||
text: appendMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle insert command: i\text or address i\text
|
||||
const insertMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?i\\(.*)$/);
|
||||
if (insertMatch) {
|
||||
return {
|
||||
type: 'i',
|
||||
address: insertMatch[1] || null,
|
||||
text: insertMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
// Handle change command: c\text or address c\text
|
||||
const changeMatch = script.match(/^(?:(\d+|\$|\/.*?\/)?)?c\\(.*)$/);
|
||||
if (changeMatch) {
|
||||
return {
|
||||
type: 'c',
|
||||
address: changeMatch[1] || null,
|
||||
text: changeMatch[2]
|
||||
};
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
private substitute(line: string, pattern: string, replacement: string, flags: string): string {
|
||||
try {
|
||||
const regexFlags = flags.includes('g') ? 'g' : '';
|
||||
const caseInsensitive = flags.includes('i');
|
||||
|
||||
const regex = new RegExp(pattern, regexFlags + (caseInsensitive ? 'i' : ''));
|
||||
return line.replace(regex, replacement);
|
||||
} catch {
|
||||
// If regex is invalid, return original line
|
||||
return line;
|
||||
}
|
||||
}
|
||||
|
||||
private matchesAddress(lineNumber: number, line: string, address: string | null): boolean {
|
||||
if (!address) {
|
||||
return true; // No address means match all lines
|
||||
}
|
||||
|
||||
// Line number address
|
||||
if (/^\d+$/.test(address)) {
|
||||
return lineNumber === parseInt(address);
|
||||
}
|
||||
|
||||
// Last line address
|
||||
if (address === '$') {
|
||||
// This is tricky to implement without knowing total lines
|
||||
// For now, we'll assume it doesn't match
|
||||
return false;
|
||||
}
|
||||
|
||||
// Pattern address /pattern/
|
||||
const patternMatch = address.match(/^\/(.*)\/$/);
|
||||
if (patternMatch) {
|
||||
try {
|
||||
const regex = new RegExp(patternMatch[1]);
|
||||
return regex.test(line);
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
private parseArgs(args: string[]): {
|
||||
options: { quiet: boolean; inPlace: boolean };
|
||||
scripts: string[];
|
||||
files: string[]
|
||||
} {
|
||||
const options = { quiet: false, inPlace: false };
|
||||
const scripts: string[] = [];
|
||||
const files: string[] = [];
|
||||
let i = 0;
|
||||
let expectingScript = false;
|
||||
|
||||
while (i < args.length) {
|
||||
const arg = args[i];
|
||||
|
||||
if (arg === '-n') {
|
||||
options.quiet = true;
|
||||
} else if (arg === '-i') {
|
||||
options.inPlace = true;
|
||||
} else if (arg === '-e') {
|
||||
expectingScript = true;
|
||||
} else if (arg.startsWith('-') && arg !== '-') {
|
||||
// Parse combined options
|
||||
for (let j = 1; j < arg.length; j++) {
|
||||
const char = arg[j];
|
||||
switch (char) {
|
||||
case 'n':
|
||||
options.quiet = true;
|
||||
break;
|
||||
case 'i':
|
||||
options.inPlace = true;
|
||||
break;
|
||||
case 'e':
|
||||
expectingScript = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (expectingScript || (scripts.length === 0 && !arg.startsWith('-'))) {
|
||||
scripts.push(arg);
|
||||
expectingScript = false;
|
||||
} else {
|
||||
files.push(arg);
|
||||
}
|
||||
|
||||
i++;
|
||||
}
|
||||
|
||||
return { options, scripts, files };
|
||||
}
|
||||
}
|
||||
|
||||
interface SedCommandSpec {
|
||||
type: 's' | 'd' | 'p' | 'q' | 'a' | 'i' | 'c';
|
||||
address?: string | null;
|
||||
pattern?: string;
|
||||
replacement?: string;
|
||||
flags?: string;
|
||||
text?: string;
|
||||
}
|
||||
+12
-73
@@ -908,16 +908,15 @@ export class Git {
|
||||
'#d': [nostrURI.d],
|
||||
};
|
||||
|
||||
// Always prioritize git.shakespeare.diy
|
||||
const shakespeareRelayUrl = 'wss://git.shakespeare.diy/';
|
||||
const otherGitRelays = [
|
||||
const gitRelays = new Set<string>([
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://relay.nostr.band/', // General purpose relay as fallback
|
||||
];
|
||||
]);
|
||||
|
||||
let events: NostrEvent[] = [];
|
||||
|
||||
// Try the specified relay first if provided
|
||||
// Try the specified relay first, then fall back to known Git relays
|
||||
if (nostrURI.relay) {
|
||||
try {
|
||||
events = await this.nostr.relay(nostrURI.relay).query([filter], { signal: AbortSignal.timeout(1000) });
|
||||
@@ -925,30 +924,11 @@ export class Git {
|
||||
console.error(`Error querying relay ${nostrURI.relay}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// If no events from specified relay, try git.shakespeare.diy first
|
||||
if (!events.length) {
|
||||
try {
|
||||
console.log(`Trying git.shakespeare.diy first...`);
|
||||
events = await this.nostr.relay(shakespeareRelayUrl).query([filter], { signal: AbortSignal.timeout(3000) });
|
||||
if (events.length > 0) {
|
||||
console.log(`✓ Found events on ${shakespeareRelayUrl}`);
|
||||
}
|
||||
events = await this.nostr.group([...gitRelays]).query([filter], { signal: AbortSignal.timeout(5000) });
|
||||
} catch (error) {
|
||||
console.error(`Error querying ${shakespeareRelayUrl}: ${error}`);
|
||||
}
|
||||
}
|
||||
|
||||
// If still no events, try other git relays
|
||||
if (!events.length) {
|
||||
try {
|
||||
console.log(`Trying other git relays: ${otherGitRelays.join(', ')}`);
|
||||
events = await this.nostr.group(otherGitRelays).query([filter], { signal: AbortSignal.timeout(5000) });
|
||||
if (events.length > 0) {
|
||||
console.log(`✓ Found events on fallback relays`);
|
||||
}
|
||||
} catch (error) {
|
||||
console.error(`Error querying fallback relays: ${error}`);
|
||||
console.error(`Error querying group relays: ${error}`);
|
||||
}
|
||||
}
|
||||
if (!events.length) {
|
||||
@@ -1410,24 +1390,13 @@ export class Git {
|
||||
}
|
||||
}
|
||||
|
||||
// Ensure git.shakespeare.diy is always included and prioritized
|
||||
const shakespeareRelay = 'wss://git.shakespeare.diy/';
|
||||
|
||||
// Remove git.shakespeare.diy from relayUrls if it exists (to avoid duplicates)
|
||||
const filteredRelayUrls = relayUrls.filter(url => url !== shakespeareRelay);
|
||||
|
||||
// Always prioritize git.shakespeare.diy by putting it first
|
||||
relayUrls.unshift(shakespeareRelay);
|
||||
|
||||
// If no relays specified in announcement, use default git-focused relays
|
||||
if (filteredRelayUrls.length === 0 && relayUrls.length === 1) {
|
||||
if (relayUrls.length === 0) {
|
||||
relayUrls.push(
|
||||
'wss://git.shakespeare.diy/',
|
||||
'wss://relay.ngit.dev/',
|
||||
'wss://relay.nostr.band/'
|
||||
);
|
||||
} else {
|
||||
// Add back the other relays after git.shakespeare.diy
|
||||
relayUrls.push(...filteredRelayUrls);
|
||||
}
|
||||
|
||||
// Get current repository state
|
||||
@@ -1448,42 +1417,12 @@ export class Git {
|
||||
// Publish the state event to Nostr relays
|
||||
console.log(`Publishing repository state to ${relayUrls.length} relays`);
|
||||
|
||||
// Always publish to git.shakespeare.diy first
|
||||
const shakespeareRelayUrl = 'wss://git.shakespeare.diy/';
|
||||
const otherRelays = relayUrls.filter(url => url !== shakespeareRelayUrl);
|
||||
|
||||
try {
|
||||
// Publish to git.shakespeare.diy first
|
||||
console.log(`Publishing to ${shakespeareRelayUrl} first...`);
|
||||
await this.nostr.relay(shakespeareRelayUrl).event(stateEvent);
|
||||
console.log(`✓ Repository state published to ${shakespeareRelayUrl} successfully`);
|
||||
|
||||
// Then publish to other relays
|
||||
if (otherRelays.length > 0) {
|
||||
console.log(`Publishing to ${otherRelays.length} additional relays...`);
|
||||
try {
|
||||
await this.nostr.group(otherRelays).event(stateEvent);
|
||||
console.log('✓ Repository state published to additional relays successfully');
|
||||
} catch (error) {
|
||||
console.warn('Failed to publish repository state to some additional relays:', error);
|
||||
// Continue even if publishing to additional relays fails
|
||||
}
|
||||
}
|
||||
|
||||
console.log('✓ Nostr push completed successfully');
|
||||
await this.nostr.group(relayUrls).event(stateEvent);
|
||||
console.log('✓ Repository state published to Nostr successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to publish repository state to git.shakespeare.diy:', error);
|
||||
// If git.shakespeare.diy fails, still try to publish to other relays as fallback
|
||||
if (otherRelays.length > 0) {
|
||||
console.log(`Attempting to publish to ${otherRelays.length} fallback relays...`);
|
||||
try {
|
||||
await this.nostr.group(otherRelays).event(stateEvent);
|
||||
console.log('✓ Repository state published to fallback relays successfully');
|
||||
} catch (fallbackError) {
|
||||
console.warn('Failed to publish repository state to fallback relays:', fallbackError);
|
||||
}
|
||||
}
|
||||
// Don't throw here - continue with Git push even if Nostr publishing fails
|
||||
console.warn('Failed to publish repository state to some relays:', error);
|
||||
// Continue with Git push even if Nostr publishing partially fails
|
||||
}
|
||||
|
||||
// Push to each clone URL
|
||||
|
||||
@@ -183,8 +183,6 @@ const resources = {
|
||||
authentication: 'Authentication',
|
||||
addCustomProviderButton: 'Add Custom Provider',
|
||||
providerExists: 'Provider with this name already exists',
|
||||
agreeToTermsOfService: 'I agree to {{providerName}}’s',
|
||||
termsOfService: 'Terms of Service',
|
||||
custom: 'Custom',
|
||||
connecting: 'Connecting...',
|
||||
connectToGitHub: 'Connect to GitHub',
|
||||
@@ -494,8 +492,6 @@ const resources = {
|
||||
authentication: 'Autenticação',
|
||||
addCustomProviderButton: 'Adicionar Provedor Personalizado',
|
||||
providerExists: 'Provedor com este nome já existe',
|
||||
agreeToTermsOfService: 'Concordo com {{providerName}}',
|
||||
termsOfService: 'Termos de Serviço',
|
||||
custom: 'Personalizado',
|
||||
connecting: 'Conectando...',
|
||||
connectToGitHub: 'Conectar ao GitHub',
|
||||
@@ -805,8 +801,6 @@ const resources = {
|
||||
authentication: '身份验证',
|
||||
addCustomProviderButton: '添加自定义提供商',
|
||||
providerExists: '此名称的提供商已存在',
|
||||
agreeToTermsOfService: '我同意{{providerName}}',
|
||||
termsOfService: '服务条款',
|
||||
custom: '自定义',
|
||||
connecting: '连接中...',
|
||||
connectToGitHub: '连接到GitHub',
|
||||
@@ -1116,8 +1110,6 @@ const resources = {
|
||||
authentication: 'Tabbatarwa',
|
||||
addCustomProviderButton: 'Ƙara Mai Samarwa na Musamman',
|
||||
providerExists: 'Mai samarwa da wannan suna ya riga ya wanzu',
|
||||
agreeToTermsOfService: 'Na yarda da {{providerName}}',
|
||||
termsOfService: 'Sharuɗɗan Sabis',
|
||||
custom: 'Na Musamman',
|
||||
connecting: 'Ana haɗawa...',
|
||||
connectToGitHub: 'Haɗu da GitHub',
|
||||
@@ -1427,8 +1419,6 @@ const resources = {
|
||||
authentication: 'Ijẹrisi',
|
||||
addCustomProviderButton: 'Fi Olupese Aṣa kun',
|
||||
providerExists: 'Olupese pẹlu orukọ yii ti wa tẹlẹ',
|
||||
agreeToTermsOfService: 'Mo gba {{providerName}}',
|
||||
termsOfService: 'Awọn Ofin Iṣẹ',
|
||||
custom: 'Aṣa',
|
||||
connecting: 'N so...',
|
||||
connectToGitHub: 'So si GitHub',
|
||||
@@ -1733,8 +1723,6 @@ const resources = {
|
||||
authentication: 'Nkwenye',
|
||||
addCustomProviderButton: 'Tinye Onye Na-enye Omenala',
|
||||
providerExists: 'Onye na-enye nwere aha a adịlarị',
|
||||
agreeToTermsOfService: 'Ekwenyere m na {{providerName}}',
|
||||
termsOfService: 'Usoro Ọrụ',
|
||||
custom: 'Omenala',
|
||||
connecting: 'Na-ejikọ...',
|
||||
connectToGitHub: 'Jikọọ na GitHub',
|
||||
|
||||
+1
-32
@@ -99,36 +99,6 @@ Users interact with Shakespeare by:
|
||||
5. **Project Management**: Organizing and accessing multiple projects from the homepage
|
||||
6. **Deploying Projects**: Publishing their creations to public URLs (requires Nostr login)
|
||||
|
||||
## Virtual Filesystem Structure
|
||||
|
||||
Shakespeare operates on a browser-based virtual filesystem (VFS) that persists all data in IndexedDB. Understanding this structure helps you navigate and work with projects effectively:
|
||||
|
||||
\`\`\`
|
||||
/
|
||||
├── projects/
|
||||
│ ├── {projectId1}/ # Individual project directory
|
||||
│ │ ├── package.json
|
||||
│ │ ├── src/
|
||||
│ │ ├── public/
|
||||
│ │ └── ... # Project files
|
||||
│ ├── {projectId2}/ # Another project
|
||||
│ │ └── ...
|
||||
│ └── ... # More projects
|
||||
├── config/ # Configuration files
|
||||
│ ├── ai.json # AI provider settings and API keys
|
||||
│ └── git.json # Git credentials and repository settings
|
||||
└── tmp/ # Temporary files and scratch space
|
||||
└── ... # Various temporary files and directories
|
||||
\`\`\`
|
||||
|
||||
### Key VFS Features
|
||||
|
||||
- **Project Isolation**: Each project has its own directory namespace at \`/projects/{projectId}/\`
|
||||
- **Cross-Project Access**: You can view other projects by exploring the \`/projects/\` directory
|
||||
- **Persistent Storage**: All files are stored in the browser's IndexedDB across sessions
|
||||
- **Full POSIX Operations**: Support for read, write, mkdir, rm, and other filesystem operations
|
||||
- **Git Integration**: Projects can be initialized as Git repositories for version control
|
||||
|
||||
## Your Role
|
||||
|
||||
As the AI assistant in Shakespeare, you help users by:
|
||||
@@ -138,9 +108,8 @@ As the AI assistant in Shakespeare, you help users by:
|
||||
- Providing suggestions and best practices
|
||||
- Troubleshooting issues and implementing fixes
|
||||
- Building complete, functional Nostr websites and applications
|
||||
- Learning from existing projects in the VFS to provide better solutions
|
||||
|
||||
The user expects you to handle all technical implementation while they focus on describing their vision and requirements. You can leverage the knowledge from other projects in the VFS to build better, more sophisticated applications.`;
|
||||
The user expects you to handle all technical implementation while they focus on describing their vision and requirements.`;
|
||||
|
||||
// Add available tools to the system prompt
|
||||
const toolNames = tools
|
||||
|
||||
@@ -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, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection 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();
|
||||
});
|
||||
|
||||
@@ -177,57 +177,6 @@ describe('ShellTool', () => {
|
||||
expect(shellTool.getCurrentWorkingDirectory()).toBe('/test/dir/subdir');
|
||||
});
|
||||
|
||||
describe('output redirection', () => {
|
||||
it('should redirect output to file with > operator', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo "hello world" > test.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'hello world\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should append output to file with >> operator', async () => {
|
||||
vi.mocked(mockFS.readFile).mockResolvedValue('existing content\n');
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo "new line" >> test.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.readFile).toHaveBeenCalledWith('/test/dir/test.txt', 'utf8');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/test.txt', 'existing content\nnew line\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should create new file with >> operator if file does not exist', async () => {
|
||||
vi.mocked(mockFS.readFile).mockRejectedValue(new Error('ENOENT: no such file or directory'));
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo "first line" >> newfile.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/newfile.txt', 'first line\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle quoted filenames in redirection', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo test > "file with spaces.txt"' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/test/dir/file with spaces.txt', 'test\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle absolute paths in redirection', async () => {
|
||||
const result = await shellTool.execute({ command: 'echo test > /tmp/absolute.txt' });
|
||||
|
||||
expect(result).toBe('(no output)');
|
||||
expect(mockFS.writeFile).toHaveBeenCalledWith('/tmp/absolute.txt', 'test\n', 'utf8');
|
||||
});
|
||||
|
||||
it('should handle redirection errors gracefully', async () => {
|
||||
vi.mocked(mockFS.writeFile).mockRejectedValue(new Error('Permission denied'));
|
||||
|
||||
const result = await shellTool.execute({ command: 'echo test > /readonly/file.txt' });
|
||||
|
||||
expect(result).toContain('Redirection error: Permission denied');
|
||||
expect(result).toContain('Exit code: 1');
|
||||
});
|
||||
});
|
||||
|
||||
describe('compound commands', () => {
|
||||
it('should execute commands with && operator (success case)', async () => {
|
||||
const result = await shellTool.execute({ command: 'pwd && echo hello' });
|
||||
|
||||
+10
-103
@@ -24,7 +24,6 @@ import {
|
||||
MvCommand,
|
||||
PwdCommand,
|
||||
RmCommand,
|
||||
SedCommand,
|
||||
SortCommand,
|
||||
TailCommand,
|
||||
TouchCommand,
|
||||
@@ -49,11 +48,11 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
private git: Git;
|
||||
private commands: Map<string, ShellCommand>;
|
||||
|
||||
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, sed, diff, which, whoami, date, env, clear, git, curl, unzip, hexdump. Supports compound commands with &&, ||, ;, and | operators, and output redirection 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(
|
||||
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'", "curl -X GET https://api.example.com", "curl -H \'Content-Type: application/json\' -d \'{"key":"value"}\' https://api.example.com". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'". Also supports output redirection with > and >> operators, e.g. "echo hello > file.txt", "ls >> output.log"'
|
||||
'Shell command to execute, e.g. "cat file.txt", "ls -la", "cd src", "pwd", "sort file.txt", "diff file1 file2", "git status", "git add .", "git commit -m \'message\'", "curl -X GET https://api.example.com", "curl -H \'Content-Type: application/json\' -d \'{"key":"value"}\' https://api.example.com". Supports compound commands with &&, ||, ;, and | operators, e.g. "pwd && ls -la", "cat file.txt | grep pattern", "git add . && git commit -m \'update\'"'
|
||||
),
|
||||
});
|
||||
|
||||
@@ -84,7 +83,6 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
this.registerCommand(new MvCommand(fs));
|
||||
this.registerCommand(new PwdCommand());
|
||||
this.registerCommand(new RmCommand(fs));
|
||||
this.registerCommand(new SedCommand(fs));
|
||||
this.registerCommand(new SortCommand(fs));
|
||||
this.registerCommand(new TailCommand(fs));
|
||||
this.registerCommand(new TouchCommand(fs));
|
||||
@@ -106,61 +104,17 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
}
|
||||
|
||||
/**
|
||||
* Parse a command string into command name, arguments, and redirection info
|
||||
* Parse a command string into command name and arguments
|
||||
*/
|
||||
private parseCommand(commandStr: string): { name: string; args: string[]; redirectType?: '>' | '>>'; redirectFile?: string } {
|
||||
// First, check for redirection operators
|
||||
let redirectType: '>' | '>>' | undefined;
|
||||
let redirectFile: string | undefined;
|
||||
let actualCommand = commandStr;
|
||||
|
||||
// Look for redirection operators (outside of quotes)
|
||||
private parseCommand(commandStr: string): { name: string; args: string[] } {
|
||||
// Simple parsing - split by spaces, respecting quoted strings
|
||||
const parts: string[] = [];
|
||||
let current = '';
|
||||
let inQuotes = false;
|
||||
let quoteChar = '';
|
||||
|
||||
for (let i = 0; i < commandStr.length; i++) {
|
||||
const char = commandStr[i];
|
||||
const nextChar = commandStr[i + 1];
|
||||
|
||||
if (!inQuotes && (char === '"' || char === "'")) {
|
||||
inQuotes = true;
|
||||
quoteChar = char;
|
||||
} else if (inQuotes && char === quoteChar) {
|
||||
inQuotes = false;
|
||||
quoteChar = '';
|
||||
} else if (!inQuotes) {
|
||||
if (char === '>' && nextChar === '>') {
|
||||
// >> append redirection
|
||||
redirectType = '>>';
|
||||
actualCommand = commandStr.substring(0, i).trim();
|
||||
redirectFile = commandStr.substring(i + 2).trim();
|
||||
break;
|
||||
} else if (char === '>' && nextChar !== '>') {
|
||||
// > overwrite redirection
|
||||
redirectType = '>';
|
||||
actualCommand = commandStr.substring(0, i).trim();
|
||||
redirectFile = commandStr.substring(i + 1).trim();
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Remove quotes from redirect file if present
|
||||
if (redirectFile) {
|
||||
if ((redirectFile.startsWith('"') && redirectFile.endsWith('"')) ||
|
||||
(redirectFile.startsWith("'") && redirectFile.endsWith("'"))) {
|
||||
redirectFile = redirectFile.slice(1, -1);
|
||||
}
|
||||
}
|
||||
|
||||
// Parse the actual command part
|
||||
const parts: string[] = [];
|
||||
let current = '';
|
||||
inQuotes = false;
|
||||
quoteChar = '';
|
||||
|
||||
for (let i = 0; i < actualCommand.length; i++) {
|
||||
const char = actualCommand[i];
|
||||
|
||||
if (!inQuotes && (char === '"' || char === "'")) {
|
||||
inQuotes = true;
|
||||
@@ -183,7 +137,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
}
|
||||
|
||||
const [name = '', ...args] = parts;
|
||||
return { name, args, redirectType, redirectFile };
|
||||
return { name, args };
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -209,7 +163,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
quoteChar = '';
|
||||
current += char;
|
||||
} else if (!inQuotes) {
|
||||
// Check for compound operators (but not redirection operators)
|
||||
// Check for compound operators
|
||||
if (char === '&' && nextChar === '&') {
|
||||
// && operator
|
||||
if (current.trim()) {
|
||||
@@ -258,7 +212,7 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
* Execute a single command and return the result
|
||||
*/
|
||||
private async executeSingleCommand(commandStr: string, input?: string): Promise<{ stdout: string; stderr: string; exitCode: number; newCwd?: string }> {
|
||||
const { name, args: cmdArgs, redirectType, redirectFile } = this.parseCommand(commandStr);
|
||||
const { name, args: cmdArgs } = this.parseCommand(commandStr);
|
||||
|
||||
if (!name) {
|
||||
return { stdout: '', stderr: 'Error: No command specified', exitCode: 1 };
|
||||
@@ -279,27 +233,6 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
// Execute the command
|
||||
const result = await command.execute(cmdArgs, this.cwd, input);
|
||||
|
||||
// Handle redirection if specified
|
||||
if (redirectType && redirectFile) {
|
||||
try {
|
||||
await this.handleRedirection(result.stdout, redirectType, redirectFile);
|
||||
// For redirection, we don't output to stdout
|
||||
return {
|
||||
stdout: '',
|
||||
stderr: result.stderr || '',
|
||||
exitCode: result.exitCode,
|
||||
newCwd: result.newCwd,
|
||||
};
|
||||
} catch (redirectError) {
|
||||
return {
|
||||
stdout: '',
|
||||
stderr: `Redirection error: ${redirectError instanceof Error ? redirectError.message : 'Unknown error'}`,
|
||||
exitCode: 1,
|
||||
newCwd: result.newCwd,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return {
|
||||
stdout: result.stdout || '',
|
||||
stderr: result.stderr || '',
|
||||
@@ -370,32 +303,6 @@ export class ShellTool implements Tool<ShellToolParams> {
|
||||
return output || '(no output)';
|
||||
}
|
||||
|
||||
/**
|
||||
* Handle output redirection to a file
|
||||
*/
|
||||
private async handleRedirection(output: string, redirectType: '>' | '>>', redirectFile: string): Promise<void> {
|
||||
// Resolve the file path relative to current working directory
|
||||
const filePath = redirectFile.startsWith('/') ? redirectFile : `${this.cwd}/${redirectFile}`;
|
||||
|
||||
if (redirectType === '>') {
|
||||
// Overwrite the file
|
||||
await this.fs.writeFile(filePath, output, 'utf8');
|
||||
} else if (redirectType === '>>') {
|
||||
// Append to the file
|
||||
try {
|
||||
const existingContent = await this.fs.readFile(filePath, 'utf8');
|
||||
await this.fs.writeFile(filePath, existingContent + output, 'utf8');
|
||||
} catch (error) {
|
||||
// If file doesn't exist, create it
|
||||
if (error instanceof Error && error.message.includes('ENOENT')) {
|
||||
await this.fs.writeFile(filePath, output, 'utf8');
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Execute compound commands with operators (&&, ||, ;, |)
|
||||
*/
|
||||
|
||||
@@ -9,29 +9,15 @@ class MockFS implements JSRuntimeFS {
|
||||
|
||||
constructor() {
|
||||
// Set up a basic project structure
|
||||
this.dirs.add('/projects');
|
||||
this.dirs.add('/projects/project1');
|
||||
this.dirs.add('/projects/project1/src');
|
||||
this.dirs.add('/projects/project1/.git');
|
||||
this.dirs.add('/projects/project2');
|
||||
this.dirs.add('/projects/project2/src');
|
||||
this.dirs.add('/project');
|
||||
this.dirs.add('/project/.git');
|
||||
this.dirs.add('/project/src');
|
||||
this.dirs.add('/project/node_modules');
|
||||
this.dirs.add('/tmp');
|
||||
|
||||
this.files.set('/projects/project1/package.json', '{"name": "project1"}');
|
||||
this.files.set('/projects/project1/src/index.ts', 'console.log("project1");');
|
||||
this.files.set('/projects/project1/.git/config', '[core]\nrepositoryformatversion = 0');
|
||||
this.files.set('/projects/project1/.git/HEAD', 'ref: refs/heads/main');
|
||||
this.files.set('/projects/project2/package.json', '{"name": "project2"}');
|
||||
this.files.set('/projects/project2/src/main.ts', 'console.log("project2");');
|
||||
this.files.set('/project/package.json', '{"name": "test"}');
|
||||
this.files.set('/project/src/index.ts', 'console.log("hello");');
|
||||
this.files.set('/project/.gitignore', 'node_modules\n.git\n');
|
||||
this.files.set('/project/.git/config', '[core]\nrepositoryformatversion = 0');
|
||||
this.files.set('/project/.git/HEAD', 'ref: refs/heads/main');
|
||||
this.files.set('/tmp/uploaded-file.txt', 'This is an uploaded file');
|
||||
|
||||
// Add binary files for testing
|
||||
@@ -79,14 +65,12 @@ class MockFS implements JSRuntimeFS {
|
||||
async readdir(path: string, options: { withFileTypes: true }): Promise<DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | DirectoryEntry[]> {
|
||||
// Normalize path by removing trailing slash
|
||||
const normalizedPath = path.replace(/\/$/, '') || '/';
|
||||
const entries: string[] = [];
|
||||
|
||||
// Find all files and directories that are direct children of this path
|
||||
for (const filePath of this.files.keys()) {
|
||||
if (filePath.startsWith(normalizedPath + '/')) {
|
||||
const relativePath = filePath.slice(normalizedPath.length + 1);
|
||||
if (filePath.startsWith(path + '/')) {
|
||||
const relativePath = filePath.slice(path.length + 1);
|
||||
const parts = relativePath.split('/');
|
||||
if (parts.length === 1) {
|
||||
entries.push(parts[0]);
|
||||
@@ -95,8 +79,8 @@ class MockFS implements JSRuntimeFS {
|
||||
}
|
||||
|
||||
for (const dirPath of this.dirs) {
|
||||
if (dirPath.startsWith(normalizedPath + '/')) {
|
||||
const relativePath = dirPath.slice(normalizedPath.length + 1);
|
||||
if (dirPath.startsWith(path + '/')) {
|
||||
const relativePath = dirPath.slice(path.length + 1);
|
||||
const parts = relativePath.split('/');
|
||||
if (parts.length === 1) {
|
||||
entries.push(parts[0]);
|
||||
@@ -107,8 +91,8 @@ class MockFS implements JSRuntimeFS {
|
||||
if (options?.withFileTypes) {
|
||||
return entries.map(name => ({
|
||||
name,
|
||||
isDirectory: () => this.dirs.has(`${normalizedPath}/${name}`),
|
||||
isFile: () => this.files.has(`${normalizedPath}/${name}`)
|
||||
isDirectory: () => this.dirs.has(`${path}/${name}`),
|
||||
isFile: () => this.files.has(`${path}/${name}`)
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -125,10 +109,7 @@ class MockFS implements JSRuntimeFS {
|
||||
size?: number;
|
||||
mtimeMs?: number;
|
||||
}> {
|
||||
// Normalize path by removing trailing slash for directories
|
||||
const normalizedPath = path.replace(/\/$/, '') || '/';
|
||||
|
||||
if (this.dirs.has(normalizedPath)) {
|
||||
if (this.dirs.has(path)) {
|
||||
return {
|
||||
isDirectory: () => true,
|
||||
isFile: () => false,
|
||||
@@ -137,11 +118,11 @@ class MockFS implements JSRuntimeFS {
|
||||
};
|
||||
}
|
||||
|
||||
if (this.files.has(normalizedPath)) {
|
||||
if (this.files.has(path)) {
|
||||
return {
|
||||
isDirectory: () => false,
|
||||
isFile: () => true,
|
||||
size: this.files.get(normalizedPath)!.length,
|
||||
size: this.files.get(path)!.length,
|
||||
mtimeMs: Date.now()
|
||||
};
|
||||
}
|
||||
@@ -186,13 +167,14 @@ describe('TextEditorViewTool', () => {
|
||||
tool = new TextEditorViewTool(mockFS, '/project');
|
||||
});
|
||||
|
||||
it('should handle viewing current directory', async () => {
|
||||
it('should handle viewing current directory without ignore library errors', async () => {
|
||||
const result = await tool.execute({ path: '.' });
|
||||
|
||||
expect(result).toContain('src/');
|
||||
expect(result).toContain('package.json');
|
||||
// .git should be filtered out by gitignore, but .gitignore should be present
|
||||
expect(result).toContain('.gitignore');
|
||||
expect(result).toContain('.git/'); // .git directory should now be visible
|
||||
expect(result).not.toContain('.git/'); // Check for .git directory specifically
|
||||
});
|
||||
|
||||
it('should handle viewing subdirectory', async () => {
|
||||
@@ -260,73 +242,4 @@ describe('TextEditorViewTool', () => {
|
||||
expect(result).toContain('[Binary file: JPG file');
|
||||
expect(result).toContain('This appears to be a binary file and cannot be displayed as text.');
|
||||
});
|
||||
|
||||
it('should show only project directories when viewing /projects', async () => {
|
||||
const result = await tool.execute({ path: '/projects' });
|
||||
|
||||
// Should show the project directories
|
||||
expect(result).toContain('project1/');
|
||||
expect(result).toContain('project2/');
|
||||
|
||||
// Should NOT show the contents of the project directories (depth 1 only)
|
||||
expect(result).not.toContain('package.json');
|
||||
expect(result).not.toContain('src/');
|
||||
expect(result).not.toContain('index.ts');
|
||||
expect(result).not.toContain('main.ts');
|
||||
});
|
||||
|
||||
it('should show only project directories when viewing /projects/', async () => {
|
||||
const result = await tool.execute({ path: '/projects/' });
|
||||
|
||||
// Should show the project directories
|
||||
expect(result).toContain('project1/');
|
||||
expect(result).toContain('project2/');
|
||||
|
||||
// Should NOT show the contents of the project directories (depth 1 only)
|
||||
expect(result).not.toContain('package.json');
|
||||
expect(result).not.toContain('src/');
|
||||
expect(result).not.toContain('index.ts');
|
||||
expect(result).not.toContain('main.ts');
|
||||
});
|
||||
|
||||
it('should show .git directory but not traverse its contents when viewing project root', async () => {
|
||||
const result = await tool.execute({ path: '/project' });
|
||||
|
||||
// Should show the .git directory
|
||||
expect(result).toContain('.git/');
|
||||
|
||||
// Should show "..." under .git instead of its contents
|
||||
expect(result).toContain('...');
|
||||
|
||||
// Should NOT show .git file contents
|
||||
expect(result).not.toContain('config');
|
||||
expect(result).not.toContain('HEAD');
|
||||
expect(result).not.toContain('repositoryformatversion');
|
||||
|
||||
// Should still show other directory contents normally
|
||||
expect(result).toContain('src/');
|
||||
expect(result).toContain('package.json');
|
||||
});
|
||||
|
||||
it('should show .git contents when explicitly viewing .git directory', async () => {
|
||||
const result = await tool.execute({ path: '/project/.git' });
|
||||
|
||||
// Should show the .git file contents when explicitly requested
|
||||
expect(result).toContain('config');
|
||||
expect(result).toContain('HEAD');
|
||||
|
||||
// Should NOT show "..." when explicitly viewing .git
|
||||
expect(result).not.toContain('...');
|
||||
});
|
||||
|
||||
it('should show .git contents when explicitly viewing .git with relative path', async () => {
|
||||
const result = await tool.execute({ path: '.git' });
|
||||
|
||||
// Should show the .git file contents when explicitly requested
|
||||
expect(result).toContain('config');
|
||||
expect(result).toContain('HEAD');
|
||||
|
||||
// Should NOT show "..." when explicitly viewing .git
|
||||
expect(result).not.toContain('...');
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import { join } from "path-browserify";
|
||||
import ignore from "ignore";
|
||||
import { z } from "zod";
|
||||
|
||||
import type { Tool } from "./Tool";
|
||||
@@ -52,19 +53,9 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
const stats = await this.fs.stat(absolutePath);
|
||||
|
||||
if (stats.isDirectory()) {
|
||||
// Special handling for /projects directory - only show project directories, not their contents
|
||||
const normalizedPath = absolutePath.replace(/\/$/, ''); // Remove trailing slash
|
||||
if (normalizedPath === '/projects') {
|
||||
const tree = await this.generateDirectoryTree(absolutePath, "", 1); // Only show immediate children
|
||||
return tree;
|
||||
}
|
||||
|
||||
// Check if we're starting from a .git directory
|
||||
const isGitRoot = absolutePath.endsWith('/.git') || absolutePath === '.git';
|
||||
|
||||
// If it's a directory, generate a tree-like listing
|
||||
// Note: start_line and end_line are ignored for directories
|
||||
const tree = await this.generateDirectoryTree(absolutePath, "", 3, 0, isGitRoot);
|
||||
const tree = await this.generateDirectoryTree(absolutePath);
|
||||
return tree;
|
||||
}
|
||||
|
||||
@@ -120,17 +111,30 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
prefix: string = "",
|
||||
maxDepth: number = 3,
|
||||
currentDepth: number = 0,
|
||||
isGitRoot: boolean = false,
|
||||
ignoreFilter?: (path: string) => boolean,
|
||||
): Promise<string> {
|
||||
if (currentDepth >= maxDepth) {
|
||||
return prefix + "...\n";
|
||||
}
|
||||
|
||||
// Create ignore filter on first call (root level)
|
||||
if (!ignoreFilter) {
|
||||
ignoreFilter = await this.createIgnoreFilter();
|
||||
}
|
||||
|
||||
try {
|
||||
const entries = await this.fs.readdir(dirPath, { withFileTypes: true });
|
||||
|
||||
// Filter entries using gitignore patterns
|
||||
const filteredEntries = entries.filter((entry) => {
|
||||
// Calculate relative path from the project root (cwd)
|
||||
const fullEntryPath = join(dirPath, entry.name);
|
||||
const entryPath = this.makeRelativeToCwd(fullEntryPath);
|
||||
return ignoreFilter!(entryPath);
|
||||
});
|
||||
|
||||
// Sort entries: directories first, then files, both alphabetically
|
||||
entries.sort((a, b) => {
|
||||
filteredEntries.sort((a, b) => {
|
||||
if (a.isDirectory() && !b.isDirectory()) return -1;
|
||||
if (!a.isDirectory() && b.isDirectory()) return 1;
|
||||
return a.name.localeCompare(b.name);
|
||||
@@ -138,28 +142,22 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
|
||||
let result = "";
|
||||
|
||||
for (let i = 0; i < entries.length; i++) {
|
||||
const entry = entries[i]!
|
||||
const isLastEntry = i === entries.length - 1;
|
||||
for (let i = 0; i < filteredEntries.length; i++) {
|
||||
const entry = filteredEntries[i]!;
|
||||
const isLastEntry = i === filteredEntries.length - 1;
|
||||
const connector = isLastEntry ? "└── " : "├── ";
|
||||
const nextPrefix = prefix + (isLastEntry ? " " : "│ ");
|
||||
|
||||
if (entry.isDirectory()) {
|
||||
result += prefix + connector + entry.name + "/\n";
|
||||
|
||||
// Special handling for .git directories - don't traverse unless we started from .git
|
||||
if (entry.name === '.git' && !isGitRoot) {
|
||||
result += nextPrefix + "...\n";
|
||||
} else {
|
||||
const subPath = join(dirPath, entry.name);
|
||||
result += await this.generateDirectoryTree(
|
||||
subPath,
|
||||
nextPrefix,
|
||||
maxDepth,
|
||||
currentDepth + 1,
|
||||
isGitRoot,
|
||||
);
|
||||
}
|
||||
const subPath = join(dirPath, entry.name);
|
||||
result += await this.generateDirectoryTree(
|
||||
subPath,
|
||||
nextPrefix,
|
||||
maxDepth,
|
||||
currentDepth + 1,
|
||||
ignoreFilter,
|
||||
);
|
||||
} else {
|
||||
result += prefix + connector + entry.name + "\n";
|
||||
}
|
||||
@@ -171,7 +169,55 @@ export class TextEditorViewTool implements Tool<TextEditorViewParams> {
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an ignore filter based on .gitignore files
|
||||
*/
|
||||
private async createIgnoreFilter(): Promise<(path: string) => boolean> {
|
||||
const ig = ignore();
|
||||
|
||||
// Always ignore .git directory
|
||||
ig.add(".git");
|
||||
|
||||
try {
|
||||
// Try to read .gitignore file
|
||||
const gitignoreContent = await this.fs.readFile(".gitignore", "utf8");
|
||||
ig.add(gitignoreContent);
|
||||
} catch {
|
||||
// If there's an error reading .gitignore, just proceed without it
|
||||
}
|
||||
|
||||
return (path: string) => !ig.ignores(path);
|
||||
}
|
||||
|
||||
/**
|
||||
* Convert an absolute path to a relative path from the current working directory
|
||||
*/
|
||||
private makeRelativeToCwd(absolutePath: string): string {
|
||||
// Handle relative paths that start with "./"
|
||||
if (absolutePath.startsWith('./')) {
|
||||
return absolutePath.slice(2); // Remove "./" prefix
|
||||
}
|
||||
|
||||
// Handle the current directory case
|
||||
if (absolutePath === '.') {
|
||||
return '.';
|
||||
}
|
||||
|
||||
// If the path starts with the cwd, remove the cwd prefix
|
||||
if (absolutePath.startsWith(this.cwd)) {
|
||||
let relativePath = absolutePath.slice(this.cwd.length);
|
||||
// Remove leading slash if present
|
||||
if (relativePath.startsWith('/')) {
|
||||
relativePath = relativePath.slice(1);
|
||||
}
|
||||
// Return '.' for empty path (current directory)
|
||||
return relativePath || '.';
|
||||
}
|
||||
|
||||
// If it doesn't start with cwd, just return the path as-is
|
||||
// This handles cases where we might have relative paths already
|
||||
return absolutePath;
|
||||
}
|
||||
|
||||
/**
|
||||
* Check if a file is likely to be binary based on file extension and content sampling
|
||||
|
||||
+83
-73
@@ -24,7 +24,6 @@ import { Button } from '@/components/ui/button';
|
||||
import { Input } from '@/components/ui/input';
|
||||
import { PasswordInput } from '@/components/ui/password-input';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { CreditsBadge } from '@/components/CreditsBadge';
|
||||
import { CreditsDialog } from '@/components/CreditsDialog';
|
||||
@@ -34,7 +33,65 @@ import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNavigate, Link } from 'react-router-dom';
|
||||
import type { AIProvider } from '@/contexts/AISettingsContext';
|
||||
import { AI_PROVIDER_PRESETS, type PresetProvider } from '@/lib/aiProviderPresets';
|
||||
|
||||
interface PresetProvider {
|
||||
id: string;
|
||||
name: string;
|
||||
baseURL: string;
|
||||
apiKeysURL?: string;
|
||||
nostr?: boolean;
|
||||
}
|
||||
|
||||
const PRESET_PROVIDERS: PresetProvider[] = [
|
||||
{
|
||||
id: "shakespeare",
|
||||
name: "Shakespeare AI",
|
||||
baseURL: "https://ai.shakespeare.diy/v1",
|
||||
nostr: true,
|
||||
},
|
||||
{
|
||||
id: "openrouter",
|
||||
name: "OpenRouter",
|
||||
baseURL: "https://openrouter.ai/api/v1",
|
||||
apiKeysURL: "https://openrouter.ai/settings/keys",
|
||||
},
|
||||
{
|
||||
id: "ppq",
|
||||
name: "PayPerQ",
|
||||
baseURL: "https://api.ppq.ai",
|
||||
apiKeysURL: "https://ppq.ai/api-docs",
|
||||
},
|
||||
{
|
||||
id: "routstr",
|
||||
name: "Routstr",
|
||||
baseURL: "https://api.routstr.com/v1",
|
||||
apiKeysURL: "https://chat.routstr.com/",
|
||||
},
|
||||
{
|
||||
id: "zai",
|
||||
name: "Z.ai",
|
||||
baseURL: "https://api.z.ai/api/paas/v4",
|
||||
apiKeysURL: "https://z.ai/manage-apikey/apikey-list",
|
||||
},
|
||||
{
|
||||
id: "openai",
|
||||
name: "OpenAI",
|
||||
baseURL: "https://api.openai.com/v1",
|
||||
apiKeysURL: "https://platform.openai.com/api-keys",
|
||||
},
|
||||
{
|
||||
id: "anthropic",
|
||||
name: "Anthropic",
|
||||
baseURL: "https://api.anthropic.com/v1",
|
||||
apiKeysURL: "https://console.anthropic.com/settings/keys",
|
||||
},
|
||||
{
|
||||
id: "xai",
|
||||
name: "xAI",
|
||||
baseURL: "https://api.x.ai/v1",
|
||||
apiKeysURL: "https://console.x.ai",
|
||||
},
|
||||
];
|
||||
|
||||
interface SortableProviderItemProps {
|
||||
provider: AIProvider;
|
||||
@@ -162,7 +219,6 @@ export function AISettings() {
|
||||
const [customApiKey, setCustomApiKey] = useState('');
|
||||
const [customAuthMethod, setCustomAuthMethod] = useState<'api-key' | 'nostr'>('api-key');
|
||||
const [presetApiKeys, setPresetApiKeys] = useState<Record<string, string>>({});
|
||||
const [presetTermsAgreements, setPresetTermsAgreements] = useState<Record<string, boolean>>({});
|
||||
const [activeCreditsDialog, setActiveCreditsDialog] = useState<string | null>(null);
|
||||
|
||||
const sensors = useSensors(
|
||||
@@ -175,9 +231,6 @@ export function AISettings() {
|
||||
const handleAddPresetProvider = (preset: PresetProvider) => {
|
||||
const apiKey = presetApiKeys[preset.id] as string | undefined;
|
||||
|
||||
// Check if user agreed to terms
|
||||
if (!presetTermsAgreements[preset.id]) return;
|
||||
|
||||
const newProvider: AIProvider = {
|
||||
id: preset.id,
|
||||
baseURL: preset.baseURL,
|
||||
@@ -193,15 +246,11 @@ export function AISettings() {
|
||||
// Auto-save: Add provider immediately to persistent storage
|
||||
setProvider(newProvider);
|
||||
|
||||
// Clear the API key input and terms agreement for this preset
|
||||
// Clear the API key input for this preset
|
||||
setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: '',
|
||||
}));
|
||||
setPresetTermsAgreements(prev => ({
|
||||
...prev,
|
||||
[preset.id]: false,
|
||||
}));
|
||||
};
|
||||
|
||||
const handleAddCustomProvider = () => {
|
||||
@@ -256,7 +305,7 @@ export function AISettings() {
|
||||
};
|
||||
|
||||
const configuredProviderIds = settings.providers.map(p => p.id);
|
||||
const availablePresets = AI_PROVIDER_PRESETS.filter(preset => !configuredProviderIds.includes(preset.id));
|
||||
const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id));
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
@@ -311,7 +360,7 @@ export function AISettings() {
|
||||
>
|
||||
<Accordion type="multiple" className="w-full space-y-2">
|
||||
{settings.providers.map((provider) => {
|
||||
const preset = AI_PROVIDER_PRESETS.find(p => p.id === provider.id);
|
||||
const preset = PRESET_PROVIDERS.find(p => p.id === provider.id);
|
||||
|
||||
return (
|
||||
<SortableProviderItem
|
||||
@@ -371,69 +420,30 @@ export function AISettings() {
|
||||
</Button>
|
||||
</div>
|
||||
) : (
|
||||
<div className="space-y-2">
|
||||
<div className="flex gap-2">
|
||||
{!preset.nostr && (
|
||||
<PasswordInput
|
||||
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
|
||||
className="flex-1"
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' &&
|
||||
presetApiKeys[preset.id]?.trim() &&
|
||||
presetTermsAgreements[preset.id]) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={
|
||||
!presetTermsAgreements[preset.id] ||
|
||||
(!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim())
|
||||
}
|
||||
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
|
||||
{/* Terms of Service Agreement */}
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Checkbox
|
||||
id={`agree-terms-${preset.id}`}
|
||||
checked={presetTermsAgreements[preset.id] || false}
|
||||
onCheckedChange={(checked) => setPresetTermsAgreements(prev => ({
|
||||
<div className="flex gap-2">
|
||||
{!preset.nostr && (
|
||||
<PasswordInput
|
||||
placeholder={preset.id === "routstr" ? t('enterCashuToken') : t('enterApiKey')}
|
||||
className="flex-1"
|
||||
value={presetApiKeys[preset.id] || ''}
|
||||
onChange={(e) => setPresetApiKeys(prev => ({
|
||||
...prev,
|
||||
[preset.id]: checked === true,
|
||||
[preset.id]: e.target.value,
|
||||
}))}
|
||||
className="size-3 [&_svg]:size-3"
|
||||
onKeyDown={(e) => {
|
||||
if (e.key === 'Enter' && presetApiKeys[preset.id]?.trim()) {
|
||||
handleAddPresetProvider(preset);
|
||||
}
|
||||
}}
|
||||
/>
|
||||
<label
|
||||
htmlFor={`agree-terms-${preset.id}`}
|
||||
className="text-xs text-muted-foreground leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70 cursor-pointer"
|
||||
>
|
||||
{t('agreeToTermsOfService', { providerName: preset.name })}{' '}
|
||||
{preset.tosURL ? (
|
||||
<a
|
||||
href={preset.tosURL}
|
||||
target="_blank"
|
||||
rel="noopener noreferrer"
|
||||
className="text-muted-foreground underline hover:text-foreground hover:no-underline"
|
||||
onClick={(e) => e.stopPropagation()}
|
||||
>
|
||||
{t('termsOfService')}
|
||||
</a>
|
||||
) : (
|
||||
t('termsOfService')
|
||||
)}
|
||||
</label>
|
||||
</div>
|
||||
)}
|
||||
<Button
|
||||
onClick={() => handleAddPresetProvider(preset)}
|
||||
disabled={!!preset.apiKeysURL && !presetApiKeys[preset.id]?.trim()}
|
||||
className={preset.nostr ? "w-full" : "h-10 px-4 ml-auto"}
|
||||
>
|
||||
{t('add')}
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
+9
-5
@@ -7,7 +7,7 @@ import { Input } from '@/components/ui/input';
|
||||
import { GitBranch, Loader2, AlertCircle, FileArchive, MoreHorizontal } from 'lucide-react';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { ZipImportDialog } from '@/components/ZipImportDialog';
|
||||
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||
import { useSeoMeta } from '@unhead/react';
|
||||
import { DropdownMenu, DropdownMenuTrigger, DropdownMenuContent, DropdownMenuItem } from '@/components/ui/dropdown-menu';
|
||||
|
||||
@@ -173,10 +173,13 @@ export default function Clone() {
|
||||
}
|
||||
}, [handleClone, searchParams]);
|
||||
|
||||
const handleImportZip = async (file: File, overwrite = false, projectId?: string) => {
|
||||
const handleImportZip = async (
|
||||
data: { file: File; projectId?: string },
|
||||
overwrite: boolean
|
||||
) => {
|
||||
try {
|
||||
// Import project from zip file
|
||||
const project = await projectsManager.importProjectFromZip(file, projectId, overwrite);
|
||||
// Single project import from ZIP file
|
||||
const project = await projectsManager.importProjectFromZip(data.file, data.projectId, overwrite);
|
||||
|
||||
// Show success toast
|
||||
toast({
|
||||
@@ -271,7 +274,8 @@ export default function Clone() {
|
||||
</div>
|
||||
|
||||
{/* ZIP Import Dialog */}
|
||||
<ZipImportDialog
|
||||
<ProjectImportDialog
|
||||
mode="single"
|
||||
onImport={handleImportZip}
|
||||
open={isZipDialogOpen}
|
||||
onOpenChange={setIsZipDialogOpen}
|
||||
|
||||
@@ -1,7 +1,8 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import { useNavigate } from 'react-router-dom';
|
||||
import { useTranslation } from 'react-i18next';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield } from 'lucide-react';
|
||||
import { useQueryClient } from '@tanstack/react-query';
|
||||
import { Download, Trash2, AlertTriangle, Loader2, Database, Info, ArrowLeft, Shield, Upload } from 'lucide-react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
||||
import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog';
|
||||
@@ -10,6 +11,8 @@ import { Switch } from '@/components/ui/switch';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { useProjectsManager } from '@/hooks/useProjectsManager';
|
||||
import { ProjectImportDialog } from '@/components/ProjectImportDialog';
|
||||
import {
|
||||
isPersistentStorageSupported,
|
||||
isPersistentStorageGranted,
|
||||
@@ -39,10 +42,13 @@ export function DataSettings() {
|
||||
const [storageInfo, setStorageInfo] = useState<StorageInfo | null>(null);
|
||||
const [storageError, setStorageError] = useState<string | null>(null);
|
||||
const [isPersistent, setIsPersistent] = useState<boolean | null>(null);
|
||||
const [isBulkImportOpen, setIsBulkImportOpen] = useState(false);
|
||||
const { toast } = useToast();
|
||||
const { fs } = useFS();
|
||||
const navigate = useNavigate();
|
||||
const isMobile = useIsMobile();
|
||||
const projectsManager = useProjectsManager();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Format bytes to human readable format
|
||||
const formatBytes = (bytes: number): string => {
|
||||
@@ -217,6 +223,67 @@ export function DataSettings() {
|
||||
}
|
||||
};
|
||||
|
||||
const handleBulkImport = async (
|
||||
data: { file: File; projectId?: string } | { projects: { id: string; files: { [path: string]: Uint8Array } }[] },
|
||||
overwrite: boolean
|
||||
) => {
|
||||
try {
|
||||
let successCount = 0;
|
||||
const errors: string[] = [];
|
||||
|
||||
// Handle both single and bulk import data
|
||||
if ('projects' in data) {
|
||||
// Bulk import
|
||||
for (const project of data.projects) {
|
||||
try {
|
||||
// Import the project directly using files (bypasses ZIP creation)
|
||||
await projectsManager.importProject(
|
||||
{ files: project.files },
|
||||
{ projectId: project.id, overwrite, projectName: project.id }
|
||||
);
|
||||
successCount++;
|
||||
} catch (error) {
|
||||
console.error(`Failed to import project ${project.id}:`, error);
|
||||
errors.push(`${project.id}: ${error instanceof Error ? error.message : 'Unknown error'}`);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
// Single import (shouldn't happen in bulk mode, but handle gracefully)
|
||||
throw new Error('Single import not supported in bulk import mode');
|
||||
}
|
||||
|
||||
// Show success/error toast and refresh project list
|
||||
if (successCount > 0) {
|
||||
// Refresh projects list to show newly imported projects
|
||||
queryClient.invalidateQueries({ queryKey: ['projects'] });
|
||||
|
||||
toast({
|
||||
title: `${successCount} Project${successCount !== 1 ? 's' : ''} Imported Successfully`,
|
||||
description: errors.length > 0
|
||||
? `${errors.length} project${errors.length !== 1 ? 's' : ''} failed to import.`
|
||||
: `All projects have been imported and are ready to use.`,
|
||||
variant: errors.length > 0 ? "destructive" : "default",
|
||||
});
|
||||
}
|
||||
|
||||
if (errors.length > 0 && successCount === 0) {
|
||||
toast({
|
||||
title: "Import Failed",
|
||||
description: `Failed to import projects: ${errors.slice(0, 3).join(', ')}${errors.length > 3 ? '...' : ''}`,
|
||||
variant: "destructive",
|
||||
});
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Bulk import failed:', error);
|
||||
toast({
|
||||
title: "Import Failed",
|
||||
description: error instanceof Error ? error.message : 'Unknown error occurred',
|
||||
variant: "destructive",
|
||||
});
|
||||
throw error; // Re-throw to let the dialog handle the error display
|
||||
}
|
||||
};
|
||||
|
||||
const handleClearAllData = async () => {
|
||||
setIsClearing(true);
|
||||
try {
|
||||
@@ -391,6 +458,28 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Import Projects */}
|
||||
<Card>
|
||||
<CardHeader>
|
||||
<CardTitle className="flex items-center gap-2">
|
||||
<Upload className="h-5 w-5" />
|
||||
Import Projects
|
||||
</CardTitle>
|
||||
<CardDescription>
|
||||
Import multiple projects from a ZIP file exported from Shakespeare. You can choose which projects to import and handle conflicts with existing projects.
|
||||
</CardDescription>
|
||||
</CardHeader>
|
||||
<CardContent>
|
||||
<Button
|
||||
onClick={() => setIsBulkImportOpen(true)}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
<Upload className="h-4 w-4 mr-2" />
|
||||
Import Projects
|
||||
</Button>
|
||||
</CardContent>
|
||||
</Card>
|
||||
|
||||
{/* Clear All Data */}
|
||||
<Card className="border-destructive/20">
|
||||
<CardHeader>
|
||||
@@ -459,6 +548,14 @@ export function DataSettings() {
|
||||
</CardContent>
|
||||
</Card>
|
||||
</div>
|
||||
|
||||
{/* Bulk Project Import Dialog */}
|
||||
<ProjectImportDialog
|
||||
mode="bulk"
|
||||
onImport={handleBulkImport}
|
||||
open={isBulkImportOpen}
|
||||
onOpenChange={setIsBulkImportOpen}
|
||||
/>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -409,8 +409,6 @@ export function ProjectView() {
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={build.isPending}
|
||||
consoleError={consoleError}
|
||||
onDismissConsoleError={handleDismissConsoleError}
|
||||
/>
|
||||
) : (
|
||||
<div className="h-full p-4 space-y-4">
|
||||
|
||||
Reference in new issue
Block a user