From 7b5c9a5581f68516fc726e22dd594b2de60df7a2 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 13:08:31 -0500 Subject: [PATCH 01/95] Convert AI providers into array instead of object, allow dragging to change their order --- package-lock.json | 56 ++++ package.json | 3 + src/components/AISettingsProvider.test.tsx | 16 +- src/components/AISettingsProvider.tsx | 62 ++-- src/components/CreditsBadge.test.tsx | 4 +- src/components/CreditsBadge.tsx | 7 +- src/components/CreditsDialog.test.tsx | 4 +- src/components/CreditsDialog.tsx | 8 +- src/components/ModelSelector.test.tsx | 35 +- src/components/OnboardingDialog.test.tsx | 9 +- src/components/OnboardingDialog.tsx | 9 +- src/components/Shakespeare/ChatPane.test.tsx | 7 +- src/contexts/AISettingsContext.ts | 11 +- src/hooks/useAICredits.ts | 7 +- src/hooks/useAIProjectId.test.ts | 118 +++---- src/hooks/useProviderModels.ts | 7 +- src/lib/SessionManager.test.ts | 7 +- src/lib/SessionManager.ts | 5 +- src/lib/ai-client.ts | 7 +- src/lib/configUtils.test.ts | 11 +- src/lib/configUtils.ts | 44 ++- src/lib/git.ts | 2 - src/lib/parseProviderModel.test.ts | 36 ++- src/lib/parseProviderModel.ts | 32 +- src/pages/AISettings.test.tsx | 9 +- src/pages/AISettings.tsx | 321 +++++++++++++------ src/pages/Index.tsx | 2 +- 27 files changed, 556 insertions(+), 283 deletions(-) diff --git a/package-lock.json b/package-lock.json index 1edd0286..73908c5f 100644 --- a/package-lock.json +++ b/package-lock.json @@ -8,6 +8,9 @@ "name": "mkstack", "version": "0.0.0", "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@fontsource-variable/inter": "^5.2.6", "@getalby/sdk": "^6.0.1", "@hookform/resolvers": "^3.9.0", @@ -347,6 +350,59 @@ "node": ">=18" } }, + "node_modules/@dnd-kit/accessibility": { + "version": "3.1.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/accessibility/-/accessibility-3.1.1.tgz", + "integrity": "sha512-2P+YgaXF+gRsIihwwY1gCsQSYnu9Zyj2py8kY5fFvUM1qm2WA2u639R6YNVfU4GWr+ZM5mqEsfHZZLoRONbemw==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/core": { + "version": "6.3.1", + "resolved": "https://registry.npmjs.org/@dnd-kit/core/-/core-6.3.1.tgz", + "integrity": "sha512-xkGBRQQab4RLwgXxoqETICr6S5JlogafbhNsidmrkVv2YRs5MLwpjoF2qpiGjQt8S9AoxtIV603s0GIUpY5eYQ==", + "license": "MIT", + "dependencies": { + "@dnd-kit/accessibility": "^3.1.1", + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0", + "react-dom": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/sortable": { + "version": "10.0.0", + "resolved": "https://registry.npmjs.org/@dnd-kit/sortable/-/sortable-10.0.0.tgz", + "integrity": "sha512-+xqhmIIzvAYMGfBYYnbKuNicfSsk4RksY2XdmJhT+HAC01nix6fHCztU68jooFiMUB01Ky3F0FyOvhG/BZrWkg==", + "license": "MIT", + "dependencies": { + "@dnd-kit/utilities": "^3.2.2", + "tslib": "^2.0.0" + }, + "peerDependencies": { + "@dnd-kit/core": "^6.3.0", + "react": ">=16.8.0" + } + }, + "node_modules/@dnd-kit/utilities": { + "version": "3.2.2", + "resolved": "https://registry.npmjs.org/@dnd-kit/utilities/-/utilities-3.2.2.tgz", + "integrity": "sha512-+MKAJEOfaBe5SmV6t34p80MMKhjvUz0vRrvVJbPT0WElzaOJ/1xs+D+KDv+tD/NE5ujfrChEcshd4fLn0wpiqg==", + "license": "MIT", + "dependencies": { + "tslib": "^2.0.0" + }, + "peerDependencies": { + "react": ">=16.8.0" + } + }, "node_modules/@esbuild/aix-ppc64": { "version": "0.25.5", "resolved": "https://registry.npmjs.org/@esbuild/aix-ppc64/-/aix-ppc64-0.25.5.tgz", diff --git a/package.json b/package.json index 267e0501..723a33d7 100644 --- a/package.json +++ b/package.json @@ -10,6 +10,9 @@ "deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup" }, "dependencies": { + "@dnd-kit/core": "^6.3.1", + "@dnd-kit/sortable": "^10.0.0", + "@dnd-kit/utilities": "^3.2.2", "@fontsource-variable/inter": "^5.2.6", "@getalby/sdk": "^6.0.1", "@hookform/resolvers": "^3.9.0", diff --git a/src/components/AISettingsProvider.test.tsx b/src/components/AISettingsProvider.test.tsx index 2ef9d26d..1e4949da 100644 --- a/src/components/AISettingsProvider.test.tsx +++ b/src/components/AISettingsProvider.test.tsx @@ -31,7 +31,7 @@ describe('AISettingsProvider', () => { // Mock the read function to return default settings const { readAISettings } = await import('@/lib/configUtils'); vi.mocked(readAISettings).mockResolvedValue({ - providers: {}, + providers: [], recentlyUsedModels: [], }); }); @@ -122,12 +122,13 @@ describe('AISettingsProvider', () => { it('should migrate old settings without recentlyUsedModels', async () => { const oldSettings = { - providers: { - openrouter: { + providers: [ + { + id: 'openrouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'test-key' } - }, + ], recentlyUsedModels: [] }; @@ -169,12 +170,13 @@ describe('AISettingsProvider', () => { act(() => { result.current.updateSettings({ - providers: { - 'test-provider': { + providers: [ + { + id: 'test-provider', baseURL: 'https://api.test.com/v1', apiKey: 'test-key' } - } + ] }); }); diff --git a/src/components/AISettingsProvider.tsx b/src/components/AISettingsProvider.tsx index 5788ba54..bececb67 100644 --- a/src/components/AISettingsProvider.tsx +++ b/src/components/AISettingsProvider.tsx @@ -1,6 +1,6 @@ import { useQueryClient } from '@tanstack/react-query'; import { ReactNode, useState, useEffect } from 'react'; -import { AISettingsContext, type AISettings, type AIConnection, type AISettingsContextType } from '@/contexts/AISettingsContext'; +import { AISettingsContext, type AISettings, type AIProvider, type AISettingsContextType } from '@/contexts/AISettingsContext'; import { useFS } from '@/hooks/useFS'; import { readAISettings, writeAISettings } from '@/lib/configUtils'; @@ -9,7 +9,7 @@ interface AISettingsProviderProps { } const DEFAULT_SETTINGS: AISettings = { - providers: {}, + providers: [], recentlyUsedModels: [], }; @@ -60,38 +60,40 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { } }; - const addProvider = (name: string, connection: AIConnection) => { - setSettings(prev => ({ - ...prev, - providers: { - ...prev.providers, - [name]: connection, - }, - })); - queryClient.invalidateQueries({ queryKey: ['provider-models'] }); - }; - - const removeProvider = (name: string) => { + const setProvider = (provider: AIProvider) => { setSettings(prev => { - const { [name]: removed, ...rest } = prev.providers; - return { - ...prev, - providers: rest, - }; + const existingIndex = prev.providers.findIndex(p => p.id === provider.id); + if (existingIndex >= 0) { + // Update existing provider + return { + ...prev, + providers: prev.providers.map(p => + p.id === provider.id ? provider : p + ), + }; + } else { + // Add new provider + return { + ...prev, + providers: [...prev.providers, provider], + }; + } }); queryClient.invalidateQueries({ queryKey: ['provider-models'] }); }; - const updateProvider = (name: string, connection: Partial) => { + const removeProvider = (id: string) => { setSettings(prev => ({ ...prev, - providers: { - ...prev.providers, - [name]: { - ...prev.providers[name], - ...connection, - }, - }, + providers: prev.providers.filter(provider => provider.id !== id), + })); + queryClient.invalidateQueries({ queryKey: ['provider-models'] }); + }; + + const setProviders = (providers: AIProvider[]) => { + setSettings(prev => ({ + ...prev, + providers, })); queryClient.invalidateQueries({ queryKey: ['provider-models'] }); }; @@ -120,14 +122,14 @@ export function AISettingsProvider({ children }: AISettingsProviderProps) { }); }; - const isConfigured = Object.entries(settings.providers).length > 0; + const isConfigured = settings.providers.length > 0; const contextValue: AISettingsContextType = { settings, updateSettings, - addProvider, + setProvider, removeProvider, - updateProvider, + setProviders, addRecentlyUsedModel, isConfigured, }; diff --git a/src/components/CreditsBadge.test.tsx b/src/components/CreditsBadge.test.tsx index 10a95b54..f5bcb70d 100644 --- a/src/components/CreditsBadge.test.tsx +++ b/src/components/CreditsBadge.test.tsx @@ -2,7 +2,7 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen, fireEvent } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; import { CreditsBadge } from './CreditsBadge'; -import type { AIConnection } from '@/contexts/AISettingsContext'; + // Mock the useAICredits hook vi.mock('@/hooks/useAICredits', () => ({ @@ -16,7 +16,7 @@ vi.mock('@/hooks/useAICredits', () => ({ // Mock the fetch function global.fetch = vi.fn(); -const mockConnection: AIConnection = { +const mockConnection = { baseURL: 'https://api.test.com/v1', apiKey: 'test-key', }; diff --git a/src/components/CreditsBadge.tsx b/src/components/CreditsBadge.tsx index c12768d8..5bdc9695 100644 --- a/src/components/CreditsBadge.tsx +++ b/src/components/CreditsBadge.tsx @@ -1,10 +1,13 @@ import { Badge } from '@/components/ui/badge'; import { useAICredits } from '@/hooks/useAICredits'; -import type { AIConnection } from '@/contexts/AISettingsContext'; interface CreditsBadgeProps { providerId: string; - connection: AIConnection; + connection: { + baseURL: string; + apiKey?: string; + nostr?: boolean; + }; className?: string; onOpenDialog?: () => void; } diff --git a/src/components/CreditsDialog.test.tsx b/src/components/CreditsDialog.test.tsx index 061e0bd1..0983203e 100644 --- a/src/components/CreditsDialog.test.tsx +++ b/src/components/CreditsDialog.test.tsx @@ -2,12 +2,12 @@ import { describe, it, expect, vi } from 'vitest'; import { render, screen } from '@testing-library/react'; import { TestApp } from '@/test/TestApp'; import { CreditsDialog } from './CreditsDialog'; -import type { AIConnection } from '@/contexts/AISettingsContext'; + // Mock the fetch function global.fetch = vi.fn(); -const mockConnection: AIConnection = { +const mockConnection = { baseURL: 'https://api.test.com/v1', apiKey: 'test-key', }; diff --git a/src/components/CreditsDialog.tsx b/src/components/CreditsDialog.tsx index 7a45d96c..89ae33af 100644 --- a/src/components/CreditsDialog.tsx +++ b/src/components/CreditsDialog.tsx @@ -13,13 +13,15 @@ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@ import { useToast } from '@/hooks/useToast'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; -import type { AIConnection } from '@/contexts/AISettingsContext'; - interface CreditsDialogProps { open: boolean; onOpenChange: (open: boolean) => void; providerId: string; - connection: AIConnection; + connection: { + baseURL: string; + apiKey?: string; + nostr?: boolean; + }; } interface Payment { diff --git a/src/components/ModelSelector.test.tsx b/src/components/ModelSelector.test.tsx index 2ce8e560..b5c7102b 100644 --- a/src/components/ModelSelector.test.tsx +++ b/src/components/ModelSelector.test.tsx @@ -34,13 +34,14 @@ describe('ModelSelector', () => { vi.clearAllMocks(); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels: [] }, + settings: { providers: [], recentlyUsedModels: [] }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); mockUseProviderModels.mockReturnValue({ @@ -69,13 +70,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels }, + settings: { providers: [], recentlyUsedModels }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( @@ -115,13 +117,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels }, + settings: { providers: [], recentlyUsedModels }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( @@ -163,13 +166,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels }, + settings: { providers: [], recentlyUsedModels }, addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( @@ -205,13 +209,14 @@ describe('ModelSelector', () => { }); mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels: [] }, // No recently used models + settings: { providers: [], recentlyUsedModels: [] }, // No recently used models addRecentlyUsedModel: mockAddRecentlyUsedModel, isConfigured: true, updateSettings: vi.fn(), removeProvider: vi.fn(), - addProvider: vi.fn(), - updateProvider: vi.fn(), + setProvider: vi.fn(), + setProviders: vi.fn(), + }); render( diff --git a/src/components/OnboardingDialog.test.tsx b/src/components/OnboardingDialog.test.tsx index a668b254..cbf028e4 100644 --- a/src/components/OnboardingDialog.test.tsx +++ b/src/components/OnboardingDialog.test.tsx @@ -6,9 +6,14 @@ import { TestApp } from '@/test/TestApp'; // Mock the hooks vi.mock('@/hooks/useAISettings', () => ({ useAISettings: () => ({ - settings: { providers: {}, recentlyUsedModels: [] }, - addProvider: vi.fn(), + settings: { providers: [], recentlyUsedModels: [] }, + setProvider: vi.fn(), + removeProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), + updateSettings: vi.fn(), + isConfigured: false, }), })); diff --git a/src/components/OnboardingDialog.tsx b/src/components/OnboardingDialog.tsx index 05225f69..ba6edb95 100644 --- a/src/components/OnboardingDialog.tsx +++ b/src/components/OnboardingDialog.tsx @@ -14,8 +14,6 @@ import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useLoginActions } from '@/hooks/useLoginActions'; import { useProviderModels } from '@/hooks/useProviderModels'; import { CreditsDialog } from '@/components/CreditsDialog'; -import type { AIConnection } from '@/contexts/AISettingsContext'; - interface OnboardingDialogProps { open: boolean; onOpenChange: (open: boolean) => void; @@ -23,7 +21,8 @@ interface OnboardingDialogProps { type OnboardingStep = 'welcome' | 'model-selection' | 'conclusion'; -const SHAKESPEARE_PROVIDER: AIConnection = { +const SHAKESPEARE_PROVIDER = { + id: "shakespeare", baseURL: "https://ai.shakespeare.diy/v1", nostr: true, }; @@ -34,7 +33,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) const [isSettingUp, setIsSettingUp] = useState(false); const [showCreditsDialog, setShowCreditsDialog] = useState(false); - const { addProvider, addRecentlyUsedModel } = useAISettings(); + const { setProvider, addRecentlyUsedModel } = useAISettings(); const { user } = useCurrentUser(); const login = useLoginActions(); const { models, isLoading: isLoadingModels } = useProviderModels(); @@ -54,7 +53,7 @@ export function OnboardingDialog({ open, onOpenChange }: OnboardingDialogProps) } // Add Shakespeare provider to their config - addProvider('shakespeare', SHAKESPEARE_PROVIDER); + setProvider(SHAKESPEARE_PROVIDER); // Move to model selection setStep('model-selection'); diff --git a/src/components/Shakespeare/ChatPane.test.tsx b/src/components/Shakespeare/ChatPane.test.tsx index 259d0830..2345596b 100644 --- a/src/components/Shakespeare/ChatPane.test.tsx +++ b/src/components/Shakespeare/ChatPane.test.tsx @@ -8,10 +8,15 @@ vi.mock('@/hooks/useAISettings', () => ({ useAISettings: () => ({ isConfigured: true, settings: { - providers: {}, + providers: [], recentlyUsedModels: ['gpt-4'], }, + setProvider: vi.fn(), + removeProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), + updateSettings: vi.fn(), }), })); diff --git a/src/contexts/AISettingsContext.ts b/src/contexts/AISettingsContext.ts index 1dcada84..56fee1b4 100644 --- a/src/contexts/AISettingsContext.ts +++ b/src/contexts/AISettingsContext.ts @@ -1,22 +1,23 @@ import { createContext } from 'react'; -export interface AIConnection { +export interface AIProvider { + id: string; baseURL: string; apiKey?: string; nostr?: boolean; } export interface AISettings { - providers: Record; + providers: AIProvider[]; recentlyUsedModels: string[]; } export interface AISettingsContextType { settings: AISettings; updateSettings: (settings: Partial) => void; - addProvider: (name: string, connection: AIConnection) => void; - removeProvider: (name: string) => void; - updateProvider: (name: string, connection: Partial) => void; + setProvider: (provider: AIProvider) => void; + removeProvider: (id: string) => void; + setProviders: (providers: AIProvider[]) => void; addRecentlyUsedModel: (modelId: string) => void; isConfigured: boolean; } diff --git a/src/hooks/useAICredits.ts b/src/hooks/useAICredits.ts index 1bc8e9f8..5d3d90ea 100644 --- a/src/hooks/useAICredits.ts +++ b/src/hooks/useAICredits.ts @@ -2,7 +2,6 @@ import { useQuery } from '@tanstack/react-query'; import { z } from 'zod'; import { createAIClient } from '@/lib/ai-client'; import { useCurrentUser } from '@/hooks/useCurrentUser'; -import type { AIConnection } from '@/contexts/AISettingsContext'; // Zod schemas for the two possible response formats const creditsResponseV1Schema = z.object({ @@ -32,7 +31,11 @@ export interface CreditsResponse { * @param connection - The AI connection configuration * @returns Query result with credits information */ -export function useAICredits(providerId: string, connection: AIConnection) { +export function useAICredits(providerId: string, connection: { + baseURL: string; + apiKey?: string; + nostr?: boolean; +}) { const { user } = useCurrentUser(); return useQuery({ diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 6a4ea59c..47e25658 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -63,12 +63,12 @@ describe('useAIProjectId', () => { it('should return not configured when AI settings are not configured', () => { mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels: [] }, + settings: { providers: [], recentlyUsedModels: [] }, isConfigured: false, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), addRecentlyUsedModel: vi.fn(), }); @@ -80,12 +80,13 @@ describe('useAIProjectId', () => { it('should throw error when trying to generate ID without configuration', async () => { mockUseAISettings.mockReturnValue({ - settings: { providers: {}, recentlyUsedModels: [] }, + settings: { providers: [], recentlyUsedModels: [] }, isConfigured: false, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -99,16 +100,17 @@ describe('useAIProjectId', () => { it('should throw error when prompt is empty', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -122,16 +124,17 @@ describe('useAIProjectId', () => { it('should have configured status when providers are available', () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -144,16 +147,17 @@ describe('useAIProjectId', () => { it('should successfully generate project ID', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -162,9 +166,9 @@ describe('useAIProjectId', () => { const projectId = await result.current.generateProjectId('openai/gpt-4', 'A social media app for developers'); expect(projectId).toBe('test-project-name'); - expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }); + expect(mockParseProviderModel).toHaveBeenCalledWith('openai/gpt-4', [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ]); expect(mockCreateAIClient).toHaveBeenCalledWith( { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' }, undefined @@ -174,16 +178,17 @@ describe('useAIProjectId', () => { it('should fallback to untitled when project exists', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -226,16 +231,17 @@ describe('useAIProjectId', () => { it('should fallback to untitled-1 when untitled exists', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -280,16 +286,17 @@ describe('useAIProjectId', () => { it('should fallback to untitled when AI generates too long name', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -329,16 +336,17 @@ describe('useAIProjectId', () => { it('should fallback to untitled when AI generates invalid name', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -378,16 +386,17 @@ describe('useAIProjectId', () => { it('should fallback to untitled-2 when untitled and untitled-1 exist', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); @@ -434,16 +443,17 @@ describe('useAIProjectId', () => { it('should handle loading state correctly', async () => { mockUseAISettings.mockReturnValue({ settings: { - providers: { - openai: { apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } - }, + providers: [ + { id: 'openai', apiKey: 'test-key', baseURL: 'https://api.openai.com/v1' } + ], recentlyUsedModels: [] }, isConfigured: true, updateSettings: vi.fn(), - addProvider: vi.fn(), + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + addRecentlyUsedModel: vi.fn(), }); diff --git a/src/hooks/useProviderModels.ts b/src/hooks/useProviderModels.ts index a0a42535..86b2e9a9 100644 --- a/src/hooks/useProviderModels.ts +++ b/src/hooks/useProviderModels.ts @@ -39,12 +39,13 @@ export function useProviderModels(): ModelFetchResult { isLoading, refetch, } = useQuery({ - queryKey: ['provider-models'], + queryKey: ['provider-models', settings.providers], queryFn: async () => { const errors: string[] = []; // Fetch models from each configured provider in parallel - const providerPromises = Object.entries(settings.providers).map(async ([providerKey, connection]) => { + const providerPromises = settings.providers.map(async (provider) => { + const { id: providerKey, ...connection } = provider; try { const openai = createAIClient(connection, user); @@ -126,7 +127,7 @@ export function useProviderModels(): ModelFetchResult { return allModels; }, - enabled: Object.keys(settings.providers).length > 0, + enabled: settings.providers.length > 0, staleTime: 5 * 60 * 1000, // Cache for 5 minutes retry: false, // Don't retry on failure }); diff --git a/src/lib/SessionManager.test.ts b/src/lib/SessionManager.test.ts index 8ccfedcc..25de75ef 100644 --- a/src/lib/SessionManager.test.ts +++ b/src/lib/SessionManager.test.ts @@ -25,12 +25,13 @@ const mockFS: JSRuntimeFS = { describe('SessionManager', () => { let sessionManager: SessionManager; const mockAISettings = { - providers: { - 'test-provider': { + providers: [ + { + id: 'test-provider', baseURL: 'https://api.test.com', apiKey: 'test-key' } - } + ] }; beforeEach(() => { diff --git a/src/lib/SessionManager.ts b/src/lib/SessionManager.ts index fc3a2fd4..52b3fd15 100644 --- a/src/lib/SessionManager.ts +++ b/src/lib/SessionManager.ts @@ -5,6 +5,7 @@ import { parseProviderModel } from './parseProviderModel'; import { createAIClient } from './ai-client'; import type { Tool } from './tools/Tool'; import type { NUser } from '@nostrify/react/login'; +import type { AIProvider } from '@/contexts/AISettingsContext'; export type AIMessage = OpenAI.Chat.Completions.ChatCompletionMessageParam | { role: 'assistant'; @@ -52,13 +53,13 @@ export class SessionManager { private sessions = new Map(); private listeners: Partial void>>> = {}; private fs: JSRuntimeFS; - private aiSettings: { providers: Record }; + private aiSettings: { providers: AIProvider[] }; private getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>; private getCurrentUser?: () => NUser | undefined; constructor( fs: JSRuntimeFS, - aiSettings: { providers: Record }, + aiSettings: { providers: AIProvider[] }, getProviderModels?: () => Array<{ id: string; provider: string; contextLength?: number; pricing?: { prompt: import('decimal.js').Decimal; completion: import('decimal.js').Decimal } }>, getCurrentUser?: () => NUser | undefined ) { diff --git a/src/lib/ai-client.ts b/src/lib/ai-client.ts index cf8580f0..8b2405e8 100644 --- a/src/lib/ai-client.ts +++ b/src/lib/ai-client.ts @@ -1,6 +1,5 @@ import OpenAI from 'openai'; import { NIP98Client } from '@nostrify/nostrify'; -import type { AIConnection } from '@/contexts/AISettingsContext'; import type { NUser } from '@nostrify/react/login'; /** @@ -8,7 +7,11 @@ import type { NUser } from '@nostrify/react/login'; * If the connection requires Nostr authentication (NIP-98), it will use * the NIP98Client for authenticated requests. */ -export function createAIClient(connection: AIConnection, user?: NUser): OpenAI { +export function createAIClient(connection: { + baseURL: string; + apiKey?: string; + nostr?: boolean; +}, user?: NUser): OpenAI { const baseConfig: ConstructorParameters[0] = { baseURL: connection.baseURL, apiKey: connection.apiKey ?? '', diff --git a/src/lib/configUtils.test.ts b/src/lib/configUtils.test.ts index f406a371..0aec9603 100644 --- a/src/lib/configUtils.test.ts +++ b/src/lib/configUtils.test.ts @@ -54,12 +54,13 @@ describe('configUtils', () => { describe('AI Settings', () => { const sampleAISettings: AISettings = { - providers: { - 'openai': { + providers: [ + { + id: 'openai', baseURL: 'https://api.openai.com/v1', apiKey: 'sk-test123', }, - }, + ], recentlyUsedModels: ['gpt-4', 'gpt-3.5-turbo'], }; @@ -80,7 +81,7 @@ describe('configUtils', () => { const result = await readAISettings(mockFS); expect(result).toEqual({ - providers: {}, + providers: [], recentlyUsedModels: [], }); }); @@ -92,7 +93,7 @@ describe('configUtils', () => { const result = await readAISettings(mockFS); expect(result).toEqual({ - providers: {}, + providers: [], recentlyUsedModels: [], }); }); diff --git a/src/lib/configUtils.ts b/src/lib/configUtils.ts index 95b7c2d0..779dc548 100644 --- a/src/lib/configUtils.ts +++ b/src/lib/configUtils.ts @@ -1,5 +1,5 @@ import type { JSRuntimeFS } from '@/lib/JSRuntime'; -import type { AISettings } from '@/contexts/AISettingsContext'; +import type { AISettings, AIProvider } from '@/contexts/AISettingsContext'; import type { GitSettings } from '@/contexts/GitSettingsContext'; const CONFIG_DIR = '/config'; @@ -27,8 +27,22 @@ async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise ({ + id, + ...(connection as Omit), + })); + } else { + providers = []; + } + const settings: AISettings = { - providers: parsed.providers || {}, + providers, recentlyUsedModels: parsed.recentlyUsedModels || [], }; @@ -51,7 +65,7 @@ async function migrateAISettingsFromLocalStorage(fs: JSRuntimeFS): Promise { const defaultSettings: AISettings = { - providers: {}, + providers: [], recentlyUsedModels: [], }; @@ -61,8 +75,30 @@ export async function readAISettings(fs: JSRuntimeFS): Promise { const parsed = JSON.parse(content); if (parsed && typeof parsed === 'object' && 'providers' in parsed) { + // Handle migration from old map format to new array format + let providers; + if (Array.isArray(parsed.providers)) { + providers = parsed.providers; + } else if (parsed.providers && typeof parsed.providers === 'object') { + // Convert map to array + providers = Object.entries(parsed.providers).map(([id, connection]) => ({ + id, + ...(connection as Omit), + })); + + // Write back the migrated format + const migratedSettings: AISettings = { + providers, + recentlyUsedModels: parsed.recentlyUsedModels || [], + }; + await writeAISettings(fs, migratedSettings); + return migratedSettings; + } else { + providers = []; + } + return { - providers: parsed.providers || {}, + providers, recentlyUsedModels: parsed.recentlyUsedModels || [], }; } diff --git a/src/lib/git.ts b/src/lib/git.ts index 4975e8a9..cfb7dd20 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -17,8 +17,6 @@ export class Git { this.corsProxy = corsProxy; } - - // Repository initialization and configuration async init(options: Omit[0], 'fs'>) { return git.init({ diff --git a/src/lib/parseProviderModel.test.ts b/src/lib/parseProviderModel.test.ts index a0c67ab9..5065c819 100644 --- a/src/lib/parseProviderModel.test.ts +++ b/src/lib/parseProviderModel.test.ts @@ -1,33 +1,41 @@ import { describe, it, expect } from 'vitest'; import { parseProviderModel } from './parseProviderModel'; -import type { AIConnection } from '@/contexts/AISettingsContext'; +import type { AIProvider } from '@/contexts/AISettingsContext'; describe('parseProviderModel', () => { - const mockProviders: Record = { - openai: { + const mockProviders: AIProvider[] = [ + { + id: 'openai', baseURL: 'https://api.openai.com/v1', apiKey: 'sk-test-key', }, - openrouter: { + { + id: 'openrouter', baseURL: 'https://openrouter.ai/api/v1', apiKey: 'sk-or-test-key', }, - anthropic: { + { + id: 'anthropic', baseURL: 'https://api.anthropic.com', apiKey: 'sk-ant-test-key', }, - unconfigured: { + { + id: 'unconfigured', baseURL: 'https://example.com/v1', apiKey: '', }, - }; + ]; it('should parse simple provider/model format', () => { const result = parseProviderModel('openai/gpt-4o', mockProviders); expect(result.provider).toBe('openai'); expect(result.model).toBe('gpt-4o'); - expect(result.connection).toEqual(mockProviders.openai); + expect(result.connection).toEqual({ + baseURL: mockProviders[0].baseURL, + apiKey: mockProviders[0].apiKey, + nostr: mockProviders[0].nostr, + }); }); it('should parse complex model names with slashes', () => { @@ -35,7 +43,11 @@ describe('parseProviderModel', () => { expect(result.provider).toBe('openrouter'); expect(result.model).toBe('anthropic/claude-sonnet-4'); - expect(result.connection).toEqual(mockProviders.openrouter); + expect(result.connection).toEqual({ + baseURL: mockProviders[1].baseURL, + apiKey: mockProviders[1].apiKey, + nostr: mockProviders[1].nostr, + }); }); it('should handle model names with multiple slashes', () => { @@ -43,7 +55,11 @@ describe('parseProviderModel', () => { expect(result.provider).toBe('openrouter'); expect(result.model).toBe('meta/llama-3.1-405b-instruct'); - expect(result.connection).toEqual(mockProviders.openrouter); + expect(result.connection).toEqual({ + baseURL: mockProviders[1].baseURL, + apiKey: mockProviders[1].apiKey, + nostr: mockProviders[1].nostr, + }); }); it('should throw error for invalid format without slash', () => { diff --git a/src/lib/parseProviderModel.ts b/src/lib/parseProviderModel.ts index 4393fb58..06ed9015 100644 --- a/src/lib/parseProviderModel.ts +++ b/src/lib/parseProviderModel.ts @@ -1,9 +1,13 @@ -import type { AIConnection } from '@/contexts/AISettingsContext'; +import type { AIProvider } from '@/contexts/AISettingsContext'; export interface ParsedProviderModel { provider: string; model: string; - connection: AIConnection; + connection: { + baseURL: string; + apiKey?: string; + nostr?: boolean; + }; } /** @@ -13,29 +17,33 @@ export interface ParsedProviderModel { */ export function parseProviderModel( providerModelString: string, - providers: Record + providers: AIProvider[] ): ParsedProviderModel { const firstSlashIndex = providerModelString.indexOf('/'); - + if (firstSlashIndex === -1) { throw new Error('Invalid format. Use provider/model (e.g., "openai/gpt-4o")'); } - + const provider = providerModelString.substring(0, firstSlashIndex); const model = providerModelString.substring(firstSlashIndex + 1); - + if (!provider || !model) { throw new Error('Invalid format. Both provider and model must be specified'); } - - const connection = providers[provider]; - if (!connection) { - throw new Error(`Provider "${provider}" not found. Available providers: ${Object.keys(providers).join(', ')}`); + + const providerObj = providers.find(p => p.id === provider); + if (!providerObj) { + throw new Error(`Provider "${provider}" not found. Available providers: ${providers.map(p => p.id).join(', ')}`); } - + return { provider, model, - connection, + connection: { + baseURL: providerObj.baseURL, + apiKey: providerObj.apiKey, + nostr: providerObj.nostr, + }, }; } \ No newline at end of file diff --git a/src/pages/AISettings.test.tsx b/src/pages/AISettings.test.tsx index 8bf83ede..91cbbcdf 100644 --- a/src/pages/AISettings.test.tsx +++ b/src/pages/AISettings.test.tsx @@ -11,10 +11,13 @@ vi.mock('@/hooks/useCurrentUser', () => ({ vi.mock('@/hooks/useAISettings', () => ({ useAISettings: vi.fn(() => ({ - settings: { providers: {} }, - addProvider: vi.fn(), + settings: { providers: [] }, + setProvider: vi.fn(), removeProvider: vi.fn(), - updateProvider: vi.fn(), + setProviders: vi.fn(), + updateSettings: vi.fn(), + addRecentlyUsedModel: vi.fn(), + isConfigured: false, })), })); diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index 9b094c6f..8f453325 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -1,6 +1,25 @@ import { useState } from 'react'; import { useTranslation } from 'react-i18next'; -import { Check, Bot, ArrowLeft, Trash2 } from 'lucide-react'; +import { Check, Bot, ArrowLeft, Trash2, GripVertical } from 'lucide-react'; +import { + DndContext, + closestCenter, + KeyboardSensor, + PointerSensor, + useSensor, + useSensors, + type DragEndEvent, +} from '@dnd-kit/core'; +import { + arrayMove, + SortableContext, + sortableKeyboardCoordinates, + verticalListSortingStrategy, +} from '@dnd-kit/sortable'; +import { + useSortable, +} from '@dnd-kit/sortable'; +import { CSS } from '@dnd-kit/utilities'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { PasswordInput } from '@/components/ui/password-input'; @@ -13,7 +32,7 @@ import { useAISettings } from '@/hooks/useAISettings'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNavigate, Link } from 'react-router-dom'; -import type { AIConnection } from '@/contexts/AISettingsContext'; +import type { AIProvider } from '@/contexts/AISettingsContext'; interface PresetProvider { id: string; @@ -80,9 +99,125 @@ const PRESET_PROVIDERS: PresetProvider[] = [ }, ]; +interface SortableProviderItemProps { + provider: AIProvider; + preset?: PresetProvider; + onRemove: (id: string) => void; + onSetProvider: (provider: AIProvider) => void; + onOpenCreditsDialog: (providerId: string) => void; + showDragHandle: boolean; +} + +function SortableProviderItem({ provider, preset, onRemove, onSetProvider, onOpenCreditsDialog, showDragHandle }: SortableProviderItemProps) { + const { t } = useTranslation(); + const { + attributes, + listeners, + setNodeRef, + transform, + transition, + isDragging, + } = useSortable({ id: provider.id }); + + const style = { + transform: CSS.Transform.toString(transform), + transition, + opacity: isDragging ? 0.5 : 1, + }; + + return ( + + +
+
+ {showDragHandle && ( +
+ +
+ )} + + {preset?.name || provider.id} + +
+
+ onOpenCreditsDialog(provider.id)} + /> + +
+
+
+ +
+
+ + onSetProvider({ ...provider, baseURL: e.target.value })} + /> +
+
+ + +
+ {!provider.nostr && ( +
+ + onSetProvider({ ...provider, apiKey: e.target.value })} + /> +
+ )} +
+
+
+ ); +} + export function AISettings() { const { t } = useTranslation(); - const { settings, addProvider, removeProvider, updateProvider } = useAISettings(); + const { settings, setProvider, removeProvider, setProviders } = useAISettings(); const isMobile = useIsMobile(); const navigate = useNavigate(); const { user } = useCurrentUser(); @@ -93,10 +228,18 @@ export function AISettings() { const [presetApiKeys, setPresetApiKeys] = useState>({}); const [activeCreditsDialog, setActiveCreditsDialog] = useState(null); + const sensors = useSensors( + useSensor(PointerSensor), + useSensor(KeyboardSensor, { + coordinateGetter: sortableKeyboardCoordinates, + }) + ); + const handleAddPresetProvider = (preset: PresetProvider) => { const apiKey = presetApiKeys[preset.id] as string | undefined; - const newProvider: AIConnection = { + const newProvider: AIProvider = { + id: preset.id, baseURL: preset.baseURL, }; @@ -108,7 +251,7 @@ export function AISettings() { } // Auto-save: Add provider immediately to persistent storage - addProvider(preset.id, newProvider); + setProvider(newProvider); // Clear the API key input for this preset setPresetApiKeys(prev => ({ @@ -120,14 +263,15 @@ export function AISettings() { const handleAddCustomProvider = () => { if (!customProviderName.trim() || !customBaseURL.trim()) return; - const newProvider: AIConnection = { + const newProvider: AIProvider = { + id: customProviderName.trim(), baseURL: customBaseURL.trim(), apiKey: customAuthMethod === 'nostr' ? undefined : customApiKey.trim(), nostr: customAuthMethod === 'nostr' || undefined, }; // Auto-save: Add provider immediately to persistent storage - addProvider(customProviderName.trim(), newProvider); + setProvider(newProvider); setCustomProviderName(''); setCustomBaseURL(''); @@ -135,14 +279,14 @@ export function AISettings() { setCustomAuthMethod('api-key'); }; - const handleRemoveProvider = (name: string) => { + const handleRemoveProvider = (id: string) => { // Auto-save: Remove provider immediately from persistent storage - removeProvider(name); + removeProvider(id); }; - const handleUpdateProvider = (name: string, connection: Partial) => { + const handleSetProvider = (provider: AIProvider) => { // Auto-save: Update provider immediately in persistent storage - updateProvider(name, connection); + setProvider(provider); }; const handleOpenCreditsDialog = (providerId: string) => { @@ -153,7 +297,21 @@ export function AISettings() { setActiveCreditsDialog(null); }; - const configuredProviderIds = Object.keys(settings.providers); + const handleDragEnd = (event: DragEndEvent) => { + const { active, over } = event; + + if (active.id !== over?.id) { + const oldIndex = settings.providers.findIndex(provider => provider.id === active.id); + const newIndex = settings.providers.findIndex(provider => provider.id === over?.id); + + if (oldIndex !== -1 && newIndex !== -1) { + const newProviders = arrayMove(settings.providers, oldIndex, newIndex); + setProviders(newProviders); + } + } + }; + + const configuredProviderIds = settings.providers.map(p => p.id); const availablePresets = PRESET_PROVIDERS.filter(preset => !configuredProviderIds.includes(preset.id)); return ( @@ -195,89 +353,37 @@ export function AISettings() {
{/* Configured Providers */} - {configuredProviderIds.length > 0 && ( + {settings.providers.length > 0 && (

{t('configuredProviders')}

- - {configuredProviderIds.map((providerId) => { - const preset = PRESET_PROVIDERS.find(p => p.id === providerId); - const provider = settings.providers[providerId]; + + p.id)} + strategy={verticalListSortingStrategy} + > + + {settings.providers.map((provider) => { + const preset = PRESET_PROVIDERS.find(p => p.id === provider.id); - return ( - - -
-
- - {preset?.name || providerId} - -
-
- handleOpenCreditsDialog(providerId)} - /> - -
-
-
- -
-
- - handleUpdateProvider(providerId, { baseURL: e.target.value })} - /> -
-
- - -
- {!provider?.nostr && ( -
- - handleUpdateProvider(providerId, { apiKey: e.target.value })} - /> -
- )} -
-
-
- ); - })} -
+ return ( + 1} + /> + ); + })} +
+ +
)} @@ -417,14 +523,14 @@ export function AISettings() { disabled={ !customProviderName.trim() || !customBaseURL.trim() || - customProviderName.trim() in settings.providers + settings.providers.some(p => p.id === customProviderName.trim()) } className="gap-2 ml-auto" > {t('addCustomProviderButton')} - {customProviderName.trim() in settings.providers && ( + {settings.providers.some(p => p.id === customProviderName.trim()) && (

{t('providerExists')}

@@ -437,18 +543,21 @@ export function AISettings() {
{/* Render credits dialog outside of accordion structure */} - {activeCreditsDialog && ( - { - if (!open) { - handleCloseCreditsDialog(); - } - }} - providerId={activeCreditsDialog} - connection={settings.providers[activeCreditsDialog]} - /> - )} + {activeCreditsDialog && (() => { + const provider = settings.providers.find(p => p.id === activeCreditsDialog); + return provider && ( + { + if (!open) { + handleCloseCreditsDialog(); + } + }} + providerId={activeCreditsDialog} + connection={{ baseURL: provider.baseURL, apiKey: provider.apiKey, nostr: provider.nostr }} + /> + ); + })()} ); } diff --git a/src/pages/Index.tsx b/src/pages/Index.tsx index 47c6456c..b45f9843 100644 --- a/src/pages/Index.tsx +++ b/src/pages/Index.tsx @@ -39,7 +39,7 @@ export default function Index() { const [isDragOver, setIsDragOver] = useState(false); // Check if any providers are configured - const hasProvidersConfigured = Object.keys(settings.providers).length > 0; + const hasProvidersConfigured = settings.providers.length > 0; useEffect(() => { if (!providerModel && settings.recentlyUsedModels?.length) { From f797ec55c5fe53018c621d521d50fa56d05a8afa Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 13:28:20 -0500 Subject: [PATCH 02/95] Break out npm tasks so the robot is faster --- package.json | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/package.json b/package.json index 723a33d7..07ecc7ed 100644 --- a/package.json +++ b/package.json @@ -6,7 +6,8 @@ "scripts": { "dev": "npm i --silent && vite", "build": "npm i --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'Project built successfully!'", - "test": "npm i --silent && tsc --noEmit && eslint && vitest run --reporter=dot --silent && vite build -l error && cp dist/index.html dist/404.html && echo 'All tests passed!'", + "typecheck": "npm i --silent && tsc --noEmit", + "test": "npm i --silent && eslint && vitest run --reporter=dot --silent && echo 'All tests passed!'", "deploy": "npm run build && npx -y nostr-deploy-cli deploy --skip-setup" }, "dependencies": { From 69c10000637e5de6d4ed5e7e194513c3a575faaf Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 14:10:45 -0500 Subject: [PATCH 03/95] Refactor Git to accept a nostr object --- src/components/ActionsMenu.tsx | 2 +- src/components/GitDialog.tsx | 2 +- src/components/Shakespeare/ChatPane.tsx | 6 +- src/components/ai/GitHistoryDialog.tsx | 2 +- src/hooks/useGit.test.ts | 52 +++++- src/hooks/useGit.ts | 11 +- src/hooks/useGitStatus.ts | 2 +- src/hooks/useProjectsManager.ts | 6 +- src/lib/ProjectsManager.test.ts | 66 +++++-- src/lib/ProjectsManager.ts | 14 +- src/lib/commands/git.test.ts | 11 +- src/lib/git.example.ts | 108 ------------ src/lib/git.test.ts | 31 +++- src/lib/git.ts | 15 +- src/lib/tools/ShellTool.example.ts | 220 ------------------------ src/lib/tools/ShellTool.test.ts | 15 +- 16 files changed, 184 insertions(+), 379 deletions(-) delete mode 100644 src/lib/git.example.ts delete mode 100644 src/lib/tools/ShellTool.example.ts diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index e9c678b5..cb69af3b 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -75,8 +75,8 @@ export function ActionsMenu({ const navigate = useNavigate(); const projectsManager = useProjectsManager(); const { toast } = useToast(); - const git = useGit(); const { fs } = useFS(); + const { git } = useGit(); const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting; diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 5b5b53a7..9397e1a3 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -58,7 +58,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); - const git = useGit(); + const { git } = useGit(); const { toast } = useToast(); const projectPath = `/projects/${projectId}`; diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 86874a48..e6dc2218 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -33,13 +33,13 @@ import { NostrReadNipsIndexTool } from '@/lib/tools/NostrReadNipsIndexTool'; import { NostrGenerateKindTool } from '@/lib/tools/NostrGenerateKindTool'; import { ShellTool } from '@/lib/tools/ShellTool'; import { TypecheckTool } from '@/lib/tools/TypecheckTool'; -import { Git } from '@/lib/git'; import { toolToOpenAI } from '@/lib/tools/openai-adapter'; import { Tool } from '@/lib/tools/Tool'; import OpenAI from 'openai'; import { makeSystemPrompt } from '@/lib/system'; import { assistantContentEmpty } from '@/lib/ai-messages'; import { saveFileToTmp } from '@/lib/fileUtils'; +import { useGit } from '@/hooks/useGit'; interface ChatPaneProps { projectId: string; @@ -94,13 +94,13 @@ export const ChatPane = forwardRef(({ const [searchParams, setSearchParams] = useSearchParams(); const { fs } = useFS(); + const { git } = useGit(); const { user, metadata } = useCurrentUser(); const { models } = useProviderModels(); // Initialize AI chat with tools const cwd = `/projects/${projectId}`; const customTools = useMemo(() => { - const git = new Git(fs); const baseTools = { git_commit: new GitCommitTool(fs, cwd, git), text_editor_view: new TextEditorViewTool(fs, cwd), @@ -129,7 +129,7 @@ export const ChatPane = forwardRef(({ } return baseTools; - }, [fs, cwd, user, projectId]); + }, [fs, git, cwd, user, projectId]); // Convert tools to OpenAI format const tools = useMemo(() => { diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index f678bcc5..9381d3a7 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -43,8 +43,8 @@ export function GitHistoryDialog({ projectId, open: controlledOpen, onOpenChange const setIsOpen = onOpenChange || setInternalOpen; const [isRollingBack, setIsRollingBack] = useState(null); const [expandedCommits, setExpandedCommits] = useState>(new Set()); - const git = useGit(); const { fs } = useFS(); + const { git } = useGit(); const { toast } = useToast(); const loadGitHistory = useCallback(async () => { diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index d24fffe2..8be35626 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -5,22 +5,40 @@ import { useFS } from './useFS'; import { useGitSettings } from './useGitSettings'; import { Git } from '@/lib/git'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; +import type { NPool } from '@nostrify/nostrify'; // Mock the dependencies vi.mock('./useFS'); vi.mock('./useGitSettings'); +vi.mock('@nostrify/react', () => ({ + useNostr: vi.fn(), +})); vi.mock('@/lib/git'); const mockUseFS = vi.mocked(useFS); const mockUseGitSettings = vi.mocked(useGitSettings); const MockGit = vi.mocked(Git); +// Import the mocked useNostr after mocking +import { useNostr } from '@nostrify/react'; +const mockUseNostr = vi.mocked(useNostr); + describe('useGit', () => { const mockFS = {} as JSRuntimeFS; + const mockNostr = { + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), + } as unknown as NPool; beforeEach(() => { vi.clearAllMocks(); mockUseFS.mockReturnValue({ fs: mockFS }); + mockUseNostr.mockReturnValue({ nostr: mockNostr }); }); it('creates Git instance with default CORS proxy', () => { @@ -36,9 +54,14 @@ describe('useGit', () => { isConfigured: false, }); - renderHook(() => useGit()); + const { result } = renderHook(() => useGit()); - expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org'); + expect(MockGit).toHaveBeenCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://cors.isomorphic-git.org', + }); + expect(result.current).toEqual({ git: expect.any(Object) }); }); it('creates Git instance with custom CORS proxy', () => { @@ -54,14 +77,17 @@ describe('useGit', () => { isConfigured: false, }); - renderHook(() => useGit()); + const { result } = renderHook(() => useGit()); - expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://custom-cors.example.com'); + expect(MockGit).toHaveBeenCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://custom-cors.example.com', + }); + expect(result.current).toEqual({ git: expect.any(Object) }); }); it('recreates Git instance when CORS proxy changes', () => { - const { rerender } = renderHook(() => useGit()); - // First render with default proxy mockUseGitSettings.mockReturnValue({ settings: { @@ -75,8 +101,12 @@ describe('useGit', () => { isConfigured: false, }); - rerender(); - expect(MockGit).toHaveBeenCalledWith(mockFS, 'https://cors.isomorphic-git.org'); + const { rerender } = renderHook(() => useGit()); + expect(MockGit).toHaveBeenCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://cors.isomorphic-git.org', + }); // Second render with custom proxy mockUseGitSettings.mockReturnValue({ @@ -92,6 +122,10 @@ describe('useGit', () => { }); rerender(); - expect(MockGit).toHaveBeenLastCalledWith(mockFS, 'https://custom-cors.example.com'); + expect(MockGit).toHaveBeenLastCalledWith({ + fs: mockFS, + nostr: mockNostr, + corsProxy: 'https://custom-cors.example.com', + }); }); }); \ No newline at end of file diff --git a/src/hooks/useGit.ts b/src/hooks/useGit.ts index 65a542d9..714441e6 100644 --- a/src/hooks/useGit.ts +++ b/src/hooks/useGit.ts @@ -1,19 +1,22 @@ import { useMemo } from 'react'; import { Git } from '@/lib/git'; import { useFS } from '@/hooks/useFS'; +import { useNostr } from '@nostrify/react'; import { useGitSettings } from '@/hooks/useGitSettings'; /** * Hook that provides a Git instance configured with the virtual filesystem * and configurable CORS proxy for GitHub/GitLab repositories. */ -export function useGit() { +export function useGit(): { git: Git } { const { fs } = useFS(); + const { nostr } = useNostr(); const { settings } = useGitSettings(); + const { corsProxy } = settings; const git = useMemo(() => { - return new Git(fs, settings.corsProxy); - }, [fs, settings.corsProxy]); + return new Git({ fs, nostr, corsProxy }); + }, [fs, nostr, corsProxy]); - return git; + return { git }; } \ No newline at end of file diff --git a/src/hooks/useGitStatus.ts b/src/hooks/useGitStatus.ts index c4ec76ac..d12a7c9f 100644 --- a/src/hooks/useGitStatus.ts +++ b/src/hooks/useGitStatus.ts @@ -40,7 +40,7 @@ interface GitStatus { } export function useGitStatus(projectId: string | null) { - const git = useGit(); + const { git } = useGit(); return useQuery({ queryKey: ['git-status', projectId], diff --git a/src/hooks/useProjectsManager.ts b/src/hooks/useProjectsManager.ts index d7d133e6..c918bd1e 100644 --- a/src/hooks/useProjectsManager.ts +++ b/src/hooks/useProjectsManager.ts @@ -1,6 +1,7 @@ import { useMemo } from 'react'; import { ProjectsManager } from '@/lib/ProjectsManager'; import { useFS } from '@/hooks/useFS'; +import { useGit } from './useGit'; /** * Hook that provides a ProjectsManager instance. @@ -8,8 +9,11 @@ import { useFS } from '@/hooks/useFS'; */ export function useProjectsManager() { const { fs } = useFS(); + const { git } = useGit(); - const projectsManager = useMemo(() => new ProjectsManager(fs), [fs]); + const projectsManager = useMemo(() => { + return new ProjectsManager({ fs, git }); + }, [fs, git]); return projectsManager; } \ No newline at end of file diff --git a/src/lib/ProjectsManager.test.ts b/src/lib/ProjectsManager.test.ts index aea9a858..f5d6a5fc 100644 --- a/src/lib/ProjectsManager.test.ts +++ b/src/lib/ProjectsManager.test.ts @@ -1,11 +1,27 @@ -import { describe, it, expect, beforeEach } from 'vitest'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; import { ProjectsManager } from './ProjectsManager'; +import { JSRuntimeFS } from './JSRuntime'; +import { Git } from './git'; +import type { NPool } from '@nostrify/nostrify'; + +const createMockNostr = (): NPool => ({ + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), +}) as unknown as NPool; // Mock filesystem for testing -class MockFS { +class MockFS implements JSRuntimeFS { private files: Map = new Map(); private dirs: Set = new Set(); + async readFile(path: string): Promise; + async readFile(path: string, encoding: "utf8"): Promise; + async readFile(path: string, encoding: string): Promise; async readFile(path: string, encoding?: string): Promise { const content = this.files.get(path); if (content === undefined) { @@ -13,10 +29,18 @@ class MockFS { error.code = 'ENOENT'; throw error; } - if (encoding === 'utf8' && typeof content === 'string') { - return content; + if (encoding === 'utf8') { + if (typeof content === 'string') { + return content; + } + // Convert Uint8Array to string + return new TextDecoder('utf-8').decode(content as Uint8Array); } - return content; + if (typeof content === 'string') { + // Convert string to Uint8Array + return new TextEncoder().encode(content); + } + return content as Uint8Array; } async writeFile(path: string, data: string | Uint8Array): Promise { @@ -28,13 +52,14 @@ class MockFS { } } - async readdir(path: string): Promise { + // @ts-expect-error I don't know how to type this properly + async readdir(path: string, options?: { withFileTypes?: boolean }): Promise { if (!this.dirs.has(path)) { const error = new Error(`ENOENT: no such file or directory, scandir '${path}'`) as NodeJS.ErrnoException; error.code = 'ENOENT'; throw error; } - + const entries: string[] = []; // Find subdirectories @@ -51,7 +76,22 @@ class MockFS { } } - return [...new Set(entries)]; + const uniqueEntries = [...new Set(entries)]; + + if (options && options.withFileTypes) { + // Provide a minimal DirectoryEntry mock + return uniqueEntries.map(name => { + const fullPath = path.endsWith('/') ? path + name : path + '/' + name; + const isDir = this.dirs.has(fullPath); + return { + name, + isDirectory: () => isDir, + isFile: () => !isDir, + } as unknown as DirectoryEntry; + }); + } + + return uniqueEntries; } async mkdir(path: string): Promise { @@ -88,12 +128,16 @@ class MockFS { } describe('ProjectsManager', () => { - let fs: MockFS; + let fs: JSRuntimeFS; + let git: Git; + let nostr: NPool; let projectsManager: ProjectsManager; beforeEach(() => { - fs = new MockFS(); - projectsManager = new ProjectsManager(fs as unknown as import('./JSRuntime').JSRuntimeFS); + fs = new MockFS() as unknown as JSRuntimeFS; + nostr = createMockNostr(); + git = new Git({ fs, nostr }); + projectsManager = new ProjectsManager({ fs, git }); }); describe('getProjects', () => { diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 91af47ab..014ac6d4 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -1,8 +1,7 @@ import { Buffer } from 'buffer'; -import { Git } from '@/lib/git'; +import type { Git } from '@/lib/git'; import type { JSRuntimeFS } from '@/lib/JSRuntime'; - // Polyfill Buffer for browser if (typeof window !== 'undefined') { (window as { Buffer?: typeof Buffer }).Buffer = Buffer; @@ -18,14 +17,19 @@ export interface Project { lastModified: Date; } +export interface ProjectsManagerOptions { + fs: JSRuntimeFS; + git: Git; +} + export class ProjectsManager { fs: JSRuntimeFS; git: Git; dir: string; - constructor(fs: JSRuntimeFS) { - this.fs = fs; - this.git = new Git(fs, 'https://cors.isomorphic-git.org'); + constructor(options: ProjectsManagerOptions) { + this.fs = options.fs; + this.git = options.git; this.dir = '/projects'; } diff --git a/src/lib/commands/git.test.ts b/src/lib/commands/git.test.ts index c05b6bed..4ecf4acd 100644 --- a/src/lib/commands/git.test.ts +++ b/src/lib/commands/git.test.ts @@ -40,7 +40,16 @@ describe('GitCommand', () => { beforeEach(() => { mockFS = createMockFS(); - const git = new Git(mockFS); + const mockNostr = { + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), + } as unknown as import('@nostrify/nostrify').NPool; + const git = new Git({ fs: mockFS, nostr: mockNostr }); gitCommand = new GitCommand({ git, fs: mockFS, cwd: testCwd }); }); diff --git a/src/lib/git.example.ts b/src/lib/git.example.ts deleted file mode 100644 index 93f73986..00000000 --- a/src/lib/git.example.ts +++ /dev/null @@ -1,108 +0,0 @@ -import { Git } from './git'; -import type { JSRuntimeFS } from './JSRuntime'; - -/** - * Example usage of the Git class - */ -export async function exampleGitUsage(fs: JSRuntimeFS) { - // Create a Git instance with fs and optional CORS proxy - const git = new Git(fs, 'https://cors.isomorphic-git.org'); - - // Initialize a new repository - await git.init({ - dir: '/my-project', - defaultBranch: 'main', - }); - - // Set up configuration - await git.setConfig({ - dir: '/my-project', - path: 'user.name', - value: 'John Doe', - }); - - await git.setConfig({ - dir: '/my-project', - path: 'user.email', - value: 'john@example.com', - }); - - // Add files to the index - await git.add({ - dir: '/my-project', - filepath: 'README.md', - }); - - // Make a commit - await git.commit({ - dir: '/my-project', - message: 'Initial commit', - author: { - name: 'John Doe', - email: 'john@example.com', - }, - }); - - // Get repository status - const statusMatrix = await git.statusMatrix({ - dir: '/my-project', - }); - - // List branches - const branches = await git.listBranches({ - dir: '/my-project', - }); - - // Get commit log - const commits = await git.log({ - dir: '/my-project', - depth: 10, - }); - - // Clone a repository - await git.clone({ - dir: '/cloned-project', - url: 'https://github.com/user/repo.git', - singleBranch: true, - depth: 1, - }); - - // Add a remote - await git.addRemote({ - dir: '/my-project', - remote: 'origin', - url: 'https://github.com/user/my-project.git', - }); - - // Push to remote (requires authentication) - try { - await git.push({ - dir: '/my-project', - remote: 'origin', - ref: 'main', - // onAuth would be needed for authentication - }); - } catch (error) { - console.log('Push failed (likely due to authentication):', error); - } - - return { - statusMatrix, - branches, - commits, - }; -} - -/** - * Example for GitHub/GitLab repositories with CORS proxy - */ -export function createGitForGitHub(fs: JSRuntimeFS) { - return new Git(fs, 'https://cors.isomorphic-git.org'); -} - -/** - * Example for self-hosted Git servers without CORS proxy - */ -export function createGitForSelfHosted(fs: JSRuntimeFS) { - return new Git(fs); // No CORS proxy needed -} \ No newline at end of file diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index bdf44f80..4958c69e 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -1,6 +1,7 @@ import { describe, it, expect, vi, beforeEach } from 'vitest'; import { Git } from './git'; import git from 'isomorphic-git'; +import type { NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; // Mock isomorphic-git @@ -9,18 +10,30 @@ vi.mock('isomorphic-git/http/web'); const mockGit = vi.mocked(git); +const createMockNostr = (): NPool => ({ + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), +}) as unknown as NPool; + describe('Git', () => { - const mockFS = {} as JSRuntimeFS; + const fs = {} as JSRuntimeFS; + const nostr = createMockNostr(); + const corsProxy = 'https://cors.example.com'; let gitInstance: Git; beforeEach(() => { vi.clearAllMocks(); - gitInstance = new Git(mockFS, 'https://cors.example.com'); + gitInstance = new Git({ fs, nostr, corsProxy }); }); describe('constructor', () => { it('creates instance with default regex when none provided', () => { - const git = new Git(mockFS, 'https://cors.example.com'); + const git = new Git({ fs, nostr, corsProxy }); expect(git).toBeInstanceOf(Git); }); @@ -39,7 +52,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -54,7 +67,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -69,7 +82,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -84,7 +97,7 @@ describe('Git', () => { }); expect(mockGit.clone).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -138,7 +151,7 @@ describe('Git', () => { }); expect(mockGit.fetch).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', @@ -153,7 +166,7 @@ describe('Git', () => { }); expect(mockGit.fetch).toHaveBeenCalledWith({ - fs: mockFS, + fs, http: expect.any(Object), corsProxy: 'https://cors.example.com', dir: '/test', diff --git a/src/lib/git.ts b/src/lib/git.ts index cfb7dd20..8e2dec5f 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -1,7 +1,14 @@ import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; +import type { NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; +export interface GitOptions { + fs: JSRuntimeFS; + nostr: NPool; + corsProxy?: string; +} + /** * Git class that wraps isomorphic-git and provides a cleaner interface. * Instantiate with an fs implementation, optional corsProxy string, and optional corsProxyRegex. @@ -10,11 +17,13 @@ import type { JSRuntimeFS } from './JSRuntime'; */ export class Git { private fs: JSRuntimeFS; + private nostr: NPool; private corsProxy?: string; - constructor(fs: JSRuntimeFS, corsProxy?: string) { - this.fs = fs; - this.corsProxy = corsProxy; + constructor(options: GitOptions) { + this.fs = options.fs; + this.nostr = options.nostr; + this.corsProxy = options.corsProxy; } // Repository initialization and configuration diff --git a/src/lib/tools/ShellTool.example.ts b/src/lib/tools/ShellTool.example.ts deleted file mode 100644 index fbd311b3..00000000 --- a/src/lib/tools/ShellTool.example.ts +++ /dev/null @@ -1,220 +0,0 @@ -/** - * Example usage of the ShellTool - * - * This file demonstrates how to use the ShellTool to execute shell commands - * in your application. The ShellTool provides a safe, sandboxed environment - * for running basic file operations. - */ - -import { ShellTool } from './ShellTool'; -import { Git } from '../git'; -import type { JSRuntimeFS } from '../JSRuntime'; - -/** - * Example function showing how to use ShellTool - */ -export async function exampleShellUsage(fs: JSRuntimeFS, projectRoot: string) { - // Create a shell tool instance - const shell = new ShellTool(fs, projectRoot, new Git(fs)); - - console.log('Available commands:', shell.getAvailableCommands()); - console.log('Current directory:', shell.getCurrentWorkingDirectory()); - - // Example 1: Display current directory - console.log('\n--- Example 1: Show current directory ---'); - const pwdResult = await shell.execute({ command: 'pwd' }); - console.log(pwdResult); - - // Example 2: List directory contents - console.log('\n--- Example 2: List files ---'); - const lsResult = await shell.execute({ command: 'ls' }); - console.log(lsResult); - - // Example 3: List with long format - console.log('\n--- Example 3: List with details ---'); - const lsLongResult = await shell.execute({ command: 'ls -l' }); - console.log(lsLongResult); - - // Example 4: Display a file - console.log('\n--- Example 4: Display package.json ---'); - const catResult = await shell.execute({ command: 'cat package.json' }); - console.log(catResult); - - // Example 5: Echo text - console.log('\n--- Example 5: Echo message ---'); - const echoResult = await shell.execute({ command: 'echo Hello, World!' }); - console.log(echoResult); - - // Example 6: Change directory - console.log('\n--- Example 6: Change directory ---'); - const cdResult = await shell.execute({ command: 'cd src' }); - console.log(cdResult); - console.log('New directory:', shell.getCurrentWorkingDirectory()); - - // Example 7: Handle errors gracefully - console.log('\n--- Example 7: Handle non-existent file ---'); - const errorResult = await shell.execute({ - command: 'cat nonexistent-file.txt' - }); - console.log(errorResult); - - // Example 8: Try unknown command - console.log('\n--- Example 8: Unknown command ---'); - const unknownResult = await shell.execute({ - command: 'unknown-command arg1 arg2' - }); - console.log(unknownResult); - - // Example 9: Compound commands with && - console.log('\n--- Example 9: Compound commands with && ---'); - const andResult = await shell.execute({ - command: 'pwd && echo "Current directory listed above"' - }); - console.log(andResult); - - // Example 10: Compound commands with || - console.log('\n--- Example 10: Compound commands with || ---'); - const orResult = await shell.execute({ - command: 'cat nonexistent.txt || echo "File not found, showing fallback message"' - }); - console.log(orResult); - - // Example 11: Sequential commands with ; - console.log('\n--- Example 11: Sequential commands with ; ---'); - const sequentialResult = await shell.execute({ - command: 'echo "First command"; echo "Second command"; pwd' - }); - console.log(sequentialResult); - - // Example 12: Pipe commands - console.log('\n--- Example 12: Pipe commands ---'); - const pipeResult = await shell.execute({ - command: 'echo "line1\nline2\nline3\nline4\nline5" | head -n 3' - }); - console.log(pipeResult); - - // Example 13: Complex pipe chain - console.log('\n--- Example 13: Complex pipe chain ---'); - const complexPipeResult = await shell.execute({ - command: 'echo "apple\nbanana\napple\ncherry\nbanana\napple" | sort | uniq' - }); - console.log(complexPipeResult); - - // Example 14: Mixed compound operators - console.log('\n--- Example 14: Mixed compound operators ---'); - const mixedResult = await shell.execute({ - command: 'echo "Processing..." && echo "data1\ndata2\ndata3" | wc -l && echo "Done!"' - }); - console.log(mixedResult); -} - -/** - * Example React hook for using ShellTool - */ -export function useShell(fs: JSRuntimeFS, cwd: string) { - const shell = new ShellTool(fs, cwd, new Git(fs)); - - const executeCommand = async (command: string): Promise => { - try { - return await shell.execute({ command }); - } catch (error) { - return `Error: ${error instanceof Error ? error.message : 'Unknown error'}`; - } - }; - - return { - executeCommand, - getCurrentDirectory: () => shell.getCurrentWorkingDirectory(), - setCurrentDirectory: (newCwd: string) => shell.setCurrentWorkingDirectory(newCwd), - getAvailableCommands: () => shell.getAvailableCommands(), - }; -} - -/** - * Example integration with AI tools - * Shows how the ShellTool can be used as part of an AI assistant - */ -export class AIShellIntegration { - private shell: ShellTool; - - constructor(fs: JSRuntimeFS, projectRoot: string) { - this.shell = new ShellTool(fs, projectRoot, new Git(fs)); - } - - /** - * Process natural language requests and convert to shell commands - */ - async processNaturalLanguageRequest(request: string): Promise { - const lowerRequest = request.toLowerCase(); - - // Simple pattern matching for demonstration - if (lowerRequest.includes('show me') && lowerRequest.includes('file')) { - // Extract filename from request - const fileMatch = request.match(/file\s+["']?([^"'\s]+)["']?/i); - if (fileMatch) { - const filename = fileMatch[1]; - return await this.shell.execute({ command: `cat ${filename}` }); - } - } - - if (lowerRequest.includes('list') && lowerRequest.includes('command')) { - const commands = this.shell.getAvailableCommands(); - return commands.map(cmd => `${cmd.name}: ${cmd.description}`).join('\n'); - } - - if (lowerRequest.includes('current') && lowerRequest.includes('directory')) { - return `Current directory: ${this.shell.getCurrentWorkingDirectory()}`; - } - - return 'I can help you with file operations. Try asking me to "show me a file" or "list available commands".'; - } -} - -/** - * Example CLI-like interface - */ -export class SimpleCLI { - private shell: ShellTool; - private history: string[] = []; - - constructor(fs: JSRuntimeFS, projectRoot: string) { - this.shell = new ShellTool(fs, projectRoot, new Git(fs)); - } - - async executeCommand(command: string): Promise { - this.history.push(command); - - // Handle built-in commands - if (command.trim() === 'help') { - const commands = this.shell.getAvailableCommands(); - return [ - 'Available commands:', - ...commands.map(cmd => ` ${cmd.usage} - ${cmd.description}`), - '', - 'Built-in commands:', - ' help - Show this help message', - ' history - Show command history', - ' pwd - Show current directory', - ].join('\n'); - } - - if (command.trim() === 'history') { - return this.history.map((cmd, i) => `${i + 1}: ${cmd}`).join('\n'); - } - - if (command.trim() === 'pwd') { - return this.shell.getCurrentWorkingDirectory(); - } - - // Execute through shell tool - return await this.shell.execute({ command }); - } - - getHistory(): string[] { - return [...this.history]; - } - - clearHistory(): void { - this.history = []; - } -} \ No newline at end of file diff --git a/src/lib/tools/ShellTool.test.ts b/src/lib/tools/ShellTool.test.ts index 38b7bba0..ba5d4e65 100644 --- a/src/lib/tools/ShellTool.test.ts +++ b/src/lib/tools/ShellTool.test.ts @@ -2,6 +2,7 @@ import { describe, it, expect, beforeEach, vi } from 'vitest'; import { ShellTool } from './ShellTool'; import { Git } from '../git'; import type { JSRuntimeFS } from '../JSRuntime'; +import { NPool } from '@nostrify/nostrify'; // Mock filesystem const createMockFS = (): JSRuntimeFS => ({ @@ -18,15 +19,27 @@ const createMockFS = (): JSRuntimeFS => ({ symlink: vi.fn(), }); +const createMockNostr = (): NPool => ({ + req: vi.fn(), + query: vi.fn(), + event: vi.fn(), + group: vi.fn(), + relay: vi.fn(), + relays: new Map(), + close: vi.fn(), +}) as unknown as NPool; + describe('ShellTool', () => { let mockFS: JSRuntimeFS; let mockGit: Git; + let mockNostr: NPool; let shellTool: ShellTool; const testCwd = '/test/dir'; beforeEach(() => { mockFS = createMockFS(); - mockGit = new Git(mockFS); + mockNostr = createMockNostr(); + mockGit = new Git({ fs: mockFS, nostr: mockNostr }); shellTool = new ShellTool(mockFS, testCwd, mockGit); }); From d3e257f75997c7c956aba5f097bcf01aa0129079 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 14:45:27 -0500 Subject: [PATCH 04/95] Transfer Nostr clone logic into Git class --- src/lib/ProjectsManager.ts | 2 +- src/lib/git.ts | 155 ++++++++++++++++++++++++++++ src/pages/Clone.tsx | 204 ++++++------------------------------- 3 files changed, 188 insertions(+), 173 deletions(-) diff --git a/src/lib/ProjectsManager.ts b/src/lib/ProjectsManager.ts index 014ac6d4..07dddad6 100644 --- a/src/lib/ProjectsManager.ts +++ b/src/lib/ProjectsManager.ts @@ -107,7 +107,7 @@ export class ProjectsManager { await this.fs.mkdir(projectPath); - // Clone the repository + // Clone the repository (Git class now handles Nostr URIs automatically) await this.git.clone({ dir: projectPath, url: repoUrl, diff --git a/src/lib/git.ts b/src/lib/git.ts index 8e2dec5f..ae8debfb 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -1,5 +1,7 @@ import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; +import { NIP05 } from '@nostrify/nostrify'; +import { nip19 } from 'nostr-tools'; import type { NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; @@ -9,6 +11,12 @@ export interface GitOptions { corsProxy?: string; } +interface NostrCloneURI { + pubkey: string; + d: string; + relay?: string; +} + /** * Git class that wraps isomorphic-git and provides a cleaner interface. * Instantiate with an fs implementation, optional corsProxy string, and optional corsProxyRegex. @@ -35,6 +43,21 @@ export class Git { } async clone(options: Omit[0], 'fs' | 'http' | 'corsProxy'>) { + // Check if the URL is a Nostr URI + if (options.url.startsWith('nostr://')) { + const nostrUri = await this.parseNostrCloneURI(options.url); + if (!nostrUri) { + throw new Error('Invalid Nostr clone URI format'); + } + + // Fetch clone URLs from Nostr + const cloneUrls = await this.fetchNostrRepository(nostrUri); + + // Try cloning from each URL in order + return this.tryCloneUrls(cloneUrls, options); + } + + // Regular Git URL return git.clone({ fs: this.fs, http, @@ -502,4 +525,136 @@ export class Git { version() { return git.version(); } + + // Nostr-specific helper methods + private async parseNostrCloneURI(uri: string): Promise { + try { + if (!uri.startsWith('nostr://')) { + return null; + } + + const path = uri.slice(8); // Remove 'nostr://' prefix + const parts = path.split('/'); + + if (parts.length < 2) { + return null; + } + + const identifier = parts[0]; + let pubkey: string; + + // Try to decode as npub first, otherwise assume it's already a hex pubkey + try { + const decoded = nip19.decode(identifier); + if (decoded.type === 'npub') { + pubkey = decoded.data; + } else { + return null; + } + } catch { + // If decoding fails, check if it's a NIP-05 identifier + if (identifier.split('@').length === 2) { + const pointer = await NIP05.lookup(identifier, { + signal: AbortSignal.timeout(3000), + }); + pubkey = pointer.pubkey; + } else { + return null; + } + } + + // Check if we have relay and d-tag or just d-tag + if (parts.length === 3) { + // Format: nostr://npub/relay/d + return { + pubkey, + relay: parts[1], + d: parts[2], + }; + } else if (parts.length === 2) { + // Format: nostr://npub/d + return { + pubkey, + d: parts[1], + }; + } + + return null; + } catch { + return null; + } + } + + private async fetchNostrRepository(nostrURI: NostrCloneURI): Promise { + const signal = AbortSignal.timeout(10000); // 10 second timeout + + // Build the filter for the NIP-34 repository announcement + const filter = { + kinds: [30617], + authors: [nostrURI.pubkey], + '#d': [nostrURI.d], + limit: 1, + }; + + // Use a specific relay if provided + const client = nostrURI.relay + ? this.nostr.relay(nostrURI.relay) + : this.nostr.group(['wss://relay.ngit.dev/', 'wss://gitnostr.com/']); + + // Query for the repository announcement event + const events = await client.query([filter], { signal }); + + if (events.length === 0) { + throw new Error('Repository not found on Nostr network'); + } + + const repoEvent = events[0]; + + // Extract clone URLs from the event tags + const cloneUrls: string[] = []; + for (const tag of repoEvent.tags) { + if (tag[0] === 'clone' && tag[1]) { + cloneUrls.push(tag[1]); + } + } + + if (cloneUrls.length === 0) { + throw new Error('No clone URLs found in repository announcement'); + } + + return cloneUrls; + } + + private async tryCloneUrls(cloneUrls: string[], originalOptions: Omit[0], 'fs' | 'http' | 'corsProxy'>): Promise { + let lastError: Error | null = null; + + for (const cloneUrl of cloneUrls) { + try { + console.log(`Attempting to clone from: ${cloneUrl}`); + + // Try cloning with a timeout + await Promise.race([ + git.clone({ + fs: this.fs, + http, + corsProxy: this.corsProxy, + ...originalOptions, + url: cloneUrl, // Override the URL with the actual Git URL + }), + new Promise((_, reject) => + setTimeout(() => reject(new Error('Clone timeout')), 30000) + ) + ]); + + return; // Success! + } catch (error) { + console.warn(`Failed to clone from ${cloneUrl}:`, error); + lastError = error instanceof Error ? error : new Error('Unknown error'); + continue; // Try the next URL + } + } + + // If we get here, all clone attempts failed + throw lastError || new Error('All clone attempts failed'); + } } \ No newline at end of file diff --git a/src/pages/Clone.tsx b/src/pages/Clone.tsx index 892b3261..49142e96 100644 --- a/src/pages/Clone.tsx +++ b/src/pages/Clone.tsx @@ -7,19 +7,9 @@ import { Input } from '@/components/ui/input'; import { GitBranch, Loader2, AlertCircle } from 'lucide-react'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; -import { NIP05 } from '@nostrify/nostrify'; -import { useNostr } from '@nostrify/react'; -import { nip19 } from 'nostr-tools'; -import type { Project } from '@/lib/ProjectsManager'; import { useSeoMeta } from '@unhead/react'; -interface NostrCloneUri { - pubkey: string; - dTag: string; - relay?: string; -} - export default function Clone() { const { t } = useTranslation(); const [repoUrl, setRepoUrl] = useState(''); @@ -29,7 +19,6 @@ export default function Clone() { const [searchParams] = useSearchParams(); const projectsManager = useProjectsManager(); const { toast } = useToast(); - const { nostr } = useNostr(); useSeoMeta({ title: `${t('importRepository')} - Shakespeare`, @@ -38,9 +27,20 @@ export default function Clone() { const extractRepoName = (url: string): string => { try { - // Handle different URL formats const cleanUrl = url.trim(); + // Handle Nostr clone URIs + if (cleanUrl.startsWith('nostr://')) { + const path = cleanUrl.slice(8); // Remove 'nostr://' prefix + const parts = path.split('/'); + + // Return the d-tag (last part) as the repo name + if (parts.length >= 2) { + return parts[parts.length - 1] || 'nostr-repo'; + } + return 'nostr-repo'; + } + // Extract from GitHub URLs, GitLab URLs, etc. const match = cleanUrl.match(/\/([^/]+?)(?:\.git)?(?:\/)?$/); if (match && match[1]) { @@ -56,70 +56,12 @@ export default function Clone() { } }; - const parseNostrCloneUri = async (uri: string): Promise => { - try { - if (!uri.startsWith('nostr://')) { - return null; - } - - const path = uri.slice(8); // Remove 'nostr://' prefix - const parts = path.split('/'); - - if (parts.length < 2) { - return null; - } - - const identifier = parts[0]; - let pubkey: string; - - // Try to decode as npub first, otherwise assume it's already a hex pubkey - try { - const decoded = nip19.decode(identifier); - if (decoded.type === 'npub') { - pubkey = decoded.data; - } else { - return null; - } - } catch { - // If decoding fails, check if it's a NIP-05 identifier - if (identifier.split('@').length === 2) { - const pointer = await NIP05.lookup(identifier, { - signal: AbortSignal.timeout(3000), - }); - pubkey = pointer.pubkey; - } else { - return null; - } - } - - // Check if we have relay and d-tag or just d-tag - if (parts.length === 3) { - // Format: nostr://npub/relay/dtag - return { - pubkey, - relay: parts[1], - dTag: parts[2], - }; - } else if (parts.length === 2) { - // Format: nostr://npub/dtag - return { - pubkey, - dTag: parts[1], - }; - } - - return null; - } catch { - return null; - } - }; - const validateGitUrl = useCallback((url: string): boolean => { if (!url.trim()) return false; // Check if it's a Nostr clone URI if (url.startsWith('nostr://')) { - return parseNostrCloneUri(url) !== null; + return true; // Git class will handle validation } // Basic URL validation @@ -134,73 +76,6 @@ export default function Clone() { return gitUrlPattern.test(url) || url.includes('github.com') || url.includes('gitlab.com'); }, []); - const fetchNostrRepository = useCallback(async (nostrUri: NostrCloneUri): Promise => { - const signal = AbortSignal.timeout(10000); // 10 second timeout - - // Build the filter for the NIP-34 repository announcement - const filter = { - kinds: [30617], - authors: [nostrUri.pubkey], - '#d': [nostrUri.dTag], - limit: 1, - }; - - // Use a specific relay if provided - const client = nostrUri.relay - ? nostr.relay(nostrUri.relay) - : nostr.group(['wss://relay.ngit.dev/', 'wss://gitnostr.com/']); - - // Query for the repository announcement event - const events = await client.query([filter], { signal }); - - if (events.length === 0) { - throw new Error('Repository not found on Nostr network'); - } - - const repoEvent = events[0]; - - // Extract clone URLs from the event tags - const cloneUrls: string[] = []; - for (const tag of repoEvent.tags) { - if (tag[0] === 'clone' && tag[1]) { - cloneUrls.push(tag[1]); - } - } - - if (cloneUrls.length === 0) { - throw new Error('No clone URLs found in repository announcement'); - } - - return cloneUrls; - }, [nostr]); - - const tryCloneUrls = useCallback(async (cloneUrls: string[], repoName: string): Promise => { - let lastError: Error | null = null; - - for (const cloneUrl of cloneUrls) { - try { - console.log(`Attempting to clone from: ${cloneUrl}`); - - // Try cloning with a timeout - const project = await Promise.race([ - projectsManager.cloneProject(repoName, cloneUrl), - new Promise((_, reject) => - setTimeout(() => reject(new Error('Clone timeout')), 30000) - ) - ]); - - return project; // Success! - } catch (error) { - console.warn(`Failed to clone from ${cloneUrl}:`, error); - lastError = error instanceof Error ? error : new Error('Unknown error'); - continue; // Try the next URL - } - } - - // If we get here, all clone attempts failed - throw lastError || new Error('All clone attempts failed'); - }, [projectsManager]); - const handleClone = useCallback(async (url?: string) => { const targetUrl = url || repoUrl; @@ -220,43 +95,28 @@ export default function Clone() { try { await projectsManager.init(); - // Check if it's a Nostr clone URI - const nostrUri = await parseNostrCloneUri(targetUrl.trim()); + // Extract repository name + const repoName = extractRepoName(targetUrl); - if (nostrUri) { - // Handle Nostr clone URI - console.log('Parsing Nostr clone URI:', nostrUri); + // Clone the repository (Git class handles both regular Git URLs and Nostr URIs) + const project = await projectsManager.cloneProject(repoName, targetUrl.trim()); - // Fetch the repository announcement from Nostr - const cloneUrls = await fetchNostrRepository(nostrUri); - console.log('Found clone URLs:', cloneUrls); + // Determine success message based on URL type + const isNostrUri = targetUrl.startsWith('nostr://'); + const successTitle = isNostrUri + ? t('nostrRepositoryImportedSuccessfully') + : t('repositoryImportedSuccessfully'); + const successDescription = isNostrUri + ? t('repositoryClonedFromNostr', { repoName }) + : t('repositoryClonedReady', { repoName }); - // Extract repository name from d-tag - const repoName = nostrUri.dTag; + toast({ + title: successTitle, + description: successDescription, + }); - // Try cloning from each URL in order - const project = await tryCloneUrls(cloneUrls, repoName); - - toast({ - title: t('nostrRepositoryImportedSuccessfully'), - description: t('repositoryClonedFromNostr', { repoName }), - }); - - // Navigate to the new project - navigate(`/project/${project.id}`); - } else { - // Handle regular Git URL - const repoName = extractRepoName(targetUrl); - const project = await projectsManager.cloneProject(repoName, targetUrl.trim()); - - toast({ - title: t('repositoryImportedSuccessfully'), - description: t('repositoryClonedReady', { repoName }), - }); - - // Navigate to the new project - navigate(`/project/${project.id}`); - } + // Navigate to the new project + navigate(`/project/${project.id}`); } catch (error) { console.error('Failed to clone repository:', error); @@ -289,7 +149,7 @@ export default function Clone() { } finally { setIsCloning(false); } - }, [fetchNostrRepository, navigate, projectsManager, repoUrl, t, toast, tryCloneUrls, validateGitUrl]); + }, [navigate, projectsManager, repoUrl, t, toast, validateGitUrl]); const handleKeyDown = (e: React.KeyboardEvent) => { if (e.key === 'Enter' && !isCloning) { From 3e502fa3a9f376e6bbcd887bed9c4f9c9398a296 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 15:38:03 -0500 Subject: [PATCH 05/95] When cloning by Nostr URI, set the URI in the remote --- src/lib/git.test.ts | 127 ++++++++++++++++++++++++++++++++++++++++++++ src/lib/git.ts | 24 +++++++++ 2 files changed, 151 insertions(+) diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index 4958c69e..8c8fe4cf 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -3,10 +3,21 @@ import { Git } from './git'; import git from 'isomorphic-git'; import type { NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; +import { nip19 } from 'nostr-tools'; // Mock isomorphic-git vi.mock('isomorphic-git'); vi.mock('isomorphic-git/http/web'); +vi.mock('nostr-tools', () => ({ + nip19: { + decode: vi.fn(), + }, +})); +vi.mock('@nostrify/nostrify', () => ({ + NIP05: { + lookup: vi.fn(), + }, +})); const mockGit = vi.mocked(git); @@ -174,4 +185,120 @@ describe('Git', () => { }); }); }); + + describe('Nostr URI cloning', () => { + beforeEach(() => { + mockGit.clone = vi.fn().mockResolvedValue(undefined); + mockGit.deleteRemote = vi.fn().mockResolvedValue(undefined); + mockGit.addRemote = vi.fn().mockResolvedValue(undefined); + + // Mock nip19 decode + vi.mocked(nip19.decode).mockReturnValue({ + type: 'npub', + data: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab' + }); + + // Mock Nostr query to return a repository event + const mockRelay = { + query: vi.fn().mockResolvedValue([{ + id: 'event123', + pubkey: 'abcd1234567890abcdef1234567890abcdef1234567890abcdef1234567890ab', + kind: 30617, + content: '', + tags: [ + ['d', 'my-repo'], + ['clone', 'https://github.com/user/repo.git'], + ['clone', 'https://gitlab.com/user/repo.git'] + ], + created_at: Date.now(), + sig: 'signature' + }]) + }; + + nostr.group = vi.fn().mockReturnValue(mockRelay); + nostr.relay = vi.fn().mockReturnValue(mockRelay); + }); + + it('successfully clones from Nostr URI and updates origin remote', async () => { + const nostrUrl = 'nostr://npub1abc123/my-repo'; + + await gitInstance.clone({ + dir: '/test', + url: nostrUrl, + }); + + // Should attempt to clone from the first URL + expect(mockGit.clone).toHaveBeenCalledWith({ + fs, + http: expect.any(Object), + corsProxy: 'https://cors.example.com', + dir: '/test', + url: 'https://github.com/user/repo.git', + }); + + // Should delete the existing origin remote + expect(mockGit.deleteRemote).toHaveBeenCalledWith({ + fs, + dir: '/test', + remote: 'origin', + }); + + // Should add the Nostr URI as the new origin + expect(mockGit.addRemote).toHaveBeenCalledWith({ + fs, + dir: '/test', + remote: 'origin', + url: nostrUrl, + }); + }); + }); + + describe('setRemoteURL', () => { + beforeEach(() => { + mockGit.deleteRemote = vi.fn().mockResolvedValue(undefined); + mockGit.addRemote = vi.fn().mockResolvedValue(undefined); + }); + + it('updates remote URL by deleting and re-adding remote', async () => { + await gitInstance.setRemoteURL({ + dir: '/test', + remote: 'origin', + url: 'https://new-repo.com/user/repo.git', + }); + + expect(mockGit.deleteRemote).toHaveBeenCalledWith({ + fs, + dir: '/test', + remote: 'origin', + }); + + expect(mockGit.addRemote).toHaveBeenCalledWith({ + fs, + dir: '/test', + remote: 'origin', + url: 'https://new-repo.com/user/repo.git', + }); + }); + + it('works with any remote name', async () => { + await gitInstance.setRemoteURL({ + dir: '/test', + remote: 'upstream', + url: 'nostr://npub1abc123/my-repo', + }); + + expect(mockGit.deleteRemote).toHaveBeenCalledWith({ + fs, + dir: '/test', + remote: 'upstream', + }); + + expect(mockGit.addRemote).toHaveBeenCalledWith({ + fs, + dir: '/test', + remote: 'upstream', + url: 'nostr://npub1abc123/my-repo', + }); + }); + }); }); \ No newline at end of file diff --git a/src/lib/git.ts b/src/lib/git.ts index ae8debfb..ea9cb139 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -646,6 +646,13 @@ export class Git { ) ]); + // After successful clone, update the origin remote to point to the Nostr URI + await this.setRemoteURL({ + dir: originalOptions.dir, + remote: 'origin', + url: originalOptions.url, + }); + return; // Success! } catch (error) { console.warn(`Failed to clone from ${cloneUrl}:`, error); @@ -657,4 +664,21 @@ export class Git { // If we get here, all clone attempts failed throw lastError || new Error('All clone attempts failed'); } + + async setRemoteURL(options: { dir: string; remote: string; url: string }): Promise { + // Remove the existing remote + await git.deleteRemote({ + fs: this.fs, + dir: options.dir, + remote: options.remote, + }); + + // Add the remote with the new URL + await git.addRemote({ + fs: this.fs, + dir: options.dir, + remote: options.remote, + url: options.url, + }); + } } \ No newline at end of file From f06c7dbe7099848f9cb5a0e4fba9b7199a2ff295 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 15:41:25 -0500 Subject: [PATCH 06/95] Remove Moonshot AI due to no CORS support --- src/pages/AISettings.tsx | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/pages/AISettings.tsx b/src/pages/AISettings.tsx index 8f453325..b9fd172c 100644 --- a/src/pages/AISettings.tsx +++ b/src/pages/AISettings.tsx @@ -73,12 +73,6 @@ const PRESET_PROVIDERS: PresetProvider[] = [ baseURL: "https://api.z.ai/api/paas/v4", apiKeysURL: "https://z.ai/manage-apikey/apikey-list", }, - { - id: "moonshot", - name: "Moonshot", - baseURL: "https://api.moonshot.ai/v1", - apiKeysURL: "https://platform.moonshot.ai/console/api-keys", - }, { id: "openai", name: "OpenAI", From 72a537ce2ec8324752ab6454098725673fcf5143 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 16:46:07 -0500 Subject: [PATCH 07/95] Refactor nostr git clone, add "nostr.repo" git config --- src/lib/commands/git/config.ts | 1 - src/lib/git.test.ts | 1 + src/lib/git.ts | 85 +++++++++++++++++++++------------- 3 files changed, 55 insertions(+), 32 deletions(-) diff --git a/src/lib/commands/git/config.ts b/src/lib/commands/git/config.ts index eb681f1c..9667cbc3 100644 --- a/src/lib/commands/git/config.ts +++ b/src/lib/commands/git/config.ts @@ -138,7 +138,6 @@ export class GitConfigCommand implements GitSubcommand { private async setConfig(key: string, value: string, global: boolean): Promise { try { await this.git.setConfig({ - dir: global ? undefined : this.pwd, path: key, value: value, diff --git a/src/lib/git.test.ts b/src/lib/git.test.ts index 8c8fe4cf..9720d919 100644 --- a/src/lib/git.test.ts +++ b/src/lib/git.test.ts @@ -11,6 +11,7 @@ vi.mock('isomorphic-git/http/web'); vi.mock('nostr-tools', () => ({ nip19: { decode: vi.fn(), + naddrEncode: vi.fn(), }, })); vi.mock('@nostrify/nostrify', () => ({ diff --git a/src/lib/git.ts b/src/lib/git.ts index ea9cb139..4cf948ee 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -2,7 +2,7 @@ import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; import { NIP05 } from '@nostrify/nostrify'; import { nip19 } from 'nostr-tools'; -import type { NPool } from '@nostrify/nostrify'; +import type { NostrEvent, NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; export interface GitOptions { @@ -45,16 +45,12 @@ export class Git { async clone(options: Omit[0], 'fs' | 'http' | 'corsProxy'>) { // Check if the URL is a Nostr URI if (options.url.startsWith('nostr://')) { - const nostrUri = await this.parseNostrCloneURI(options.url); - if (!nostrUri) { + const nostrURI = await this.parseNostrCloneURI(options.url); + if (!nostrURI) { throw new Error('Invalid Nostr clone URI format'); } - - // Fetch clone URLs from Nostr - const cloneUrls = await this.fetchNostrRepository(nostrUri); - - // Try cloning from each URL in order - return this.tryCloneUrls(cloneUrls, options); + // Try cloning from Nostr + return this.nostrClone(nostrURI, options); } // Regular Git URL @@ -585,12 +581,13 @@ export class Git { } } - private async fetchNostrRepository(nostrURI: NostrCloneURI): Promise { - const signal = AbortSignal.timeout(10000); // 10 second timeout - + private async fetchNostrRepo( + nostrURI: NostrCloneURI, + signal?: AbortSignal, + ): Promise<{ repo?: NostrEvent; state?: NostrEvent }> { // Build the filter for the NIP-34 repository announcement const filter = { - kinds: [30617], + kinds: [30617, 30618], authors: [nostrURI.pubkey], '#d': [nostrURI.d], limit: 1, @@ -599,7 +596,11 @@ export class Git { // Use a specific relay if provided const client = nostrURI.relay ? this.nostr.relay(nostrURI.relay) - : this.nostr.group(['wss://relay.ngit.dev/', 'wss://gitnostr.com/']); + : this.nostr.group([ + 'wss://git.shakespeare.diy/', + 'wss://relay.ngit.dev/', + 'wss://gitnostr.com/', + ]); // Query for the repository announcement event const events = await client.query([filter], { signal }); @@ -608,24 +609,35 @@ export class Git { throw new Error('Repository not found on Nostr network'); } - const repoEvent = events[0]; + const repo = events.find((e) => e.kind === 30617); + const state = events.find((e) => e.kind === 30618); - // Extract clone URLs from the event tags - const cloneUrls: string[] = []; - for (const tag of repoEvent.tags) { - if (tag[0] === 'clone' && tag[1]) { - cloneUrls.push(tag[1]); + return { repo, state }; + } + + private async nostrClone(nostrURI: NostrCloneURI, options: Omit[0], 'fs' | 'http' | 'corsProxy'>): Promise { + // Fetch events from Nostr + const { repo } = await this.fetchNostrRepo(nostrURI); + + if (!repo) { + throw new Error('Repository not found'); + } + + // Collect valid clone URLs from the repo event tags + const cloneUrls = new Set(); + for (const [name, value] of repo.tags) { + if (name === 'clone') { + try { + const url = new URL(value); + if (url.protocol === 'http:' || url.protocol === 'https:') { + cloneUrls.add(url.href); + } + } catch { + // Ignore invalid URLs + } } } - if (cloneUrls.length === 0) { - throw new Error('No clone URLs found in repository announcement'); - } - - return cloneUrls; - } - - private async tryCloneUrls(cloneUrls: string[], originalOptions: Omit[0], 'fs' | 'http' | 'corsProxy'>): Promise { let lastError: Error | null = null; for (const cloneUrl of cloneUrls) { @@ -638,7 +650,7 @@ export class Git { fs: this.fs, http, corsProxy: this.corsProxy, - ...originalOptions, + ...options, url: cloneUrl, // Override the URL with the actual Git URL }), new Promise((_, reject) => @@ -648,9 +660,20 @@ export class Git { // After successful clone, update the origin remote to point to the Nostr URI await this.setRemoteURL({ - dir: originalOptions.dir, remote: 'origin', - url: originalOptions.url, + dir: options.dir, + url: options.url, + }); + + // Set the nostr.repo config to the naddr + await this.setConfig({ + dir: options.dir, + path: 'nostr.repo', + value: nip19.naddrEncode({ + kind: 30617, + pubkey: nostrURI.pubkey, + identifier: nostrURI.d, + }) }); return; // Success! From 93983f88af9dac1d4f245c55cecc936d5686051e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 17:03:20 -0500 Subject: [PATCH 08/95] Clone with the state commit from Nostr --- src/lib/git.ts | 344 +++++++++++++++++++++++++++++++++++++++++-------- 1 file changed, 292 insertions(+), 52 deletions(-) diff --git a/src/lib/git.ts b/src/lib/git.ts index 4cf948ee..a7f7b5d8 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -523,6 +523,108 @@ export class Git { } // Nostr-specific helper methods + + /** + * Extract repository state information from a NIP-34 repository state event + */ + private extractRepositoryState(stateEvent: NostrEvent): { + HEAD?: string; + headCommit?: string; + headBranch?: string; + refs: Record; + } { + const refs: Record = {}; + let HEAD: string | undefined; + let headCommit: string | undefined; + let headBranch: string | undefined; + + for (const [name, value] of stateEvent.tags) { + if (name === 'HEAD' && value) { + HEAD = value; + + // Parse HEAD reference to extract branch name + if (value.startsWith('ref: refs/heads/')) { + headBranch = value.slice(16); // Remove "ref: refs/heads/" prefix + } + } else if (name.startsWith('refs/') && value) { + refs[name] = value; + + // If this ref matches the HEAD, store the commit + if (HEAD === `ref: ${name}`) { + headCommit = value; + } + } + } + + return { HEAD, headCommit, headBranch, refs }; + } + + /** + * Validate that a cloned repository matches the expected repository state + */ + private async validateRepositoryState( + dir: string, + expectedCommit?: string, + expectedBranch?: string, + expectedRefs?: Record + ): Promise<{ valid: boolean; warnings: string[] }> { + const warnings: string[] = []; + let valid = true; + + try { + // Check if expected commit exists + if (expectedCommit) { + try { + await git.readCommit({ + fs: this.fs, + dir, + oid: expectedCommit, + }); + console.log(`✓ Expected commit ${expectedCommit} found in repository`); + } catch { + warnings.push(`Expected commit ${expectedCommit} not found in cloned repository`); + valid = false; + } + } + + // Check if expected branch exists and is current + if (expectedBranch) { + try { + const currentBranch = await git.currentBranch({ fs: this.fs, dir }); + if (currentBranch !== expectedBranch) { + warnings.push(`Expected branch '${expectedBranch}' but currently on '${currentBranch || 'detached HEAD'}'`); + } else { + console.log(`✓ On expected branch: ${expectedBranch}`); + } + } catch (error) { + warnings.push(`Could not determine current branch: ${error}`); + } + } + + // Validate key refs if provided + if (expectedRefs && Object.keys(expectedRefs).length > 0) { + try { + const localRefs = await git.listRefs({ fs: this.fs, dir }); + const missingRefs = Object.keys(expectedRefs).filter(ref => !localRefs.includes(ref)); + + if (missingRefs.length > 0) { + warnings.push(`Missing expected refs: ${missingRefs.join(', ')}`); + } else { + console.log(`✓ All expected refs found in repository`); + } + } catch (error) { + warnings.push(`Could not validate refs: ${error}`); + } + } + + } catch (error) { + warnings.push(`Repository validation failed: ${error}`); + valid = false; + } + + return { valid, warnings }; + } + private async parseNostrCloneURI(uri: string): Promise { try { if (!uri.startsWith('nostr://')) { @@ -585,44 +687,75 @@ export class Git { nostrURI: NostrCloneURI, signal?: AbortSignal, ): Promise<{ repo?: NostrEvent; state?: NostrEvent }> { - // Build the filter for the NIP-34 repository announcement + // Build the filter for both NIP-34 repository announcement and state events const filter = { kinds: [30617, 30618], authors: [nostrURI.pubkey], '#d': [nostrURI.d], - limit: 1, + limit: 2, // We want both repo and state events if they exist }; - // Use a specific relay if provided + // Use a specific relay if provided, otherwise try git-focused relays const client = nostrURI.relay ? this.nostr.relay(nostrURI.relay) : this.nostr.group([ 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/', 'wss://gitnostr.com/', + 'wss://relay.nostr.band/', // Fallback to general relay ]); - // Query for the repository announcement event - const events = await client.query([filter], { signal }); + try { + // Query for both repository announcement and state events + const events = await client.query([filter], { + signal: signal || AbortSignal.timeout(5000) + }); - if (events.length === 0) { - throw new Error('Repository not found on Nostr network'); + const repo = events.find((e) => e.kind === 30617); + const state = events.find((e) => e.kind === 30618); + + if (!repo) { + throw new Error('Repository announcement not found on Nostr network'); + } + + if (state) { + console.log(`Found repository state event with ${state.tags.length} tags`); + } else { + console.log('No repository state event found, proceeding with basic clone'); + } + + return { repo, state }; + } catch (error) { + if (error instanceof Error) { + throw new Error(`Failed to fetch repository from Nostr: ${error.message}`); + } + throw new Error('Failed to fetch repository from Nostr network'); } - - const repo = events.find((e) => e.kind === 30617); - const state = events.find((e) => e.kind === 30618); - - return { repo, state }; } private async nostrClone(nostrURI: NostrCloneURI, options: Omit[0], 'fs' | 'http' | 'corsProxy'>): Promise { // Fetch events from Nostr - const { repo } = await this.fetchNostrRepo(nostrURI); + const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); if (!repo) { throw new Error('Repository not found'); } + // Extract repository state information if available + let expectedCommit: string | undefined; + let expectedBranch: string | undefined; + let repositoryRefs: Record = {}; + + if (state) { + const stateInfo = this.extractRepositoryState(state); + expectedCommit = stateInfo.headCommit; + expectedBranch = stateInfo.headBranch; + repositoryRefs = stateInfo.refs; + + console.log(`Repository state: HEAD=${stateInfo.HEAD}, commit=${expectedCommit}, branch=${expectedBranch}`); + console.log(`Available refs:`, Object.keys(repositoryRefs)); + } + // Collect valid clone URLs from the repo event tags const cloneUrls = new Set(); for (const [name, value] of repo.tags) { @@ -638,54 +771,161 @@ export class Git { } } + if (cloneUrls.size === 0) { + throw new Error('No valid clone URLs found in repository announcement'); + } + let lastError: Error | null = null; + let cloneSuccessful = false; - for (const cloneUrl of cloneUrls) { - try { - console.log(`Attempting to clone from: ${cloneUrl}`); + // If we have state information, try to find a clone URL that contains the expected commit + if (expectedCommit) { + console.log(`Looking for repository with commit: ${expectedCommit}`); - // Try cloning with a timeout - await Promise.race([ - git.clone({ - fs: this.fs, - http, - corsProxy: this.corsProxy, - ...options, - url: cloneUrl, // Override the URL with the actual Git URL - }), - new Promise((_, reject) => - setTimeout(() => reject(new Error('Clone timeout')), 30000) - ) - ]); + for (const cloneUrl of cloneUrls) { + try { + console.log(`Checking remote info for: ${cloneUrl}`); - // After successful clone, update the origin remote to point to the Nostr URI - await this.setRemoteURL({ - remote: 'origin', - dir: options.dir, - url: options.url, - }); + // Get remote repository information to check if it has the expected commit + const remoteInfo = await Promise.race([ + git.getRemoteInfo({ + http, + corsProxy: this.corsProxy, + url: cloneUrl, + }), + new Promise((_, reject) => + setTimeout(() => reject(new Error('Remote info timeout')), 10000) + ) + ]); - // Set the nostr.repo config to the naddr - await this.setConfig({ - dir: options.dir, - path: 'nostr.repo', - value: nip19.naddrEncode({ - kind: 30617, - pubkey: nostrURI.pubkey, - identifier: nostrURI.d, - }) - }); + // Check if the expected commit exists in any of the remote refs + const hasExpectedCommit = Object.values(remoteInfo.refs).includes(expectedCommit); - return; // Success! - } catch (error) { - console.warn(`Failed to clone from ${cloneUrl}:`, error); - lastError = error instanceof Error ? error : new Error('Unknown error'); - continue; // Try the next URL + if (hasExpectedCommit) { + console.log(`Found expected commit ${expectedCommit} in ${cloneUrl}`); + + // Clone from this URL since it has the expected commit + await Promise.race([ + git.clone({ + fs: this.fs, + http, + corsProxy: this.corsProxy, + ...options, + url: cloneUrl, + }), + new Promise((_, reject) => + setTimeout(() => reject(new Error('Clone timeout')), 30000) + ) + ]); + + // Verify the cloned repository has the expected commit + try { + await git.readCommit({ + fs: this.fs, + dir: options.dir, + oid: expectedCommit, + }); + + // If we have an expected branch, check out to it + if (expectedBranch) { + try { + await git.checkout({ + fs: this.fs, + dir: options.dir, + ref: expectedBranch, + }); + } catch (checkoutError) { + console.warn(`Failed to checkout branch ${expectedBranch}:`, checkoutError); + // Continue anyway, the clone was successful + } + } + + cloneSuccessful = true; + break; + } catch (commitError) { + console.warn(`Cloned repository doesn't contain expected commit ${expectedCommit}:`, commitError); + // Continue to try other URLs + } + } + } catch (error) { + console.warn(`Failed to check/clone from ${cloneUrl}:`, error); + lastError = error instanceof Error ? error : new Error('Unknown error'); + continue; + } } } - // If we get here, all clone attempts failed - throw lastError || new Error('All clone attempts failed'); + // If we couldn't find the specific commit or don't have state info, try regular cloning + if (!cloneSuccessful) { + console.log('Falling back to regular clone from available URLs'); + + for (const cloneUrl of cloneUrls) { + try { + console.log(`Attempting to clone from: ${cloneUrl}`); + + await Promise.race([ + git.clone({ + fs: this.fs, + http, + corsProxy: this.corsProxy, + ...options, + url: cloneUrl, + }), + new Promise((_, reject) => + setTimeout(() => reject(new Error('Clone timeout')), 30000) + ) + ]); + + cloneSuccessful = true; + break; + } catch (error) { + console.warn(`Failed to clone from ${cloneUrl}:`, error); + lastError = error instanceof Error ? error : new Error('Unknown error'); + continue; + } + } + } + + if (!cloneSuccessful) { + throw lastError || new Error('All clone attempts failed'); + } + + // After successful clone, update the origin remote to point to the Nostr URI + await this.setRemoteURL({ + remote: 'origin', + dir: options.dir, + url: options.url, + }); + + // Set the nostr.repo config to the naddr + await this.setConfig({ + dir: options.dir, + path: 'nostr.repo', + value: nip19.naddrEncode({ + kind: 30617, + pubkey: nostrURI.pubkey, + identifier: nostrURI.d, + }) + }); + + // Validate the cloned repository against the expected state + if (state && cloneSuccessful) { + const validation = await this.validateRepositoryState( + options.dir, + expectedCommit, + expectedBranch, + repositoryRefs + ); + + if (validation.valid) { + console.log('✓ Repository successfully cloned and validated against Nostr state'); + } else { + console.warn('⚠ Repository cloned but validation warnings:'); + validation.warnings.forEach(warning => console.warn(` - ${warning}`)); + } + } else if (cloneSuccessful) { + console.log('✓ Repository cloned successfully (no state validation available)'); + } } async setRemoteURL(options: { dir: string; remote: string; url: string }): Promise { From bc907fdd63468337714bb4cf15bac5dc429b5cbf Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 17:27:12 -0500 Subject: [PATCH 09/95] Implement nostr fetch, pull --- src/lib/git.ts | 378 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 378 insertions(+) diff --git a/src/lib/git.ts b/src/lib/git.ts index a7f7b5d8..74b7c20d 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -180,6 +180,16 @@ export class Git { } async fetch(options: Omit[0], 'fs' | 'http' | 'corsProxy'>) { + // Check if this is a Nostr repository by looking at the remote URL + const remote = options.remote || 'origin'; + const dir = options.dir || '.'; + const remoteUrl = await this.getRemoteURL(dir, remote); + + if (remoteUrl && remoteUrl.startsWith('nostr://')) { + return this.nostrFetch(remoteUrl, { ...options, remote, dir }); + } + + // Regular Git fetch return git.fetch({ fs: this.fs, http, @@ -189,6 +199,16 @@ export class Git { } async pull(options: Omit[0], 'fs' | 'http' | 'corsProxy'>) { + // Check if this is a Nostr repository by looking at the remote URL + const remote = options.remote || 'origin'; + const dir = options.dir || '.'; + const remoteUrl = await this.getRemoteURL(dir, remote); + + if (remoteUrl && remoteUrl.startsWith('nostr://')) { + return this.nostrPull(remoteUrl, { ...options, remote, dir }); + } + + // Regular Git pull return git.pull({ fs: this.fs, http, @@ -944,4 +964,362 @@ export class Git { url: options.url, }); } + + async getRemoteURL(dir: string, remote: string): Promise { + try { + const remotes = await git.listRemotes({ fs: this.fs, dir }); + const remoteInfo = remotes.find(r => r.remote === remote); + return remoteInfo?.url || null; + } catch { + return null; + } + } + + private async nostrFetch(nostrUrl: string, options: Omit[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise<{ fetchHead?: string; fetchHeadDescription?: string }> { + // Parse the Nostr URI + const nostrURI = await this.parseNostrCloneURI(nostrUrl); + if (!nostrURI) { + throw new Error('Invalid Nostr URI format'); + } + + console.log(`Fetching updates from Nostr repository: ${nostrUrl}`); + + // Fetch the latest repository state from Nostr + const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + + if (!repo) { + throw new Error('Repository not found on Nostr network'); + } + + // If we have a state event, update our refs to match + if (state) { + const stateInfo = this.extractRepositoryState(state); + console.log(`Updating repository state from Nostr: HEAD=${stateInfo.HEAD}, refs=${Object.keys(stateInfo.refs).length}`); + + // Update local refs to match the Nostr state + const updatedRefs: string[] = []; + for (const [refName, commitId] of Object.entries(stateInfo.refs)) { + try { + // Check if we have this commit locally + try { + await git.readCommit({ + fs: this.fs, + dir: options.dir, + oid: commitId, + }); + + // We have the commit, update the ref + await git.writeRef({ + fs: this.fs, + dir: options.dir, + ref: refName, + value: commitId, + }); + + updatedRefs.push(refName); + console.log(`✓ Updated ${refName} to ${commitId}`); + } catch { + // We don't have this commit, need to fetch from the actual Git remote + console.log(`⚠ Commit ${commitId} for ${refName} not found locally, need to fetch from Git remote`); + } + } catch (error) { + console.warn(`Failed to update ref ${refName}:`, error); + } + } + + // If we updated refs but some commits are missing, try to fetch from Git remotes + if (updatedRefs.length < Object.keys(stateInfo.refs).length) { + await this.fetchMissingCommitsFromGitRemotes(repo, options.dir, stateInfo.refs); + } + + // Update HEAD if specified + if (stateInfo.HEAD) { + try { + await git.writeRef({ + fs: this.fs, + dir: options.dir, + ref: 'HEAD', + value: stateInfo.HEAD, + symbolic: true, + }); + console.log(`✓ Updated HEAD to ${stateInfo.HEAD}`); + } catch (error) { + console.warn(`Failed to update HEAD:`, error); + } + } + + return { + fetchHead: stateInfo.headCommit, + fetchHeadDescription: `Fetched from Nostr repository state (${updatedRefs.length} refs updated)`, + }; + } else { + console.log('No repository state found on Nostr, checking for updates from Git remotes'); + + // No state event, try to fetch from the Git clone URLs + return this.fetchFromGitRemotes(repo, options.dir); + } + } + + private async nostrPull(nostrUrl: string, options: Omit[0], 'fs' | 'http' | 'corsProxy'> & { remote: string; dir: string }): Promise { + // First, fetch the latest state + const fetchResult = await this.nostrFetch(nostrUrl, options); + + // Get the current branch + const currentBranch = await git.currentBranch({ fs: this.fs, dir: options.dir }); + + if (!currentBranch) { + throw new Error('Cannot pull: not on any branch (detached HEAD)'); + } + + // Check if we can fast-forward + const currentCommit = await git.resolveRef({ + fs: this.fs, + dir: options.dir, + ref: 'HEAD', + }); + + const upstreamRef = `refs/remotes/${options.remote}/${currentBranch}`; + let upstreamCommit: string; + + try { + upstreamCommit = await git.resolveRef({ + fs: this.fs, + dir: options.dir, + ref: upstreamRef, + }); + } catch { + // No upstream tracking branch, use fetchHead if available + if (fetchResult.fetchHead) { + upstreamCommit = fetchResult.fetchHead; + } else { + throw new Error(`No upstream branch found for ${currentBranch}`); + } + } + + // Check if we're already up to date + if (currentCommit === upstreamCommit) { + console.log('Already up to date'); + return; + } + + // Check if we can fast-forward (current commit should be ancestor of upstream) + const canFastForward = await git.isDescendent({ + fs: this.fs, + dir: options.dir, + oid: upstreamCommit, + ancestor: currentCommit, + }).catch(() => false); + + if (canFastForward) { + // Fast-forward merge by updating the branch ref + await git.writeRef({ + fs: this.fs, + dir: options.dir, + ref: `refs/heads/${currentBranch}`, + value: upstreamCommit, + }); + + // Update the working directory + await git.checkout({ + fs: this.fs, + dir: options.dir, + ref: currentBranch, + force: true, + }); + + console.log(`Fast-forwarded ${currentBranch} to ${upstreamCommit}`); + } else { + // Need to merge + const mergeResult = await git.merge({ + fs: this.fs, + dir: options.dir, + ours: currentCommit, + theirs: upstreamCommit, + message: `Merge remote-tracking branch '${options.remote}/${currentBranch}' from Nostr`, + }); + + if (mergeResult.alreadyMerged) { + console.log('Already up to date'); + } else { + console.log(`Merged ${upstreamCommit} into ${currentBranch}`); + } + } + } + + private async fetchMissingCommitsFromGitRemotes(repo: NostrEvent, dir: string, refs: Record): Promise { + // Get clone URLs from the repository announcement + const cloneUrls = new Set(); + for (const [name, value] of repo.tags) { + if (name === 'clone') { + try { + const url = new URL(value); + if (url.protocol === 'http:' || url.protocol === 'https:') { + cloneUrls.add(url.href); + } + } catch { + // Ignore invalid URLs + } + } + } + + if (cloneUrls.size === 0) { + console.warn('No Git clone URLs available to fetch missing commits'); + return; + } + + // Try to fetch missing commits from each Git remote + for (const cloneUrl of cloneUrls) { + try { + console.log(`Fetching missing commits from: ${cloneUrl}`); + + // Add a temporary remote + const tempRemoteName = `temp-${Date.now()}`; + await git.addRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + url: cloneUrl, + }); + + try { + // Fetch from the temporary remote + await git.fetch({ + fs: this.fs, + http, + corsProxy: this.corsProxy, + dir, + remote: tempRemoteName, + }); + + // Update our refs to match the Nostr state + for (const [refName, commitId] of Object.entries(refs)) { + try { + // Check if we now have this commit + await git.readCommit({ + fs: this.fs, + dir, + oid: commitId, + }); + + // Update the ref + await git.writeRef({ + fs: this.fs, + dir, + ref: refName, + value: commitId, + }); + + console.log(`✓ Updated ${refName} to ${commitId} after fetching`); + } catch { + // Still don't have this commit + console.warn(`Still missing commit ${commitId} for ${refName}`); + } + } + + // Remove the temporary remote + await git.deleteRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + }); + + // Successfully fetched from this remote + return; + } catch (fetchError) { + console.warn(`Failed to fetch from ${cloneUrl}:`, fetchError); + + // Clean up the temporary remote + try { + await git.deleteRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + }); + } catch { + // Ignore cleanup errors + } + } + } catch (error) { + console.warn(`Failed to set up temporary remote for ${cloneUrl}:`, error); + } + } + } + + private async fetchFromGitRemotes(repo: NostrEvent, dir: string): Promise<{ fetchHead?: string; fetchHeadDescription?: string }> { + // Get clone URLs from the repository announcement + const cloneUrls = new Set(); + for (const [name, value] of repo.tags) { + if (name === 'clone') { + try { + const url = new URL(value); + if (url.protocol === 'http:' || url.protocol === 'https:') { + cloneUrls.add(url.href); + } + } catch { + // Ignore invalid URLs + } + } + } + + if (cloneUrls.size === 0) { + throw new Error('No Git clone URLs available for fetching'); + } + + // Try to fetch from each Git remote + let lastError: Error | null = null; + for (const cloneUrl of cloneUrls) { + try { + console.log(`Fetching from Git remote: ${cloneUrl}`); + + // Add a temporary remote + const tempRemoteName = `temp-${Date.now()}`; + await git.addRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + url: cloneUrl, + }); + + try { + // Fetch from the temporary remote + const fetchResult = await git.fetch({ + fs: this.fs, + http, + corsProxy: this.corsProxy, + dir, + remote: tempRemoteName, + }); + + // Remove the temporary remote + await git.deleteRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + }); + + return { + fetchHead: fetchResult.fetchHead || undefined, + fetchHeadDescription: `Fetched from Git remote: ${cloneUrl}`, + }; + } catch (fetchError) { + // Clean up the temporary remote + try { + await git.deleteRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + }); + } catch { + // Ignore cleanup errors + } + throw fetchError; + } + } catch (error) { + console.warn(`Failed to fetch from ${cloneUrl}:`, error); + lastError = error instanceof Error ? error : new Error('Unknown error'); + } + } + + throw lastError || new Error('All fetch attempts failed'); + } } \ No newline at end of file From 154b9330d4064ea39133f1c73bdcf180b3bb13da Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 17:42:08 -0500 Subject: [PATCH 10/95] Simplify git onAuth calls --- src/components/GitDialog.tsx | 29 ++--------------------------- src/lib/commands/git/push.ts | 11 +---------- src/lib/gitCredentials.test.ts | 12 ++++++------ src/lib/gitCredentials.ts | 6 ++---- 4 files changed, 11 insertions(+), 47 deletions(-) diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 9397e1a3..d1be2ddb 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -63,15 +63,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const projectPath = `/projects/${projectId}`; - // Get credentials for the current repository - const getCredentialsForCurrentRepo = () => { - if (!gitStatus?.remotes.length) return null; - const remoteUrl = gitStatus.remotes[0].url; // Use first remote (usually 'origin') - return findCredentialsForRepo(remoteUrl, settings.credentials); - }; - - const currentCredentials = getCredentialsForCurrentRepo(); - const handlePush = async () => { if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { toast({ @@ -106,19 +97,11 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') - // Prepare authentication if credentials are available - const authOptions = currentCredentials ? { - onAuth: () => ({ - username: currentCredentials.username, - password: currentCredentials.password - }), - } : {}; - await git.push({ dir: projectPath, remote: remote.name, ref: gitStatus.currentBranch, - ...authOptions, + onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`); @@ -167,14 +150,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') - // Prepare authentication if credentials are available - const authOptions = currentCredentials ? { - onAuth: () => ({ - username: currentCredentials.username, - password: currentCredentials.password - }), - } : {}; - await git.pull({ dir: projectPath, ref: gitStatus.currentBranch, @@ -183,7 +158,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog name: 'shakespeare.diy', email: 'assistant@shakespeare.diy', }, - ...authOptions, + onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`); diff --git a/src/lib/commands/git/push.ts b/src/lib/commands/git/push.ts index 95351115..e21502a5 100644 --- a/src/lib/commands/git/push.ts +++ b/src/lib/commands/git/push.ts @@ -65,15 +65,6 @@ export class GitPushCommand implements GitSubcommand { } const settings = await readGitSettings(this.fs); - const currentCredentials = findCredentialsForRepo(remoteUrl, settings.credentials); - - // Prepare authentication if credentials are available - const authOptions = currentCredentials ? { - onAuth: () => ({ - username: currentCredentials.username, - password: currentCredentials.password, - }), - } : {}; try { await this.git.push({ @@ -81,7 +72,7 @@ export class GitPushCommand implements GitSubcommand { remote: remote, ref: targetBranch, remoteRef: targetBranch, - ...authOptions, + onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); return createSuccessResult(`To ${remoteUrl}\n ${targetBranch} -> ${targetBranch}\n`); diff --git a/src/lib/gitCredentials.test.ts b/src/lib/gitCredentials.test.ts index fe2838dd..790edcb3 100644 --- a/src/lib/gitCredentials.test.ts +++ b/src/lib/gitCredentials.test.ts @@ -64,17 +64,17 @@ describe('gitCredentials', () => { .toEqual({ username: 'git', password: 'github-token' }); }); - it('should return null when no credentials found', () => { + it('should return undefined when no credentials found', () => { expect(findCredentialsForRepo('https://unknown.com/user/repo.git', mockCredentials)) - .toBe(null); - + .toBe(undefined); + expect(findCredentialsForRepo('invalid-url', mockCredentials)) - .toBe(null); + .toBe(undefined); }); - it('should return null for empty credentials', () => { + it('should return undefined for empty credentials', () => { expect(findCredentialsForRepo('https://github.com/user/repo.git', {})) - .toBe(null); + .toBe(undefined); }); }); diff --git a/src/lib/gitCredentials.ts b/src/lib/gitCredentials.ts index ed90ed80..45942d8d 100644 --- a/src/lib/gitCredentials.ts +++ b/src/lib/gitCredentials.ts @@ -31,9 +31,9 @@ export function extractGitOrigin(gitUrl: string): string | null { export function findCredentialsForRepo( repoUrl: string, credentials: Record -): GitCredential | null { +): GitCredential | undefined { const repoOrigin = extractGitOrigin(repoUrl); - if (!repoOrigin) return null; + if (!repoOrigin) return; // Direct match if (credentials[repoOrigin]) { @@ -57,8 +57,6 @@ export function findCredentialsForRepo( return credential; } } - - return null; } /** From 9678041502749b2c91e96b10db065007ab7e7b36 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 17:55:14 -0500 Subject: [PATCH 11/95] git push over Nostr --- src/lib/git.ts | 231 ++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 229 insertions(+), 2 deletions(-) diff --git a/src/lib/git.ts b/src/lib/git.ts index 74b7c20d..89905c5b 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -2,7 +2,7 @@ import git from 'isomorphic-git'; import http from 'isomorphic-git/http/web'; import { NIP05 } from '@nostrify/nostrify'; import { nip19 } from 'nostr-tools'; -import type { NostrEvent, NPool } from '@nostrify/nostrify'; +import type { NostrEvent, NostrSigner, NPool } from '@nostrify/nostrify'; import type { JSRuntimeFS } from './JSRuntime'; export interface GitOptions { @@ -217,7 +217,19 @@ export class Git { }); } - async push(options: Omit[0], 'fs' | 'http' | 'corsProxy'>) { + async push(options: Omit[0], 'fs' | 'http' | 'corsProxy'> & { signer?: NostrSigner }) { + // Check if this is a Nostr repository by looking at the remote URL + const remote = options.remote || 'origin'; + const dir = options.dir || '.'; + const remoteUrl = await this.getRemoteURL(dir, remote); + + if (remoteUrl && remoteUrl.startsWith('nostr://')) { + if (!options.signer) { + throw new Error('Nostr signer is required for pushing to Nostr repositories'); + } + return this.nostrPush(remoteUrl, { ...options, remote, dir: dir, signer: options.signer }); + } + return git.push({ fs: this.fs, http, @@ -544,6 +556,71 @@ export class Git { // Nostr-specific helper methods + /** + * Get current repository state for creating a NIP-34 repository state event + */ + private async getCurrentRepositoryState(dir: string): Promise<{ + refTags: string[][]; + headRef?: string; + }> { + const refTags: string[][] = []; + let headRef: string | undefined; + + try { + // Get all refs in the repository + const refs = await git.listRefs({ fs: this.fs, dir }); + + // Process each ref to create tags + for (const ref of refs) { + try { + const commitId = await git.resolveRef({ + fs: this.fs, + dir, + ref, + }); + + // Only include heads and tags refs in the state event + if (ref.startsWith('refs/heads/') || ref.startsWith('refs/tags/')) { + refTags.push([ref, commitId]); + } + } catch (error) { + console.warn(`Failed to resolve ref ${ref}:`, error); + } + } + + // Get HEAD reference + try { + const headValue = await git.resolveRef({ + fs: this.fs, + dir, + ref: 'HEAD', + depth: 1, // Don't resolve symbolic refs + }); + + // Check if HEAD is symbolic (points to a branch) + try { + const currentBranch = await git.currentBranch({ fs: this.fs, dir }); + if (currentBranch) { + headRef = `ref: refs/heads/${currentBranch}`; + } + } catch { + // HEAD is detached, use the commit ID directly + if (headValue) { + headRef = headValue; + } + } + } catch (error) { + console.warn('Failed to resolve HEAD:', error); + } + + console.log(`Repository state: ${refTags.length} refs, HEAD=${headRef}`); + return { refTags, headRef }; + } catch (error) { + console.error('Failed to get repository state:', error); + throw new Error(`Failed to get repository state: ${error}`); + } + } + /** * Extract repository state information from a NIP-34 repository state event */ @@ -1146,6 +1223,156 @@ export class Git { } } + private async nostrPush(nostrUrl: string, options: Omit[0], 'fs' | 'http' | 'corsProxy'> & { signer: NostrSigner }) { + const { signer, ...gitPushOptions } = options; + const dir = options.dir || '.'; + + // Parse the Nostr URI + const nostrURI = await this.parseNostrCloneURI(nostrUrl); + if (!nostrURI) { + throw new Error('Invalid Nostr URI format'); + } + + console.log(`Pushing to Nostr repository: ${nostrUrl}`); + + // Fetch the repository announcement to get relay information and clone URLs + const { repo } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + if (!repo) { + throw new Error('Repository announcement not found on Nostr network'); + } + + // Extract relay URLs from the repository announcement + const relayUrls: string[] = []; + const cloneUrls: string[] = []; + + for (const [name, value] of repo.tags) { + if (name === 'relays' && value) { + relayUrls.push(value); + } else if (name === 'clone' && value) { + try { + const url = new URL(value); + if (url.protocol === 'http:' || url.protocol === 'https:') { + cloneUrls.push(url.href); + } + } catch { + // Ignore invalid URLs + } + } + } + + // If no relays specified in announcement, use default git-focused relays + if (relayUrls.length === 0) { + relayUrls.push( + 'wss://git.shakespeare.diy/', + 'wss://relay.ngit.dev/', + 'wss://gitnostr.com/', + 'wss://relay.nostr.band/' + ); + } + + // Get current repository state + const repoState = await this.getCurrentRepositoryState(dir); + + // Create repository state event (kind 30618) + const stateEvent: Omit = { + kind: 30618, + created_at: Math.floor(Date.now() / 1000), + pubkey: '', // Will be set by signer + content: '', + tags: [ + ['d', nostrURI.d], // Repository identifier + ...repoState.refTags, + ...(repoState.headRef ? [['HEAD', repoState.headRef]] : []), + ], + }; + + // Sign the event + const signedStateEvent = await signer.signEvent(stateEvent); + + // Publish the state event to Nostr relays + console.log(`Publishing repository state to ${relayUrls.length} relays`); + + try { + await this.nostr.group(relayUrls).event(signedStateEvent); + console.log('✓ Repository state published to Nostr successfully'); + } catch (error) { + 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 + if (cloneUrls.length === 0) { + console.warn('No Git clone URLs found in repository announcement'); + return; + } + + let pushSuccessful = false; + let lastError: Error | null = null; + + for (const cloneUrl of cloneUrls) { + try { + console.log(`Pushing to Git remote: ${cloneUrl}`); + + // Add a temporary remote for this clone URL + const tempRemoteName = `temp-push-${Date.now()}`; + await git.addRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + url: cloneUrl, + }); + + try { + // Push to the temporary remote + await git.push({ + fs: this.fs, + http, + corsProxy: this.corsProxy, + dir, + remote: tempRemoteName, + ...gitPushOptions, + }); + + pushSuccessful = true; + console.log(`✓ Successfully pushed to ${cloneUrl}`); + + // Remove the temporary remote + await git.deleteRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + }); + + // If one push succeeds, we can break (unless we want to push to all remotes) + break; + } catch (pushError) { + console.warn(`Failed to push to ${cloneUrl}:`, pushError); + lastError = pushError instanceof Error ? pushError : new Error('Unknown push error'); + + // Clean up the temporary remote + try { + await git.deleteRemote({ + fs: this.fs, + dir, + remote: tempRemoteName, + }); + } catch { + // Ignore cleanup errors + } + } + } catch (error) { + console.warn(`Failed to set up remote for ${cloneUrl}:`, error); + lastError = error instanceof Error ? error : new Error('Unknown error'); + } + } + + if (!pushSuccessful) { + throw lastError || new Error('All push attempts failed'); + } + + console.log('✓ Nostr push completed successfully'); + } + private async fetchMissingCommitsFromGitRemotes(repo: NostrEvent, dir: string, refs: Record): Promise { // Get clone URLs from the repository announcement const cloneUrls = new Set(); From c0e00d40f77a2a84156ba2a71c186d2e97a4c62b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 18:03:27 -0500 Subject: [PATCH 12/95] Add getNostrRemoteInfo --- src/lib/git.ts | 101 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 101 insertions(+) diff --git a/src/lib/git.ts b/src/lib/git.ts index 89905c5b..4fb75145 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -172,6 +172,11 @@ export class Git { } async getRemoteInfo(options: Omit[0], 'http' | 'corsProxy'>) { + // Check if the URL is a Nostr URI + if (options.url.startsWith('nostr://')) { + return this.getNostrRemoteInfo(options.url); + } + return git.getRemoteInfo({ http, corsProxy: this.corsProxy, @@ -556,6 +561,102 @@ export class Git { // Nostr-specific helper methods + /** + * Get remote info for a Nostr repository URI + */ + private async getNostrRemoteInfo(nostrUrl: string): Promise<{ + capabilities: string[]; + refs: Record; + HEAD?: string; + }> { + // Parse the Nostr URI + const nostrURI = await this.parseNostrCloneURI(nostrUrl); + if (!nostrURI) { + throw new Error('Invalid Nostr URI format'); + } + + console.log(`Getting remote info for Nostr repository: ${nostrUrl}`); + + // Fetch the repository announcement and state from Nostr + const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + + if (!repo) { + throw new Error('Repository announcement not found on Nostr network'); + } + + // Extract refs from the state event if available + const refs: Record = {}; + let HEAD: string | undefined; + + if (state) { + const stateInfo = this.extractRepositoryState(state); + + // Add all refs from the state + Object.assign(refs, stateInfo.refs); + + // Set HEAD + if (stateInfo.HEAD) { + HEAD = stateInfo.HEAD; + } + } else { + // No state event, try to get info from the first available clone URL + const cloneUrls: string[] = []; + for (const [name, value] of repo.tags) { + if (name === 'clone') { + try { + const url = new URL(value); + if (url.protocol === 'http:' || url.protocol === 'https:') { + cloneUrls.push(url.href); + } + } catch { + // Ignore invalid URLs + } + } + } + + if (cloneUrls.length > 0) { + // Try to get remote info from the first clone URL + try { + const gitRemoteInfo = await git.getRemoteInfo({ + http, + corsProxy: this.corsProxy, + url: cloneUrls[0], + }); + + Object.assign(refs, gitRemoteInfo.refs); + HEAD = gitRemoteInfo.HEAD; + } catch (error) { + console.warn(`Failed to get remote info from ${cloneUrls[0]}:`, error); + // Continue with empty refs if we can't get git remote info + } + } + } + + // Nostr repositories support the same capabilities as regular Git repos + const capabilities = [ + 'multi_ack', + 'thin-pack', + 'side-band', + 'side-band-64k', + 'ofs-delta', + 'shallow', + 'deepen-since', + 'deepen-not', + 'deepen-relative', + 'no-progress', + 'include-tag', + 'multi_ack_detailed', + 'allow-tip-sha1-in-want', + 'allow-reachable-sha1-in-want', + ]; + + return { + capabilities, + refs, + HEAD, + }; + } + /** * Get current repository state for creating a NIP-34 repository state event */ From ce29d036ad702223ff8d57b1fb84b7ca00a14b8e Mon Sep 17 00:00:00 2001 From: Mary Kate Fain Date: Sun, 21 Sep 2025 18:54:53 -0500 Subject: [PATCH 13/95] Replace complex Nostr login/signup modals with simpler Soapbox/Ditto-inspired design - Created SimpleLoginDialog and SimpleSignupDialog with clean, minimal design - Simplified step-based flow similar to Soapbox/Ditto implementation - Reduced visual complexity while maintaining all functionality - Updated LoginArea and NostrSettings to use new simple modals - Updated tests to reference new components - All tests passing --- src/components/auth/LoginArea.test.tsx | 4 +- src/components/auth/LoginArea.tsx | 8 +- src/components/auth/SimpleLoginDialog.tsx | 339 +++++++++++++++++++++ src/components/auth/SimpleSignupDialog.tsx | 315 +++++++++++++++++++ src/pages/NostrSettings.tsx | 8 +- 5 files changed, 664 insertions(+), 10 deletions(-) create mode 100644 src/components/auth/SimpleLoginDialog.tsx create mode 100644 src/components/auth/SimpleSignupDialog.tsx diff --git a/src/components/auth/LoginArea.test.tsx b/src/components/auth/LoginArea.test.tsx index 62df7a0e..91e3a537 100644 --- a/src/components/auth/LoginArea.test.tsx +++ b/src/components/auth/LoginArea.test.tsx @@ -35,12 +35,12 @@ vi.mock('@/components/RelaySelector', () => ({ ) })); -vi.mock('./LoginDialog', () => ({ +vi.mock('./SimpleLoginDialog', () => ({ default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) => isOpen ?
Login Dialog
: null })); -vi.mock('./SignupDialog', () => ({ +vi.mock('./SimpleSignupDialog', () => ({ default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) => isOpen ?
Signup Dialog
: null })); diff --git a/src/components/auth/LoginArea.tsx b/src/components/auth/LoginArea.tsx index 67a10ff0..b7aacb53 100644 --- a/src/components/auth/LoginArea.tsx +++ b/src/components/auth/LoginArea.tsx @@ -12,8 +12,8 @@ import { DropdownMenuTrigger, } from '@/components/ui/dropdown-menu.tsx'; import { Avatar, AvatarFallback } from '@/components/ui/avatar.tsx'; -import LoginDialog from './LoginDialog'; -import SignupDialog from './SignupDialog'; +import SimpleLoginDialog from './SimpleLoginDialog'; +import SimpleSignupDialog from './SimpleSignupDialog'; import { useLoggedInAccounts } from '@/hooks/useLoggedInAccounts'; import { AccountSwitcher } from './AccountSwitcher'; import { cn } from '@/lib/utils'; @@ -88,14 +88,14 @@ export function LoginArea({ className }: LoginAreaProps) { )} - setLoginDialogOpen(false)} onLogin={handleLogin} onSignup={() => setSignupDialogOpen(true)} /> - setSignupDialogOpen(false)} /> diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx new file mode 100644 index 00000000..bd5bc00a --- /dev/null +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -0,0 +1,339 @@ +import React, { useState, useEffect } from 'react'; +import { Shield, Key, Cloud, AlertTriangle } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { Alert, AlertDescription } from '@/components/ui/alert'; +import { useLoginActions } from '@/hooks/useLoginActions'; +import { cn } from '@/lib/utils'; + +type Step = 'extension' | 'key-add'; + +interface SimpleLoginDialogProps { + isOpen: boolean; + onClose: () => void; + onLogin: () => void; + onSignup?: () => void; +} + +const validateNsec = (nsec: string) => { + return /^nsec1[a-zA-Z0-9]{58}$/.test(nsec); +}; + +const validateBunkerUri = (uri: string) => { + return uri.startsWith('bunker://'); +}; + +const SimpleLoginDialog: React.FC = ({ + isOpen, + onClose, + onLogin, + onSignup +}) => { + const [step, setStep] = useState('extension'); + const [isLoading, setIsLoading] = useState(false); + const [nsec, setNsec] = useState(''); + const [bunkerUri, setBunkerUri] = useState(''); + const [activeTab, setActiveTab] = useState<'nsec' | 'bunker'>('nsec'); + const [errors, setErrors] = useState<{ + nsec?: string; + bunker?: string; + extension?: string; + }>({}); + + const login = useLoginActions(); + + // Reset state when dialog opens/closes + useEffect(() => { + if (isOpen) { + setStep(window.nostr ? 'extension' : 'key-add'); + setIsLoading(false); + setNsec(''); + setBunkerUri(''); + setActiveTab('nsec'); + setErrors({}); + } + }, [isOpen]); + + const handleExtensionLogin = async () => { + setIsLoading(true); + setErrors(prev => ({ ...prev, extension: undefined })); + + try { + if (!('nostr' in window)) { + throw new Error('Nostr extension not found. Please install a NIP-07 extension.'); + } + await login.extension(); + onLogin(); + onClose(); + } catch (e: unknown) { + const error = e as Error; + setErrors(prev => ({ + ...prev, + extension: error instanceof Error ? error.message : 'Extension login failed' + })); + } finally { + setIsLoading(false); + } + }; + + const handleKeyLogin = () => { + if (!nsec.trim()) { + setErrors(prev => ({ ...prev, nsec: 'Please enter your secret key' })); + return; + } + + if (!validateNsec(nsec)) { + setErrors(prev => ({ ...prev, nsec: 'Invalid secret key format. Must be a valid nsec starting with nsec1.' })); + return; + } + + setIsLoading(true); + setErrors({}); + + setTimeout(() => { + try { + login.nsec(nsec); + onLogin(); + onClose(); + } catch { + setErrors({ nsec: "Failed to login with this key. Please check that it's correct." }); + setIsLoading(false); + } + }, 50); + }; + + const handleBunkerLogin = async () => { + if (!bunkerUri.trim()) { + setErrors(prev => ({ ...prev, bunker: 'Please enter a bunker URI' })); + return; + } + + if (!validateBunkerUri(bunkerUri)) { + setErrors(prev => ({ ...prev, bunker: 'Invalid bunker URI format. Must start with bunker://' })); + return; + } + + setIsLoading(true); + setErrors(prev => ({ ...prev, bunker: undefined })); + + try { + await login.bunker(bunkerUri); + onLogin(); + onClose(); + setBunkerUri(''); + } catch { + setErrors(prev => ({ + ...prev, + bunker: 'Failed to connect to bunker. Please check the URI.' + })); + } finally { + setIsLoading(false); + } + }; + + const handleSignupClick = () => { + onClose(); + if (onSignup) { + onSignup(); + } + }; + + if (step === 'extension') { + return ( + + + + Log in + + +
+
+

Welcome to Shakespeare

+
+ +
+ +
+ + {errors.extension && ( + + + {errors.extension} + + )} + +
+ + +
+
+
+
+
+ or +
+
+ + + +
+ New on Shakespeare? + +
+
+
+
+
+ ); + } + + return ( + + + + Import Key + + +
+
+ +
+ +
+ {/* Tab selector */} +
+ + +
+ + {activeTab === 'nsec' && ( +
+
+ { + setNsec(e.target.value); + if (errors.nsec) setErrors(prev => ({ ...prev, nsec: undefined })); + }} + placeholder="nsec1..." + className={errors.nsec ? 'border-red-500' : ''} + /> + {errors.nsec && ( +

{errors.nsec}

+ )} +
+ + +
+ )} + + {activeTab === 'bunker' && ( +
+
+ { + setBunkerUri(e.target.value); + if (errors.bunker) setErrors(prev => ({ ...prev, bunker: undefined })); + }} + placeholder="bunker://" + className={errors.bunker ? 'border-red-500' : ''} + /> + {errors.bunker && ( +

{errors.bunker}

+ )} +
+ + +
+ )} + +
+
+
+
+
+ or +
+
+ + {/* Extension indicator */} +
+

+ {window.nostr ? ( + + ) : ( + 'Browser extension not found.' + )} +

+
+
+
+
+
+ ); +}; + +export default SimpleLoginDialog; \ No newline at end of file diff --git a/src/components/auth/SimpleSignupDialog.tsx b/src/components/auth/SimpleSignupDialog.tsx new file mode 100644 index 00000000..78d48f60 --- /dev/null +++ b/src/components/auth/SimpleSignupDialog.tsx @@ -0,0 +1,315 @@ +import React, { useState, useEffect, useMemo } from 'react'; +import { Key, Download, UserPlus, Shield } from 'lucide-react'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; +import { toast } from '@/hooks/useToast'; +import { useLoginActions } from '@/hooks/useLoginActions'; +import { generateSecretKey, nip19 } from 'nostr-tools'; +import { cn } from '@/lib/utils'; + +type Step = 'extension' | 'key' | 'keygen'; + +interface SimpleSignupDialogProps { + isOpen: boolean; + onClose: () => void; + onComplete?: () => void; +} + +const SimpleSignupDialog: React.FC = ({ + isOpen, + onClose, + onComplete +}) => { + const [step, setStep] = useState('key'); + const [isLoading, setIsLoading] = useState(false); + const [downloaded, setDownloaded] = useState(false); + + const login = useLoginActions(); + + // Generate key once and keep it stable + const secretKey = useMemo(() => generateSecretKey(), []); + const nsec = useMemo(() => nip19.nsecEncode(secretKey), [secretKey]); + + // Reset state when dialog opens/closes + useEffect(() => { + if (isOpen) { + setStep(window.nostr ? 'extension' : 'key'); + setIsLoading(false); + setDownloaded(false); + } + }, [isOpen]); + + const handleExtensionSignup = async () => { + setIsLoading(true); + + try { + if (!('nostr' in window)) { + throw new Error('Nostr extension not found. Please install a NIP-07 extension.'); + } + await login.extension(); + onClose(); + if (onComplete) { + setTimeout(() => { + onComplete(); + }, 600); + } + } catch (e: unknown) { + const error = e as Error; + toast({ + title: 'Extension signup failed', + description: error instanceof Error ? error.message : 'Extension signup failed', + variant: 'destructive', + }); + } finally { + setIsLoading(false); + } + }; + + const handleDownload = () => { + try { + const blob = new Blob([nsec], { type: 'text/plain; charset=utf-8' }); + const url = globalThis.URL.createObjectURL(blob); + const a = document.createElement('a'); + a.href = url; + a.download = 'secret-key.txt'; + a.style.display = 'none'; + document.body.appendChild(a); + a.click(); + globalThis.URL.revokeObjectURL(url); + document.body.removeChild(a); + setDownloaded(true); + toast({ + title: 'Secret Key Saved!', + description: 'Your key has been safely stored.', + }); + } catch { + toast({ + title: 'Download failed', + description: 'Could not download the key file. Please copy it manually.', + variant: 'destructive', + }); + } + }; + + const handleNext = async () => { + setIsLoading(true); + try { + login.nsec(nsec); + + // Mark signup completion time for fallback welcome modal + localStorage.setItem('signup_completed', Date.now().toString()); + + onClose(); + if (onComplete) { + setTimeout(() => { + onComplete(); + }, 600); + } + } catch { + toast({ + title: 'Login Failed', + description: 'Failed to login with the generated key. Please try again.', + variant: 'destructive', + }); + } finally { + setIsLoading(false); + } + }; + + const handleLoginClick = () => { + onClose(); + // This would typically open the login modal + // Since we don't have direct access to the login modal state here, + // we'll rely on the parent component to handle this + }; + + if (step === 'extension') { + return ( + + + + Sign up + + +
+
+

Welcome to Shakespeare

+
+ +
+ +
+ +
+ + +
+
+
+
+
+ or +
+
+ + + +
+ New on Shakespeare? + +
+
+
+
+
+ ); + } + + if (step === 'key') { + return ( + + + + Sign up + + +
+
+

You need a key to continue

+
+ +
+ +
+ +
+ + + +
+ +
+
+
+
+
+ or +
+
+ + {/* Extension indicator */} +
+

+ {window.nostr ? ( + + ) : ( + 'Browser extension not found.' + )} +

+
+
+
+
+ ); + } + + return ( + + + + Your new key + + +
+
+ +
+ +
+
+ + +
+ +
+

+ Back up your secret key in a secure place. If lost, your account cannot be recovered. + Never share your secret key with anyone. +

+
+ +
+ + + +
+
+
+
+
+ ); +}; + +export default SimpleSignupDialog; \ No newline at end of file diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index 26b5aaef..9996b9c5 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -6,8 +6,8 @@ import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Avatar, AvatarFallback, AvatarImage } from '@/components/ui/avatar'; import { Skeleton } from '@/components/ui/skeleton'; import { RelaySelector } from '@/components/RelaySelector'; -import LoginDialog from '@/components/auth/LoginDialog'; -import SignupDialog from '@/components/auth/SignupDialog'; +import SimpleLoginDialog from '@/components/auth/SimpleLoginDialog'; +import SimpleSignupDialog from '@/components/auth/SimpleSignupDialog'; import { useIsMobile } from '@/hooks/useIsMobile'; import { useNavigate } from 'react-router-dom'; import { useLoggedInAccounts, type Account } from '@/hooks/useLoggedInAccounts'; @@ -207,7 +207,7 @@ export function NostrSettings() { {/* Login Dialog */} - setShowLoginDialog(false)} onLogin={handleLoginSuccess} @@ -218,7 +218,7 @@ export function NostrSettings() { /> {/* Signup Dialog */} - setShowSignupDialog(false)} onComplete={handleSignupComplete} From d5c5132662cabfd4fa2f3d6c51c1fcdb64d0bca6 Mon Sep 17 00:00:00 2001 From: Mary Kate Fain Date: Sun, 21 Sep 2025 19:00:39 -0500 Subject: [PATCH 14/95] Prioritize account creation and key generation as default user experience - Make signup the primary action in dropdown menu (moved above login) - Start with key generation as default signup flow instead of extension - Only show extension options when browser extension is detected - Remove complex step navigation - direct to key creation for new users - Update copy to be more welcoming for new users vs returning users - Clean up unused imports and simplify component structure - All tests passing --- src/components/auth/LoginArea.tsx | 14 +- src/components/auth/SimpleLoginDialog.tsx | 132 +++++------------- src/components/auth/SimpleSignupDialog.tsx | 154 +++++++-------------- 3 files changed, 93 insertions(+), 207 deletions(-) diff --git a/src/components/auth/LoginArea.tsx b/src/components/auth/LoginArea.tsx index b7aacb53..1bd7c128 100644 --- a/src/components/auth/LoginArea.tsx +++ b/src/components/auth/LoginArea.tsx @@ -70,13 +70,6 @@ export function LoginArea({ className }: LoginAreaProps) { {t('help')} - setLoginDialogOpen(true)} - className='flex items-center gap-2 cursor-pointer p-2 rounded-md' - > - - {t('logIn')} - setSignupDialogOpen(true)} className='flex items-center gap-2 cursor-pointer p-2 rounded-md' @@ -84,6 +77,13 @@ export function LoginArea({ className }: LoginAreaProps) { {t('signUp')} + setLoginDialogOpen(true)} + className='flex items-center gap-2 cursor-pointer p-2 rounded-md' + > + + {t('logIn')} + )} diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx index bd5bc00a..9b272307 100644 --- a/src/components/auth/SimpleLoginDialog.tsx +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -1,13 +1,13 @@ import React, { useState, useEffect } from 'react'; -import { Shield, Key, Cloud, AlertTriangle } from 'lucide-react'; +import { Key, Cloud } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; -import { Alert, AlertDescription } from '@/components/ui/alert'; +// Alert components removed as they're not used in the simplified design import { useLoginActions } from '@/hooks/useLoginActions'; import { cn } from '@/lib/utils'; -type Step = 'extension' | 'key-add'; +// Only using key-add step now interface SimpleLoginDialogProps { isOpen: boolean; @@ -24,13 +24,13 @@ const validateBunkerUri = (uri: string) => { return uri.startsWith('bunker://'); }; -const SimpleLoginDialog: React.FC = ({ - isOpen, - onClose, - onLogin, - onSignup +const SimpleLoginDialog: React.FC = ({ + isOpen, + onClose, + onLogin, + onSignup }) => { - const [step, setStep] = useState('extension'); + // Removed step state - we only have one step now const [isLoading, setIsLoading] = useState(false); const [nsec, setNsec] = useState(''); const [bunkerUri, setBunkerUri] = useState(''); @@ -40,13 +40,12 @@ const SimpleLoginDialog: React.FC = ({ bunker?: string; extension?: string; }>({}); - + const login = useLoginActions(); // Reset state when dialog opens/closes useEffect(() => { if (isOpen) { - setStep(window.nostr ? 'extension' : 'key-add'); setIsLoading(false); setNsec(''); setBunkerUri(''); @@ -139,82 +138,19 @@ const SimpleLoginDialog: React.FC = ({ } }; - if (step === 'extension') { - return ( - - - - Log in - - -
-
-

Welcome to Shakespeare

-
- -
- -
- - {errors.extension && ( - - - {errors.extension} - - )} - -
- - -
-
-
-
-
- or -
-
- - - -
- New on Shakespeare? - -
-
-
-
-
- ); - } - return ( - Import Key + Log in - +
+
+

Welcome back to Shakespeare

+

Sign in to your existing account

+
+
@@ -226,8 +162,8 @@ const SimpleLoginDialog: React.FC = ({ onClick={() => setActiveTab('nsec')} className={cn( "flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors", - activeTab === 'nsec' - ? "bg-background text-foreground shadow-sm" + activeTab === 'nsec' + ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground" )} > @@ -237,8 +173,8 @@ const SimpleLoginDialog: React.FC = ({ onClick={() => setActiveTab('bunker')} className={cn( "flex-1 px-3 py-2 text-sm font-medium rounded-md transition-colors", - activeTab === 'bunker' - ? "bg-background text-foreground shadow-sm" + activeTab === 'bunker' + ? "bg-background text-foreground shadow-sm" : "text-muted-foreground hover:text-foreground" )} > @@ -313,21 +249,29 @@ const SimpleLoginDialog: React.FC = ({
- {/* Extension indicator */} -
-

- {window.nostr ? ( - - ) : ( - 'Browser extension not found.' - )} -

+

+
+ )} + +
+ New to Shakespeare? +
diff --git a/src/components/auth/SimpleSignupDialog.tsx b/src/components/auth/SimpleSignupDialog.tsx index 78d48f60..12f792be 100644 --- a/src/components/auth/SimpleSignupDialog.tsx +++ b/src/components/auth/SimpleSignupDialog.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useMemo } from 'react'; -import { Key, Download, UserPlus, Shield } from 'lucide-react'; +import { Key, Download, UserPlus } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; @@ -8,7 +8,7 @@ import { useLoginActions } from '@/hooks/useLoginActions'; import { generateSecretKey, nip19 } from 'nostr-tools'; import { cn } from '@/lib/utils'; -type Step = 'extension' | 'key' | 'keygen'; +type Step = 'key' | 'keygen'; interface SimpleSignupDialogProps { isOpen: boolean; @@ -16,15 +16,15 @@ interface SimpleSignupDialogProps { onComplete?: () => void; } -const SimpleSignupDialog: React.FC = ({ - isOpen, - onClose, - onComplete +const SimpleSignupDialog: React.FC = ({ + isOpen, + onClose, + onComplete }) => { const [step, setStep] = useState('key'); const [isLoading, setIsLoading] = useState(false); const [downloaded, setDownloaded] = useState(false); - + const login = useLoginActions(); // Generate key once and keep it stable @@ -34,7 +34,8 @@ const SimpleSignupDialog: React.FC = ({ // Reset state when dialog opens/closes useEffect(() => { if (isOpen) { - setStep(window.nostr ? 'extension' : 'key'); + // Always start with key generation as the default experience + setStep('key'); setIsLoading(false); setDownloaded(false); } @@ -96,10 +97,10 @@ const SimpleSignupDialog: React.FC = ({ setIsLoading(true); try { login.nsec(nsec); - + // Mark signup completion time for fallback welcome modal localStorage.setItem('signup_completed', Date.now().toString()); - + onClose(); if (onComplete) { setTimeout(() => { @@ -124,66 +125,6 @@ const SimpleSignupDialog: React.FC = ({ // we'll rely on the parent component to handle this }; - if (step === 'extension') { - return ( - - - - Sign up - - -
-
-

Welcome to Shakespeare

-
- -
- -
- -
- - -
-
-
-
-
- or -
-
- - - -
- New on Shakespeare? - -
-
-
-
-
- ); - } - if (step === 'key') { return ( @@ -191,10 +132,11 @@ const SimpleSignupDialog: React.FC = ({ Sign up - +
-

You need a key to continue

+

Welcome to Shakespeare

+

Create your account to get started

@@ -202,49 +144,49 @@ const SimpleSignupDialog: React.FC = ({
- -
-
-
-
-
-
- or -
-
+ {/* Extension indicator - only show if extension is detected */} + {window.nostr && ( + <> +
+
+
+
+
+ or +
+
- {/* Extension indicator */} -
-

- {window.nostr ? ( - - ) : ( - 'Browser extension not found.' - )} -

-
+
+

+ +

+
+ + )}
@@ -257,7 +199,7 @@ const SimpleSignupDialog: React.FC = ({ Your new key - +
@@ -276,15 +218,15 @@ const SimpleSignupDialog: React.FC = ({

- Back up your secret key in a secure place. If lost, your account cannot be recovered. + Back up your secret key in a secure place. If lost, your account cannot be recovered. Never share your secret key with anyone.

-
); diff --git a/src/components/auth/SimpleSignupDialog.tsx b/src/components/auth/SimpleSignupDialog.tsx index 12f792be..916c6fff 100644 --- a/src/components/auth/SimpleSignupDialog.tsx +++ b/src/components/auth/SimpleSignupDialog.tsx @@ -14,12 +14,14 @@ interface SimpleSignupDialogProps { isOpen: boolean; onClose: () => void; onComplete?: () => void; + onLogin?: () => void; } const SimpleSignupDialog: React.FC = ({ isOpen, onClose, - onComplete + onComplete, + onLogin }) => { const [step, setStep] = useState('key'); const [isLoading, setIsLoading] = useState(false); @@ -120,9 +122,9 @@ const SimpleSignupDialog: React.FC = ({ const handleLoginClick = () => { onClose(); - // This would typically open the login modal - // Since we don't have direct access to the login modal state here, - // we'll rely on the parent component to handle this + if (onLogin) { + onLogin(); + } }; if (step === 'key') { diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index 9996b9c5..cf8112a9 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -222,6 +222,10 @@ export function NostrSettings() { isOpen={showSignupDialog} onClose={() => setShowSignupDialog(false)} onComplete={handleSignupComplete} + onLogin={() => { + setShowSignupDialog(false); + setShowLoginDialog(true); + }} />
); From 7d0c0b6ba24990d19291d8b5ff8997edf92aed33 Mon Sep 17 00:00:00 2001 From: Mary Kate Fain Date: Sun, 21 Sep 2025 19:11:22 -0500 Subject: [PATCH 16/95] Replace key icons with emoji key in circular background MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Replace Lucide Key icons with 🔑 emoji in both login and signup dialogs - Add circular background with primary color tint (bg-primary/10) - Maintain consistent sizing (w-20 h-20 circle, text-4xl emoji) - Remove unused Key import from both components - Creates friendlier, more approachable visual design - All tests passing --- src/components/auth/SimpleLoginDialog.tsx | 6 ++++-- src/components/auth/SimpleSignupDialog.tsx | 10 +++++++--- 2 files changed, 11 insertions(+), 5 deletions(-) diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx index 9b272307..73c6476e 100644 --- a/src/components/auth/SimpleLoginDialog.tsx +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect } from 'react'; -import { Key, Cloud } from 'lucide-react'; +import { Cloud } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; @@ -152,7 +152,9 @@ const SimpleLoginDialog: React.FC = ({
- +
+ 🔑 +
diff --git a/src/components/auth/SimpleSignupDialog.tsx b/src/components/auth/SimpleSignupDialog.tsx index 916c6fff..aaf31af8 100644 --- a/src/components/auth/SimpleSignupDialog.tsx +++ b/src/components/auth/SimpleSignupDialog.tsx @@ -1,5 +1,5 @@ import React, { useState, useEffect, useMemo } from 'react'; -import { Key, Download, UserPlus } from 'lucide-react'; +import { Download, UserPlus } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Dialog, DialogContent, DialogHeader, DialogTitle } from "@/components/ui/dialog"; @@ -142,7 +142,9 @@ const SimpleSignupDialog: React.FC = ({
- +
+ 🔑 +
@@ -204,7 +206,9 @@ const SimpleSignupDialog: React.FC = ({
- +
+ 🔑 +
From 691077d754949faa3d1a62f68a8a8600195fce1e Mon Sep 17 00:00:00 2001 From: Mary Kate Fain Date: Sun, 21 Sep 2025 19:13:09 -0500 Subject: [PATCH 17/95] Increase emoji key size from text-4xl to text-8xl MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Make the 🔑 emoji 2x bigger as requested - Applied to all instances in both SimpleLoginDialog and SimpleSignupDialog - Creates more prominent visual focal point in the authentication flows - All tests passing --- src/components/auth/SimpleLoginDialog.tsx | 2 +- src/components/auth/SimpleSignupDialog.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx index 73c6476e..6366e0af 100644 --- a/src/components/auth/SimpleLoginDialog.tsx +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -153,7 +153,7 @@ const SimpleLoginDialog: React.FC = ({
- 🔑 + 🔑
diff --git a/src/components/auth/SimpleSignupDialog.tsx b/src/components/auth/SimpleSignupDialog.tsx index aaf31af8..a3f3653f 100644 --- a/src/components/auth/SimpleSignupDialog.tsx +++ b/src/components/auth/SimpleSignupDialog.tsx @@ -143,7 +143,7 @@ const SimpleSignupDialog: React.FC = ({
- 🔑 + 🔑
@@ -207,7 +207,7 @@ const SimpleSignupDialog: React.FC = ({
- 🔑 + 🔑
From b28f7006005cff7108594a6a14dfbcc362422dfd Mon Sep 17 00:00:00 2001 From: Mary Kate Fain Date: Sun, 21 Sep 2025 19:14:16 -0500 Subject: [PATCH 18/95] Increase circle size to match larger emoji key - Change circle from w-20 h-20 to w-32 h-32 to better accommodate text-8xl emoji - Now the circle fills the entire container space for better visual balance - Applied consistently across all instances in both login and signup dialogs - Creates better proportional relationship between emoji and background circle - All tests passing --- src/components/auth/SimpleLoginDialog.tsx | 2 +- src/components/auth/SimpleSignupDialog.tsx | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx index 6366e0af..df368503 100644 --- a/src/components/auth/SimpleLoginDialog.tsx +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -152,7 +152,7 @@ const SimpleLoginDialog: React.FC = ({
-
+
🔑
diff --git a/src/components/auth/SimpleSignupDialog.tsx b/src/components/auth/SimpleSignupDialog.tsx index a3f3653f..3a2366eb 100644 --- a/src/components/auth/SimpleSignupDialog.tsx +++ b/src/components/auth/SimpleSignupDialog.tsx @@ -142,7 +142,7 @@ const SimpleSignupDialog: React.FC = ({
-
+
🔑
@@ -206,7 +206,7 @@ const SimpleSignupDialog: React.FC = ({
-
+
🔑
From 61254d2ee3eeb6544aacb75d48557bab4625ec4e Mon Sep 17 00:00:00 2001 From: Mary Kate Fain Date: Sun, 21 Sep 2025 19:15:28 -0500 Subject: [PATCH 19/95] Increase circle size to w-40 h-40 for better emoji proportion - Change both container and circle from w-32 h-32 to w-40 h-40 (10rem / 160px) - Provides more generous spacing around the text-8xl emoji key - Creates better visual balance and prevents the emoji from appearing cramped - Applied consistently across all instances in both login and signup dialogs - All tests passing --- src/components/auth/SimpleLoginDialog.tsx | 4 ++-- src/components/auth/SimpleSignupDialog.tsx | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/components/auth/SimpleLoginDialog.tsx b/src/components/auth/SimpleLoginDialog.tsx index df368503..b43136a7 100644 --- a/src/components/auth/SimpleLoginDialog.tsx +++ b/src/components/auth/SimpleLoginDialog.tsx @@ -151,8 +151,8 @@ const SimpleLoginDialog: React.FC = ({

Sign in to your existing account

-
-
+
+
🔑
diff --git a/src/components/auth/SimpleSignupDialog.tsx b/src/components/auth/SimpleSignupDialog.tsx index 3a2366eb..57170dc5 100644 --- a/src/components/auth/SimpleSignupDialog.tsx +++ b/src/components/auth/SimpleSignupDialog.tsx @@ -141,8 +141,8 @@ const SimpleSignupDialog: React.FC = ({

Create your account to get started

-
-
+
+
🔑
@@ -205,8 +205,8 @@ const SimpleSignupDialog: React.FC = ({
-
-
+
+
🔑
From 230d4bc4435bcc97da77ffc8365d6070fb2a9ab6 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 20:07:55 -0500 Subject: [PATCH 20/95] Push to Nostr works! --- src/components/GitDialog.tsx | 241 +++++++++++++++++++++++- src/components/NostrProvider.tsx | 35 +++- src/lib/git.ts | 304 ++++++++++++++----------------- 3 files changed, 411 insertions(+), 169 deletions(-) diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index d1be2ddb..56ef8f13 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -34,13 +34,20 @@ import { RefreshCw, Settings, AlertTriangle, + Zap, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; import { useGit } from '@/hooks/useGit'; import { useToast } from '@/hooks/useToast'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useNostr } from '@nostrify/react'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; import { cn } from '@/lib/utils'; import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials'; +import { nip19 } from 'nostr-tools'; + +const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"]; interface GitDialogProps { projectId: string; @@ -52,6 +59,7 @@ interface GitDialogProps { export function GitDialog({ projectId, children, open, onOpenChange }: GitDialogProps) { const [isPushing, setIsPushing] = useState(false); const [isPulling, setIsPulling] = useState(false); + const [isPushingToNostr, setIsPushingToNostr] = useState(false); const [pushResult, setPushResult] = useState(null); const [pullResult, setPullResult] = useState(null); const navigate = useNavigate(); @@ -60,9 +68,217 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const { settings } = useGitSettings(); const { git } = useGit(); const { toast } = useToast(); + const { user } = useCurrentUser(); + const { nostr } = useNostr(); + const { mutateAsync: publishEvent } = useNostrPublish(); const projectPath = `/projects/${projectId}`; + const handlePushToNostr = async () => { + if (!user) { + toast({ + title: "Cannot push to Nostr", + description: "You must be logged in to push to Nostr", + variant: "destructive", + }); + return; + } + + if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { + toast({ + title: "Cannot push to Nostr", + description: "Not a git repository or no current branch", + variant: "destructive", + }); + return; + } + + setIsPushingToNostr(true); + setPushResult(null); + + try { + // Check if repo announcement already exists + const existingRepoEvents = await nostr.query([{ + kinds: [30617], + authors: [user.pubkey], + '#d': [projectId], + limit: 1, + }], { signal: AbortSignal.timeout(5000) }); + + if (existingRepoEvents.length > 0) { + throw new Error(`Repository announcement already exists for project "${projectId}". Cannot create duplicate.`); + } + + // Create repo announcement event (NIP-34 kind 30617) + const cloneUrls = GRASP_SERVERS.map(server => + `https://${server}/${nip19.npubEncode(user.pubkey)}/${projectId}.git` + ); + const relayUrls = GRASP_SERVERS.map(server => `wss://${server}`); + + await publishEvent({ + kind: 30617, + content: "", + tags: [ + ["d", projectId], + ["clone", ...cloneUrls], + ["relays", ...relayUrls], + ], + }); + + // Get current repository state + const refTags: string[][] = []; + + // First check if we have any commits at all + try { + const log = await git.log({ dir: projectPath, depth: 1 }); + if (log.length === 0) { + throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.'); + } + console.log(`Repository has ${log.length} commit(s), latest: ${log[0].oid}`); + } catch (error) { + if (error instanceof Error && error.message.includes('no commits')) { + throw error; // Re-throw our custom error + } + throw new Error('Repository has no commits. Please make at least one commit before publishing to Nostr.'); + } + + try { + // Get all refs using listRefs + const refs = await git.listRefs({ dir: projectPath }); + console.log('Found refs:', refs); + + for (const ref of refs) { + try { + const commitId = await git.resolveRef({ + dir: projectPath, + ref, + }); + if (ref.startsWith('refs/heads/') || ref.startsWith('refs/tags/')) { + refTags.push([ref, commitId]); + } + } catch (error) { + console.warn(`Failed to resolve ref ${ref}:`, error); + } + } + } catch (error) { + console.warn('Failed to list refs, trying alternative approach:', error); + } + + // If no refs found, try to get the current branch directly + if (refTags.length === 0) { + try { + const currentBranch = await git.currentBranch({ dir: projectPath }); + if (currentBranch) { + const currentCommit = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + refTags.push([`refs/heads/${currentBranch}`, currentCommit]); + console.log(`Added current branch: refs/heads/${currentBranch} -> ${currentCommit}`); + } else { + // Try to get HEAD directly even if no current branch + try { + const headCommit = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + refTags.push(['refs/heads/main', headCommit]); // Assume main branch + console.log(`Added assumed main branch: refs/heads/main -> ${headCommit}`); + } catch (headError) { + console.warn('Failed to resolve HEAD directly:', headError); + } + } + } catch (error) { + console.warn('Failed to get current branch:', error); + } + } + + if (refTags.length === 0) { + throw new Error('Could not determine repository state. The repository might not have any commits or branches.'); + } + + // Get HEAD reference + let headRef: string | undefined; + try { + const currentBranch = await git.currentBranch({ dir: projectPath }); + if (currentBranch) { + headRef = `ref: refs/heads/${currentBranch}`; + console.log(`HEAD points to: ${headRef}`); + } else { + // HEAD is detached, use the commit ID directly + const headValue = await git.resolveRef({ + dir: projectPath, + ref: 'HEAD', + }); + if (headValue) { + headRef = headValue; + console.log(`HEAD is detached at: ${headRef}`); + } + } + } catch (error) { + console.warn('Failed to resolve HEAD:', error); + } + + // Create repo state event (NIP-34 kind 30618) + await publishEvent({ + kind: 30618, + content: "", + tags: [ + ["d", projectId], + ...refTags, + ...(headRef ? [["HEAD", headRef]] : []), + ], + }); + + // Set origin remote to Nostr URL + const nostrUrl = `nostr://${nip19.npubEncode(user.pubkey)}/git.shakespeare.diy/${projectId}`; + + try { + // Remove existing origin if it exists + await git.deleteRemote({ + dir: projectPath, + remote: 'origin', + }); + } catch { + // Ignore if origin doesn't exist + } + + await git.addRemote({ + dir: projectPath, + remote: 'origin', + url: nostrUrl, + }); + + // Set nostr.repo config + await git.setConfig({ + dir: projectPath, + path: 'nostr.repo', + value: nip19.naddrEncode({ + kind: 30617, + pubkey: user.pubkey, + identifier: projectId, + }), + }); + + toast({ + title: "Repository published to Nostr", + description: "Waiting for GRASP servers to update...", + }); + + setPushResult(`✅ Successfully published repository to Nostr`); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + setPushResult(`❌ Push to Nostr failed: ${errorMessage}`); + toast({ + title: "Push to Nostr failed", + description: errorMessage, + variant: "destructive", + }); + } finally { + setIsPushingToNostr(false); + } + }; + const handlePush = async () => { if (!gitStatus?.isGitRepo || !gitStatus.currentBranch) { toast({ @@ -102,6 +318,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog remote: remote.name, ref: gitStatus.currentBranch, onAuth: (url) => findCredentialsForRepo(url, settings.credentials), + signer: user?.signer, // For signing if pushing to Nostr }); setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`); @@ -427,7 +644,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
+
+ )} + {/* Operation Results */} {(pushResult || pullResult) && (
diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 6d745971..7b89ae81 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -1,5 +1,5 @@ import React, { useEffect, useRef } from 'react'; -import { NostrEvent, NPool, NRelay1 } from '@nostrify/nostrify'; +import { NostrEvent, NostrFilter, NPool, NRelay1 } from '@nostrify/nostrify'; import { NostrContext } from '@nostrify/react'; import { useQueryClient } from '@tanstack/react-query'; import { useAppContext } from '@/hooks/useAppContext'; @@ -8,6 +8,19 @@ interface NostrProviderProps { children: React.ReactNode; } +const GIT_KINDS = [ + 30617, // NIP-34 Repository Announcement + 30618, // NIP-34 Commit Announcement + 1617, // NIP-34 Patch + 1621, // NIP-34 Issue +]; + +const GIT_RELAYS = [ + 'wss://git.shakespeare.diy/', + 'wss://relay.ngit.dev/', + 'wss://gitnostr.com/', +]; + const NostrProvider: React.FC = (props) => { const { children } = props; const { config, presetRelays } = useAppContext(); @@ -33,12 +46,28 @@ const NostrProvider: React.FC = (props) => { return new NRelay1(url); }, reqRouter(filters) { - return new Map([[relayUrl.current, filters]]); + const routes = new Map(); + routes.set(relayUrl.current, filters); + + if (filters.every((f) => f.kinds?.every((k) => GIT_KINDS.includes(k)))) { + // If all filters are git-related, route to all git relays + for (const url of GIT_RELAYS) { + routes.set(url, filters); + } + } + return routes; }, - eventRouter(_event: NostrEvent) { + eventRouter(event: NostrEvent) { // Publish to the selected relay const allRelays = new Set([relayUrl.current]); + // If it's a git-related event, also publish to the git relays + if (GIT_KINDS.includes(event.kind)) { + for (const url of GIT_RELAYS) { + allRelays.add(url); + } + } + // Also publish to the preset relays, capped to 5 for (const { url } of (presetRelays ?? [])) { allRelays.add(url); diff --git a/src/lib/git.ts b/src/lib/git.ts index 4fb75145..776eb294 100644 --- a/src/lib/git.ts +++ b/src/lib/git.ts @@ -578,7 +578,7 @@ export class Git { console.log(`Getting remote info for Nostr repository: ${nostrUrl}`); // Fetch the repository announcement and state from Nostr - const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo, state } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository announcement not found on Nostr network'); @@ -689,6 +689,33 @@ export class Git { } } + // If no refs found, try to get the current branch directly + if (refTags.length === 0) { + try { + const currentBranch = await this.currentBranch({ dir }); + if (currentBranch) { + const currentCommit = await this.resolveRef({ dir, ref: 'HEAD' }); + refTags.push([`refs/heads/${currentBranch}`, currentCommit]); + console.log(`Added current branch: refs/heads/${currentBranch} -> ${currentCommit}`); + } else { + // Try to get HEAD directly even if no current branch + try { + const headCommit = await this.resolveRef({ dir, ref: 'HEAD' }); + refTags.push(['refs/heads/main', headCommit]); // Assume main branch + console.log(`Added assumed main branch: refs/heads/main -> ${headCommit}`); + } catch (headError) { + console.warn('Failed to resolve HEAD directly:', headError); + } + } + } catch (error) { + console.warn('Failed to get current branch:', error); + } + } + + if (refTags.length === 0) { + throw new Error('Could not determine repository state. The repository might not have any commits or branches.'); + } + // Get HEAD reference try { const headValue = await git.resolveRef({ @@ -864,7 +891,7 @@ export class Git { // Format: nostr://npub/relay/d return { pubkey, - relay: parts[1], + relay: `wss://${parts[1]}/`, d: parts[2], }; } else if (parts.length === 2) { @@ -881,59 +908,61 @@ export class Git { } } - private async fetchNostrRepo( - nostrURI: NostrCloneURI, - signal?: AbortSignal, - ): Promise<{ repo?: NostrEvent; state?: NostrEvent }> { + private async fetchNostrRepo(nostrURI: NostrCloneURI): Promise<{ repo?: NostrEvent; state?: NostrEvent }> { // Build the filter for both NIP-34 repository announcement and state events const filter = { kinds: [30617, 30618], authors: [nostrURI.pubkey], '#d': [nostrURI.d], - limit: 2, // We want both repo and state events if they exist }; - // Use a specific relay if provided, otherwise try git-focused relays - const client = nostrURI.relay - ? this.nostr.relay(nostrURI.relay) - : this.nostr.group([ - 'wss://git.shakespeare.diy/', - 'wss://relay.ngit.dev/', - 'wss://gitnostr.com/', - 'wss://relay.nostr.band/', // Fallback to general relay - ]); + const gitRelays = new Set([ + 'wss://git.shakespeare.diy/', + 'wss://relay.ngit.dev/', + 'wss://gitnostr.com/', + 'wss://relay.nostr.band/', // General purpose relay as fallback + ]); - try { - // Query for both repository announcement and state events - const events = await client.query([filter], { - signal: signal || AbortSignal.timeout(5000) - }); + let events: NostrEvent[] = []; - const repo = events.find((e) => e.kind === 30617); - const state = events.find((e) => e.kind === 30618); - - if (!repo) { - throw new Error('Repository announcement not found on Nostr network'); + // 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) }); + } catch (error) { + console.error(`Error querying relay ${nostrURI.relay}: ${error}`); } - - if (state) { - console.log(`Found repository state event with ${state.tags.length} tags`); - } else { - console.log('No repository state event found, proceeding with basic clone'); - } - - return { repo, state }; - } catch (error) { - if (error instanceof Error) { - throw new Error(`Failed to fetch repository from Nostr: ${error.message}`); - } - throw new Error('Failed to fetch repository from Nostr network'); } + if (!events.length) { + try { + events = await this.nostr.group([...gitRelays]).query([filter], { signal: AbortSignal.timeout(5000) }); + } catch (error) { + console.error(`Error querying group relays: ${error}`); + } + } + if (!events.length) { + throw new Error('No events found for the specified Nostr repository'); + } + + const repo = events.find((e) => e.kind === 30617); + const state = events.find((e) => e.kind === 30618); + + if (!repo) { + throw new Error('Repository announcement not found on Nostr network'); + } + + if (state) { + console.log(`Found repository state event with ${state.tags.length} tags`); + } else { + console.log('No repository state event found, proceeding with basic clone'); + } + + return { repo, state }; } private async nostrClone(nostrURI: NostrCloneURI, options: Omit[0], 'fs' | 'http' | 'corsProxy'>): Promise { // Fetch events from Nostr - const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo, state } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository not found'); @@ -1163,7 +1192,7 @@ export class Git { console.log(`Fetching updates from Nostr repository: ${nostrUrl}`); // Fetch the latest repository state from Nostr - const { repo, state } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo, state } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository not found on Nostr network'); @@ -1337,7 +1366,7 @@ export class Git { console.log(`Pushing to Nostr repository: ${nostrUrl}`); // Fetch the repository announcement to get relay information and clone URLs - const { repo } = await this.fetchNostrRepo(nostrURI, AbortSignal.timeout(10000)); + const { repo } = await this.fetchNostrRepo(nostrURI); if (!repo) { throw new Error('Repository announcement not found on Nostr network'); } @@ -1346,17 +1375,28 @@ export class Git { const relayUrls: string[] = []; const cloneUrls: string[] = []; - for (const [name, value] of repo.tags) { - if (name === 'relays' && value) { - relayUrls.push(value); - } else if (name === 'clone' && value) { - try { - const url = new URL(value); - if (url.protocol === 'http:' || url.protocol === 'https:') { - cloneUrls.push(url.href); + for (const [name, ...values] of repo.tags) { + if (name === 'relays' && values.length > 0) { + for (const value of values) { + try { + const url = new URL(value); + if (url.protocol === 'wss:') { + relayUrls.push(url.href); + } + } catch { + // Ignore invalid URLs + } + } + } else if (name === 'clone' && values.length > 0) { + for (const value of values) { + try { + const url = new URL(value); + if (url.protocol === 'https:') { + cloneUrls.push(url.href); + } + } catch { + // Ignore invalid URLs } - } catch { - // Ignore invalid URLs } } } @@ -1375,26 +1415,22 @@ export class Git { const repoState = await this.getCurrentRepositoryState(dir); // Create repository state event (kind 30618) - const stateEvent: Omit = { + const stateEvent = await signer.signEvent({ kind: 30618, created_at: Math.floor(Date.now() / 1000), - pubkey: '', // Will be set by signer content: '', tags: [ ['d', nostrURI.d], // Repository identifier ...repoState.refTags, ...(repoState.headRef ? [['HEAD', repoState.headRef]] : []), ], - }; - - // Sign the event - const signedStateEvent = await signer.signEvent(stateEvent); + }); // Publish the state event to Nostr relays console.log(`Publishing repository state to ${relayUrls.length} relays`); try { - await this.nostr.group(relayUrls).event(signedStateEvent); + await this.nostr.group(relayUrls).event(stateEvent); console.log('✓ Repository state published to Nostr successfully'); } catch (error) { console.warn('Failed to publish repository state to some relays:', error); @@ -1407,63 +1443,34 @@ export class Git { return; } + // Wait 5 seconds for GRASP servers to update + await new Promise(resolve => setTimeout(resolve, 5000)); + let pushSuccessful = false; let lastError: Error | null = null; for (const cloneUrl of cloneUrls) { - try { - console.log(`Pushing to Git remote: ${cloneUrl}`); + console.log(`Pushing to Git remote: ${cloneUrl}`); - // Add a temporary remote for this clone URL - const tempRemoteName = `temp-push-${Date.now()}`; - await git.addRemote({ + try { + // Push to the temporary remote + await git.push({ fs: this.fs, + http, + corsProxy: this.corsProxy, dir, - remote: tempRemoteName, url: cloneUrl, + ...gitPushOptions, }); - try { - // Push to the temporary remote - await git.push({ - fs: this.fs, - http, - corsProxy: this.corsProxy, - dir, - remote: tempRemoteName, - ...gitPushOptions, - }); + pushSuccessful = true; + console.log(`✓ Successfully pushed to ${cloneUrl}`); - pushSuccessful = true; - console.log(`✓ Successfully pushed to ${cloneUrl}`); - - // Remove the temporary remote - await git.deleteRemote({ - fs: this.fs, - dir, - remote: tempRemoteName, - }); - - // If one push succeeds, we can break (unless we want to push to all remotes) - break; - } catch (pushError) { - console.warn(`Failed to push to ${cloneUrl}:`, pushError); - lastError = pushError instanceof Error ? pushError : new Error('Unknown push error'); - - // Clean up the temporary remote - try { - await git.deleteRemote({ - fs: this.fs, - dir, - remote: tempRemoteName, - }); - } catch { - // Ignore cleanup errors - } - } - } catch (error) { - console.warn(`Failed to set up remote for ${cloneUrl}:`, error); - lastError = error instanceof Error ? error : new Error('Unknown error'); + // If one push succeeds, we can break (unless we want to push to all remotes) + break; + } catch (pushError) { + console.warn(`Failed to push to ${cloneUrl}:`, pushError); + lastError = pushError instanceof Error ? pushError : new Error('Unknown push error'); } } @@ -1497,78 +1504,47 @@ export class Git { // Try to fetch missing commits from each Git remote for (const cloneUrl of cloneUrls) { - try { - console.log(`Fetching missing commits from: ${cloneUrl}`); + console.log(`Fetching missing commits from: ${cloneUrl}`); - // Add a temporary remote - const tempRemoteName = `temp-${Date.now()}`; - await git.addRemote({ + try { + // Fetch from the clone URL + await git.fetch({ fs: this.fs, + http, + corsProxy: this.corsProxy, dir, - remote: tempRemoteName, url: cloneUrl, }); - try { - // Fetch from the temporary remote - await git.fetch({ - fs: this.fs, - http, - corsProxy: this.corsProxy, - dir, - remote: tempRemoteName, - }); - - // Update our refs to match the Nostr state - for (const [refName, commitId] of Object.entries(refs)) { - try { - // Check if we now have this commit - await git.readCommit({ - fs: this.fs, - dir, - oid: commitId, - }); - - // Update the ref - await git.writeRef({ - fs: this.fs, - dir, - ref: refName, - value: commitId, - }); - - console.log(`✓ Updated ${refName} to ${commitId} after fetching`); - } catch { - // Still don't have this commit - console.warn(`Still missing commit ${commitId} for ${refName}`); - } - } - - // Remove the temporary remote - await git.deleteRemote({ - fs: this.fs, - dir, - remote: tempRemoteName, - }); - - // Successfully fetched from this remote - return; - } catch (fetchError) { - console.warn(`Failed to fetch from ${cloneUrl}:`, fetchError); - - // Clean up the temporary remote + // Update our refs to match the Nostr state + for (const [refName, commitId] of Object.entries(refs)) { try { - await git.deleteRemote({ + // Check if we now have this commit + await git.readCommit({ fs: this.fs, dir, - remote: tempRemoteName, + oid: commitId, }); + + // Update the ref + await git.writeRef({ + fs: this.fs, + dir, + ref: refName, + value: commitId, + }); + + console.log(`✓ Updated ${refName} to ${commitId} after fetching`); } catch { - // Ignore cleanup errors + // Still don't have this commit + console.warn(`Still missing commit ${commitId} for ${refName}`); } } - } catch (error) { - console.warn(`Failed to set up temporary remote for ${cloneUrl}:`, error); + + // Successfully fetched from this remote + return; + } catch (fetchError) { + console.warn(`Failed to fetch from ${cloneUrl}:`, fetchError); } } } From f6dc218ae7f34ac6c8e3f6755a0a26f157c8d2d6 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 21:59:24 -0500 Subject: [PATCH 21/95] Remove "Repository Information" from GitDialog --- src/components/GitDialog.test.tsx | 8 ++-- src/components/GitDialog.tsx | 77 +------------------------------ 2 files changed, 4 insertions(+), 81 deletions(-) diff --git a/src/components/GitDialog.test.tsx b/src/components/GitDialog.test.tsx index faf4e17b..fa03051d 100644 --- a/src/components/GitDialog.test.tsx +++ b/src/components/GitDialog.test.tsx @@ -64,7 +64,7 @@ describe('GitDialog', () => { }); }); - it('renders git repository information', () => { + it('renders git dialog without repository information section', () => { render( {}}> @@ -74,10 +74,8 @@ describe('GitDialog', () => { ); expect(screen.getByText('Git Repository Status')).toBeInTheDocument(); - expect(screen.getByText('Repository Information')).toBeInTheDocument(); - expect(screen.getByText('main')).toBeInTheDocument(); - expect(screen.getByText('5')).toBeInTheDocument(); - expect(screen.getAllByText('origin')).toHaveLength(2); // Appears in remotes and credentials sections + expect(screen.queryByText('Repository Information')).not.toBeInTheDocument(); + expect(screen.getByText('origin')).toBeInTheDocument(); // Appears in credentials section }); it('shows sync status', () => { diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 56ef8f13..8c444aff 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -31,7 +31,6 @@ import { Plus, Minus, Edit, - RefreshCw, Settings, AlertTriangle, Zap, @@ -399,11 +398,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } }; - const handleRefresh = async () => { - await refetchGitStatus(); - setPushResult(null); - setPullResult(null); - }; + const getFileStatusIcon = (status: string) => { switch (status) { @@ -486,76 +481,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
- {/* Repository Info */} - - - - Repository Information - - - - - {gitStatus?.isGitRepo ? ( - <> -
- Current Branch: - - {gitStatus.currentBranch || 'unknown'} - -
- -
- Total Commits: - {gitStatus.totalCommits} -
- - {gitStatus.latestCommit && ( -
- Latest Commit: -
-
- {gitStatus.latestCommit.oid.substring(0, 7)} -
-
{gitStatus.latestCommit.message}
-
- - {new Date(gitStatus.latestCommit.author.timestamp * 1000).toLocaleString()} -
-
-
- )} - - {gitStatus.remotes.length > 0 && ( -
- Remotes: - {gitStatus.remotes.map((remote) => ( -
-
- {remote.name} - - {remote.url} - -
-
- ))} -
- )} - - ) : ( -
- -

Not a Git repository

-
- )} -
-
{/* Credentials Status */} {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && ( From fed44cef5e0ece564013d572597276e67298297e Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 23:36:08 -0500 Subject: [PATCH 22/95] GitDialog improvements --- src/components/GitDialog.test.tsx | 66 +++++-- src/components/GitDialog.tsx | 293 +++++++++++++++++++----------- 2 files changed, 240 insertions(+), 119 deletions(-) diff --git a/src/components/GitDialog.test.tsx b/src/components/GitDialog.test.tsx index fa03051d..ab2a5081 100644 --- a/src/components/GitDialog.test.tsx +++ b/src/components/GitDialog.test.tsx @@ -43,17 +43,10 @@ vi.mock('@/hooks/useToast', () => ({ })), })); +const mockUseGitSettings = vi.fn(); + vi.mock('@/hooks/useGitSettings', () => ({ - useGitSettings: vi.fn(() => ({ - settings: { - credentials: { - 'https://github.com': { - username: 'git', - password: 'github-token', - }, - }, - }, - })), + useGitSettings: () => mockUseGitSettings(), })); describe('GitDialog', () => { @@ -62,6 +55,17 @@ describe('GitDialog', () => { data: baseGitStatus, refetch: mockRefetch, }); + + mockUseGitSettings.mockReturnValue({ + settings: { + credentials: { + 'https://github.com': { + username: 'git', + password: 'github-token', + }, + }, + }, + }); }); it('renders git dialog without repository information section', () => { @@ -73,9 +77,9 @@ describe('GitDialog', () => { ); - expect(screen.getByText('Git Repository Status')).toBeInTheDocument(); + expect(screen.getByText('Repository')).toBeInTheDocument(); expect(screen.queryByText('Repository Information')).not.toBeInTheDocument(); - expect(screen.getByText('origin')).toBeInTheDocument(); // Appears in credentials section + expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed }); it('shows sync status', () => { @@ -143,7 +147,7 @@ describe('GitDialog', () => { expect(pushButton.closest('button')).toBeDisabled(); }); - it('shows configured credentials status', () => { + it('does not show credentials warning when credentials are configured', () => { render( {}}> @@ -152,8 +156,38 @@ describe('GitDialog', () => { ); - expect(screen.getByText('Authentication')).toBeInTheDocument(); - expect(screen.getByText('github.com')).toBeInTheDocument(); - expect(screen.getByText('Configured')).toBeInTheDocument(); + // Should not show warning when credentials are configured + expect(screen.queryByText(/No credentials configured/)).not.toBeInTheDocument(); + expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed + }); + + it('shows credentials warning when no credentials are configured', () => { + // Mock git settings with no credentials and mock git status with an https remote + mockUseGitSettings.mockReturnValue({ + settings: { + credentials: {}, + }, + }); + + mockUseGitStatus.mockReturnValue({ + data: { + ...baseGitStatus, + remotes: [{ name: 'origin', url: 'https://github.com/example/repo.git' }], + }, + refetch: mockRefetch, + }); + + render( + + {}}> + + + + ); + + // Should show warning when credentials are missing + expect(screen.getByText(/You are not logged into github.com/)).toBeInTheDocument(); + expect(screen.getByText('log in')).toBeInTheDocument(); + expect(screen.queryByText('Authentication')).not.toBeInTheDocument(); // Authentication section is removed }); }); \ No newline at end of file diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 8c444aff..da1ef12c 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -1,10 +1,9 @@ -import { useState } from 'react'; +import { useState, useEffect } from 'react'; import { useNavigate } from 'react-router-dom'; import { Button } from '@/components/ui/button'; import { Dialog, DialogContent, - DialogDescription, DialogHeader, DialogTitle, DialogTrigger, @@ -19,6 +18,8 @@ import { import { Badge } from '@/components/ui/badge'; import { ScrollArea } from '@/components/ui/scroll-area'; import { Alert, AlertDescription } from '@/components/ui/alert'; +import { Input } from '@/components/ui/input'; +import { Label } from '@/components/ui/label'; import { GitBranch, Upload, @@ -31,9 +32,9 @@ import { Plus, Minus, Edit, - Settings, AlertTriangle, Zap, + Save, } from 'lucide-react'; import { useGitStatus } from '@/hooks/useGitStatus'; import { useGitSettings } from '@/hooks/useGitSettings'; @@ -43,7 +44,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser'; import { useNostr } from '@nostrify/react'; import { useNostrPublish } from '@/hooks/useNostrPublish'; import { cn } from '@/lib/utils'; -import { findCredentialsForRepo, getOriginDisplayName } from '@/lib/gitCredentials'; +import { findCredentialsForRepo } from '@/lib/gitCredentials'; import { nip19 } from 'nostr-tools'; const GRASP_SERVERS = ["git.shakespeare.diy", "relay.ngit.dev", "gitnostr.com"]; @@ -59,8 +60,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const [isPushing, setIsPushing] = useState(false); const [isPulling, setIsPulling] = useState(false); const [isPushingToNostr, setIsPushingToNostr] = useState(false); - const [pushResult, setPushResult] = useState(null); - const [pullResult, setPullResult] = useState(null); + const [originUrl, setOriginUrl] = useState(''); + const [isSavingOrigin, setIsSavingOrigin] = useState(false); const navigate = useNavigate(); const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId); @@ -73,6 +74,70 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog const projectPath = `/projects/${projectId}`; + // Initialize origin URL from git status + useEffect(() => { + if (gitStatus?.remotes) { + const originRemote = gitStatus.remotes.find(remote => remote.name === 'origin'); + setOriginUrl(originRemote?.url || ''); + } + }, [gitStatus?.remotes]); + + const handleSaveOrigin = async () => { + if (!gitStatus?.isGitRepo) { + toast({ + title: "Cannot configure origin", + description: "Not a git repository", + variant: "destructive", + }); + return; + } + + setIsSavingOrigin(true); + + try { + // Remove existing origin if it exists + try { + await git.deleteRemote({ + dir: projectPath, + remote: 'origin', + }); + } catch { + // Ignore if origin doesn't exist + } + + // Add new origin if URL is provided + if (originUrl.trim()) { + await git.addRemote({ + dir: projectPath, + remote: 'origin', + url: originUrl.trim(), + }); + + toast({ + title: "Origin configured", + description: `Origin remote set to ${originUrl.trim()}`, + }); + } else { + toast({ + title: "Origin removed", + description: "Origin remote has been removed", + }); + } + + // Refresh git status after changing origin + await refetchGitStatus(); + } catch (error) { + const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; + toast({ + title: "Failed to configure origin", + description: errorMessage, + variant: "destructive", + }); + } finally { + setIsSavingOrigin(false); + } + }; + const handlePushToNostr = async () => { if (!user) { toast({ @@ -93,7 +158,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } setIsPushingToNostr(true); - setPushResult(null); try { // Check if repo announcement already exists @@ -264,10 +328,8 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog description: "Waiting for GRASP servers to update...", }); - setPushResult(`✅ Successfully published repository to Nostr`); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; - setPushResult(`❌ Push to Nostr failed: ${errorMessage}`); toast({ title: "Push to Nostr failed", description: errorMessage, @@ -307,7 +369,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } setIsPushing(true); - setPushResult(null); try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') @@ -320,7 +381,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog signer: user?.signer, // For signing if pushing to Nostr }); - setPushResult(`✅ Successfully pushed ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} to ${remote.name}/${gitStatus.currentBranch}`); + toast({ title: "Push successful", description: `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} pushed to ${remote.name}/${gitStatus.currentBranch}`, @@ -330,7 +391,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog await refetchGitStatus(); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; - setPushResult(`❌ Push failed: ${errorMessage}`); toast({ title: "Push failed", description: errorMessage, @@ -361,7 +421,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog } setIsPulling(true); - setPullResult(null); try { const remote = gitStatus.remotes[0]; // Use first remote (usually 'origin') @@ -377,7 +436,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog onAuth: (url) => findCredentialsForRepo(url, settings.credentials), }); - setPullResult(`✅ Successfully pulled from ${remote.name}/${gitStatus.currentBranch}`); + toast({ title: "Pull successful", description: `Latest changes pulled from ${remote.name}/${gitStatus.currentBranch}`, @@ -387,7 +446,6 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog await refetchGitStatus(); } catch (error) { const errorMessage = error instanceof Error ? error.message : 'Unknown error occurred'; - setPullResult(`❌ Pull failed: ${errorMessage}`); toast({ title: "Pull failed", description: errorMessage, @@ -472,85 +530,128 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog - Git Repository Status + Repository - - View repository status and sync with remote repositories - + {/* URL Configuration */} + {gitStatus?.isGitRepo && ( + + + Git URL + + +
+
+ + setOriginUrl(e.target.value)} + disabled={isSavingOrigin} + /> +
+ +
+ + {/* Credentials Warning */} + {gitStatus.remotes.length > 0 && ( + (() => { + const remoteWithoutCredentials = gitStatus.remotes.find((remote) => !findCredentialsForRepo(remote.url, settings.credentials)); + if (!remoteWithoutCredentials) return null; + + let protocol = ''; + let hostname = 'the remote host'; + try { + const url = new URL(remoteWithoutCredentials.url); + protocol = url.protocol; + hostname = url.hostname; + } catch { + // Invalid URL + return ( + + + + Invalid URL format. Enter an https URL. + + + ); + } + + // Check for unsupported protocols + if (protocol !== 'https:' && protocol !== 'nostr:') { + return ( + + + + The {protocol.replace(':', '')} URL type is not supported. Enter an https URL. + + + ); + } + + // For nostr protocol, only show warning if user is not logged in + if (protocol === 'nostr:' && !user) { + return ( + + + + You are not logged into Nostr. Push & pull might not work unless you{' '} + . + + + ); + } + + // For https protocol, show warning if no credentials + if (protocol === 'https:') { + return ( + + + + You are not logged into {hostname}. Push & pull might not work unless you{' '} + . + + + ); + } + + return null; + })() + )} +
+
+ )} +
- {/* Credentials Status */} - {gitStatus?.isGitRepo && gitStatus.remotes.length > 0 && ( - - - - Authentication - - - - Credentials for push/pull operations - - - - {gitStatus.remotes.map((remote) => { - const credentials = findCredentialsForRepo(remote.url, settings.credentials); - const originDisplayName = getOriginDisplayName(remote.url); - - return ( -
-
-
- {remote.name} - - {originDisplayName} - -
- {credentials ? ( -
- - Configured -
- ) : ( -
- - No credentials -
- )} -
- - {!credentials && ( - - - - No credentials configured for {originDisplayName}. - Push/pull operations may fail for private repositories.{' '} - - - - )} -
- ); - })} -
-
- )} - {/* Sync Status */} {gitStatus?.isGitRepo && ( @@ -619,21 +720,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
)} - {/* Operation Results */} - {(pushResult || pullResult) && ( -
- {pushResult && ( -
- {pushResult} -
- )} - {pullResult && ( -
- {pullResult} -
- )} -
- )} + )} From 16ee1235d394e7f788de40705ca483d26d6da2ea Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Sun, 21 Sep 2025 23:49:02 -0500 Subject: [PATCH 23/95] Fix Git History overflow --- src/components/ai/GitHistoryDialog.tsx | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index 9381d3a7..e84845a4 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -1,7 +1,6 @@ import { useState, useEffect, useCallback } from 'react'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; -import { ScrollArea } from '@/components/ui/scroll-area'; import { Badge } from '@/components/ui/badge'; import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react'; @@ -289,7 +288,7 @@ ${commitsToRevert.map(c => { )} - + @@ -300,7 +299,7 @@ ${commitsToRevert.map(c => { -
+
{isLoading ? (
@@ -329,7 +328,7 @@ ${commitsToRevert.map(c => {
) : ( - +
{commits.map((commit, index) => { const { firstLine, hasMoreLines, fullMessage } = getCommitMessageLines(commit.commit.message); @@ -340,7 +339,7 @@ ${commitsToRevert.map(c => {
-

+

{firstLine}

{hasMoreLines && ( @@ -440,7 +439,7 @@ ${commitsToRevert.map(c => { ); })}
- +
)}
From 25f11dbe1d4f3e6c59bda7d57ba6a391a48a0232 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Sep 2025 00:02:52 -0500 Subject: [PATCH 24/95] Start simplifying 3-dots menu --- src/components/ActionsMenu.tsx | 21 +---- src/components/AppSettingsDialog.tsx | 108 ------------------------- src/components/ai/GitHistoryDialog.tsx | 25 +++--- 3 files changed, 20 insertions(+), 134 deletions(-) delete mode 100644 src/components/AppSettingsDialog.tsx diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index cb69af3b..ba54787b 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -24,15 +24,13 @@ import { Play, CloudUpload, Loader2, - GitBranch, + History, Download, Trash2, - Settings, GitMerge, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { GitDialog } from '@/components/GitDialog'; -import { AppSettingsDialog } from '@/components/AppSettingsDialog'; import { useNavigate } from 'react-router-dom'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; @@ -222,7 +220,7 @@ export function ActionsMenu({ className="gap-2" > - Git Status + Repository - - Git History + + Rollback - - e.preventDefault()} - > - - Settings - - - { - // Validate deploy server - if (!deployServer.trim()) { - toast({ - title: "Invalid deploy server", - description: "Deploy server cannot be empty.", - variant: "destructive", - }); - return; - } - - // Remove protocol if present - const cleanDeployServer = deployServer.replace(/^https?:\/\//, ''); - - updateConfig((current) => ({ - ...current, - deployServer: cleanDeployServer, - })); - - toast({ - title: "Settings saved", - description: "Your deployment settings have been updated.", - }); - - setOpen(false); - }; - - const handleCancel = () => { - // Reset to current config - setDeployServer(config.deployServer); - setOpen(false); - }; - - return ( - - - {children || ( - - )} - - - - App Settings - - Configure your application preferences and deployment settings. - - - -
- - - Deployment - - -
- - setDeployServer(e.target.value)} - placeholder="shakespeare.wtf" - className="font-mono" - /> -

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

-
-
-
-
- -
- - -
-
-
- ); -} \ No newline at end of file diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index e84845a4..2dc7f3fa 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -1,7 +1,7 @@ import { useState, useEffect, useCallback } from 'react'; import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'; import { Button } from '@/components/ui/button'; -import { Badge } from '@/components/ui/badge'; + import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, AlertDialogTrigger } from '@/components/ui/alert-dialog'; import { History, GitCommit, RotateCcw, AlertTriangle, ChevronDown, ChevronUp } from 'lucide-react'; import { useGit } from '@/hooks/useGit'; @@ -291,11 +291,11 @@ ${commitsToRevert.map(c => { - - Git History + + Rollback - View the commit history for this project + Revert to an older commit @@ -371,7 +371,18 @@ ${commitsToRevert.map(c => {
- {index > 0 && ( // Don't show rollback for the most recent commit + {index === 0 ? ( + // Show "Current" for the most recent commit + + ) : ( + // Show rollback button for older commits
From 6478ed21bb2c742e72ab248bf42d33b0ec5b06c8 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Sep 2025 00:10:08 -0500 Subject: [PATCH 25/95] Remove pointless "File Explorer" header --- src/components/Shakespeare/PreviewPane.tsx | 32 ++++++---------------- src/lib/i18n.ts | 3 -- 2 files changed, 9 insertions(+), 26 deletions(-) diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 7d7ed0d7..19c54fe3 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -536,24 +536,16 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { {isMobile ? (
{mobileCodeView === 'explorer' ? ( - <> -
-
-

{t('fileExplorer')}

- -
+ + +
+
- - -
- -
-
- +
) : ( <>
@@ -604,12 +596,6 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { ) : (
-
-
-

{t('fileExplorer')}

- -
-
diff --git a/src/lib/i18n.ts b/src/lib/i18n.ts index 48e19e05..81a6d02e 100644 --- a/src/lib/i18n.ts +++ b/src/lib/i18n.ts @@ -111,7 +111,6 @@ const resources = { // Preview Pane projectPreview: 'Project Preview', buildProjectToSeePreview: 'Build your project to see the preview here', - fileExplorer: 'File Explorer', fileEditor: 'File Editor', selectFileFromExplorer: 'Select a file from the explorer to edit', openFileExplorer: 'Open File Explorer', @@ -404,7 +403,6 @@ const resources = { // Preview Pane projectPreview: 'Visualização do Projeto', buildProjectToSeePreview: 'Construa seu projeto para ver a visualização aqui', - fileExplorer: 'Explorador de Arquivos', fileEditor: 'Editor de Arquivos', selectFileFromExplorer: 'Selecione um arquivo do explorador para editar', openFileExplorer: 'Abrir Explorador de Arquivos', @@ -697,7 +695,6 @@ const resources = { // Preview Pane projectPreview: '项目预览', buildProjectToSeePreview: '构建您的项目以在此处查看预览', - fileExplorer: '文件浏览器', fileEditor: '文件编辑器', selectFileFromExplorer: '从浏览器中选择一个文件进行编辑', openFileExplorer: '打开文件浏览器', From 369286383028dfc08972d99e0f4a6434b6b50188 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Sep 2025 00:20:56 -0500 Subject: [PATCH 26/95] GitDialog tweaks --- src/components/ActionsMenu.tsx | 4 ++-- src/components/GitDialog.tsx | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index ba54787b..1d18e4bd 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -19,6 +19,7 @@ import { AlertDialogTrigger, } from '@/components/ui/alert-dialog'; import { + GitBranch, MoreHorizontal, MessageSquarePlus, Play, @@ -27,7 +28,6 @@ import { History, Download, Trash2, - GitMerge, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; import { GitDialog } from '@/components/GitDialog'; @@ -219,7 +219,7 @@ export function ActionsMenu({ disabled={isAnyLoading} className="gap-2" > - + Repository diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index da1ef12c..1aa22072 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -526,7 +526,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog return ( {children && {children}} - + e.preventDefault()}> @@ -559,7 +559,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog disabled={isSavingOrigin} variant="outline" size="sm" - className="shrink-0" + className="h-10 shrink-0" > {isSavingOrigin ? ( From 668a6c79d9d5921da3b4ef4c6030af24626f2696 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Sep 2025 01:08:05 -0500 Subject: [PATCH 27/95] Greatly simplify ProjectInfoDialog, move Export Project into there --- src/components/ActionsMenu.tsx | 108 +------ src/components/ProjectInfoDialog.tsx | 409 +++++++-------------------- 2 files changed, 99 insertions(+), 418 deletions(-) diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 1d18e4bd..3a861ec1 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -26,7 +26,6 @@ import { CloudUpload, Loader2, History, - Download, Trash2, } from 'lucide-react'; import { GitHistoryDialog } from '@/components/ai/GitHistoryDialog'; @@ -34,9 +33,6 @@ import { GitDialog } from '@/components/GitDialog'; import { useNavigate } from 'react-router-dom'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useToast } from '@/hooks/useToast'; -import { useGit } from '@/hooks/useGit'; -import { useFS } from '@/hooks/useFS'; -import JSZip from 'jszip'; interface ActionsMenuProps { projectId: string; @@ -68,15 +64,12 @@ export function ActionsMenu({ const [gitHistoryOpen, setGitHistoryOpen] = useState(false); const [gitDialogOpen, setGitDialogOpen] = useState(false); const [isDeleting, setIsDeleting] = useState(false); - const [isExporting, setIsExporting] = useState(false); const navigate = useNavigate(); const projectsManager = useProjectsManager(); const { toast } = useToast(); - const { fs } = useFS(); - const { git } = useGit(); - const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting || isExporting; + const isAnyLoading = isLoading || isBuildLoading || isDeployLoading || isDeleting; const handleDeleteProject = async () => { setIsDeleting(true); @@ -104,92 +97,6 @@ export function ActionsMenu({ } }; - const handleExportProject = async () => { - setIsExporting(true); - try { - const zip = new JSZip(); - const projectPath = `/projects/${projectId}`; - - // Recursive function to add files and directories to zip from a specific project - const addProjectToZip = async (dirPath: string, zipFolder: JSZip) => { - try { - const entries = await fs.readdir(dirPath, { withFileTypes: true }); - - for (const entry of entries) { - const fullPath = `${dirPath}/${entry.name}`; - - if (entry.isDirectory()) { - // Create folder in zip and recursively add its contents - const folder = zipFolder.folder(entry.name); - if (folder) { - await addProjectToZip(fullPath, folder); - } - } else if (entry.isFile()) { - // Add file to zip - try { - const fileContent = await fs.readFile(fullPath); - zipFolder.file(entry.name, fileContent); - } catch (error) { - console.warn(`Failed to read file ${fullPath}:`, error); - } - } - } - } catch (error) { - console.warn(`Failed to read directory ${dirPath}:`, error); - } - }; - - // Start from the project directory - await addProjectToZip(projectPath, zip); - - // Generate zip file - const content = await zip.generateAsync({ type: 'blob' }); - - // Create download link - const url = URL.createObjectURL(content); - const link = document.createElement('a'); - link.href = url; - - // Generate filename with commit hash - let filename = `${projectName}.zip`; - try { - // Get the current commit hash - const commits = await git.log({ - dir: projectPath, - depth: 1, - }); - - if (commits.length > 0) { - const commitHash = commits[0].oid.substring(0, 7); // Truncate to 7 characters - filename = `${projectName}-${commitHash}.zip`; - } - } catch (error) { - console.warn('Failed to get commit hash, using project name only:', error); - } - - link.download = filename; - - document.body.appendChild(link); - link.click(); - document.body.removeChild(link); - URL.revokeObjectURL(url); - - toast({ - title: "Project exported successfully", - description: `"${projectName}" has been downloaded as a zip file.`, - }); - } catch (error) { - console.error('Failed to export project:', error); - toast({ - title: "Failed to export project", - description: error instanceof Error ? error.message : "An unexpected error occurred", - variant: "destructive", - }); - } finally { - setIsExporting(false); - } - }; - return ( <> @@ -232,19 +139,6 @@ export function ActionsMenu({ Rollback - - {isExporting ? ( - - ) : ( - - )} - {isExporting ? 'Exporting...' : 'Export Project'} - - { if (onFirstInteraction) onFirstInteraction(); diff --git a/src/components/ProjectInfoDialog.tsx b/src/components/ProjectInfoDialog.tsx index 33fdf923..0c4bb8cd 100644 --- a/src/components/ProjectInfoDialog.tsx +++ b/src/components/ProjectInfoDialog.tsx @@ -1,36 +1,21 @@ -import { useState, useEffect } from 'react'; +import { useState } from 'react'; import { type Project } from '@/lib/ProjectsManager'; -import { useProjectsManager } from '@/hooks/useProjectsManager'; -import { useGitStatus } from '@/hooks/useGitStatus'; import { Dialog, DialogContent, - DialogDescription, DialogHeader, DialogTitle, } from '@/components/ui/dialog'; -import { Badge } from '@/components/ui/badge'; -import { Separator } from '@/components/ui/separator'; -import { Skeleton } from '@/components/ui/skeleton'; +import { Button } from '@/components/ui/button'; +import { useToast } from '@/hooks/useToast'; +import { useFS } from '@/hooks/useFS'; import { Calendar, Folder, - GitBranch, - Package, - FileText, - GitCommit, - GitMerge, - Globe, - Clock, - User, - Hash, - AlertCircle, - CheckCircle, - Plus, - Minus, - Edit, - Eye + Download, + Loader2, } from 'lucide-react'; +import JSZip from 'jszip'; interface ProjectInfoDialogProps { project: Project; @@ -38,75 +23,10 @@ interface ProjectInfoDialogProps { onOpenChange: (open: boolean) => void; } -interface ProjectMetadata { - description?: string; - version?: string; - nostrRepoAddress?: string; - fileCount?: number; -} - export function ProjectInfoDialog({ project, open, onOpenChange }: ProjectInfoDialogProps) { - const [metadata, setMetadata] = useState({}); - const [isLoading, setIsLoading] = useState(false); - const projectsManager = useProjectsManager(); - const gitStatus = useGitStatus(project.id); - - useEffect(() => { - if (!open) return; - - const loadProjectMetadata = async () => { - setIsLoading(true); - try { - const meta: ProjectMetadata = {}; - - // Try to read package.json - try { - const packageJsonContent = await projectsManager.readFile(project.id, 'package.json'); - const packageJson = JSON.parse(packageJsonContent); - meta.description = packageJson.description; - meta.version = packageJson.version; - } catch { - // package.json doesn't exist or is invalid - } - - // Get Nostr repo address - try { - const repoAddress = await projectsManager.getNostrRepoAddress(project.id); - if (repoAddress) { - meta.nostrRepoAddress = repoAddress; - } - } catch { - // No Nostr repo configured - } - - // Calculate file count and size (simplified) - try { - const files = await projectsManager.listFiles(project.id); - meta.fileCount = files.length; - } catch { - // Can't read directory - } - - setMetadata(meta); - } catch (error) { - console.error('Failed to load project metadata:', error); - } finally { - setIsLoading(false); - } - }; - - loadProjectMetadata(); - }, [open, project.id, projectsManager]); - - const formatDate = (date: Date) => { - return new Intl.DateTimeFormat('en-US', { - year: 'numeric', - month: 'long', - day: 'numeric', - hour: '2-digit', - minute: '2-digit', - }).format(date); - }; + const [isExporting, setIsExporting] = useState(false); + const { toast } = useToast(); + const { fs } = useFS(); const formatDistanceToNow = (date: Date) => { const now = new Date(); @@ -120,239 +40,106 @@ export function ProjectInfoDialog({ project, open, onOpenChange }: ProjectInfoDi return `${Math.floor(diffInSeconds / 31536000)} years ago`; }; + const handleExportProject = async () => { + setIsExporting(true); + try { + const zip = new JSZip(); + const projectPath = `/projects/${project.id}`; + + // Recursive function to add files and directories to zip from a specific project + const addFolderToZip = async (dirPath: string, zipFolder: JSZip) => { + try { + const entries = await fs.readdir(dirPath, { withFileTypes: true }); + + for (const entry of entries) { + const fullPath = `${dirPath}/${entry.name}`; + + if (entry.isDirectory()) { + // Create folder in zip and recursively add its contents + const folder = zipFolder.folder(entry.name); + if (folder) { + await addFolderToZip(fullPath, folder); + } + } else if (entry.isFile()) { + // Add file to zip + try { + const fileContent = await fs.readFile(fullPath); + zipFolder.file(entry.name, fileContent); + } catch (error) { + console.warn(`Failed to read file ${fullPath}:`, error); + } + } + } + } catch (error) { + console.warn(`Failed to read directory ${dirPath}:`, error); + } + }; + + // Start from the project directory + await addFolderToZip(projectPath, zip); + + // Generate zip file + const content = await zip.generateAsync({ type: 'blob' }); + + // Create download link + const url = URL.createObjectURL(content); + const link = document.createElement('a'); + link.href = url; + link.download = `${project.id}.zip`; + document.body.appendChild(link); + link.click(); + document.body.removeChild(link); + URL.revokeObjectURL(url); + + toast({ + title: "Project exported successfully", + description: `"${project.name}" has been downloaded as a zip file.`, + }); + } catch (error) { + console.error('Failed to export project:', error); + toast({ + title: "Failed to export project", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + } finally { + setIsExporting(false); + } + }; + return ( - + {project.name} - - Project information and metadata - - {isLoading ? ( -
-
-
-
-
+
+ {/* Last Modified */} +
+ + Last Modified: + {formatDistanceToNow(project.lastModified)}
- ) : ( -
- {/* Basic Information */} -
-

- Basic Information -

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

{metadata.description}

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

- - Nostr Repository -

-
- Repository Address: - - {metadata.nostrRepoAddress} - -
-
- + {/* Export Project Button */} +
- )} + {isExporting ? 'Exporting...' : 'Export Project'} + +
); From 46a5ca2a1e655bcfb07a89bcb6355197d0278082 Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Sep 2025 01:24:31 -0500 Subject: [PATCH 28/95] Add useBuildProject, useDeployProject hooks --- src/hooks/useBuildProject.ts | 17 ++++++ src/hooks/useDeployProject.ts | 26 ++++++++ src/pages/ProjectView.tsx | 109 ++++++++++++++-------------------- 3 files changed, 86 insertions(+), 66 deletions(-) create mode 100644 src/hooks/useBuildProject.ts create mode 100644 src/hooks/useDeployProject.ts diff --git a/src/hooks/useBuildProject.ts b/src/hooks/useBuildProject.ts new file mode 100644 index 00000000..3fd705db --- /dev/null +++ b/src/hooks/useBuildProject.ts @@ -0,0 +1,17 @@ +import { useMutation } from "@tanstack/react-query"; +import { buildProject } from "@/lib/build"; +import { useFS } from "./useFS"; + +export function useBuildProject(projectId: string) { + const { fs } = useFS(); + + return useMutation({ + mutationFn: async () => { + return await buildProject({ + fs, + projectPath: `/projects/${projectId}`, + domParser: new DOMParser(), + }); + }, + }); +} \ No newline at end of file diff --git a/src/hooks/useDeployProject.ts b/src/hooks/useDeployProject.ts new file mode 100644 index 00000000..9793ee1d --- /dev/null +++ b/src/hooks/useDeployProject.ts @@ -0,0 +1,26 @@ +import { useMutation } from "@tanstack/react-query"; +import { deployProject } from "@/lib/deploy"; +import { useFS } from "./useFS"; +import { useAppContext } from "./useAppContext"; +import { useCurrentUser } from "./useCurrentUser"; + +export function useDeployProject(projectId: string) { + const { fs } = useFS(); + const { user } = useCurrentUser(); + const { config } = useAppContext(); + + return useMutation({ + mutationFn: async () => { + if (!user) { + throw new Error("You must be logged into Nostr to deploy a project"); + } + return await deployProject({ + fs, + projectId: projectId, + deployServer: config.deployServer, + projectPath: `/projects/${projectId}`, + signer: user.signer, + }); + }, + }); +} \ No newline at end of file diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 01e9d2fd..439bf9a1 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -13,18 +13,14 @@ import { Skeleton } from '@/components/ui/skeleton'; import { ArrowLeft, MessageSquare, Eye, Code, Menu } from 'lucide-react'; import { useNavigate } from 'react-router-dom'; import { ActionsMenu } from '@/components/ActionsMenu'; - import { useIsMobile } from '@/hooks/useIsMobile'; -import { useFS } from '@/hooks/useFS'; import { useKeepAlive } from '@/hooks/useKeepAlive'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { StarButton } from '@/components/StarButton'; - -import { buildProject } from "@/lib/build"; -import { deployProject } from "@/lib/deploy"; import { useCurrentUser } from "@/hooks/useCurrentUser"; -import { useAppContext } from "@/hooks/useAppContext"; import { useToast } from "@/hooks/useToast"; +import { useBuildProject } from '@/hooks/useBuildProject'; +import { useDeployProject } from '@/hooks/useDeployProject'; export function ProjectView() { const { projectId } = useParams<{ projectId: string }>(); @@ -33,23 +29,22 @@ export function ProjectView() { const [isLoading, setIsLoading] = useState(true); const [activeTab, setActiveTab] = useState<'preview' | 'code'>('preview'); const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat'); - const [isBuildLoading, setIsBuildLoading] = useState(false); - const [isDeployLoading, setIsDeployLoading] = useState(false); const [isAILoading, setIsAILoading] = useState(false); const [isProjectInfoOpen, setIsProjectInfoOpen] = useState(false); const projectsManager = useProjectsManager(); const chatPaneRef = useRef(null); const navigate = useNavigate(); const isMobile = useIsMobile(); - const { fs } = useFS(); const { user } = useCurrentUser(); - const { config } = useAppContext(); const { toast } = useToast(); const [isSidebarVisible, setIsSidebarVisible] = useState(!isMobile); + const build = useBuildProject(projectId!); + const deploy = useDeployProject(projectId!); + // Keep-alive functionality to prevent tab throttling during AI processing const { updateMetadata } = useKeepAlive({ - enabled: isAILoading || isBuildLoading || isDeployLoading, + enabled: isAILoading || build.isPending || deploy.isPending, title: 'Shakespeare', artist: project ? `Working on ${project.name}...` : 'Working...', artwork: [ @@ -79,28 +74,21 @@ export function ProjectView() { }, [loadProject]); const runBuild = async () => { - if (isBuildLoading || !project) return; - - setIsBuildLoading(true); + if (build.isPending || !project) return; updateMetadata('Shakespeare', `Building ${project.name}...`); - try { - const result = await buildProject({ - fs, - projectPath: `/projects/${project.id}`, - domParser: new DOMParser(), - }); - - console.log('Build completed:', result); - } catch (error) { - console.error('Build failed:', error); - } finally { - setIsBuildLoading(false); - } + await build.mutateAsync(undefined, { + onSuccess(result) { + console.log('Project built:', result); + }, + onError(error) { + console.error('Build failed:', error); + }, + }); }; const runDeploy = async () => { - if (isDeployLoading || !project) return; + if (deploy.isPending || !project) return; // Check if user is logged in if (!user || !user.signer) { @@ -112,38 +100,27 @@ export function ProjectView() { return; } - setIsDeployLoading(true); updateMetadata('Shakespeare', `Deploying ${project.name}...`); - try { - const result = await deployProject({ - projectId: project.id, - deployServer: config.deployServer, - fs, - projectPath: `/projects/${project.id}`, - signer: user.signer, - }); - - console.log('Project deployed:', result.url); - - toast({ - title: "Deployment successful!", - description: `Your project is now live at ${result.hostname}`, - }); - - // Open the deployed site in a new tab - window.open(result.url, '_blank'); - } catch (error) { - console.error('Deploy failed:', error); - - toast({ - title: "Deployment failed", - description: error instanceof Error ? error.message : "An unexpected error occurred", - variant: "destructive", - }); - } finally { - setIsDeployLoading(false); - } + await deploy.mutateAsync(undefined, { + onSuccess(result) { + console.log('Project deployed:', result.url); + toast({ + title: "Deployment successful!", + description: `Your project is now live at ${result.hostname}`, + }); + // Open the deployed site in a new tab + window.open(result.url, '_blank'); + }, + onError(error) { + console.error('Deploy failed:', error); + toast({ + title: "Deployment failed", + description: error instanceof Error ? error.message : "An unexpected error occurred", + variant: "destructive", + }); + }, + }); }; const handleNewChat = () => { @@ -228,8 +205,8 @@ export function ProjectView() { onBuild={runBuild} onDeploy={runDeploy} isLoading={isAILoading} - isBuildLoading={isBuildLoading} - isDeployLoading={isDeployLoading} + isBuildLoading={build.isPending} + isDeployLoading={deploy.isPending} onFirstInteraction={handleFirstInteraction} onProjectDeleted={handleProjectDeleted} /> @@ -283,8 +260,8 @@ export function ProjectView() { onFirstInteraction={handleFirstInteraction} onLoadingChange={handleAILoadingChange} isLoading={isAILoading} - isBuildLoading={isBuildLoading} - isDeployLoading={isDeployLoading} + isBuildLoading={build.isPending} + isDeployLoading={deploy.isPending} /> ) : (
@@ -435,8 +412,8 @@ export function ProjectView() { onBuild={runBuild} onDeploy={runDeploy} isLoading={isAILoading} - isBuildLoading={isBuildLoading} - isDeployLoading={isDeployLoading} + isBuildLoading={build.isPending} + isDeployLoading={deploy.isPending} onFirstInteraction={handleFirstInteraction} onProjectDeleted={handleProjectDeleted} /> @@ -463,8 +440,8 @@ export function ProjectView() { onFirstInteraction={handleFirstInteraction} onLoadingChange={handleAILoadingChange} isLoading={isAILoading} - isBuildLoading={isBuildLoading} - isDeployLoading={isDeployLoading} + isBuildLoading={build.isPending} + isDeployLoading={deploy.isPending} /> ) : (
From 7cbaaec734958d2a6a5c50650bd9c763a46d1abb Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Mon, 22 Sep 2025 01:55:34 -0500 Subject: [PATCH 29/95] Move build button into PreviewPane --- src/components/ActionsMenu.tsx | 19 -- src/components/Shakespeare/PreviewPane.tsx | 248 +++++++++++++-------- src/pages/ProjectView.tsx | 2 - 3 files changed, 156 insertions(+), 113 deletions(-) diff --git a/src/components/ActionsMenu.tsx b/src/components/ActionsMenu.tsx index 3a861ec1..6f9eadad 100644 --- a/src/components/ActionsMenu.tsx +++ b/src/components/ActionsMenu.tsx @@ -22,7 +22,6 @@ import { GitBranch, MoreHorizontal, MessageSquarePlus, - Play, CloudUpload, Loader2, History, @@ -38,7 +37,6 @@ interface ActionsMenuProps { projectId: string; projectName: string; onNewChat: () => void; - onBuild: () => void; onDeploy: () => void; isLoading?: boolean; isBuildLoading?: boolean; @@ -52,7 +50,6 @@ export function ActionsMenu({ projectId, projectName, onNewChat, - onBuild, onDeploy, isLoading = false, isBuildLoading = false, @@ -139,22 +136,6 @@ export function ActionsMenu({ Rollback - { - if (onFirstInteraction) onFirstInteraction(); - onBuild(); - }} - disabled={isAnyLoading} - className="gap-2" - > - {isBuildLoading ? ( - - ) : ( - - )} - {isBuildLoading ? 'Building...' : 'Build'} - - { if (onFirstInteraction) onFirstInteraction(); diff --git a/src/components/Shakespeare/PreviewPane.tsx b/src/components/Shakespeare/PreviewPane.tsx index 19c54fe3..cb1b6571 100644 --- a/src/components/Shakespeare/PreviewPane.tsx +++ b/src/components/Shakespeare/PreviewPane.tsx @@ -3,16 +3,18 @@ import { useState, useEffect, useCallback, useRef } from 'react'; import { useTranslation } from 'react-i18next'; import { useProjectsManager } from '@/hooks/useProjectsManager'; import { useFS } from '@/hooks/useFS'; +import { useBuildProject } from '@/hooks/useBuildProject'; import { Tabs, TabsContent } from '@/components/ui/tabs'; import { ScrollArea, ScrollBar } from '@/components/ui/scroll-area'; import { Button } from '@/components/ui/button'; -import { FolderOpen, ArrowLeft, X, Bug, Copy, Check } from 'lucide-react'; +import { FolderOpen, ArrowLeft, X, Bug, Copy, Check, Play, Loader2, MenuIcon } from 'lucide-react'; import { useIsMobile } from '@/hooks/useIsMobile'; import { GitStatusIndicator } from '@/components/GitStatusIndicator'; import { BrowserAddressBar } from '@/components/ui/browser-address-bar'; import { DropdownMenu, DropdownMenuContent, + DropdownMenuItem, DropdownMenuTrigger, } from '@/components/ui/dropdown-menu'; @@ -79,6 +81,15 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const iframeRef = useRef(null); const { fs } = useFS(); const projectsManager = useProjectsManager(); + const { mutate: buildProject, isPending: isBuildLoading } = useBuildProject(projectId); + + const handleBuildProject = () => { + buildProject(undefined, { + onError: (error) => { + console.error('Build failed:', error); + } + }); + }; const loadFileContent = useCallback(async (filePath: string) => { setIsLoading(true); @@ -132,16 +143,15 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { const refreshIframe = useCallback(() => { if (iframeRef.current) { // Force reload the iframe by updating its src - const currentSrc = iframeRef.current.src; - iframeRef.current.src = ''; + iframeRef.current.src = '/'; // Use a small timeout to ensure the src is cleared before setting it back setTimeout(() => { if (iframeRef.current) { - iframeRef.current.src = currentSrc; + iframeRef.current.src = `https://${projectId}.${IFRAME_DOMAIN}${currentPath}`; } }, 10); } - }, []); + }, [currentPath, projectId]); const navigateToPath = useCallback((path: string) => { if (iframeRef.current) { @@ -399,100 +409,131 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { }; const ConsoleDropdown = () => { - const getLevelColor = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return 'text-red-500'; - case 'warn': return 'text-yellow-500'; - case 'info': return 'text-blue-500'; - case 'debug': return 'text-gray-500'; - default: return 'text-gray-400'; - } - }; + const getLevelColor = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return 'text-red-500'; + case 'warn': return 'text-yellow-500'; + case 'info': return 'text-blue-500'; + case 'debug': return 'text-gray-500'; + default: return 'text-gray-400'; + } + }; - const getLevelIcon = (level: ConsoleMessage['level']) => { - switch (level) { - case 'error': return '!'; - case 'warn': return '⚠'; - case 'info': return 'ℹ'; - case 'debug': return '🔍'; - default: return '•'; - } - }; + const getLevelIcon = (level: ConsoleMessage['level']) => { + switch (level) { + case 'error': return '!'; + case 'warn': return '⚠'; + case 'info': return 'ℹ'; + case 'debug': return '🔍'; + default: return '•'; + } + }; - const clearConsole = () => { - setConsoleMessages([]); - }; + const clearConsole = () => { + setConsoleMessages([]); + }; - const copyMessageToClipboard = async (msg: ConsoleMessage) => { - try { - // Create a formatted string with all message details - const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`; + const copyMessageToClipboard = async (msg: ConsoleMessage) => { + try { + // Create a formatted string with all message details + const formattedMessage = `[${msg.level.toUpperCase()}] ${msg.message}`; - await navigator.clipboard.writeText(formattedMessage); - setCopiedMessageId(msg.id); + await navigator.clipboard.writeText(formattedMessage); + setCopiedMessageId(msg.id); - // Reset the copied state after 2 seconds - setTimeout(() => { - setCopiedMessageId(null); - }, 2000); - } catch (error) { - console.error('Failed to copy message to clipboard:', error); - } - }; + // Reset the copied state after 2 seconds + setTimeout(() => { + setCopiedMessageId(null); + }, 2000); + } catch (error) { + console.error('Failed to copy message to clipboard:', error); + } + }; - return ( - - - - - -
- Console Output ({consoleMessages.length}) - -
- -
- {consoleMessages.length === 0 ? ( -
- No console messages -
- ) : ( - consoleMessages.map((msg) => ( -
-
-
{getLevelIcon(msg.level)} {msg.message}
- -
-
- )) + return ( + + + + + +
+ Console Output ({consoleMessages.length}) +
- -
-
- ); -}; + +
+ {consoleMessages.length === 0 ? ( +
+ No console messages +
+ ) : ( + consoleMessages.map((msg) => ( +
+
+
{getLevelIcon(msg.level)} {msg.message}
+ +
+
+ )) + )} +
+
+ + + ); + }; + + const Menu = () => { + return ( + + + + + + + {isBuildLoading ? ( + + ) : ( + + )} + {isBuildLoading ? 'Building...' : 'Build'} + + + + ); + }; return (
@@ -509,7 +550,12 @@ export function PreviewPane({ projectId, activeTab }: PreviewPaneProps) { onForward={goForward} canGoBack={historyIndex > 0} canGoForward={historyIndex < navigationHistory.length - 1} - extraContent={} + extraContent={( +
+ + +
+ )} />