From d79ed7df68ae4368db020e1d7c2d2d369eeae22b Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Tue, 4 Nov 2025 22:27:15 -0600 Subject: [PATCH] Connect to multiple Nostr relays. Sync NIP-65 relay list --- AGENTS.md | 24 +- src/App.tsx | 20 +- src/components/AppProvider.tsx | 18 +- src/components/AppShowcase.tsx | 10 +- src/components/NostrProvider.tsx | 38 +-- src/components/NostrSync.tsx | 62 +++++ src/components/RelayListManager.tsx | 254 ++++++++++++++++++ src/components/RelaySelector.tsx | 174 ------------ src/components/SentryProvider.test.tsx | 20 +- src/components/auth/AccountSwitcher.test.tsx | 7 - src/components/auth/LoginArea.test.tsx | 6 - .../git/AnnounceRepositoryDialog.tsx | 23 +- src/components/git/PullRequestDialog.tsx | 5 +- src/contexts/AppContext.ts | 13 +- src/hooks/useAIProjectId.test.ts | 5 +- src/hooks/useGit.test.ts | 5 +- src/hooks/useZaps.ts | 7 +- src/locales/en.json | 17 ++ src/pages/NostrSettings.tsx | 7 +- src/test/TestApp.tsx | 7 +- 20 files changed, 468 insertions(+), 254 deletions(-) create mode 100644 src/components/NostrSync.tsx create mode 100644 src/components/RelayListManager.tsx delete mode 100644 src/components/RelaySelector.tsx diff --git a/AGENTS.md b/AGENTS.md index cffde24c..953dbea9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1098,12 +1098,19 @@ The project includes an `AppProvider` that manages global application state incl ```typescript const defaultConfig: AppConfig = { - theme: "light", - relayUrl: "wss://relay.nostr.band", + theme: "system", + relayMetadata: { + relays: [ + { url: 'wss://relay.ditto.pub', read: true, write: true }, + { url: 'wss://relay.nostr.band', read: true, write: true }, + ], + updatedAt: 0, + }, + // ... other config options }; ``` -Preset relays are available including Ditto, Nostr.Band, Damus, and Primal. The app uses local storage to persist user preferences. +The app uses NIP-65 relay lists for managing multiple relays with read/write permissions. Configuration is persisted in local storage. ## Routing @@ -1157,11 +1164,12 @@ The router includes automatic scroll-to-top functionality and a 404 NotFound pag ### Empty States and No Content Found -When no content is found (empty search results, no data available, etc.), display a minimalist empty state with the `RelaySelector` component. This allows users to easily switch relays to discover content from different sources. +When no content is found (empty search results, no data available, etc.), display a minimalist empty state that guides users to take action or provides helpful context. ```tsx -import { RelaySelector } from '@/components/RelaySelector'; import { Card, CardContent } from '@/components/ui/card'; +import { Button } from '@/components/ui/button'; +import { Link } from 'react-router-dom'; // Empty state example
@@ -1169,9 +1177,11 @@ import { Card, CardContent } from '@/components/ui/card';

- No results found. Try another relay? + No results found. Configure your relays to discover more content.

- +
diff --git a/src/App.tsx b/src/App.tsx index 2efc8071..53436598 100644 --- a/src/App.tsx +++ b/src/App.tsx @@ -7,6 +7,7 @@ import { InferSeoMetaPlugin } from '@unhead/addons'; import { Suspense, useEffect } from 'react'; import LightningFS from '@isomorphic-git/lightning-fs'; import NostrProvider from '@/components/NostrProvider'; +import { NostrSync } from '@/components/NostrSync'; import { Toaster } from "@/components/ui/toaster"; import { TooltipProvider } from "@/components/ui/tooltip"; import { NostrLoginProvider } from '@nostrify/react/login'; @@ -89,7 +90,14 @@ const electronPaths = getElectronDefaultPaths(); const defaultConfig: AppConfig = { theme: "system", - relayUrl: "wss://relay.ditto.pub", + relayMetadata: { + relays: [ + { url: 'wss://relay.ditto.pub', read: true, write: true }, + { url: 'wss://relay.nostr.band', read: true, write: true }, + { url: 'wss://relay.primal.net', read: true, write: true }, + ], + updatedAt: 0, + }, projectTemplate: "https://gitlab.com/soapbox-pub/mkstack.git", esmUrl: "https://esm.sh", corsProxy: "https://proxy.shakespeare.diy/?url={href}", @@ -105,13 +113,6 @@ const defaultConfig: AppConfig = { sentryEnabled: true, }; -const presetRelays = [ - { url: 'wss://relay.ditto.pub', name: 'Ditto' }, - { url: 'wss://relay.nostr.band', name: 'Nostr.Band' }, - { url: 'wss://relay.damus.io', name: 'Damus' }, - { url: 'wss://relay.primal.net', name: 'Primal' }, -]; - // Initialize filesystem adapter based on environment // In Electron, use Electron filesystem at ~/shakespeare // In browser, use LightningFS (IndexedDB-backed virtual filesystem) @@ -138,13 +139,14 @@ export function App() { - + + diff --git a/src/components/AppProvider.tsx b/src/components/AppProvider.tsx index 3acce193..3e98e979 100644 --- a/src/components/AppProvider.tsx +++ b/src/components/AppProvider.tsx @@ -1,7 +1,7 @@ import { ReactNode, useEffect } from 'react'; import { z } from 'zod'; import { useLocalStorage } from '@/hooks/useLocalStorage'; -import { AppContext, type AppConfig, type AppContextType, type Theme } from '@/contexts/AppContext'; +import { AppContext, type AppConfig, type AppContextType, type Theme, type RelayMetadata } from '@/contexts/AppContext'; import i18n from '@/lib/i18n'; interface AppProviderProps { @@ -10,14 +10,22 @@ interface AppProviderProps { storageKey: string; /** Default app configuration */ defaultConfig: AppConfig; - /** Optional list of preset relays to display in the RelaySelector */ - presetRelays?: { name: string; url: string }[]; } +// Zod schema for RelayMetadata +const RelayMetadataSchema = z.object({ + relays: z.array(z.object({ + url: z.string().url(), + read: z.boolean(), + write: z.boolean(), + })), + updatedAt: z.number(), +}) satisfies z.ZodType; + // Zod schema for AppConfig validation const AppConfigSchema = z.object({ theme: z.enum(['dark', 'light', 'system']), - relayUrl: z.string().url(), + relayMetadata: RelayMetadataSchema, projectTemplate: z.string().url(), esmUrl: z.string().url(), corsProxy: z.string().url(), @@ -39,7 +47,6 @@ export function AppProvider(props: AppProviderProps) { children, storageKey, defaultConfig, - presetRelays, } = props; // App configuration state with localStorage persistence @@ -71,7 +78,6 @@ export function AppProvider(props: AppProviderProps) { const appContextValue: AppContextType = { config, updateConfig, - presetRelays, }; // Apply theme effects to document diff --git a/src/components/AppShowcase.tsx b/src/components/AppShowcase.tsx index e25c0f91..ad91ca20 100644 --- a/src/components/AppShowcase.tsx +++ b/src/components/AppShowcase.tsx @@ -12,9 +12,10 @@ import { nip19 } from 'nostr-tools'; import { shuffleArray } from "@/lib/utils"; import { Skeleton } from "@/components/ui/skeleton"; import { Card, CardContent } from "@/components/ui/card"; -import { RelaySelector } from "@/components/RelaySelector"; import { useAppContext } from "@/hooks/useAppContext"; import { useTranslation } from 'react-i18next'; +import { Link } from 'react-router-dom'; +import { Settings } from 'lucide-react'; export function AppShowcase() { const { t } = useTranslation(); @@ -105,7 +106,12 @@ export function AppShowcase() {

{t('noAppsFound')}

- +
diff --git a/src/components/NostrProvider.tsx b/src/components/NostrProvider.tsx index 6cf60289..535e559f 100644 --- a/src/components/NostrProvider.tsx +++ b/src/components/NostrProvider.tsx @@ -17,7 +17,7 @@ const GIT_KINDS = [ const NostrProvider: React.FC = (props) => { const { children } = props; - const { config, presetRelays } = useAppContext(); + const { config } = useAppContext(); const gitRelays = config.ngitServers.map(server => `wss://${server}/`); const queryClient = useQueryClient(); @@ -26,13 +26,13 @@ const NostrProvider: React.FC = (props) => { const pool = useRef(undefined); // Use refs so the pool always has the latest data - const relayUrl = useRef(config.relayUrl); + const relayMetadata = useRef(config.relayMetadata); // Update refs when config changes useEffect(() => { - relayUrl.current = config.relayUrl; + relayMetadata.current = config.relayMetadata; queryClient.invalidateQueries({ queryKey: ['nostr'] }); - }, [config.relayUrl, queryClient]); + }, [config.relayMetadata, queryClient]); // Initialize NPool only once if (!pool.current) { @@ -42,19 +42,32 @@ const NostrProvider: React.FC = (props) => { }, reqRouter(filters) { const routes = new Map(); - routes.set(relayUrl.current, filters); + // Route to all read relays + const readRelays = relayMetadata.current.relays + .filter(r => r.read) + .map(r => r.url); + + for (const url of readRelays) { + routes.set(url, filters); + } + + // If all filters are git-related, also route to all git relays 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 gitRelays) { routes.set(url, filters); } } + return routes; }, eventRouter(event: NostrEvent) { - // Publish to the selected relay - const allRelays = new Set([relayUrl.current]); + // Get write relays from metadata + const writeRelays = relayMetadata.current.relays + .filter(r => r.write) + .map(r => r.url); + + const allRelays = new Set(writeRelays); // If it's a git-related event, also publish to the git relays if (GIT_KINDS.includes(event.kind)) { @@ -63,15 +76,6 @@ const NostrProvider: React.FC = (props) => { } } - // Also publish to the preset relays, capped to 5 - for (const { url } of (presetRelays ?? [])) { - allRelays.add(url); - - if (allRelays.size >= 5) { - break; - } - } - return [...allRelays]; }, }); diff --git a/src/components/NostrSync.tsx b/src/components/NostrSync.tsx new file mode 100644 index 00000000..d637ad0e --- /dev/null +++ b/src/components/NostrSync.tsx @@ -0,0 +1,62 @@ +import { useEffect } from 'react'; +import { useNostr } from '@nostrify/react'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useAppContext } from '@/hooks/useAppContext'; + +/** + * NostrSync - Syncs user's Nostr data + * + * This component runs globally to sync various Nostr data when the user logs in. + * Currently syncs: + * - NIP-65 relay list (kind 10002) + */ +export function NostrSync() { + const { nostr } = useNostr(); + const { user } = useCurrentUser(); + const { config, updateConfig } = useAppContext(); + + useEffect(() => { + if (!user) return; + + const syncRelaysFromNostr = async () => { + try { + const events = await nostr.query( + [{ kinds: [10002], authors: [user.pubkey], limit: 1 }], + { signal: AbortSignal.timeout(5000) } + ); + + if (events.length > 0) { + const event = events[0]; + + // Only update if the event is newer than our stored data + if (event.created_at > config.relayMetadata.updatedAt) { + const fetchedRelays = event.tags + .filter(([name]) => name === 'r') + .map(([_, url, marker]) => ({ + url, + read: !marker || marker === 'read', + write: !marker || marker === 'write', + })); + + if (fetchedRelays.length > 0) { + console.log('Syncing relay list from Nostr:', fetchedRelays); + updateConfig((current) => ({ + ...current, + relayMetadata: { + relays: fetchedRelays, + updatedAt: event.created_at, + }, + })); + } + } + } + } catch (error) { + console.error('Failed to sync relays from Nostr:', error); + } + }; + + syncRelaysFromNostr(); + }, [user, config.relayMetadata.updatedAt, nostr, updateConfig]); + + return null; +} diff --git a/src/components/RelayListManager.tsx b/src/components/RelayListManager.tsx new file mode 100644 index 00000000..67776e47 --- /dev/null +++ b/src/components/RelayListManager.tsx @@ -0,0 +1,254 @@ +import { useState, useEffect } from 'react'; +import { Plus, X, Wifi } from 'lucide-react'; +import { useTranslation } from 'react-i18next'; +import { Button } from '@/components/ui/button'; +import { Label } from '@/components/ui/label'; +import { Input } from '@/components/ui/input'; +import { Switch } from '@/components/ui/switch'; +import { useAppContext } from '@/hooks/useAppContext'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; +import { toast } from '@/hooks/useToast'; + +interface Relay { + url: string; + read: boolean; + write: boolean; +} + +export function RelayListManager() { + const { t } = useTranslation(); + const { config, updateConfig } = useAppContext(); + const { user } = useCurrentUser(); + const { mutate: publishEvent } = useNostrPublish(); + + const [relays, setRelays] = useState(config.relayMetadata.relays); + const [newRelayUrl, setNewRelayUrl] = useState(''); + + // Sync local state with config when it changes (e.g., from NostrProvider sync) + useEffect(() => { + setRelays(config.relayMetadata.relays); + }, [config.relayMetadata.relays]); + + const normalizeRelayUrl = (url: string): string => { + const trimmed = url.trim(); + if (!trimmed) return trimmed; + + if (trimmed.includes('://')) { + return trimmed; + } + + return `wss://${trimmed}`; + }; + + const isValidRelayUrl = (url: string): boolean => { + const trimmed = url.trim(); + if (!trimmed) return false; + + const normalized = normalizeRelayUrl(trimmed); + try { + new URL(normalized); + return true; + } catch { + return false; + } + }; + + const handleAddRelay = () => { + if (!isValidRelayUrl(newRelayUrl)) { + toast({ + title: t('invalidRelayUrl'), + description: t('invalidRelayUrlDescription'), + variant: 'destructive', + }); + return; + } + + const normalized = normalizeRelayUrl(newRelayUrl); + + if (relays.some(r => r.url === normalized)) { + toast({ + title: t('relayAlreadyExists'), + description: t('relayAlreadyExistsDescription'), + variant: 'destructive', + }); + return; + } + + const newRelays = [...relays, { url: normalized, read: true, write: true }]; + setRelays(newRelays); + setNewRelayUrl(''); + + saveRelays(newRelays); + }; + + const handleRemoveRelay = (url: string) => { + const newRelays = relays.filter(r => r.url !== url); + setRelays(newRelays); + saveRelays(newRelays); + }; + + const handleToggleRead = (url: string) => { + const newRelays = relays.map(r => + r.url === url ? { ...r, read: !r.read } : r + ); + setRelays(newRelays); + saveRelays(newRelays); + }; + + const handleToggleWrite = (url: string) => { + const newRelays = relays.map(r => + r.url === url ? { ...r, write: !r.write } : r + ); + setRelays(newRelays); + saveRelays(newRelays); + }; + + const saveRelays = (newRelays: Relay[]) => { + const now = Math.floor(Date.now() / 1000); + + // Update local config + updateConfig((current) => ({ + ...current, + relayMetadata: { + relays: newRelays, + updatedAt: now, + }, + })); + + // Publish to Nostr if user is logged in + if (user) { + publishNIP65RelayList(newRelays); + } + }; + + const publishNIP65RelayList = (relayList: Relay[]) => { + const tags = relayList.map(relay => { + if (relay.read && relay.write) { + return ['r', relay.url]; + } else if (relay.read) { + return ['r', relay.url, 'read']; + } else if (relay.write) { + return ['r', relay.url, 'write']; + } + // If neither read nor write, don't include (shouldn't happen) + return null; + }).filter((tag): tag is string[] => tag !== null); + + publishEvent( + { + kind: 10002, + content: '', + tags, + }, + { + onSuccess: () => { + toast({ + title: t('relayListPublished'), + description: t('relayListPublishedDescription'), + }); + }, + onError: (error) => { + console.error('Failed to publish relay list:', error); + toast({ + title: t('relayListPublishFailed'), + description: t('relayListPublishFailedDescription'), + variant: 'destructive', + }); + }, + } + ); + }; + + return ( +
+ {/* Relay List */} +
+ {relays.map((relay) => ( +
+ + + {relay.url.replace(/^wss?:\/\//, '')} + + + {/* Read Switch */} +
+ + handleToggleRead(relay.url)} + className="data-[state=checked]:bg-green-500" + /> +
+ + {/* Write Switch */} +
+ + handleToggleWrite(relay.url)} + className="data-[state=checked]:bg-blue-500" + /> +
+ + {/* Remove Button */} + +
+ ))} +
+ + {/* Add Relay Form */} +
+
+ + setNewRelayUrl(e.target.value)} + onKeyDown={(e) => { + if (e.key === 'Enter') { + handleAddRelay(); + } + }} + /> +
+ +
+ + {!user && ( +

+ {t('loginToSyncRelays')} +

+ )} +
+ ); +} diff --git a/src/components/RelaySelector.tsx b/src/components/RelaySelector.tsx deleted file mode 100644 index afdd6588..00000000 --- a/src/components/RelaySelector.tsx +++ /dev/null @@ -1,174 +0,0 @@ -import { Check, ChevronsUpDown, Wifi, Plus } from "lucide-react"; -import { cn } from "@/lib/utils"; -import { Button } from "@/components/ui/button"; -import { - Command, - CommandEmpty, - CommandGroup, - CommandInput, - CommandItem, - CommandList, -} from "@/components/ui/command"; -import { - Popover, - PopoverContent, - PopoverTrigger, -} from "@/components/ui/popover"; -import { useState } from "react"; -import { useAppContext } from "@/hooks/useAppContext"; - -interface RelaySelectorProps { - className?: string; -} - -export function RelaySelector(props: RelaySelectorProps) { - const { className } = props; - const { config, updateConfig, presetRelays = [] } = useAppContext(); - - const selectedRelay = config.relayUrl; - const setSelectedRelay = (relay: string) => { - updateConfig((current) => ({ ...current, relayUrl: relay })); - }; - - const [open, setOpen] = useState(false); - const [inputValue, setInputValue] = useState(""); - - const selectedOption = presetRelays.find((option) => option.url === selectedRelay); - - // Function to normalize relay URL by adding wss:// if no protocol is present - const normalizeRelayUrl = (url: string): string => { - const trimmed = url.trim(); - if (!trimmed) return trimmed; - - // Check if it already has a protocol - if (trimmed.includes('://')) { - return trimmed; - } - - // Add wss:// prefix - return `wss://${trimmed}`; - }; - - // Handle adding a custom relay - const handleAddCustomRelay = (url: string) => { - setSelectedRelay?.(normalizeRelayUrl(url)); - setOpen(false); - setInputValue(""); - }; - - // Check if input value looks like a valid relay URL - const isValidRelayInput = (value: string): boolean => { - const trimmed = value.trim(); - if (!trimmed) return false; - - // Basic validation - should contain at least a domain-like structure - const normalized = normalizeRelayUrl(trimmed); - try { - new URL(normalized); - return true; - } catch { - return false; - } - }; - - return ( - - - - - - - - - - {inputValue && isValidRelayInput(inputValue) ? ( - handleAddCustomRelay(inputValue)} - className="cursor-pointer" - > - -
- Add custom relay - - {normalizeRelayUrl(inputValue)} - -
-
- ) : ( -
- {inputValue ? "Invalid relay URL" : "No relay found."} -
- )} -
- - {presetRelays - .filter((option) => - !inputValue || - option.name.toLowerCase().includes(inputValue.toLowerCase()) || - option.url.toLowerCase().includes(inputValue.toLowerCase()) - ) - .map((option) => ( - { - setSelectedRelay(normalizeRelayUrl(currentValue)); - setOpen(false); - setInputValue(""); - }} - > - -
- {option.name} - {option.url} -
-
- ))} - {inputValue && isValidRelayInput(inputValue) && ( - handleAddCustomRelay(inputValue)} - className="cursor-pointer border-t" - > - -
- Add custom relay - - {normalizeRelayUrl(inputValue)} - -
-
- )} -
-
-
-
-
- ); -} \ No newline at end of file diff --git a/src/components/SentryProvider.test.tsx b/src/components/SentryProvider.test.tsx index c81b055c..fcca4b97 100644 --- a/src/components/SentryProvider.test.tsx +++ b/src/components/SentryProvider.test.tsx @@ -23,7 +23,10 @@ describe('SentryProvider', () => { sentryDsn: 'https://test@sentry.io/123', sentryEnabled: true, theme: 'light' as const, - relayUrl: 'wss://relay.test', + relayMetadata: { + relays: [{ url: 'wss://relay.test', read: true, write: true }], + updatedAt: 0, + }, projectTemplate: 'https://test.git', esmUrl: 'https://esm.test', corsProxy: 'https://proxy.test/{href}', @@ -55,7 +58,10 @@ describe('SentryProvider', () => { sentryDsn: '', sentryEnabled: true, theme: 'light' as const, - relayUrl: 'wss://relay.test', + relayMetadata: { + relays: [{ url: 'wss://relay.test', read: true, write: true }], + updatedAt: 0, + }, projectTemplate: 'https://test.git', esmUrl: 'https://esm.test', corsProxy: 'https://proxy.test/{href}', @@ -88,7 +94,10 @@ describe('SentryProvider', () => { sentryDsn: 'https://test@sentry.io/123', sentryEnabled: false, theme: 'light' as const, - relayUrl: 'wss://relay.test', + relayMetadata: { + relays: [{ url: 'wss://relay.test', read: true, write: true }], + updatedAt: 0, + }, projectTemplate: 'https://test.git', esmUrl: 'https://esm.test', corsProxy: 'https://proxy.test/{href}', @@ -124,7 +133,10 @@ describe('SentryProvider', () => { sentryDsn: '', sentryEnabled: false, theme: 'light' as const, - relayUrl: 'wss://relay.test', + relayMetadata: { + relays: [{ url: 'wss://relay.test', read: true, write: true }], + updatedAt: 0, + }, projectTemplate: 'https://test.git', esmUrl: 'https://esm.test', corsProxy: 'https://proxy.test/{href}', diff --git a/src/components/auth/AccountSwitcher.test.tsx b/src/components/auth/AccountSwitcher.test.tsx index 5899e82b..4830e066 100644 --- a/src/components/auth/AccountSwitcher.test.tsx +++ b/src/components/auth/AccountSwitcher.test.tsx @@ -9,13 +9,6 @@ vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() })); -// Mock the RelaySelector component -vi.mock('@/components/RelaySelector', () => ({ - RelaySelector: ({ className }: { className?: string }) => ( -
Relay Selector
- ) -})); - const mockUseLoggedInAccounts = vi.mocked(useLoggedInAccounts); describe('AccountSwitcher', () => { diff --git a/src/components/auth/LoginArea.test.tsx b/src/components/auth/LoginArea.test.tsx index 91e3a537..541670db 100644 --- a/src/components/auth/LoginArea.test.tsx +++ b/src/components/auth/LoginArea.test.tsx @@ -29,12 +29,6 @@ vi.mock('react-router-dom', () => ({ useNavigate: () => vi.fn() })); -vi.mock('@/components/RelaySelector', () => ({ - RelaySelector: ({ className }: { className?: string }) => ( -
Relay Selector
- ) -})); - vi.mock('./SimpleLoginDialog', () => ({ default: ({ isOpen }: { isOpen: boolean; onClose: () => void }) => isOpen ?
Login Dialog
: null diff --git a/src/components/git/AnnounceRepositoryDialog.tsx b/src/components/git/AnnounceRepositoryDialog.tsx index 706eb28c..5a010663 100644 --- a/src/components/git/AnnounceRepositoryDialog.tsx +++ b/src/components/git/AnnounceRepositoryDialog.tsx @@ -160,14 +160,17 @@ export function AnnounceRepositoryDialog({ const relayUrls = config.ngitServers.map(server => `wss://${server}`); setRelays(relayUrls); } else { - // Fallback to default relay if no ngitServers configured - setRelays([config.relayUrl || 'wss://relay.nostr.band']); + // Fallback to write relays if no ngitServers configured + const writeRelays = config.relayMetadata.relays + .filter(r => r.write) + .map(r => r.url); + setRelays(writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']); } } // Get earliest commit await getEarliestCommit(); - }, [projectId, config.relayUrl, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]); + }, [projectId, config.relayMetadata, config.ngitServers, user?.pubkey, getEarliestCommit, cloneUrls.length, relays.length]); // Load existing repository data if editing useEffect(() => { @@ -191,9 +194,12 @@ export function AnnounceRepositoryDialog({ }; const signal = AbortSignal.timeout(3000); + const readRelays = config.relayMetadata.relays + .filter(r => r.read) + .map(r => r.url); const events = await nostr.query([filter], { signal, - relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : [config.relayUrl] + relays: naddrRelays && naddrRelays.length > 0 ? naddrRelays : readRelays }); if (events.length === 0) { @@ -236,7 +242,7 @@ export function AnnounceRepositoryDialog({ prepopulateFields(); setIsPrepopulated(true); } - }, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayUrl, toast]); + }, [isOpen, isPrepopulated, prepopulateFields, editNaddr, nostr, config.relayMetadata, toast]); const addWebUrl = () => { if (newWebUrl.trim() && !webUrls.includes(newWebUrl.trim())) { @@ -326,8 +332,11 @@ export function AnnounceRepositoryDialog({ console.log('Event coordinate:', `30617:${user.pubkey}:${repoId.trim()}`); // Publish to Nostr relays - // Repository announcements go to: global relayUrl + relays specified in the announcement - const publishRelays = [config.relayUrl, ...relays]; + // Repository announcements go to: write relays + relays specified in the announcement + const writeRelays = config.relayMetadata.relays + .filter(r => r.write) + .map(r => r.url); + const publishRelays = [...new Set([...writeRelays, ...relays])]; console.log('Publishing repository announcement to relays:', publishRelays); await nostr.event(signedEvent, { relays: publishRelays }); diff --git a/src/components/git/PullRequestDialog.tsx b/src/components/git/PullRequestDialog.tsx index 5711041c..7772f2ff 100644 --- a/src/components/git/PullRequestDialog.tsx +++ b/src/components/git/PullRequestDialog.tsx @@ -708,7 +708,10 @@ export function PullRequestDialog({ console.log(`Repository announcement query returned ${repoEvents.length} events`); let earliestUniqueCommit: string | null = null; - let publishRelays = [config.relayUrl]; // Use configured relay + const writeRelays = config.relayMetadata.relays + .filter(r => r.write) + .map(r => r.url); + let publishRelays = writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band']; // Use write relays if (repoEvents.length > 0) { const repoEvent = repoEvents[0]; diff --git a/src/contexts/AppContext.ts b/src/contexts/AppContext.ts index d1ac8228..7fd99395 100644 --- a/src/contexts/AppContext.ts +++ b/src/contexts/AppContext.ts @@ -2,11 +2,18 @@ import { createContext } from "react"; export type Theme = "dark" | "light" | "system"; +export interface RelayMetadata { + /** List of relays with read/write permissions */ + relays: { url: string; read: boolean; write: boolean }[]; + /** Unix timestamp of when the relay list was last updated */ + updatedAt: number; +} + export interface AppConfig { /** Current theme */ theme: Theme; - /** Selected relay URL */ - relayUrl: string; + /** NIP-65 relay list metadata */ + relayMetadata: RelayMetadata; /** Git repository URL to use as project template */ projectTemplate: string; /** ESM CDN URL for package imports */ @@ -42,8 +49,6 @@ export interface AppContextType { config: AppConfig; /** Update configuration using a callback that receives current config and returns new config */ updateConfig: (updater: (currentConfig: Partial) => Partial) => void; - /** Optional list of preset relays to display in the RelaySelector */ - presetRelays?: { name: string; url: string }[]; } export const AppContext = createContext(undefined); diff --git a/src/hooks/useAIProjectId.test.ts b/src/hooks/useAIProjectId.test.ts index 3b3f25b7..b4c10752 100644 --- a/src/hooks/useAIProjectId.test.ts +++ b/src/hooks/useAIProjectId.test.ts @@ -41,7 +41,10 @@ describe('useAIProjectId', () => { mockUseAppContext.mockReturnValue({ config: { theme: 'dark', - relayUrl: 'wss://relay.damus.io', + relayMetadata: { + relays: [{ url: 'wss://relay.damus.io', read: true, write: true }], + updatedAt: 0, + }, projectTemplate: 'https://github.com/example/template', esmUrl: 'https://esm.sh', corsProxy: 'https://proxy.example.com/{href}', diff --git a/src/hooks/useGit.test.ts b/src/hooks/useGit.test.ts index e23deaec..288d2fa1 100644 --- a/src/hooks/useGit.test.ts +++ b/src/hooks/useGit.test.ts @@ -33,7 +33,10 @@ function createWrapper(corsProxy: string) { return function Wrapper({ children }: { children: React.ReactNode }) { const defaultConfig: AppConfig = { theme: 'light', - relayUrl: 'wss://relay.test', + relayMetadata: { + relays: [{ url: 'wss://relay.test', read: true, write: true }], + updatedAt: 0, + }, projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git', esmUrl: 'https://esm.test', corsProxy, diff --git a/src/hooks/useZaps.ts b/src/hooks/useZaps.ts index 4246bf55..08ac6b36 100644 --- a/src/hooks/useZaps.ts +++ b/src/hooks/useZaps.ts @@ -194,10 +194,13 @@ export function useZaps( const zapAmount = amount * 1000; // convert to millisats + const writeRelays = config.relayMetadata.relays + .filter(r => r.write) + .map(r => r.url); const zapRequest = nip57.makeZapRequest({ event: actualTarget, amount: zapAmount, - relays: [config.relayUrl], + relays: writeRelays.length > 0 ? writeRelays : ['wss://relay.nostr.band'], comment }); @@ -255,7 +258,7 @@ export function useZaps( }); } } - + if (webln) { // Try WebLN next try { await webln.sendPayment(newInvoice); diff --git a/src/locales/en.json b/src/locales/en.json index 75eb8caa..594414fa 100644 --- a/src/locales/en.json +++ b/src/locales/en.json @@ -300,6 +300,23 @@ "addAccount": "Add Account", "relayConfiguration": "Relay Configuration", "selectedRelay": "Selected Relay", + "read": "Read", + "write": "Write", + "relayUrl": "Relay URL", + "enterRelayUrl": "Enter relay URL (e.g., relay.ditto.pub)", + "addRelay": "Add Relay", + "invalidRelayUrl": "Invalid Relay URL", + "invalidRelayUrlDescription": "Please enter a valid relay URL.", + "relayAlreadyExists": "Relay Already Exists", + "relayAlreadyExistsDescription": "This relay is already in your list.", + "relayListPublished": "Relay List Published", + "relayListPublishedDescription": "Your relay list has been published to Nostr.", + "relayListPublishFailed": "Failed to Publish Relay List", + "relayListPublishFailedDescription": "Could not publish your relay list to Nostr.", + "syncingRelays": "Syncing relays from Nostr...", + "relaysSynced": "Relays Synced", + "relaysSyncedDescription": "Your relay list has been synced from Nostr.", + "loginToSyncRelays": "Log in to automatically sync your relay list with Nostr.", "nostrGitServers": "Nostr Git Servers", "addServer": "Add Server", "serverHostname": "Server Hostname", diff --git a/src/pages/NostrSettings.tsx b/src/pages/NostrSettings.tsx index f8108439..bda06180 100644 --- a/src/pages/NostrSettings.tsx +++ b/src/pages/NostrSettings.tsx @@ -6,7 +6,7 @@ import { Input } from '@/components/ui/input'; 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 { RelayListManager } from '@/components/RelayListManager'; import SimpleLoginDialog from '@/components/auth/SimpleLoginDialog'; import SimpleSignupDialog from '@/components/auth/SimpleSignupDialog'; import { useIsMobile } from '@/hooks/useIsMobile'; @@ -299,10 +299,7 @@ export function NostrSettings() { -
- - -
+
diff --git a/src/test/TestApp.tsx b/src/test/TestApp.tsx index ae134a43..0f73ebbc 100644 --- a/src/test/TestApp.tsx +++ b/src/test/TestApp.tsx @@ -29,7 +29,12 @@ export function TestApp({ children }: TestAppProps) { const defaultConfig: AppConfig = { theme: 'light', - relayUrl: 'wss://relay.nostr.band', + relayMetadata: { + relays: [ + { url: 'wss://relay.nostr.band', read: true, write: true }, + ], + updatedAt: 0, + }, projectTemplate: 'https://gitlab.com/soapbox-pub/mkstack.git', esmUrl: 'https://esm.shakespeare.diy', corsProxy: 'https://proxy.shakespeare.diy/?url={href}',