From ed55e600d4654621040aeff772b7fbeb5c212a4d Mon Sep 17 00:00:00 2001 From: Alex Gleason Date: Thu, 2 Apr 2026 01:36:15 -0500 Subject: [PATCH] Add NIP-89 kind 31990 app management for projects - AppDialog with app preview card, Blossom icon upload, and collapsible advanced section - AppTool for AI to view/update app with view-before-update guard - Shared buildAppEvent utility for DRY event construction - Auto-fill website from deployment URL, default name from project ID - Add repo 'a' tag when origin is a nostr:// URI owned by the user - Custom tool call rendering with AppWindow icon - System prompt guidance for app publishing workflow and prerequisites - Store app coordinate in .git/shakespeare/app.json via DotAI --- src/components/AppDialog.tsx | 567 ++++++++++++++++++++++++ src/components/ProjectTitleMenu.tsx | 12 + src/components/Shakespeare/ChatPane.tsx | 10 +- src/components/ToolCallDisplay.tsx | 20 + src/hooks/useAppEvent.ts | 104 +++++ src/lib/DotAI.ts | 43 ++ src/lib/appEvent.ts | 89 ++++ src/lib/system.ts | 24 +- src/lib/tools/AppTool.ts | 276 ++++++++++++ src/pages/ProjectView.tsx | 9 + 10 files changed, 1152 insertions(+), 2 deletions(-) create mode 100644 src/components/AppDialog.tsx create mode 100644 src/hooks/useAppEvent.ts create mode 100644 src/lib/appEvent.ts create mode 100644 src/lib/tools/AppTool.ts diff --git a/src/components/AppDialog.tsx b/src/components/AppDialog.tsx new file mode 100644 index 00000000..4e6ad802 --- /dev/null +++ b/src/components/AppDialog.tsx @@ -0,0 +1,567 @@ +import { useState, useEffect, useCallback, useRef } from 'react'; +import { + Dialog, + DialogContent, + DialogHeader, + DialogTitle, + DialogDescription, +} from '@/components/ui/dialog'; +import { Collapsible, CollapsibleContent, CollapsibleTrigger } from '@/components/ui/collapsible'; +import { Button } from '@/components/ui/button'; +import { Input } from '@/components/ui/input'; +import { Textarea } from '@/components/ui/textarea'; +import { Label } from '@/components/ui/label'; +import { Skeleton } from '@/components/ui/skeleton'; +import { Badge } from '@/components/ui/badge'; +import { Avatar, AvatarImage, AvatarFallback } from '@/components/ui/avatar'; +import { useToast } from '@/hooks/useToast'; +import { useFS } from '@/hooks/useFS'; +import { useFSPaths } from '@/hooks/useFSPaths'; +import { useCurrentUser } from '@/hooks/useCurrentUser'; +import { useNostrPublish } from '@/hooks/useNostrPublish'; +import { useUploadFile } from '@/hooks/useUploadFile'; +import { useAppEvent } from '@/hooks/useAppEvent'; +import { useProjectDeploySettings } from '@/hooks/useProjectDeploySettings'; +import { useQueryClient } from '@tanstack/react-query'; +import { DotAI } from '@/lib/DotAI'; +import { buildAppEvent } from '@/lib/appEvent'; +import { + Loader2, + Save, + Plus, + X, + ExternalLink, + Pencil, + Upload, + ChevronDown, + CircleHelp, +} from 'lucide-react'; +import type { NostrEvent } from '@nostrify/nostrify'; + +interface AppDialogProps { + projectId: string; + open: boolean; + onOpenChange: (open: boolean) => void; +} + +interface AppFormData { + name: string; + about: string; + picture: string; + website: string; + dTag: string; + supportedKinds: string[]; + webHandlers: Array<{ url: string; type: string }>; +} + +/** Parse a kind 31990 event into form data */ +function eventToFormData(event: NostrEvent): AppFormData { + let metadata: Record = {}; + try { + if (event.content) { + metadata = JSON.parse(event.content); + } + } catch { + // Invalid JSON content, use empty metadata + } + + const dTag = event.tags.find(([t]) => t === 'd')?.[1] ?? ''; + const supportedKinds = event.tags + .filter(([t]) => t === 'k') + .map(([, v]) => v) + .filter(Boolean); + + const webHandlers = event.tags + .filter(([t]) => t === 'web') + .map(([, url, type]) => ({ url: url ?? '', type: type ?? '' })); + + return { + name: metadata.name ?? '', + about: metadata.about ?? '', + picture: metadata.picture ?? '', + website: metadata.website ?? '', + dTag, + supportedKinds, + webHandlers, + }; +} + +/** Convert a slug like "my-cool-app" to title case like "My Cool App" */ +function toTitleCase(slug: string): string { + return slug + .replace(/[-_]+/g, ' ') + .replace(/\b\w/g, (c) => c.toUpperCase()) + .trim(); +} + +/** Create empty form data for a new app */ +function emptyFormData(projectId: string): AppFormData { + return { + name: toTitleCase(projectId), + about: '', + picture: '', + website: '', + dTag: projectId, + supportedKinds: [], + webHandlers: [], + }; +} + +export function AppDialog({ projectId, open, onOpenChange }: AppDialogProps) { + const { fs } = useFS(); + const { projectsPath } = useFSPaths(); + const { user } = useCurrentUser(); + const { toast } = useToast(); + const queryClient = useQueryClient(); + const { mutateAsync: publishEvent } = useNostrPublish(); + const { mutateAsync: uploadFile, isPending: isUploading } = useUploadFile(); + const cwd = `${projectsPath}/${projectId}`; + + const { event, isLoading, aTag, hasApp, refetch } = useAppEvent({ cwd }); + const { settings: deploySettings, isLoading: isDeployLoading } = useProjectDeploySettings(projectId); + + const [formData, setFormData] = useState(emptyFormData(projectId)); + const [isSaving, setIsSaving] = useState(false); + const [newKind, setNewKind] = useState(''); + const [newHandlerUrl, setNewHandlerUrl] = useState(''); + const [newHandlerType, setNewHandlerType] = useState(''); + const [advancedOpen, setAdvancedOpen] = useState(false); + + const fileInputRef = useRef(null); + + // Get the deployed URL from project deploy settings + const deployedUrl = (() => { + if (!deploySettings?.currentProvider || !deploySettings?.providers) return null; + const config = deploySettings.providers[deploySettings.currentProvider]; + return config?.url ?? null; + })(); + + // Populate form when event loads + useEffect(() => { + if (event) { + setFormData(eventToFormData(event)); + } else if (!isLoading && !hasApp) { + setFormData(emptyFormData(projectId)); + } + }, [event, isLoading, hasApp, projectId]); + + // Auto-fill website from deployment URL when creating a new app (not editing existing) + useEffect(() => { + if (!hasApp && !isDeployLoading && deployedUrl && !formData.website) { + setFormData(prev => ({ ...prev, website: deployedUrl })); + } + }, [hasApp, isDeployLoading, deployedUrl, formData.website]); + + const updateField = useCallback((key: K, value: AppFormData[K]) => { + setFormData(prev => ({ ...prev, [key]: value })); + }, []); + + const addKind = useCallback(() => { + const kind = newKind.trim(); + if (kind && !formData.supportedKinds.includes(kind)) { + updateField('supportedKinds', [...formData.supportedKinds, kind]); + setNewKind(''); + } + }, [newKind, formData.supportedKinds, updateField]); + + const removeKind = useCallback((kind: string) => { + updateField('supportedKinds', formData.supportedKinds.filter(k => k !== kind)); + }, [formData.supportedKinds, updateField]); + + const addHandler = useCallback(() => { + const url = newHandlerUrl.trim(); + if (url) { + updateField('webHandlers', [...formData.webHandlers, { url, type: newHandlerType.trim() }]); + setNewHandlerUrl(''); + setNewHandlerType(''); + } + }, [newHandlerUrl, newHandlerType, formData.webHandlers, updateField]); + + const removeHandler = useCallback((index: number) => { + updateField('webHandlers', formData.webHandlers.filter((_, i) => i !== index)); + }, [formData.webHandlers, updateField]); + + const handleIconUpload = useCallback(async (e: React.ChangeEvent) => { + const file = e.target.files?.[0]; + if (!file) return; + + try { + const tags = await uploadFile(file); + const url = tags[0]?.[1]; + if (url) { + updateField('picture', url); + toast({ title: 'Icon uploaded', description: 'Your app icon has been uploaded.' }); + } + } catch (error) { + toast({ + title: 'Upload failed', + description: error instanceof Error ? error.message : 'Failed to upload icon.', + variant: 'destructive', + }); + } finally { + // Reset input so re-selecting the same file triggers onChange + if (fileInputRef.current) { + fileInputRef.current.value = ''; + } + } + }, [uploadFile, updateField, toast]); + + const handleSave = async () => { + if (!user) { + toast({ + title: 'Not logged in', + description: 'You must be logged in with Nostr to publish an app.', + variant: 'destructive', + }); + return; + } + + if (!formData.name.trim()) { + toast({ + title: 'Name required', + description: 'Please enter a name for your app.', + variant: 'destructive', + }); + return; + } + + if (!formData.dTag.trim()) { + toast({ + title: 'Identifier required', + description: 'Please enter a unique identifier (d-tag) for your app.', + variant: 'destructive', + }); + return; + } + + setIsSaving(true); + + try { + // Build event content and tags + const { content, tags } = await buildAppEvent( + { + name: formData.name, + about: formData.about, + picture: formData.picture, + website: formData.website, + dTag: formData.dTag, + supportedKinds: formData.supportedKinds, + webHandlers: formData.webHandlers, + }, + { fs, cwd, pubkey: user.pubkey }, + ); + + // Publish the event + const published = await publishEvent({ + kind: 31990, + content, + tags, + }); + + // Store the "a" coordinate in .git/shakespeare/app.json + const aValue = `31990:${published.pubkey}:${formData.dTag.trim()}`; + const dotAI = new DotAI(fs, cwd); + await dotAI.writeAppConfig({ a: aValue }); + + // Invalidate queries + await queryClient.invalidateQueries({ queryKey: ['app-event'] }); + await refetch(); + + toast({ + title: hasApp ? 'App updated' : 'App published', + description: `"${formData.name}" has been ${hasApp ? 'updated' : 'published'} to Nostr.`, + }); + + onOpenChange(false); + } catch (error) { + console.error('Failed to publish app:', error); + toast({ + title: 'Failed to publish', + description: error instanceof Error ? error.message : 'An unexpected error occurred', + variant: 'destructive', + }); + } finally { + setIsSaving(false); + } + }; + + if (!user) { + return ( + + + + App + +

+ You must be logged in with Nostr to manage your app. +

+
+
+ ); + } + + return ( + + + + {hasApp ? 'Edit App' : 'Publish App'} + + {hasApp + ? 'Update your app\'s listing on Nostr.' + : 'Publish your project as a Nostr app.'} + + + + {isLoading ? ( +
+
+ +
+ + + +
+
+ +
+ ) : ( +
+ {/* App Preview Card */} +
+ {/* Icon with upload */} +
+ + +
+ + {/* Name & Description inline */} +
+ updateField('name', e.target.value)} + placeholder="App Name" + disabled={isSaving} + /> +