mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-06 08:37:22 +00:00
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
This commit is contained in:
10 files changed
+1152
-2
No files matched your search
@@ -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<string, string> = {};
|
||||||
|
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<AppFormData>(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<HTMLInputElement>(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(<K extends keyof AppFormData>(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<HTMLInputElement>) => {
|
||||||
|
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 (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-w-md">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>App</DialogTitle>
|
||||||
|
</DialogHeader>
|
||||||
|
<p className="text-sm text-muted-foreground">
|
||||||
|
You must be logged in with Nostr to manage your app.
|
||||||
|
</p>
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||||
|
<DialogContent className="max-w-lg max-h-[85vh] overflow-y-auto">
|
||||||
|
<DialogHeader>
|
||||||
|
<DialogTitle>{hasApp ? 'Edit App' : 'Publish App'}</DialogTitle>
|
||||||
|
<DialogDescription>
|
||||||
|
{hasApp
|
||||||
|
? 'Update your app\'s listing on Nostr.'
|
||||||
|
: 'Publish your project as a Nostr app.'}
|
||||||
|
</DialogDescription>
|
||||||
|
</DialogHeader>
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex items-start gap-4">
|
||||||
|
<Skeleton className="h-20 w-20 rounded-2xl flex-shrink-0" />
|
||||||
|
<div className="flex-1 space-y-2 pt-1">
|
||||||
|
<Skeleton className="h-5 w-40" />
|
||||||
|
<Skeleton className="h-4 w-full" />
|
||||||
|
<Skeleton className="h-4 w-2/3" />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<Skeleton className="h-10 w-full" />
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="space-y-5">
|
||||||
|
{/* App Preview Card */}
|
||||||
|
<div className="flex items-start gap-4">
|
||||||
|
{/* Icon with upload */}
|
||||||
|
<div className="relative flex-shrink-0 group">
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept="image/*"
|
||||||
|
onChange={handleIconUpload}
|
||||||
|
className="hidden"
|
||||||
|
disabled={isSaving || isUploading}
|
||||||
|
/>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={isSaving || isUploading}
|
||||||
|
className="relative block rounded-2xl overflow-hidden focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 disabled:pointer-events-none"
|
||||||
|
>
|
||||||
|
{formData.picture ? (
|
||||||
|
<>
|
||||||
|
<Avatar className="h-20 w-20 rounded-2xl">
|
||||||
|
<AvatarImage src={formData.picture} alt={formData.name || 'App icon'} className="object-cover" />
|
||||||
|
<AvatarFallback className="rounded-2xl bg-muted" />
|
||||||
|
</Avatar>
|
||||||
|
<div className="absolute inset-0 flex items-center justify-center bg-black/50 opacity-0 group-hover:opacity-100 transition-opacity rounded-2xl">
|
||||||
|
{isUploading ? (
|
||||||
|
<Loader2 className="h-5 w-5 text-white animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Pencil className="h-4 w-4 text-white" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</>
|
||||||
|
) : (
|
||||||
|
<div className="h-20 w-20 rounded-2xl bg-muted flex items-center justify-center transition-colors group-hover:bg-muted-foreground">
|
||||||
|
{isUploading ? (
|
||||||
|
<Loader2 className="h-6 w-6 text-muted-foreground animate-spin group-hover:text-background" />
|
||||||
|
) : (
|
||||||
|
<Upload className="h-6 w-6 text-muted-foreground transition-colors group-hover:text-background" />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Name & Description inline */}
|
||||||
|
<div className="flex-1 min-w-0 space-y-2">
|
||||||
|
<Input
|
||||||
|
value={formData.name}
|
||||||
|
onChange={e => updateField('name', e.target.value)}
|
||||||
|
placeholder="App Name"
|
||||||
|
disabled={isSaving}
|
||||||
|
/>
|
||||||
|
<Textarea
|
||||||
|
value={formData.about}
|
||||||
|
onChange={e => updateField('about', e.target.value)}
|
||||||
|
placeholder="A short description of your app..."
|
||||||
|
rows={2}
|
||||||
|
disabled={isSaving}
|
||||||
|
className="resize-none"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Website */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="app-website" className="text-xs text-muted-foreground">Website</Label>
|
||||||
|
<Input
|
||||||
|
id="app-website"
|
||||||
|
value={formData.website}
|
||||||
|
onChange={e => updateField('website', e.target.value)}
|
||||||
|
placeholder={deployedUrl || 'https://myapp.example.com'}
|
||||||
|
disabled={isSaving}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Existing app coordinate info */}
|
||||||
|
{aTag && (
|
||||||
|
<div className="text-xs text-muted-foreground space-y-1">
|
||||||
|
<p className="font-medium">Nostr Coordinate</p>
|
||||||
|
<code className="block p-2 bg-muted rounded text-xs break-all select-all">{aTag}</code>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{/* Advanced Section */}
|
||||||
|
<Collapsible open={advancedOpen} onOpenChange={setAdvancedOpen}>
|
||||||
|
<CollapsibleTrigger asChild>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="flex items-center gap-2 w-full text-sm text-muted-foreground hover:text-foreground transition-colors py-2 border-t"
|
||||||
|
>
|
||||||
|
<ChevronDown className={`h-4 w-4 transition-transform ${advancedOpen ? 'rotate-180' : ''}`} />
|
||||||
|
<span>Advanced</span>
|
||||||
|
</button>
|
||||||
|
</CollapsibleTrigger>
|
||||||
|
<CollapsibleContent>
|
||||||
|
<div className="space-y-4 pt-2">
|
||||||
|
{/* Hint to use AI */}
|
||||||
|
<div className="flex items-start gap-2 text-xs text-muted-foreground bg-muted/50 rounded-lg p-3">
|
||||||
|
<CircleHelp className="h-3.5 w-3.5 mt-0.5 flex-shrink-0" />
|
||||||
|
<span>Not sure? Ask Shakespeare to update your app.</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Identifier (d-tag) */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label htmlFor="app-dtag" className="text-xs">Identifier</Label>
|
||||||
|
<Input
|
||||||
|
id="app-dtag"
|
||||||
|
value={formData.dTag}
|
||||||
|
onChange={e => updateField('dTag', e.target.value)}
|
||||||
|
placeholder="my-app"
|
||||||
|
disabled={isSaving || hasApp}
|
||||||
|
/>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
{hasApp ? 'Cannot be changed after publishing.' : 'Unique identifier for this app. Defaults to the project ID.'}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Supported Kinds */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-xs">Supported Event Kinds</Label>
|
||||||
|
{formData.supportedKinds.length > 0 && (
|
||||||
|
<div className="flex flex-wrap gap-1">
|
||||||
|
{formData.supportedKinds.map(kind => (
|
||||||
|
<Badge key={kind} variant="secondary" className="gap-1">
|
||||||
|
{kind}
|
||||||
|
<button
|
||||||
|
onClick={() => removeKind(kind)}
|
||||||
|
disabled={isSaving}
|
||||||
|
className="hover:text-destructive"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</Badge>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
value={newKind}
|
||||||
|
onChange={e => setNewKind(e.target.value)}
|
||||||
|
placeholder="Kind number (e.g. 1)"
|
||||||
|
disabled={isSaving}
|
||||||
|
onKeyDown={e => {
|
||||||
|
if (e.key === 'Enter') {
|
||||||
|
e.preventDefault();
|
||||||
|
addKind();
|
||||||
|
}
|
||||||
|
}}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={addKind}
|
||||||
|
disabled={isSaving || !newKind.trim()}
|
||||||
|
className="h-9"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Web Handlers */}
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<Label className="text-xs">Web Handlers</Label>
|
||||||
|
{formData.webHandlers.length > 0 && (
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
{formData.webHandlers.map((handler, index) => (
|
||||||
|
<div key={index} className="flex items-center gap-2 text-sm bg-muted/50 p-2 rounded-md">
|
||||||
|
<ExternalLink className="h-3 w-3 text-muted-foreground flex-shrink-0" />
|
||||||
|
<span className="truncate flex-1">{handler.url}</span>
|
||||||
|
{handler.type && (
|
||||||
|
<Badge variant="outline" className="text-xs flex-shrink-0">{handler.type}</Badge>
|
||||||
|
)}
|
||||||
|
<button
|
||||||
|
onClick={() => removeHandler(index)}
|
||||||
|
disabled={isSaving}
|
||||||
|
className="hover:text-destructive flex-shrink-0"
|
||||||
|
>
|
||||||
|
<X className="h-3 w-3" />
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="flex gap-2">
|
||||||
|
<Input
|
||||||
|
value={newHandlerUrl}
|
||||||
|
onChange={e => setNewHandlerUrl(e.target.value)}
|
||||||
|
placeholder="https://app.example.com/e/<bech32>"
|
||||||
|
disabled={isSaving}
|
||||||
|
className="flex-1"
|
||||||
|
/>
|
||||||
|
<Input
|
||||||
|
value={newHandlerType}
|
||||||
|
onChange={e => setNewHandlerType(e.target.value)}
|
||||||
|
placeholder="nevent"
|
||||||
|
disabled={isSaving}
|
||||||
|
className="w-24"
|
||||||
|
/>
|
||||||
|
<Button
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={addHandler}
|
||||||
|
disabled={isSaving || !newHandlerUrl.trim()}
|
||||||
|
className="h-9"
|
||||||
|
>
|
||||||
|
<Plus className="h-4 w-4" />
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
<p className="text-xs text-muted-foreground">
|
||||||
|
URL patterns where <code className="text-xs">{'<bech32>'}</code> will be replaced with the NIP-19 entity.
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</CollapsibleContent>
|
||||||
|
</Collapsible>
|
||||||
|
|
||||||
|
{/* Save Button */}
|
||||||
|
<Button
|
||||||
|
onClick={handleSave}
|
||||||
|
disabled={isSaving || !formData.name.trim()}
|
||||||
|
className="w-full gap-2"
|
||||||
|
>
|
||||||
|
{isSaving ? (
|
||||||
|
<Loader2 className="h-4 w-4 animate-spin" />
|
||||||
|
) : (
|
||||||
|
<Save className="h-4 w-4" />
|
||||||
|
)}
|
||||||
|
{isSaving
|
||||||
|
? (hasApp ? 'Updating...' : 'Publishing...')
|
||||||
|
: (hasApp ? 'Update App' : 'Publish App')}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</DialogContent>
|
||||||
|
</Dialog>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -14,6 +14,7 @@ import {
|
|||||||
ChevronDown,
|
ChevronDown,
|
||||||
Trash2,
|
Trash2,
|
||||||
Star,
|
Star,
|
||||||
|
AppWindow,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
import { useLocalStorage } from '@/hooks/useLocalStorage';
|
||||||
@@ -27,6 +28,7 @@ interface ProjectTitleMenuProps {
|
|||||||
onDuplicate: () => void;
|
onDuplicate: () => void;
|
||||||
onDelete: () => void;
|
onDelete: () => void;
|
||||||
onProjectDetails: () => void;
|
onProjectDetails: () => void;
|
||||||
|
onApp: () => void;
|
||||||
isAnyLoading: boolean;
|
isAnyLoading: boolean;
|
||||||
className?: string;
|
className?: string;
|
||||||
}
|
}
|
||||||
@@ -39,6 +41,7 @@ export function ProjectTitleMenu({
|
|||||||
onDuplicate,
|
onDuplicate,
|
||||||
onDelete,
|
onDelete,
|
||||||
onProjectDetails,
|
onProjectDetails,
|
||||||
|
onApp,
|
||||||
isAnyLoading,
|
isAnyLoading,
|
||||||
className = '',
|
className = '',
|
||||||
}: ProjectTitleMenuProps) {
|
}: ProjectTitleMenuProps) {
|
||||||
@@ -98,6 +101,15 @@ export function ProjectTitleMenu({
|
|||||||
Project Details
|
Project Details
|
||||||
</DropdownMenuItem>
|
</DropdownMenuItem>
|
||||||
|
|
||||||
|
<DropdownMenuItem
|
||||||
|
onClick={onApp}
|
||||||
|
disabled={isAnyLoading}
|
||||||
|
className="gap-2"
|
||||||
|
>
|
||||||
|
<AppWindow className="h-4 w-4" />
|
||||||
|
App
|
||||||
|
</DropdownMenuItem>
|
||||||
|
|
||||||
<DropdownMenuItem
|
<DropdownMenuItem
|
||||||
onClick={onGitHistory}
|
onClick={onGitHistory}
|
||||||
disabled={isAnyLoading}
|
disabled={isAnyLoading}
|
||||||
|
|||||||
@@ -49,6 +49,7 @@ import { WebSearchTool } from '@/lib/tools/WebSearchTool';
|
|||||||
import { createMCPTools } from '@/lib/tools/MCPTool';
|
import { createMCPTools } from '@/lib/tools/MCPTool';
|
||||||
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
|
import { TodoWriteTool } from '@/lib/tools/TodoWriteTool';
|
||||||
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
|
import { TodoReadTool } from '@/lib/tools/TodoReadTool';
|
||||||
|
import { AppTool } from '@/lib/tools/AppTool';
|
||||||
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
import { ProjectPreviewConsoleError } from '@/lib/consoleMessages';
|
||||||
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
import { toolToOpenAI } from '@/lib/tools/openai-adapter';
|
||||||
import { Tool } from '@/lib/tools/Tool';
|
import { Tool } from '@/lib/tools/Tool';
|
||||||
@@ -230,6 +231,13 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
websearch: new WebSearchTool(),
|
websearch: new WebSearchTool(),
|
||||||
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
|
todowrite: new TodoWriteTool(fs, projectId, { projectsPath }),
|
||||||
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
|
todoread: new TodoReadTool(fs, projectId, { projectsPath }),
|
||||||
|
app: new AppTool(
|
||||||
|
fs,
|
||||||
|
cwd,
|
||||||
|
user?.signer,
|
||||||
|
user?.pubkey,
|
||||||
|
config.relayMetadata.relays.filter(r => r.write).map(r => r.url),
|
||||||
|
),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Add generate_image tool if imageModel is configured
|
// Add generate_image tool if imageModel is configured
|
||||||
@@ -281,7 +289,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
|||||||
}
|
}
|
||||||
|
|
||||||
return tools;
|
return tools;
|
||||||
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
|
}, [fs, git, cwd, user, projectsPath, tmpPath, config.corsProxy, config.relayMetadata, settings, aiSettings, models, handleFileChanged, handleCommit, projectId, availableSkills]);
|
||||||
|
|
||||||
// MCP tools wrapped for execution
|
// MCP tools wrapped for execution
|
||||||
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]);
|
||||||
|
|||||||
@@ -28,6 +28,7 @@ import {
|
|||||||
X,
|
X,
|
||||||
Search,
|
Search,
|
||||||
Clipboard,
|
Clipboard,
|
||||||
|
AppWindow,
|
||||||
} from 'lucide-react';
|
} from 'lucide-react';
|
||||||
import { cn } from '@/lib/utils';
|
import { cn } from '@/lib/utils';
|
||||||
import { VFSImage } from '@/components/VFSImage';
|
import { VFSImage } from '@/components/VFSImage';
|
||||||
@@ -412,6 +413,25 @@ function getToolInfo(toolName: string, args: Record<string, unknown>, projectId?
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
case 'app': {
|
||||||
|
const action = args.action as string | undefined;
|
||||||
|
if (action === 'view_app') {
|
||||||
|
return {
|
||||||
|
icon: AppWindow,
|
||||||
|
title: 'Viewed app',
|
||||||
|
callingTitle: 'Viewing app',
|
||||||
|
errorTitle: 'Failed to view app',
|
||||||
|
};
|
||||||
|
}
|
||||||
|
const name = args.name ? String(args.name) : 'app';
|
||||||
|
return {
|
||||||
|
icon: AppWindow,
|
||||||
|
title: `Updated ${name}`,
|
||||||
|
callingTitle: `Updating ${name}`,
|
||||||
|
errorTitle: `Failed to update ${name}`,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
default: {
|
default: {
|
||||||
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
|
const formattedName = toolName.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase());
|
||||||
return {
|
return {
|
||||||
|
|||||||
@@ -0,0 +1,104 @@
|
|||||||
|
import { useNostr } from '@nostrify/react';
|
||||||
|
import { useQuery } from '@tanstack/react-query';
|
||||||
|
import { useEffect, useState } from 'react';
|
||||||
|
import type { NostrEvent } from '@nostrify/nostrify';
|
||||||
|
|
||||||
|
import { useFS } from '@/hooks/useFS';
|
||||||
|
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||||
|
import { DotAI } from '@/lib/DotAI';
|
||||||
|
|
||||||
|
interface UseAppEventOptions {
|
||||||
|
/** Project working directory (e.g. /projects/<id>) */
|
||||||
|
cwd: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Hook to fetch the kind 31990 app event associated with this project.
|
||||||
|
* Reads the stored "a" coordinate from .git/shakespeare/app.json,
|
||||||
|
* then queries relays for the matching event.
|
||||||
|
*/
|
||||||
|
export function useAppEvent({ cwd }: UseAppEventOptions) {
|
||||||
|
const { nostr } = useNostr();
|
||||||
|
const { fs } = useFS();
|
||||||
|
const { user } = useCurrentUser();
|
||||||
|
const [aTag, setATag] = useState<string | null>(null);
|
||||||
|
const [isLoadingConfig, setIsLoadingConfig] = useState(true);
|
||||||
|
|
||||||
|
// Read the stored "a" coordinate on mount
|
||||||
|
useEffect(() => {
|
||||||
|
const loadConfig = async () => {
|
||||||
|
try {
|
||||||
|
const dotAI = new DotAI(fs, cwd);
|
||||||
|
const config = await dotAI.readAppConfig();
|
||||||
|
setATag(config?.a ?? null);
|
||||||
|
} catch {
|
||||||
|
setATag(null);
|
||||||
|
} finally {
|
||||||
|
setIsLoadingConfig(false);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
loadConfig();
|
||||||
|
}, [fs, cwd]);
|
||||||
|
|
||||||
|
// Parse the "a" coordinate into filter components
|
||||||
|
const parsed = aTag ? parseATag(aTag) : null;
|
||||||
|
|
||||||
|
const query = useQuery<NostrEvent | null>({
|
||||||
|
queryKey: ['app-event', aTag],
|
||||||
|
queryFn: async ({ signal }) => {
|
||||||
|
if (!parsed) return null;
|
||||||
|
|
||||||
|
const events = await nostr.query(
|
||||||
|
[{
|
||||||
|
kinds: [parsed.kind],
|
||||||
|
authors: [parsed.pubkey],
|
||||||
|
'#d': [parsed.dTag],
|
||||||
|
limit: 1,
|
||||||
|
}],
|
||||||
|
{ signal: AbortSignal.any([signal, AbortSignal.timeout(5000)]) },
|
||||||
|
);
|
||||||
|
|
||||||
|
if (events.length === 0) return null;
|
||||||
|
|
||||||
|
// Return the most recent event
|
||||||
|
return events.reduce((latest, current) =>
|
||||||
|
current.created_at > latest.created_at ? current : latest,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
enabled: !!parsed && !isLoadingConfig,
|
||||||
|
});
|
||||||
|
|
||||||
|
return {
|
||||||
|
/** The stored "a" coordinate (e.g. "31990:<pubkey>:<d-tag>") */
|
||||||
|
aTag,
|
||||||
|
/** Set the "a" coordinate (updates local state; caller must persist) */
|
||||||
|
setATag,
|
||||||
|
/** The fetched kind 31990 event, or null */
|
||||||
|
event: query.data ?? null,
|
||||||
|
/** Whether the config or event is still loading */
|
||||||
|
isLoading: isLoadingConfig || query.isLoading,
|
||||||
|
/** Whether there is an existing app event for this project */
|
||||||
|
hasApp: !!aTag,
|
||||||
|
/** The current user's pubkey */
|
||||||
|
userPubkey: user?.pubkey,
|
||||||
|
/** Refetch the event from relays */
|
||||||
|
refetch: query.refetch,
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Parse a Nostr "a" coordinate string into its components */
|
||||||
|
function parseATag(a: string): { kind: number; pubkey: string; dTag: string } | null {
|
||||||
|
const parts = a.split(':');
|
||||||
|
if (parts.length < 3) return null;
|
||||||
|
|
||||||
|
const kind = parseInt(parts[0], 10);
|
||||||
|
if (isNaN(kind)) return null;
|
||||||
|
|
||||||
|
const pubkey = parts[1];
|
||||||
|
const dTag = parts.slice(2).join(':'); // d-tag may contain colons
|
||||||
|
|
||||||
|
if (!pubkey || dTag === undefined) return null;
|
||||||
|
|
||||||
|
return { kind, pubkey, dTag };
|
||||||
|
}
|
||||||
@@ -393,4 +393,47 @@ export class DotAI {
|
|||||||
console.warn(`Failed to write .git/ai/FINISH_REASON file: ${error}`);
|
console.warn(`Failed to write .git/ai/FINISH_REASON file: ${error}`);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Read app config from .git/shakespeare/app.json file.
|
||||||
|
* Stores the Nostr "a" coordinate for the project's kind 31990 app event.
|
||||||
|
* @returns App config object or null if not found or invalid
|
||||||
|
*/
|
||||||
|
async readAppConfig(): Promise<AppConfig | null> {
|
||||||
|
try {
|
||||||
|
const appPath = join(this.workingDir, ".git", "shakespeare", "app.json");
|
||||||
|
const content = await this.fs.readFile(appPath, "utf8");
|
||||||
|
const data = JSON.parse(content);
|
||||||
|
|
||||||
|
if (data && typeof data.a === 'string' && data.a.length > 0) {
|
||||||
|
return { a: data.a };
|
||||||
|
}
|
||||||
|
|
||||||
|
return null;
|
||||||
|
} catch {
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Write app config to .git/shakespeare/app.json file.
|
||||||
|
* @param config App config with the Nostr "a" coordinate (e.g. "31990:<pubkey>:<d-tag>")
|
||||||
|
*/
|
||||||
|
async writeAppConfig(config: AppConfig): Promise<void> {
|
||||||
|
const shakespeareDir = join(this.workingDir, ".git", "shakespeare");
|
||||||
|
const appPath = join(shakespeareDir, "app.json");
|
||||||
|
|
||||||
|
try {
|
||||||
|
await this.fs.mkdir(shakespeareDir, { recursive: true });
|
||||||
|
await this.fs.writeFile(appPath, JSON.stringify(config, null, 2) + "\n");
|
||||||
|
} catch (error) {
|
||||||
|
console.warn(`Failed to write .git/shakespeare/app.json file: ${error}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** App config stored in .git/shakespeare/app.json */
|
||||||
|
export interface AppConfig {
|
||||||
|
/** Nostr "a" coordinate for the kind 31990 event (e.g. "31990:<pubkey>:<d-tag>") */
|
||||||
|
a: string;
|
||||||
}
|
}
|
||||||
@@ -0,0 +1,89 @@
|
|||||||
|
import git from 'isomorphic-git';
|
||||||
|
import { NostrURI } from './NostrURI';
|
||||||
|
import type { JSRuntimeFS } from './JSRuntime';
|
||||||
|
|
||||||
|
/** Input for building a kind 31990 app event. */
|
||||||
|
export interface AppEventInput {
|
||||||
|
name: string;
|
||||||
|
about?: string;
|
||||||
|
picture?: string;
|
||||||
|
website?: string;
|
||||||
|
dTag: string;
|
||||||
|
supportedKinds?: string[];
|
||||||
|
webHandlers?: Array<{ url: string; type?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/** The content and tags for a kind 31990 event, ready to be signed/published. */
|
||||||
|
export interface AppEventData {
|
||||||
|
content: string;
|
||||||
|
tags: string[][];
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Build the content JSON and tags array for a kind 31990 app event.
|
||||||
|
*
|
||||||
|
* Optionally inspects the project's git origin remote. If it's a `nostr://`
|
||||||
|
* URI owned by the given pubkey, an `a` tag referencing the kind 30617 repo
|
||||||
|
* event is included.
|
||||||
|
*/
|
||||||
|
export async function buildAppEvent(
|
||||||
|
input: AppEventInput,
|
||||||
|
opts?: {
|
||||||
|
fs?: JSRuntimeFS;
|
||||||
|
cwd?: string;
|
||||||
|
pubkey?: string;
|
||||||
|
},
|
||||||
|
): Promise<AppEventData> {
|
||||||
|
// Build content (kind-0-style metadata JSON)
|
||||||
|
const content: Record<string, string> = {};
|
||||||
|
if (input.name.trim()) content.name = input.name.trim();
|
||||||
|
if (input.about?.trim()) content.about = input.about.trim();
|
||||||
|
if (input.picture?.trim()) content.picture = input.picture.trim();
|
||||||
|
if (input.website?.trim()) content.website = input.website.trim();
|
||||||
|
|
||||||
|
// Build tags
|
||||||
|
const tags: string[][] = [
|
||||||
|
['d', input.dTag.trim()],
|
||||||
|
];
|
||||||
|
|
||||||
|
// Add k tags for supported kinds
|
||||||
|
if (input.supportedKinds) {
|
||||||
|
for (const kind of input.supportedKinds) {
|
||||||
|
tags.push(['k', kind]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Add web handler tags
|
||||||
|
if (input.webHandlers) {
|
||||||
|
for (const handler of input.webHandlers) {
|
||||||
|
if (handler.url) {
|
||||||
|
const webTag = ['web', handler.url];
|
||||||
|
if (handler.type) {
|
||||||
|
webTag.push(handler.type);
|
||||||
|
}
|
||||||
|
tags.push(webTag);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// If origin remote is a nostr:// URI owned by the given pubkey, add an "a" tag for the repo
|
||||||
|
if (opts?.fs && opts.cwd && opts.pubkey) {
|
||||||
|
try {
|
||||||
|
const remotes = await git.listRemotes({ fs: opts.fs, dir: opts.cwd });
|
||||||
|
const originUrl = remotes.find(r => r.remote === 'origin')?.url;
|
||||||
|
if (originUrl?.startsWith('nostr://')) {
|
||||||
|
const nostrURI = await NostrURI.parse(originUrl);
|
||||||
|
if (nostrURI.pubkey === opts.pubkey) {
|
||||||
|
tags.push(['a', `30617:${nostrURI.pubkey}:${nostrURI.identifier}`]);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// No remote or parse error, skip
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: JSON.stringify(content),
|
||||||
|
tags,
|
||||||
|
};
|
||||||
|
}
|
||||||
+23
-1
@@ -275,7 +275,29 @@ This project has a repository URL configured, so you can create an "Edit with Sh
|
|||||||
|
|
||||||
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
|
Note: the badge should be displayed at its natural size. It is recommended to omit width/height attributes to ensure proper scaling, or use \`height: auto\` in CSS (or \`"h-auto"\` in Tailwind CSS) when applicable.{% else %}
|
||||||
|
|
||||||
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}{% if README %}
|
**Important**: This project does not currently have a repository URL configured. If the user asks about adding an "Edit with Shakespeare" button, inform them that they must first initialize a public Git repository from their Shakespeare project. Once a repository URL is available, an "Edit with Shakespeare" button can be created.{% endif %}
|
||||||
|
|
||||||
|
## Publishing an App
|
||||||
|
|
||||||
|
Users can publish their project as a Nostr app (NIP-89 kind 31990) using the \`app\` tool. This creates a discoverable app listing on Nostr with metadata like name, description, icon, and website.
|
||||||
|
|
||||||
|
### Before Publishing
|
||||||
|
|
||||||
|
When a user asks to publish an app, follow this process:
|
||||||
|
|
||||||
|
1. **Check app state first**: Always call the \`app\` tool with \`view_app\` before doing anything else to see if an app has already been published.
|
||||||
|
2. **Require deployment**: The project should be deployed to a public URL before publishing an app. If it hasn't been deployed yet, strongly encourage the user to deploy first — an app listing without a working URL is not useful.
|
||||||
|
3. **Ensure the site is polished**: Push back if the site is incomplete. Before publishing, the project should have:
|
||||||
|
- A **custom favicon** (not the default Vite/React favicon)
|
||||||
|
- **Open Graph meta tags** (\`og:title\`, \`og:description\`, \`og:image\`, \`og:url\`)
|
||||||
|
- A proper **og:image** that will display well when shared on social media
|
||||||
|
- The site should generally look finished and presentable
|
||||||
|
4. **Find a suitable app icon**: Check the project files for existing icons or images suitable for the app icon (e.g., a logo, favicon SVG, or brand image). If a suitable image exists and the project is deployed, use the deployed site's public URL to that image (e.g., \`https://deployed-url.com/logo.png\`). If no suitable icon exists, stop and let the user know — offer to generate one, let the user upload one, or suggest they use the "App" dialog in the project menu directly.
|
||||||
|
5. **Update the app**: Once all prerequisites are met, call the \`app\` tool with \`update_app\` to publish or update the app listing. Set the \`website\` field to the deployed URL.
|
||||||
|
|
||||||
|
### The App Dialog
|
||||||
|
|
||||||
|
Users can also manage their app listing manually through the **App** option in the project dropdown menu. If the user prefers a visual form over the chat-based approach, point them to this dialog.{% if README %}
|
||||||
|
|
||||||
{{ README }}{% endif %}{% if AGENTS %}
|
{{ README }}{% endif %}{% if AGENTS %}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,276 @@
|
|||||||
|
import { z } from 'zod';
|
||||||
|
import { NPool, NRelay1 } from '@nostrify/nostrify';
|
||||||
|
import type { NostrEvent, NostrSigner } from '@nostrify/nostrify';
|
||||||
|
|
||||||
|
import { DotAI } from '../DotAI';
|
||||||
|
import { buildAppEvent } from '../appEvent';
|
||||||
|
import type { Tool, ToolResult } from './Tool';
|
||||||
|
import type { JSRuntimeFS } from '../JSRuntime';
|
||||||
|
|
||||||
|
interface AppToolParams {
|
||||||
|
action: 'view_app' | 'update_app';
|
||||||
|
name?: string;
|
||||||
|
about?: string;
|
||||||
|
picture?: string;
|
||||||
|
website?: string;
|
||||||
|
d?: string;
|
||||||
|
supported_kinds?: string[];
|
||||||
|
web_handlers?: Array<{ url: string; type?: string }>;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AI tool for viewing and updating the project's NIP-89 kind 31990 app event.
|
||||||
|
*
|
||||||
|
* The agent must call `view_app` at least once in a session before calling `update_app`.
|
||||||
|
* This ensures the agent is aware of the current state before making changes.
|
||||||
|
*/
|
||||||
|
export class AppTool implements Tool<AppToolParams> {
|
||||||
|
private hasViewed = false;
|
||||||
|
|
||||||
|
readonly description =
|
||||||
|
'View or update the project\'s Nostr app (NIP-89 kind 31990). ' +
|
||||||
|
'Use "view_app" to see the current app event. ' +
|
||||||
|
'Use "update_app" to create or update the app event (you MUST call view_app first in this session before updating). ' +
|
||||||
|
'This publishes the event using the user\'s own Nostr signer.';
|
||||||
|
|
||||||
|
readonly inputSchema = z.object({
|
||||||
|
action: z.enum(['view_app', 'update_app']).describe('The action to perform.'),
|
||||||
|
name: z.string().optional().describe('App name (required for update_app if creating new).'),
|
||||||
|
about: z.string().optional().describe('Short description of the app.'),
|
||||||
|
picture: z.string().optional().describe('URL to the app icon.'),
|
||||||
|
website: z.string().optional().describe('App website URL.'),
|
||||||
|
d: z.string().optional().describe('Unique identifier (d-tag) for the app. Defaults to the project ID. Cannot be changed after first publish.'),
|
||||||
|
supported_kinds: z.array(z.string()).optional().describe('Array of event kind numbers this app handles.'),
|
||||||
|
web_handlers: z.array(z.object({
|
||||||
|
url: z.string().describe('Handler URL pattern with <bech32> placeholder.'),
|
||||||
|
type: z.string().optional().describe('NIP-19 type handled by this URL (e.g. "nevent", "nprofile").'),
|
||||||
|
})).optional().describe('Web handler URL patterns.'),
|
||||||
|
});
|
||||||
|
|
||||||
|
constructor(
|
||||||
|
private fs: JSRuntimeFS,
|
||||||
|
private cwd: string,
|
||||||
|
private signer: NostrSigner | undefined,
|
||||||
|
private pubkey: string | undefined,
|
||||||
|
private relayUrls: string[],
|
||||||
|
) {}
|
||||||
|
|
||||||
|
async execute(args: AppToolParams): Promise<ToolResult> {
|
||||||
|
switch (args.action) {
|
||||||
|
case 'view_app':
|
||||||
|
return this.viewApp();
|
||||||
|
case 'update_app':
|
||||||
|
return this.updateApp(args);
|
||||||
|
default:
|
||||||
|
throw new Error(`Unknown action: ${args.action}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async viewApp(): Promise<ToolResult> {
|
||||||
|
const dotAI = new DotAI(this.fs, this.cwd);
|
||||||
|
const config = await dotAI.readAppConfig();
|
||||||
|
|
||||||
|
if (!config) {
|
||||||
|
this.hasViewed = true;
|
||||||
|
return {
|
||||||
|
content: JSON.stringify({
|
||||||
|
status: 'no_app',
|
||||||
|
message: 'No app has been published for this project yet. Use update_app to create one.',
|
||||||
|
}, null, 2),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
// Parse the "a" coordinate
|
||||||
|
const parts = config.a.split(':');
|
||||||
|
if (parts.length < 3) {
|
||||||
|
this.hasViewed = true;
|
||||||
|
return {
|
||||||
|
content: JSON.stringify({
|
||||||
|
status: 'error',
|
||||||
|
message: `Invalid app coordinate stored: ${config.a}`,
|
||||||
|
}, null, 2),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const kind = parseInt(parts[0], 10);
|
||||||
|
const pubkey = parts[1];
|
||||||
|
const dTag = parts.slice(2).join(':');
|
||||||
|
|
||||||
|
// Query relays for the event
|
||||||
|
const pool = this.createPool();
|
||||||
|
|
||||||
|
try {
|
||||||
|
const events = await pool.query(
|
||||||
|
[{
|
||||||
|
kinds: [kind],
|
||||||
|
authors: [pubkey],
|
||||||
|
'#d': [dTag],
|
||||||
|
limit: 1,
|
||||||
|
}],
|
||||||
|
{ signal: AbortSignal.timeout(5000) },
|
||||||
|
);
|
||||||
|
|
||||||
|
this.hasViewed = true;
|
||||||
|
|
||||||
|
if (events.length === 0) {
|
||||||
|
return {
|
||||||
|
content: JSON.stringify({
|
||||||
|
status: 'not_found',
|
||||||
|
a: config.a,
|
||||||
|
message: 'App coordinate is stored locally but the event was not found on relays. It may have been deleted or the relays are unavailable. Use update_app to republish.',
|
||||||
|
}, null, 2),
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
const event = events.reduce((latest, current) =>
|
||||||
|
current.created_at > latest.created_at ? current : latest,
|
||||||
|
);
|
||||||
|
|
||||||
|
// Parse content metadata
|
||||||
|
let metadata: Record<string, string> = {};
|
||||||
|
try {
|
||||||
|
if (event.content) {
|
||||||
|
metadata = JSON.parse(event.content);
|
||||||
|
}
|
||||||
|
} catch {
|
||||||
|
// Invalid JSON content
|
||||||
|
}
|
||||||
|
|
||||||
|
const supportedKinds = event.tags
|
||||||
|
.filter(([t]) => t === 'k')
|
||||||
|
.map(([, v]) => v);
|
||||||
|
|
||||||
|
const webHandlers = event.tags
|
||||||
|
.filter(([t]) => t === 'web')
|
||||||
|
.map(([, url, type]) => ({ url, type }));
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: JSON.stringify({
|
||||||
|
status: 'found',
|
||||||
|
a: config.a,
|
||||||
|
id: event.id,
|
||||||
|
pubkey: event.pubkey,
|
||||||
|
created_at: event.created_at,
|
||||||
|
metadata: {
|
||||||
|
name: metadata.name ?? null,
|
||||||
|
about: metadata.about ?? null,
|
||||||
|
picture: metadata.picture ?? null,
|
||||||
|
website: metadata.website ?? null,
|
||||||
|
},
|
||||||
|
d_tag: dTag,
|
||||||
|
supported_kinds: supportedKinds,
|
||||||
|
web_handlers: webHandlers,
|
||||||
|
all_tags: event.tags,
|
||||||
|
}, null, 2),
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
await pool.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async updateApp(args: AppToolParams): Promise<ToolResult> {
|
||||||
|
if (!this.hasViewed) {
|
||||||
|
throw new Error(
|
||||||
|
'You must call view_app first before updating the app. ' +
|
||||||
|
'This ensures you are aware of the current state of the app before making changes.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.signer) {
|
||||||
|
throw new Error('User must be logged in with Nostr to publish an app event.');
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!this.pubkey) {
|
||||||
|
throw new Error('User pubkey is not available.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Check if an existing app is stored
|
||||||
|
const dotAI = new DotAI(this.fs, this.cwd);
|
||||||
|
const existingConfig = await dotAI.readAppConfig();
|
||||||
|
|
||||||
|
// Determine the d-tag
|
||||||
|
let dTag: string;
|
||||||
|
if (existingConfig) {
|
||||||
|
// Use existing d-tag (cannot be changed)
|
||||||
|
const parts = existingConfig.a.split(':');
|
||||||
|
dTag = parts.slice(2).join(':');
|
||||||
|
} else {
|
||||||
|
// Use provided d-tag or derive from project path
|
||||||
|
dTag = args.d?.trim() || this.cwd.split('/').pop() || crypto.randomUUID();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!args.name?.trim()) {
|
||||||
|
throw new Error('App name is required. Provide a "name" parameter.');
|
||||||
|
}
|
||||||
|
|
||||||
|
// Build event content and tags
|
||||||
|
const { content, tags } = await buildAppEvent(
|
||||||
|
{
|
||||||
|
name: args.name,
|
||||||
|
about: args.about,
|
||||||
|
picture: args.picture,
|
||||||
|
website: args.website,
|
||||||
|
dTag,
|
||||||
|
supportedKinds: args.supported_kinds,
|
||||||
|
webHandlers: args.web_handlers,
|
||||||
|
},
|
||||||
|
{ fs: this.fs, cwd: this.cwd, pubkey: this.pubkey },
|
||||||
|
);
|
||||||
|
|
||||||
|
// Add client tag
|
||||||
|
if (typeof location !== 'undefined' && location.protocol === 'https:') {
|
||||||
|
tags.push(['client', location.hostname]);
|
||||||
|
}
|
||||||
|
|
||||||
|
// Sign the event
|
||||||
|
const event = await this.signer.signEvent({
|
||||||
|
kind: 31990,
|
||||||
|
content,
|
||||||
|
tags,
|
||||||
|
created_at: Math.floor(Date.now() / 1000),
|
||||||
|
});
|
||||||
|
|
||||||
|
// Publish to relays
|
||||||
|
const pool = this.createPool();
|
||||||
|
|
||||||
|
try {
|
||||||
|
await pool.event(event, { signal: AbortSignal.timeout(10_000) });
|
||||||
|
|
||||||
|
// Store the "a" coordinate
|
||||||
|
const aValue = `31990:${event.pubkey}:${dTag}`;
|
||||||
|
await dotAI.writeAppConfig({ a: aValue });
|
||||||
|
|
||||||
|
return {
|
||||||
|
content: JSON.stringify({
|
||||||
|
status: 'published',
|
||||||
|
a: aValue,
|
||||||
|
id: event.id,
|
||||||
|
pubkey: event.pubkey,
|
||||||
|
name: args.name!.trim(),
|
||||||
|
message: existingConfig
|
||||||
|
? `App "${args.name!.trim()}" has been updated on Nostr.`
|
||||||
|
: `App "${args.name!.trim()}" has been published to Nostr.`,
|
||||||
|
}, null, 2),
|
||||||
|
};
|
||||||
|
} finally {
|
||||||
|
await pool.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private createPool(): NPool {
|
||||||
|
const relayUrls = this.relayUrls;
|
||||||
|
return new NPool({
|
||||||
|
open(url) {
|
||||||
|
return new NRelay1(url);
|
||||||
|
},
|
||||||
|
eventRouter() {
|
||||||
|
return [...relayUrls];
|
||||||
|
},
|
||||||
|
reqRouter(filters) {
|
||||||
|
return new Map(
|
||||||
|
relayUrls.map((url) => [url, filters]),
|
||||||
|
);
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -8,6 +8,7 @@ import { PreviewPane } from '@/components/Shakespeare/PreviewPane';
|
|||||||
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
import { ProjectSidebar } from '@/components/ProjectSidebar';
|
||||||
import { ProjectDetailsDialog } from '@/components/ProjectDetailsDialog';
|
import { ProjectDetailsDialog } from '@/components/ProjectDetailsDialog';
|
||||||
import { DeleteProjectDialog } from '@/components/DeleteProjectDialog';
|
import { DeleteProjectDialog } from '@/components/DeleteProjectDialog';
|
||||||
|
import { AppDialog } from '@/components/AppDialog';
|
||||||
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
|
import { ResizablePanelGroup, ResizablePanel, ResizableHandle } from '@/components/ui/resizable';
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from '@/components/ui/button';
|
||||||
import { Skeleton } from '@/components/ui/skeleton';
|
import { Skeleton } from '@/components/ui/skeleton';
|
||||||
@@ -44,6 +45,7 @@ export function ProjectView() {
|
|||||||
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
const [gitHistoryOpen, setGitHistoryOpen] = useState(false);
|
||||||
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
|
const [duplicateDialogOpen, setDuplicateDialogOpen] = useState(false);
|
||||||
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
const [deleteDialogOpen, setDeleteDialogOpen] = useState(false);
|
||||||
|
const [appDialogOpen, setAppDialogOpen] = useState(false);
|
||||||
const [isDeleting, setIsDeleting] = useState(false);
|
const [isDeleting, setIsDeleting] = useState(false);
|
||||||
|
|
||||||
// Use console error state from provider
|
// Use console error state from provider
|
||||||
@@ -217,6 +219,7 @@ export function ProjectView() {
|
|||||||
onDuplicate={() => setDuplicateDialogOpen(true)}
|
onDuplicate={() => setDuplicateDialogOpen(true)}
|
||||||
onDelete={() => setDeleteDialogOpen(true)}
|
onDelete={() => setDeleteDialogOpen(true)}
|
||||||
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
||||||
|
onApp={() => setAppDialogOpen(true)}
|
||||||
isAnyLoading={isAnyLoading || isDeleting}
|
isAnyLoading={isAnyLoading || isDeleting}
|
||||||
className="text-base"
|
className="text-base"
|
||||||
/>
|
/>
|
||||||
@@ -446,6 +449,7 @@ export function ProjectView() {
|
|||||||
onDuplicate={() => setDuplicateDialogOpen(true)}
|
onDuplicate={() => setDuplicateDialogOpen(true)}
|
||||||
onDelete={() => setDeleteDialogOpen(true)}
|
onDelete={() => setDeleteDialogOpen(true)}
|
||||||
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
onProjectDetails={() => setIsProjectDetailsOpen(true)}
|
||||||
|
onApp={() => setAppDialogOpen(true)}
|
||||||
isAnyLoading={isAnyLoading || isDeleting}
|
isAnyLoading={isAnyLoading || isDeleting}
|
||||||
className="text-lg"
|
className="text-lg"
|
||||||
/>
|
/>
|
||||||
@@ -557,6 +561,11 @@ export function ProjectView() {
|
|||||||
open={deleteDialogOpen}
|
open={deleteDialogOpen}
|
||||||
onOpenChange={setDeleteDialogOpen}
|
onOpenChange={setDeleteDialogOpen}
|
||||||
/>
|
/>
|
||||||
|
<AppDialog
|
||||||
|
projectId={project.id}
|
||||||
|
open={appDialogOpen}
|
||||||
|
onOpenChange={setAppDialogOpen}
|
||||||
|
/>
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</div>
|
</div>
|
||||||
|
|||||||
Reference in new issue
Block a user