mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-04 16:13:34 +00:00
Compare commits
13
Commits
skills
...
push-reminder
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
262414257a | ||
|
|
c25517a58f | ||
|
|
a7164c0292 | ||
|
|
66a37ec92c | ||
|
|
5de01c6130 | ||
|
|
e116f7e9ec | ||
|
|
cbf18d482d | ||
|
|
d11a52992e | ||
|
|
056f2a0b5f | ||
|
|
50897e1164 | ||
|
|
db001beeb5 | ||
|
|
301b0d526b | ||
|
|
c474cd5c6c |
No files matched your search
@@ -91,6 +91,7 @@ Shakespeare provides full Git functionality in the browser using `isomorphic-git
|
||||
- **LightningFSAdapter**: Adapts LightningFS to the unified JSRuntimeFS interface
|
||||
- **GitCommitTool**: AI tool for automated commits with staging and validation
|
||||
- **useGitStatus Hook**: Real-time Git status monitoring (updates every 5 seconds)
|
||||
- **useGitFetch Hook**: Automatic remote fetch with change detection (updates every 60 seconds, shows toast notifications)
|
||||
- **ProjectsManager**: Handles project creation, Git initialization, and template cloning
|
||||
|
||||
#### Core Features
|
||||
@@ -219,6 +220,7 @@ This project is a Nostr client application built with React 18.x, TailwindCSS 3.
|
||||
- `useGitSettings`: Manage Git credentials and repository settings
|
||||
- `useSessionManager`: Access session management for AI chat sessions
|
||||
- `useGitStatus`: Real-time Git repository status monitoring
|
||||
- `useGitFetch`: Automatic remote fetch with change detection and toast notifications
|
||||
- `useProjects`: Project management and CRUD operations
|
||||
- `useProjectsManager`: Advanced project operations (creation, cloning, building, ZIP import)
|
||||
- `useTheme`: Theme management
|
||||
|
||||
@@ -47,6 +47,7 @@ import {
|
||||
GitPullRequest,
|
||||
ExternalLink,
|
||||
Copy,
|
||||
RefreshCw,
|
||||
} from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { useGitSettings } from '@/hooks/useGitSettings';
|
||||
@@ -56,6 +57,7 @@ import { useToast } from '@/hooks/useToast';
|
||||
import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@nostrify/react';
|
||||
import { usePullRequests } from '@/hooks/usePullRequests';
|
||||
import { useGitFetch } from '@/hooks/useGitFetch';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
@@ -63,6 +65,22 @@ import { GitManagementDialog } from '@/components/git/GitManagementDialog';
|
||||
import { MergeDialog } from '@/components/git/MergeDialog';
|
||||
import { PullRequestDialog } from '@/components/git/PullRequestDialog';
|
||||
import { AnnounceRepositoryDialog, type AnnounceRepositoryResult } from '@/components/git/AnnounceRepositoryDialog';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
// Helper function to format fetch timestamp with special "fetched" prefix
|
||||
function formatFetchTime(date: Date | number): string {
|
||||
const timestamp = typeof date === 'number' ? date : date.getTime();
|
||||
const now = Date.now();
|
||||
const diffMs = now - timestamp;
|
||||
|
||||
// Less than 20 seconds - use special "fetched just now" message
|
||||
if (diffMs < 20 * 1000) {
|
||||
return 'fetched just now';
|
||||
}
|
||||
|
||||
// Otherwise use the standard relative time formatter
|
||||
return formatRelativeTime(timestamp);
|
||||
}
|
||||
|
||||
interface GitDialogProps {
|
||||
projectId: string;
|
||||
@@ -89,6 +107,7 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const [isCreatingBranch, setIsCreatingBranch] = useState(false);
|
||||
const [newBranchName, setNewBranchName] = useState('');
|
||||
const [isCreateBranchDialogOpen, setIsCreateBranchDialogOpen] = useState(false);
|
||||
const [, setUpdateTrigger] = useState(0);
|
||||
|
||||
const { data: gitStatus, refetch: refetchGitStatus } = useGitStatus(projectId);
|
||||
const { settings } = useGitSettings();
|
||||
@@ -98,9 +117,19 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
const { user } = useCurrentUser();
|
||||
const { nostr } = useNostr();
|
||||
const { data: pullRequests, isLoading: isLoadingPRs } = usePullRequests(originUrl);
|
||||
const { data: gitFetchData, isFetching: isFetchingRemote, refetch: refetchRemote } = useGitFetch(projectId);
|
||||
|
||||
const projectPath = `${projectsPath}/${projectId}`;
|
||||
|
||||
// Update the "last fetched" timestamp display every 10 seconds
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setUpdateTrigger(prev => prev + 1);
|
||||
}, 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, []);
|
||||
|
||||
// Initialize origin URL from git status and load nostr.repo config
|
||||
useEffect(() => {
|
||||
const loadGitConfig = async () => {
|
||||
@@ -1041,6 +1070,29 @@ export function GitDialog({ projectId, children, open, onOpenChange }: GitDialog
|
||||
<span className={cn("text-sm font-medium", syncStatus.color)}>
|
||||
{syncStatus.text}
|
||||
</span>
|
||||
|
||||
{/* Last Fetched Info - inline with sync status */}
|
||||
{gitStatus.remotes.length > 0 && gitFetchData?.fetchedAt && (
|
||||
<>
|
||||
<span className="text-xs text-muted-foreground">
|
||||
· {formatFetchTime(gitFetchData.fetchedAt)}
|
||||
</span>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={() => refetchRemote()}
|
||||
disabled={isFetchingRemote}
|
||||
className="h-5 w-5 p-0 -ml-1 hover:bg-transparent"
|
||||
title="Refresh remote status"
|
||||
>
|
||||
{isFetchingRemote ? (
|
||||
<Loader2 className="h-3 w-3 animate-spin" />
|
||||
) : (
|
||||
<RefreshCw className="h-3 w-3 hover:text-foreground transition-colors" />
|
||||
)}
|
||||
</Button>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{gitStatus.remotes.length > 0 && (
|
||||
|
||||
@@ -7,13 +7,14 @@ import { Label } from '@/components/ui/label';
|
||||
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion';
|
||||
import { Separator } from '@/components/ui/separator';
|
||||
import { usePlugins } from '@/hooks/usePlugins';
|
||||
import { usePluginGitInfo } from '@/hooks/usePluginGitInfo';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { Alert, AlertDescription } from '@/components/ui/alert';
|
||||
|
||||
export function PluginsSection() {
|
||||
const { t } = useTranslation();
|
||||
const { toast } = useToast();
|
||||
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin, getPluginGitInfo } = usePlugins();
|
||||
const { plugins, skills, clonePlugin, syncPlugin, deletePlugin } = usePlugins();
|
||||
const [gitUrl, setGitUrl] = useState('');
|
||||
|
||||
const handleAddPlugin = async () => {
|
||||
@@ -108,7 +109,6 @@ export function PluginsSection() {
|
||||
isDeleting={isDeleting}
|
||||
onSync={handleSyncPlugin}
|
||||
onDelete={handleDeletePlugin}
|
||||
getPluginGitInfo={getPluginGitInfo}
|
||||
/>;
|
||||
})}
|
||||
</div>
|
||||
@@ -180,12 +180,11 @@ interface PluginItemProps {
|
||||
isDeleting: boolean;
|
||||
onSync: (pluginName: string) => void;
|
||||
onDelete: (pluginName: string) => void;
|
||||
getPluginGitInfo: (pluginName: string) => { data: { commitHash: string; commitDate: Date; commitMessage: string } | null | undefined; isLoading: boolean };
|
||||
}
|
||||
|
||||
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete, getPluginGitInfo }: PluginItemProps) {
|
||||
function PluginItem({ pluginName, pluginSkills, isSyncing, isDeleting, onSync, onDelete }: PluginItemProps) {
|
||||
const { t } = useTranslation();
|
||||
const { data: gitInfo } = getPluginGitInfo(pluginName);
|
||||
const { data: gitInfo } = usePluginGitInfo(pluginName);
|
||||
|
||||
return (
|
||||
<Accordion type="single" collapsible className="w-full">
|
||||
|
||||
@@ -0,0 +1,176 @@
|
||||
import { useState, useEffect } from 'react';
|
||||
import {
|
||||
Dialog,
|
||||
DialogContent,
|
||||
DialogDescription,
|
||||
DialogHeader,
|
||||
DialogTitle,
|
||||
DialogFooter,
|
||||
} from '@/components/ui/dialog';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { Checkbox } from '@/components/ui/checkbox';
|
||||
import { Label } from '@/components/ui/label';
|
||||
import { GitBranch, Upload, AlertTriangle, X } from 'lucide-react';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
|
||||
interface PushReminderDialogProps {
|
||||
projectId: string;
|
||||
open: boolean;
|
||||
onOpenChange: (open: boolean) => void;
|
||||
onDisableReminders: () => void;
|
||||
onDismiss: () => void;
|
||||
}
|
||||
|
||||
export function PushReminderDialog({
|
||||
projectId,
|
||||
open,
|
||||
onOpenChange,
|
||||
onDisableReminders,
|
||||
onDismiss,
|
||||
}: PushReminderDialogProps) {
|
||||
const [dontShowAgain, setDontShowAgain] = useState(false);
|
||||
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
// Close the reminder dialog when git dialog opens
|
||||
useEffect(() => {
|
||||
if (isGitDialogOpen) {
|
||||
onOpenChange(false);
|
||||
onDismiss();
|
||||
}
|
||||
}, [isGitDialogOpen, onOpenChange, onDismiss]);
|
||||
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const hasNoRemote = gitStatus.remotes.length === 0;
|
||||
const hasCommitsAhead = gitStatus.ahead > 0;
|
||||
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
|
||||
|
||||
const handleDismiss = () => {
|
||||
if (dontShowAgain) {
|
||||
onDisableReminders();
|
||||
}
|
||||
onDismiss();
|
||||
onOpenChange(false);
|
||||
};
|
||||
|
||||
const handlePrimaryAction = () => {
|
||||
if (dontShowAgain) {
|
||||
onDisableReminders();
|
||||
}
|
||||
|
||||
if (hasNoRemote) {
|
||||
// Close reminder dialog and open git dialog
|
||||
onOpenChange(false);
|
||||
setIsGitDialogOpen(true);
|
||||
} else {
|
||||
// Close reminder dialog and open git dialog for push
|
||||
onOpenChange(false);
|
||||
setIsGitDialogOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
// Determine dialog content based on git status
|
||||
let icon = AlertTriangle;
|
||||
let iconColor = 'text-amber-600 dark:text-amber-500';
|
||||
let title = '';
|
||||
let description = '';
|
||||
let primaryActionLabel = '';
|
||||
|
||||
if (hasNoRemote) {
|
||||
icon = GitBranch;
|
||||
iconColor = 'text-yellow-600 dark:text-yellow-500';
|
||||
title = 'No Remote Repository Configured';
|
||||
description = 'Your work is only stored locally in your browser. Configure a remote repository to prevent data loss if you clear your browser data.';
|
||||
primaryActionLabel = 'Configure Remote';
|
||||
} else if (hasCommitsAhead) {
|
||||
icon = Upload;
|
||||
iconColor = 'text-blue-600 dark:text-blue-500';
|
||||
title = 'Unpushed Commits';
|
||||
description = `You have ${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} that ${gitStatus.ahead !== 1 ? 'haven\'t' : 'hasn\'t'} been pushed to your remote repository. Push your changes to prevent data loss.`;
|
||||
primaryActionLabel = 'Push Changes';
|
||||
} else if (hasUncommittedChanges) {
|
||||
icon = AlertTriangle;
|
||||
iconColor = 'text-amber-600 dark:text-amber-500';
|
||||
title = 'Uncommitted Changes';
|
||||
description = `You have ${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}. Commit and push your changes to keep your work safe.`;
|
||||
primaryActionLabel = 'Commit & Push';
|
||||
}
|
||||
|
||||
const Icon = icon;
|
||||
|
||||
return (
|
||||
<>
|
||||
<Dialog open={open} onOpenChange={onOpenChange}>
|
||||
<DialogContent className="sm:max-w-md">
|
||||
<DialogHeader>
|
||||
<div className="flex items-start gap-3">
|
||||
<div className={`rounded-full p-2 bg-muted ${iconColor}`}>
|
||||
<Icon className="h-5 w-5" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<DialogTitle className="text-left">{title}</DialogTitle>
|
||||
<DialogDescription className="text-left mt-2">
|
||||
{description}
|
||||
</DialogDescription>
|
||||
</div>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
className="h-6 w-6 p-0 -mt-1"
|
||||
onClick={handleDismiss}
|
||||
>
|
||||
<X className="h-4 w-4" />
|
||||
</Button>
|
||||
</div>
|
||||
</DialogHeader>
|
||||
|
||||
<div className="flex items-start gap-2 p-3 rounded-md bg-muted/50 border">
|
||||
<Checkbox
|
||||
id="dont-show"
|
||||
checked={dontShowAgain}
|
||||
onCheckedChange={(checked) => setDontShowAgain(checked === true)}
|
||||
/>
|
||||
<div className="grid gap-1.5 leading-none">
|
||||
<Label
|
||||
htmlFor="dont-show"
|
||||
className="text-sm font-medium leading-none peer-disabled:cursor-not-allowed peer-disabled:opacity-70"
|
||||
>
|
||||
Don't show this again
|
||||
</Label>
|
||||
<p className="text-xs text-muted-foreground">
|
||||
You can re-enable push reminders in Settings > Preferences
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DialogFooter className="flex-col sm:flex-row gap-2">
|
||||
<Button
|
||||
variant="outline"
|
||||
onClick={handleDismiss}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
Remind Me Later
|
||||
</Button>
|
||||
<Button
|
||||
onClick={handlePrimaryAction}
|
||||
className="w-full sm:w-auto"
|
||||
>
|
||||
{primaryActionLabel}
|
||||
</Button>
|
||||
</DialogFooter>
|
||||
</DialogContent>
|
||||
</Dialog>
|
||||
|
||||
{/* Git Dialog - opened when user clicks primary action */}
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={isGitDialogOpen}
|
||||
onOpenChange={setIsGitDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
import { useState } from 'react';
|
||||
import { Button } from '@/components/ui/button';
|
||||
import { GitDialog } from '@/components/GitDialog';
|
||||
import { AlertTriangle, Upload, GitBranch } from 'lucide-react';
|
||||
import { cn } from '@/lib/utils';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import {
|
||||
Tooltip,
|
||||
TooltipContent,
|
||||
TooltipProvider,
|
||||
TooltipTrigger,
|
||||
} from '@/components/ui/tooltip';
|
||||
|
||||
interface PushWarningButtonProps {
|
||||
projectId: string;
|
||||
className?: string;
|
||||
variant?: 'icon' | 'full';
|
||||
}
|
||||
|
||||
export function PushWarningButton({
|
||||
projectId,
|
||||
className,
|
||||
variant = 'icon'
|
||||
}: PushWarningButtonProps) {
|
||||
const [isGitDialogOpen, setIsGitDialogOpen] = useState(false);
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
if (!gitStatus?.isGitRepo) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Determine warning state
|
||||
const hasNoRemote = gitStatus.remotes.length === 0;
|
||||
const hasUncommittedChanges = gitStatus.hasUncommittedChanges;
|
||||
const hasCommitsAhead = gitStatus.ahead > 0;
|
||||
|
||||
// Don't show if everything is synced
|
||||
if (!hasNoRemote && !hasUncommittedChanges && !hasCommitsAhead) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// Determine icon and message
|
||||
let icon = AlertTriangle;
|
||||
let message = '';
|
||||
let action = '';
|
||||
|
||||
if (hasNoRemote) {
|
||||
icon = GitBranch;
|
||||
message = 'No remote configured';
|
||||
action = 'Configure remote to prevent data loss';
|
||||
} else if (hasCommitsAhead) {
|
||||
icon = Upload;
|
||||
message = `${gitStatus.ahead} commit${gitStatus.ahead !== 1 ? 's' : ''} not pushed`;
|
||||
action = 'Push to remote';
|
||||
} else if (hasUncommittedChanges) {
|
||||
icon = AlertTriangle;
|
||||
message = `${gitStatus.changedFiles.length} uncommitted change${gitStatus.changedFiles.length !== 1 ? 's' : ''}`;
|
||||
action = 'Commit and push your changes';
|
||||
}
|
||||
|
||||
const Icon = icon;
|
||||
|
||||
const handleClick = () => {
|
||||
if (hasNoRemote) {
|
||||
// If no remote, open git dialog to configure
|
||||
setIsGitDialogOpen(true);
|
||||
} else {
|
||||
// If remote exists, open git dialog for push/commit
|
||||
setIsGitDialogOpen(true);
|
||||
}
|
||||
};
|
||||
|
||||
if (variant === 'icon') {
|
||||
return (
|
||||
<>
|
||||
<TooltipProvider>
|
||||
<Tooltip>
|
||||
<TooltipTrigger asChild>
|
||||
<Button
|
||||
variant="ghost"
|
||||
size="sm"
|
||||
onClick={handleClick}
|
||||
className={cn(
|
||||
"h-8 w-8 p-0",
|
||||
hasNoRemote && "text-yellow-600 hover:text-yellow-700 dark:text-yellow-500 dark:hover:text-yellow-400",
|
||||
hasCommitsAhead && "text-blue-600 hover:text-blue-700 dark:text-blue-500 dark:hover:text-blue-400",
|
||||
hasUncommittedChanges && !hasCommitsAhead && "text-amber-600 hover:text-amber-700 dark:text-amber-500 dark:hover:text-amber-400",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 animate-pulse" />
|
||||
</Button>
|
||||
</TooltipTrigger>
|
||||
<TooltipContent>
|
||||
<div className="space-y-1">
|
||||
<p className="font-medium">{message}</p>
|
||||
<p className="text-xs text-muted-foreground">{action}</p>
|
||||
</div>
|
||||
</TooltipContent>
|
||||
</Tooltip>
|
||||
</TooltipProvider>
|
||||
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={isGitDialogOpen}
|
||||
onOpenChange={setIsGitDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
|
||||
// Full button variant
|
||||
return (
|
||||
<>
|
||||
<Button
|
||||
variant="outline"
|
||||
size="sm"
|
||||
onClick={handleClick}
|
||||
className={cn(
|
||||
"gap-2 border-2",
|
||||
hasNoRemote && "border-yellow-500/50 bg-yellow-50 hover:bg-yellow-100 dark:bg-yellow-950/20 dark:hover:bg-yellow-950/30 text-yellow-700 dark:text-yellow-400",
|
||||
hasCommitsAhead && "border-blue-500/50 bg-blue-50 hover:bg-blue-100 dark:bg-blue-950/20 dark:hover:bg-blue-950/30 text-blue-700 dark:text-blue-400",
|
||||
hasUncommittedChanges && !hasCommitsAhead && "border-amber-500/50 bg-amber-50 hover:bg-amber-100 dark:bg-amber-950/20 dark:hover:bg-amber-950/30 text-amber-700 dark:text-amber-400",
|
||||
className
|
||||
)}
|
||||
>
|
||||
<Icon className="h-4 w-4 animate-pulse" />
|
||||
<span className="text-sm font-medium">{message}</span>
|
||||
</Button>
|
||||
|
||||
<GitDialog
|
||||
projectId={projectId}
|
||||
open={isGitDialogOpen}
|
||||
onOpenChange={setIsGitDialogOpen}
|
||||
/>
|
||||
</>
|
||||
);
|
||||
}
|
||||
@@ -52,6 +52,7 @@ interface ChatPaneProps {
|
||||
onNewChat: () => void;
|
||||
onFirstInteraction?: () => void;
|
||||
onLoadingChange?: (isLoading: boolean) => void;
|
||||
onMessageSent?: () => void;
|
||||
isLoading?: boolean;
|
||||
isBuildLoading?: boolean;
|
||||
consoleError?: ProjectPreviewConsoleError | null;
|
||||
@@ -67,6 +68,7 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
onNewChat,
|
||||
onFirstInteraction,
|
||||
onLoadingChange,
|
||||
onMessageSent,
|
||||
isLoading: externalIsLoading,
|
||||
isBuildLoading: externalIsBuildLoading,
|
||||
consoleError,
|
||||
@@ -478,7 +480,12 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
// Send as text parts if we have multiple parts, otherwise send as string for simplicity
|
||||
const messageContent = contentParts.length === 1 ? contentParts[0].text : contentParts;
|
||||
await sendMessage(messageContent, modelToUse);
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath]);
|
||||
|
||||
// Notify parent that a message was sent (for push reminder tracking)
|
||||
if (onMessageSent) {
|
||||
onMessageSent();
|
||||
}
|
||||
}, [addRecentlyUsedModel, fs, isConfigured, isLoading, providerModel, sendMessage, tmpPath, onMessageSent]);
|
||||
|
||||
// Handle textarea focus - show onboarding if not configured
|
||||
const handleTextareaFocus = useCallback(() => {
|
||||
|
||||
@@ -10,6 +10,7 @@ import { useFSPaths } from '@/hooks/useFSPaths';
|
||||
import { useFS } from '@/hooks/useFS';
|
||||
import { useToast } from '@/hooks/useToast';
|
||||
import { useGitStatus } from '@/hooks/useGitStatus';
|
||||
import { formatRelativeTime } from '@/lib/utils';
|
||||
|
||||
interface GitCommit {
|
||||
oid: string;
|
||||
@@ -336,24 +337,6 @@ ${commitsToRevert.map(c => {
|
||||
}
|
||||
}, [isOpen, loadGitHistory]);
|
||||
|
||||
const formatRelativeTime = (timestamp: number) => {
|
||||
const now = Date.now();
|
||||
const commitTime = timestamp * 1000;
|
||||
const diffMs = now - commitTime;
|
||||
|
||||
const diffMinutes = Math.floor(diffMs / (1000 * 60));
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
|
||||
if (diffMinutes < 60) {
|
||||
return `${diffMinutes} minutes ago`;
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours} hours ago`;
|
||||
} else {
|
||||
return `${diffDays} days ago`;
|
||||
}
|
||||
};
|
||||
|
||||
const getCommitMessageLines = (message: string) => {
|
||||
const lines = message.split('\n').filter(line => line.trim() !== '');
|
||||
return {
|
||||
|
||||
@@ -39,6 +39,7 @@ import {
|
||||
createRepositoryNaddr,
|
||||
validateRepositoryAnnouncementData,
|
||||
validateRepositoryId,
|
||||
parseRepositoryAnnouncement,
|
||||
} from '@/lib/announceRepository';
|
||||
|
||||
export interface AnnounceRepositoryResult {
|
||||
@@ -209,21 +210,16 @@ export function AnnounceRepositoryDialog({
|
||||
// Use the most recent event
|
||||
const event = events.sort((a, b) => b.created_at - a.created_at)[0];
|
||||
|
||||
// Parse tags to populate form fields
|
||||
const nameTag = event.tags.find(([name]) => name === 'name');
|
||||
const descriptionTag = event.tags.find(([name]) => name === 'description');
|
||||
const webTag = event.tags.find(([name]) => name === 'web');
|
||||
const cloneTag = event.tags.find(([name]) => name === 'clone');
|
||||
const relaysTag = event.tags.find(([name]) => name === 'relays');
|
||||
const eucTag = event.tags.find(([name, , marker]) => name === 'r' && marker === 'euc');
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
setRepoId(identifier);
|
||||
setName(nameTag?.[1] || '');
|
||||
setDescription(descriptionTag?.[1] || '');
|
||||
setWebUrls(webTag ? webTag.slice(1) : []);
|
||||
setCloneUrls(cloneTag ? cloneTag.slice(1) : []);
|
||||
setRelays(relaysTag ? relaysTag.slice(1) : []);
|
||||
setEarliestCommit(eucTag?.[1] || '');
|
||||
setRepoId(parsed.identifier);
|
||||
setName(parsed.name || '');
|
||||
setDescription(parsed.description || '');
|
||||
setWebUrls(parsed.webUrls);
|
||||
setCloneUrls(parsed.httpsCloneUrls);
|
||||
setRelays(parsed.relays);
|
||||
setEarliestCommit(parsed.earliestCommit || '');
|
||||
|
||||
setIsPrepopulated(true);
|
||||
} catch (error) {
|
||||
|
||||
@@ -39,6 +39,7 @@ import { useCurrentUser } from '@/hooks/useCurrentUser';
|
||||
import { useNostr } from '@/hooks/useNostr';
|
||||
import { useAppContext } from '@/hooks/useAppContext';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
import type { GitCredential } from '@/contexts/GitSettingsContext';
|
||||
|
||||
@@ -717,21 +718,20 @@ export function PullRequestDialog({
|
||||
const repoEvent = repoEvents[0];
|
||||
console.log('Found repository announcement event:', repoEvent);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const repoAnn = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// Get earliest unique commit from repository announcement
|
||||
const eucTag = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc');
|
||||
if (eucTag) {
|
||||
earliestUniqueCommit = eucTag[1];
|
||||
if (repoAnn.earliestCommit) {
|
||||
earliestUniqueCommit = repoAnn.earliestCommit;
|
||||
console.log('Found earliest unique commit:', earliestUniqueCommit);
|
||||
} else {
|
||||
console.warn('No euc tag found in repository announcement');
|
||||
}
|
||||
|
||||
// Get relay hints from repository announcement
|
||||
// Per NIP-34, all relays are in a single tag: ["relays", "wss://...", "wss://...", ...]
|
||||
const relayTag = repoEvent.tags.find((t: string[]) => t[0] === 'relays');
|
||||
if (relayTag && relayTag.length > 1) {
|
||||
// Extract all relay URLs from the tag (skip the first element which is "relays")
|
||||
publishRelays = relayTag.slice(1);
|
||||
if (repoAnn.relays.length > 0) {
|
||||
publishRelays = repoAnn.relays;
|
||||
console.log('Publishing to repository relays:', publishRelays);
|
||||
} else {
|
||||
console.log('No relay hints in repository announcement, using configured relay');
|
||||
|
||||
@@ -0,0 +1,95 @@
|
||||
import { describe, it, expect, vi } from 'vitest';
|
||||
import { renderHook, waitFor } from '@testing-library/react';
|
||||
import { useGitFetch } from './useGitFetch';
|
||||
import { TestApp } from '@/test/TestApp';
|
||||
|
||||
// Mock the git operations
|
||||
vi.mock('./useGit', () => ({
|
||||
useGit: () => ({
|
||||
git: {
|
||||
findRoot: vi.fn().mockResolvedValue('/projects/test-project'),
|
||||
listRemotes: vi.fn().mockResolvedValue([
|
||||
{ remote: 'origin', url: 'https://github.com/test/repo.git' }
|
||||
]),
|
||||
currentBranch: vi.fn().mockResolvedValue('main'),
|
||||
getRemoteInfo: vi.fn().mockResolvedValue({
|
||||
refs: {
|
||||
HEAD: {
|
||||
type: 'symref',
|
||||
target: 'refs/heads/main',
|
||||
},
|
||||
},
|
||||
}),
|
||||
resolveRef: vi.fn()
|
||||
.mockResolvedValueOnce('abc123') // before default
|
||||
.mockResolvedValueOnce('abc123') // before current
|
||||
.mockResolvedValueOnce('abc123') // after default
|
||||
.mockResolvedValueOnce('abc123'), // after current
|
||||
fetch: vi.fn().mockResolvedValue(undefined),
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useGitSettings', () => ({
|
||||
useGitSettings: () => ({
|
||||
settings: {
|
||||
credentials: [],
|
||||
},
|
||||
}),
|
||||
}));
|
||||
|
||||
vi.mock('./useFSPaths', () => ({
|
||||
useFSPaths: () => ({
|
||||
projectsPath: '/projects',
|
||||
}),
|
||||
}));
|
||||
|
||||
describe('useGitFetch', () => {
|
||||
it('returns null state when projectId is null', async () => {
|
||||
const { result } = renderHook(() => useGitFetch(null), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
// When projectId is null, the query is disabled and won't fetch
|
||||
// So we just check the initial state
|
||||
expect(result.current.data).toBeUndefined();
|
||||
expect(result.current.isLoading).toBe(false);
|
||||
expect(result.current.isSuccess).toBe(false);
|
||||
});
|
||||
|
||||
it('fetches remote updates successfully', async () => {
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
expect(result.current.data).toMatchObject({
|
||||
defaultBranch: 'main',
|
||||
currentBranch: 'main',
|
||||
remoteUrl: 'https://github.com/test/repo.git',
|
||||
hasChanges: false,
|
||||
});
|
||||
});
|
||||
|
||||
it('can be manually refetched', async () => {
|
||||
const { result } = renderHook(() => useGitFetch('test-project'), {
|
||||
wrapper: TestApp,
|
||||
});
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.isSuccess).toBe(true);
|
||||
});
|
||||
|
||||
const firstFetchTime = result.current.data?.fetchedAt;
|
||||
|
||||
// Manually trigger refetch
|
||||
await result.current.refetch();
|
||||
|
||||
await waitFor(() => {
|
||||
expect(result.current.data?.fetchedAt).toBeGreaterThanOrEqual(firstFetchTime || 0);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,335 @@
|
||||
import { useQuery, useQueryClient } from '@tanstack/react-query';
|
||||
import { useGit } from './useGit';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { useGitSettings } from './useGitSettings';
|
||||
import { useToast } from './useToast';
|
||||
import { findCredentialsForRepo } from '@/lib/gitCredentials';
|
||||
import { useEffect, useRef } from 'react';
|
||||
|
||||
interface FetchResult {
|
||||
defaultBranch: string | null;
|
||||
defaultBranchOid: string | null;
|
||||
currentBranch: string | null;
|
||||
currentBranchOid: string | null;
|
||||
fetchedAt: number;
|
||||
hasChanges: boolean;
|
||||
remoteUrl: string | null;
|
||||
}
|
||||
|
||||
/**
|
||||
* Hook to fetch updates from remote repository and detect changes.
|
||||
* Polls every 60 seconds and shows toast notifications when changes are detected.
|
||||
*
|
||||
* @param projectId - The project ID to fetch for
|
||||
* @returns Query result with manual refetch capability
|
||||
*/
|
||||
export function useGitFetch(projectId: string | null) {
|
||||
const { git } = useGit();
|
||||
const { projectsPath } = useFSPaths();
|
||||
const { settings } = useGitSettings();
|
||||
const { toast } = useToast();
|
||||
const queryClient = useQueryClient();
|
||||
|
||||
// Track previous state to detect changes
|
||||
const previousStateRef = useRef<{
|
||||
defaultBranchOid: string | null;
|
||||
currentBranchOid: string | null;
|
||||
} | null>(null);
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['git-fetch', projectId],
|
||||
queryFn: async (): Promise<FetchResult> => {
|
||||
console.log('=== GIT FETCH STARTING ===');
|
||||
console.log('Project ID:', projectId);
|
||||
|
||||
if (!projectId) {
|
||||
console.log('No project ID, returning empty result');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
try {
|
||||
const cwd = `${projectsPath}/${projectId}`;
|
||||
console.log('Working directory:', cwd);
|
||||
|
||||
// Check if we're in a git repository
|
||||
try {
|
||||
await git.findRoot({ filepath: cwd });
|
||||
console.log('Git repository found');
|
||||
} catch {
|
||||
console.log('Not a git repository');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get remotes
|
||||
const remotes = await git.listRemotes({ dir: cwd });
|
||||
console.log('Remotes found:', remotes);
|
||||
|
||||
if (remotes.length === 0) {
|
||||
console.log('No remotes configured');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
const remote = remotes[0]; // Use first remote (usually 'origin')
|
||||
const remoteUrl = remote.url || null;
|
||||
console.log('Using remote:', remote.remote, 'URL:', remoteUrl);
|
||||
|
||||
if (!remoteUrl) {
|
||||
console.log('No remote URL found');
|
||||
return {
|
||||
defaultBranch: null,
|
||||
defaultBranchOid: null,
|
||||
currentBranch: null,
|
||||
currentBranchOid: null,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges: false,
|
||||
remoteUrl: null,
|
||||
};
|
||||
}
|
||||
|
||||
// Get credentials for authentication
|
||||
const credentials = findCredentialsForRepo(remoteUrl, settings.credentials);
|
||||
console.log('Credentials found:', !!credentials);
|
||||
|
||||
// Get current branch before fetch
|
||||
let currentBranch: string | null = null;
|
||||
try {
|
||||
const branch = await git.currentBranch({
|
||||
dir: cwd,
|
||||
fullname: false,
|
||||
});
|
||||
currentBranch = (branch && branch.trim() !== '') ? branch : null;
|
||||
console.log('Current branch:', currentBranch);
|
||||
} catch (error) {
|
||||
console.warn('Could not get current branch:', error);
|
||||
}
|
||||
|
||||
// Store OIDs before fetch
|
||||
let beforeDefaultOid: string | null = null;
|
||||
let beforeCurrentOid: string | null = null;
|
||||
|
||||
// Get remote info to find default branch
|
||||
let defaultBranch: string | null = null;
|
||||
try {
|
||||
console.log('Fetching remote info...');
|
||||
const remoteInfo = await git.getRemoteInfo({
|
||||
url: remoteUrl,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
|
||||
// Extract default branch from symbolic ref
|
||||
if (remoteInfo.refs?.HEAD?.type === 'symref') {
|
||||
const symref = remoteInfo.refs.HEAD.target;
|
||||
defaultBranch = symref?.replace('refs/heads/', '') || null;
|
||||
console.log('Default branch from remote:', defaultBranch);
|
||||
}
|
||||
|
||||
// If we have a default branch, try to get its OID before fetch
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
beforeDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID before fetch:', beforeDefaultOid);
|
||||
} catch {
|
||||
console.log('Remote default branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
} catch (error) {
|
||||
console.warn('Could not get remote info:', error);
|
||||
}
|
||||
|
||||
// Get current branch OID before fetch
|
||||
if (currentBranch) {
|
||||
try {
|
||||
beforeCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID before fetch:', beforeCurrentOid);
|
||||
} catch {
|
||||
console.log('Remote current branch not in local repo yet');
|
||||
}
|
||||
}
|
||||
|
||||
// Perform fetch
|
||||
try {
|
||||
console.log('Fetching from remote...');
|
||||
await git.fetch({
|
||||
dir: cwd,
|
||||
remote: remote.remote,
|
||||
...(credentials && {
|
||||
onAuth: () => ({
|
||||
username: credentials.username,
|
||||
password: credentials.password,
|
||||
}),
|
||||
}),
|
||||
});
|
||||
console.log('Fetch completed successfully');
|
||||
} catch (error) {
|
||||
console.error('Failed to fetch from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
|
||||
// Get OIDs after fetch
|
||||
let afterDefaultOid: string | null = null;
|
||||
let afterCurrentOid: string | null = null;
|
||||
|
||||
if (defaultBranch) {
|
||||
try {
|
||||
afterDefaultOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${defaultBranch}`,
|
||||
});
|
||||
console.log('Default branch OID after fetch:', afterDefaultOid);
|
||||
} catch {
|
||||
console.log('Could not resolve default branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
if (currentBranch) {
|
||||
try {
|
||||
afterCurrentOid = await git.resolveRef({
|
||||
dir: cwd,
|
||||
ref: `${remote.remote}/${currentBranch}`,
|
||||
});
|
||||
console.log('Current branch OID after fetch:', afterCurrentOid);
|
||||
} catch {
|
||||
console.log('Could not resolve current branch after fetch');
|
||||
}
|
||||
}
|
||||
|
||||
// Detect changes
|
||||
const defaultBranchChanged = beforeDefaultOid !== null &&
|
||||
afterDefaultOid !== null &&
|
||||
beforeDefaultOid !== afterDefaultOid;
|
||||
|
||||
const currentBranchChanged = beforeCurrentOid !== null &&
|
||||
afterCurrentOid !== null &&
|
||||
beforeCurrentOid !== afterCurrentOid &&
|
||||
currentBranch !== defaultBranch; // Don't double-report if they're the same
|
||||
|
||||
const hasChanges = defaultBranchChanged || currentBranchChanged;
|
||||
|
||||
console.log('Changes detected:', {
|
||||
defaultBranchChanged,
|
||||
currentBranchChanged,
|
||||
hasChanges,
|
||||
});
|
||||
|
||||
const result = {
|
||||
defaultBranch,
|
||||
defaultBranchOid: afterDefaultOid,
|
||||
currentBranch,
|
||||
currentBranchOid: afterCurrentOid,
|
||||
fetchedAt: Date.now(),
|
||||
hasChanges,
|
||||
remoteUrl,
|
||||
};
|
||||
|
||||
console.log('=== GIT FETCH COMPLETE ===');
|
||||
console.log('Result:', result);
|
||||
|
||||
return result;
|
||||
} catch (error) {
|
||||
console.error('Error fetching from remote:', error);
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
enabled: !!projectId,
|
||||
refetchInterval: 60000, // Fetch every 60 seconds
|
||||
staleTime: 30000, // Consider data stale after 30 seconds
|
||||
retry: 1, // Only retry once on failure
|
||||
});
|
||||
|
||||
// Show toast notifications when changes are detected
|
||||
useEffect(() => {
|
||||
if (!query.data || !query.isSuccess) {
|
||||
return;
|
||||
}
|
||||
|
||||
const currentState = {
|
||||
defaultBranchOid: query.data.defaultBranchOid,
|
||||
currentBranchOid: query.data.currentBranchOid,
|
||||
};
|
||||
|
||||
// Skip on first load
|
||||
if (previousStateRef.current === null) {
|
||||
previousStateRef.current = currentState;
|
||||
return;
|
||||
}
|
||||
|
||||
const prevState = previousStateRef.current;
|
||||
|
||||
// Detect default branch changes
|
||||
const defaultBranchChanged =
|
||||
prevState.defaultBranchOid !== null &&
|
||||
currentState.defaultBranchOid !== null &&
|
||||
prevState.defaultBranchOid !== currentState.defaultBranchOid;
|
||||
|
||||
// Detect current branch changes
|
||||
const currentBranchChanged =
|
||||
prevState.currentBranchOid !== null &&
|
||||
currentState.currentBranchOid !== null &&
|
||||
prevState.currentBranchOid !== currentState.currentBranchOid &&
|
||||
query.data.currentBranch !== query.data.defaultBranch;
|
||||
|
||||
// Show toast for default branch changes
|
||||
if (defaultBranchChanged && query.data.defaultBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.defaultBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
|
||||
// Show toast for current branch changes (if different from default)
|
||||
if (currentBranchChanged && query.data.currentBranch) {
|
||||
toast({
|
||||
title: 'Remote changes detected',
|
||||
description: `The ${query.data.currentBranch} branch has new commits available.`,
|
||||
variant: 'default',
|
||||
});
|
||||
|
||||
// Invalidate git status to show new ahead/behind counts
|
||||
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
|
||||
}
|
||||
|
||||
// Update previous state
|
||||
previousStateRef.current = currentState;
|
||||
}, [query.data, query.isSuccess, toast, queryClient, projectId]);
|
||||
|
||||
return query;
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { getPluginGitInfo } from '@/lib/plugins';
|
||||
|
||||
/**
|
||||
* Hook to get git info for a specific plugin
|
||||
*/
|
||||
export function usePluginGitInfo(pluginName: string) {
|
||||
const { fs } = useFS();
|
||||
const { pluginsPath } = useFSPaths();
|
||||
|
||||
return useQuery({
|
||||
queryKey: ['plugin-git-info', pluginsPath, pluginName],
|
||||
queryFn: async () => {
|
||||
return await getPluginGitInfo(fs, pluginsPath, pluginName);
|
||||
},
|
||||
enabled: !!pluginName,
|
||||
});
|
||||
}
|
||||
+5
-12
@@ -1,7 +1,7 @@
|
||||
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query';
|
||||
import { useFS } from './useFS';
|
||||
import { useFSPaths } from './useFSPaths';
|
||||
import { getPlugins, getAllSkills, deletePlugin as deletePluginFn, getPluginGitInfo, type PluginGitInfo } from '@/lib/plugins';
|
||||
import { getPlugins, getAllSkills, deletePlugin as deletePluginFn } from '@/lib/plugins';
|
||||
import { useGit } from './useGit';
|
||||
import { join } from 'path-browserify';
|
||||
|
||||
@@ -91,6 +91,10 @@ export function usePlugins() {
|
||||
dir: pluginDir,
|
||||
singleBranch: true,
|
||||
fastForward: true,
|
||||
author: {
|
||||
name: 'shakespeare.diy',
|
||||
email: '[email protected]',
|
||||
},
|
||||
});
|
||||
|
||||
return pluginName;
|
||||
@@ -115,16 +119,6 @@ export function usePlugins() {
|
||||
},
|
||||
});
|
||||
|
||||
// Function to get git info for a specific plugin
|
||||
const getPluginGitInfoQuery = (pluginName: string) => {
|
||||
return useQuery({
|
||||
queryKey: ['plugin-git-info', pluginsPath, pluginName],
|
||||
queryFn: async () => {
|
||||
return await getPluginGitInfo(fs, pluginsPath, pluginName);
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
return {
|
||||
plugins: pluginsQuery.data || [],
|
||||
isLoadingPlugins: pluginsQuery.isLoading,
|
||||
@@ -133,6 +127,5 @@ export function usePlugins() {
|
||||
clonePlugin,
|
||||
syncPlugin,
|
||||
deletePlugin,
|
||||
getPluginGitInfo: getPluginGitInfoQuery,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useEffect, useCallback } from 'react';
|
||||
import { useLocalStorage } from './useLocalStorage';
|
||||
import { useGitStatus } from './useGitStatus';
|
||||
|
||||
interface PushReminderState {
|
||||
/** Whether push reminders are enabled */
|
||||
enabled: boolean;
|
||||
/** Number of messages since last push */
|
||||
messagesSinceLastPush: number;
|
||||
/** Timestamp when user last pushed or dismissed a reminder */
|
||||
lastInteraction: number;
|
||||
/** Project ID being tracked */
|
||||
currentProjectId: string | null;
|
||||
}
|
||||
|
||||
const DEFAULT_STATE: PushReminderState = {
|
||||
enabled: true,
|
||||
messagesSinceLastPush: 0,
|
||||
lastInteraction: 0, // Start at 0 so reminders can show immediately
|
||||
currentProjectId: null,
|
||||
};
|
||||
|
||||
/** Number of messages before showing push reminder */
|
||||
const MESSAGE_THRESHOLD = 5;
|
||||
|
||||
/** Minimum time in ms between showing reminders (5 minutes) */
|
||||
const MIN_REMINDER_INTERVAL = 5 * 60 * 1000;
|
||||
|
||||
export function usePushReminder(projectId: string | null) {
|
||||
const [state, setState] = useLocalStorage<PushReminderState>(
|
||||
'push-reminder-state',
|
||||
DEFAULT_STATE
|
||||
);
|
||||
|
||||
const { data: gitStatus } = useGitStatus(projectId);
|
||||
|
||||
// Reset counter when switching projects
|
||||
useEffect(() => {
|
||||
if (projectId && state.currentProjectId !== projectId) {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
currentProjectId: projectId,
|
||||
messagesSinceLastPush: 0,
|
||||
// Don't reset lastInteraction - keep the cooldown across project switches
|
||||
}));
|
||||
}
|
||||
}, [projectId, state.currentProjectId, setState]);
|
||||
|
||||
// Check if should show reminder
|
||||
const shouldShowReminder = useCallback(() => {
|
||||
if (!state.enabled || !projectId || !gitStatus?.isGitRepo) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Don't show if user recently interacted with push reminder
|
||||
const timeSinceLastInteraction = Date.now() - state.lastInteraction;
|
||||
if (timeSinceLastInteraction < MIN_REMINDER_INTERVAL) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Show if:
|
||||
// 1. There are uncommitted changes OR commits ahead of remote OR no remote configured
|
||||
// 2. Enough messages have been sent since last interaction
|
||||
const hasUnpushedWork =
|
||||
gitStatus.hasUncommittedChanges ||
|
||||
gitStatus.ahead > 0 ||
|
||||
gitStatus.remotes.length === 0;
|
||||
const enoughMessages = state.messagesSinceLastPush >= MESSAGE_THRESHOLD;
|
||||
|
||||
return hasUnpushedWork && enoughMessages;
|
||||
}, [state, projectId, gitStatus]);
|
||||
|
||||
// Increment message counter
|
||||
const incrementMessages = useCallback(() => {
|
||||
if (!state.enabled || !projectId) return;
|
||||
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
messagesSinceLastPush: prev.messagesSinceLastPush + 1,
|
||||
}));
|
||||
}, [state.enabled, projectId, setState]);
|
||||
|
||||
// Reset counter (called after push or dismiss)
|
||||
const resetReminder = useCallback(() => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
messagesSinceLastPush: 0,
|
||||
lastInteraction: Date.now(),
|
||||
}));
|
||||
}, [setState]);
|
||||
|
||||
// Enable/disable reminders
|
||||
const setEnabled = useCallback((enabled: boolean) => {
|
||||
setState((prev) => ({
|
||||
...prev,
|
||||
enabled,
|
||||
messagesSinceLastPush: 0,
|
||||
lastInteraction: Date.now(),
|
||||
}));
|
||||
}, [setState]);
|
||||
|
||||
// Check if there's unpushed work that should trigger warning icon
|
||||
const hasUnpushedWork = gitStatus?.isGitRepo && (
|
||||
gitStatus.hasUncommittedChanges ||
|
||||
gitStatus.ahead > 0 ||
|
||||
gitStatus.remotes.length === 0
|
||||
);
|
||||
|
||||
return {
|
||||
shouldShowReminder: shouldShowReminder(),
|
||||
incrementMessages,
|
||||
resetReminder,
|
||||
enabled: state.enabled,
|
||||
setEnabled,
|
||||
hasUnpushedWork: hasUnpushedWork || false,
|
||||
gitStatus,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { parseRepositoryAnnouncement } from './announceRepository';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
// Valid test npub for GRASP URL testing
|
||||
const TEST_NPUB = 'npub1cmzxsdtwlu5m42vmqrkkcx50pc7anr5754ncmn380gmf4gcjsgms7vk7pj';
|
||||
|
||||
|
||||
describe('parseRepositoryAnnouncement', () => {
|
||||
// Helper to create a mock repository announcement event
|
||||
const createMockEvent = (tags: string[][]): NostrEvent => ({
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
kind: 30617,
|
||||
content: '',
|
||||
tags,
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
sig: 'test-sig',
|
||||
});
|
||||
|
||||
it('should throw error for non-30617 events', () => {
|
||||
const event = createMockEvent([]);
|
||||
event.kind = 1;
|
||||
|
||||
expect(() => parseRepositoryAnnouncement(event)).toThrow('Expected kind 30617, got 1');
|
||||
});
|
||||
|
||||
it('should parse basic repository fields', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'my-repo'],
|
||||
['name', 'My Repository'],
|
||||
['description', 'A test repository'],
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('my-repo');
|
||||
expect(result.name).toBe('My Repository');
|
||||
expect(result.description).toBe('A test repository');
|
||||
expect(result.httpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should handle missing optional fields', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'minimal-repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('minimal-repo');
|
||||
expect(result.name).toBeUndefined();
|
||||
expect(result.description).toBeUndefined();
|
||||
expect(result.earliestCommit).toBeUndefined();
|
||||
expect(result.maintainers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should parse multiple values in single tag (NIP-34 format)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['web', 'https://example.com', 'https://mirror.example.com'],
|
||||
['clone', 'https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://relay1.com', 'wss://relay2.com'],
|
||||
['maintainers', 'pubkey1', 'pubkey2', 'pubkey3'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.webUrls).toEqual(['https://example.com', 'https://mirror.example.com']);
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://github.com/user/repo.git',
|
||||
'https://gitlab.com/user/repo.git',
|
||||
]);
|
||||
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
|
||||
expect(result.maintainers).toEqual(['pubkey1', 'pubkey2', 'pubkey3']);
|
||||
});
|
||||
|
||||
it('should parse multiple separate tags (backward compatibility)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://relay1.com'],
|
||||
['relays', 'wss://relay2.com'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://github.com/user/repo.git',
|
||||
'https://gitlab.com/user/repo.git',
|
||||
]);
|
||||
expect(result.relays).toEqual(['wss://relay1.com', 'wss://relay2.com']);
|
||||
});
|
||||
|
||||
it('should extract earliest unique commit (euc)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['r', 'abc123def456', 'euc'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.earliestCommit).toBe('abc123def456');
|
||||
});
|
||||
|
||||
it('should ignore r tags without euc marker', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['r', 'abc123def456'],
|
||||
['r', 'other-value', 'other-marker'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.earliestCommit).toBeUndefined();
|
||||
});
|
||||
|
||||
describe('graspServers - GRASP server detection', () => {
|
||||
it('should identify GRASP servers from clone and relays tags (NIP-34 format)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
expect(parsed.graspServers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(parsed.graspServers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should identify GRASP servers from clone and relays tags (multiple tags format)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should require both clone and relays tags to identify GRASP server', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
// Missing relays tag for git.shakespeare.diy
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
// Missing clone tag for relay.ngit.dev
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`]);
|
||||
});
|
||||
|
||||
it('should validate npub pattern in clone URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://git.shakespeare.diy/invalid-npub/myrepo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://git.shakespeare.diy/invalid-npub/myrepo.git']);
|
||||
});
|
||||
|
||||
it('should require .git extension in clone URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([`https://git.shakespeare.diy/${TEST_NPUB}/myrepo`]);
|
||||
});
|
||||
|
||||
it('should handle multiple clone URLs for same server', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo1.git`],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo2.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should reject http:// clone URLs and only accept https://', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `http://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
// Only https://relay.ngit.dev should be identified as GRASP server
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
expect(servers).toHaveLength(1);
|
||||
// http:// URL should not be included in httpsCloneUrls at all
|
||||
expect(parsed.httpsCloneUrls).toEqual([`https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle ws and wss protocols', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'ws://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (separate tags)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (mixed in single tag)', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git', 'https://gitlab.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should return empty array when no GRASP servers found', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['relays', 'wss://relay.nostr.band/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual(['https://github.com/user/repo.git']);
|
||||
});
|
||||
|
||||
it('should handle invalid URLs gracefully', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'not-a-valid-url'],
|
||||
['relays', 'also-invalid'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle paths with subdirectories after npub', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/org/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle empty tags array', () => {
|
||||
const event = createMockEvent([]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle tags with empty values', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', ''],
|
||||
['relays', ''],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual([]);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle clone URLs with trailing slashes', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle relay URLs without trailing slashes', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle mixed trailing slashes in clone and relay URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
const servers = parsed.graspServers;
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
expect(parsed.nonGraspHttpsCloneUrls).toEqual([]);
|
||||
});
|
||||
});
|
||||
|
||||
it('should filter out invalid URLs', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://valid.com/repo.git', 'not-a-url', 'ftp://invalid.com/repo.git'],
|
||||
['relays', 'wss://valid.com', 'not-a-url', 'http://invalid.com'],
|
||||
['web', 'https://valid.com', 'not-a-url'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.httpsCloneUrls).toEqual(['https://valid.com/repo.git']);
|
||||
expect(result.relays).toEqual(['wss://valid.com']);
|
||||
expect(result.webUrls).toEqual(['https://valid.com', 'not-a-url']); // web URLs are not validated
|
||||
});
|
||||
|
||||
it('should preserve raw event', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.event).toBe(event);
|
||||
expect(result.event.id).toBe('test-id');
|
||||
expect(result.event.pubkey).toBe('test-pubkey');
|
||||
});
|
||||
|
||||
it('should handle empty identifier gracefully', () => {
|
||||
const event = createMockEvent([
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.identifier).toBe('');
|
||||
});
|
||||
|
||||
it('should handle empty arrays for missing multi-value tags', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.webUrls).toEqual([]);
|
||||
expect(result.relays).toEqual([]);
|
||||
expect(result.maintainers).toEqual([]);
|
||||
expect(result.graspServers).toEqual([]);
|
||||
expect(result.nonGraspRelays).toEqual([]);
|
||||
});
|
||||
|
||||
it('should accept both ws and wss protocols for relays', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'https://example.com/repo.git'],
|
||||
['relays', 'ws://insecure.example.com', 'wss://secure.example.com'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
expect(result.relays).toEqual([
|
||||
'ws://insecure.example.com',
|
||||
'wss://secure.example.com',
|
||||
]);
|
||||
});
|
||||
|
||||
it('should only accept https:// protocol for clone URLs (reject http://)', () => {
|
||||
const event = createMockEvent([
|
||||
['d', 'repo'],
|
||||
['clone', 'http://insecure.example.com/repo.git', 'https://secure.example.com/repo.git'],
|
||||
]);
|
||||
|
||||
const result = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Only https:// URL should be included
|
||||
expect(result.httpsCloneUrls).toEqual([
|
||||
'https://secure.example.com/repo.git',
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -1,4 +1,5 @@
|
||||
import type { EventTemplate } from 'nostr-tools';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { nip19 } from 'nostr-tools';
|
||||
|
||||
export interface RepositoryAnnouncementData {
|
||||
@@ -18,6 +19,36 @@ export interface RepositoryAnnouncementData {
|
||||
earliestCommit?: string;
|
||||
}
|
||||
|
||||
/**
|
||||
* Parsed NIP-34 repository announcement with categorized data
|
||||
*/
|
||||
export interface RepositoryAnnouncement {
|
||||
/** Repository identifier (d tag) */
|
||||
identifier: string;
|
||||
/** Human-readable name */
|
||||
name?: string;
|
||||
/** Description of the repository */
|
||||
description?: string;
|
||||
/** Web URLs where repository can be browsed */
|
||||
webUrls: string[];
|
||||
/** All clone URLs (https) - to support http we would need to store graspServers with ws|wss:// prefix */
|
||||
httpsCloneUrls: string[];
|
||||
/** valid ws:// or wss:// Repository relay URLs*/
|
||||
relays: string[];
|
||||
/** Earliest unique commit (root commit SHA) */
|
||||
earliestCommit?: string;
|
||||
/** Maintainer public keys */
|
||||
maintainers: string[];
|
||||
/** GRASP servers (hostname only) - servers that appear in both clone and relays with valid pattern */
|
||||
graspServers: string[];
|
||||
/** Clone URLs that are NOT GRASP servers */
|
||||
nonGraspHttpsCloneUrls: string[];
|
||||
/** Relay URLs that are NOT GRASP servers */
|
||||
nonGraspRelays: string[];
|
||||
/** Raw event for advanced use */
|
||||
event: NostrEvent;
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a NIP-34 repository announcement event (kind 30617)
|
||||
*
|
||||
@@ -150,3 +181,181 @@ export function validateRepositoryAnnouncementData(
|
||||
throw new Error('At least one clone URL is required');
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Parses a NIP-34 repository announcement event (kind 30617) into a structured format.
|
||||
*
|
||||
* This function extracts all relevant data from the event tags and categorizes servers
|
||||
* into GRASP and non-GRASP categories. GRASP servers are identified by matching:
|
||||
* - clone tag contains URL(s) matching: [http|https]://<hostname>/<valid-npub>/<repo>.git
|
||||
* - relays tag contains URL(s) matching: [ws|wss]://<hostname>
|
||||
*
|
||||
* @param event - A kind 30617 repository announcement event
|
||||
* @returns Parsed repository data with categorized servers
|
||||
* @throws Error if event is not kind 30617
|
||||
*
|
||||
* @example
|
||||
* ```typescript
|
||||
* const repo = parseRepositoryAnnouncement(event);
|
||||
* console.log(repo.identifier); // "my-repo"
|
||||
* console.log(repo.graspServers); // ["git.example.com"]
|
||||
* console.log(repo.nonGraspCloneUrls); // ["https://github.com/user/repo.git"]
|
||||
* ```
|
||||
*/
|
||||
export function parseRepositoryAnnouncement(event: NostrEvent): RepositoryAnnouncement {
|
||||
if (event.kind !== 30617) {
|
||||
throw new Error(`Expected kind 30617, got ${event.kind}`);
|
||||
}
|
||||
|
||||
// Extract basic fields
|
||||
const identifier = event.tags.find(([name]) => name === 'd')?.[1] || '';
|
||||
const name = event.tags.find(([name]) => name === 'name')?.[1];
|
||||
const description = event.tags.find(([name]) => name === 'description')?.[1];
|
||||
|
||||
// Extract multi-value tags
|
||||
const webUrls: string[] = [];
|
||||
const httpsCloneUrls: string[] = [];
|
||||
const relays: string[] = [];
|
||||
const maintainers: string[] = [];
|
||||
let earliestCommit: string | undefined;
|
||||
|
||||
// Track servers for GRASP detection
|
||||
const validCloneServers = new Set<string>(); // Servers with valid GRASP clone URLs
|
||||
const relayServers = new Set<string>(); // Servers in relays tags
|
||||
const cloneUrlsByServer = new Map<string, string[]>(); // Map hostname -> clone URLs
|
||||
const relayUrlsByServer = new Map<string, string[]>(); // Map hostname -> relay URLs
|
||||
|
||||
for (const [name, ...values] of event.tags) {
|
||||
switch (name) {
|
||||
case 'web':
|
||||
// All values after tag name are web URLs
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
webUrls.push(value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'clone':
|
||||
// All values after tag name are clone URLs
|
||||
// Also track which ones match GRASP pattern
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
|
||||
// Only accept https:// URLs (reject http://)
|
||||
if (url.protocol === 'https:') {
|
||||
httpsCloneUrls.push(value); // Use original value to preserve exact format
|
||||
|
||||
// Check if this matches GRASP pattern: https://<hostname>/<npub>/<repo>.git
|
||||
if ((value.endsWith('.git/') || value.endsWith('.git')) && value.includes('/npub1')) {
|
||||
// Extract and validate the npub using nip19.decode
|
||||
// Match npub1 followed by alphanumeric chars, ending at /
|
||||
const npubMatch = value.match(/\/npub1([a-z0-9]+)\//);
|
||||
if (npubMatch) {
|
||||
const npub = `npub1${npubMatch[1]}`;
|
||||
try {
|
||||
const decoded = nip19.decode(npub);
|
||||
if (decoded.type === 'npub') {
|
||||
// Valid GRASP clone URL
|
||||
validCloneServers.add(url.hostname);
|
||||
|
||||
if (!cloneUrlsByServer.has(url.hostname)) {
|
||||
cloneUrlsByServer.set(url.hostname, []);
|
||||
}
|
||||
cloneUrlsByServer.get(url.hostname)!.push(value);
|
||||
}
|
||||
} catch {
|
||||
// Invalid npub, not a GRASP server
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'relays':
|
||||
// All values after tag name are relay URLs
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
try {
|
||||
const url = new URL(value);
|
||||
if (url.protocol === 'ws:' || url.protocol === 'wss:') {
|
||||
relays.push(value); // Use original value to preserve exact format
|
||||
relayServers.add(url.hostname);
|
||||
|
||||
if (!relayUrlsByServer.has(url.hostname)) {
|
||||
relayUrlsByServer.set(url.hostname, []);
|
||||
}
|
||||
relayUrlsByServer.get(url.hostname)!.push(value);
|
||||
}
|
||||
} catch {
|
||||
// Invalid URL, skip
|
||||
}
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'maintainers':
|
||||
// All values after tag name are maintainer pubkeys
|
||||
for (const value of values) {
|
||||
if (value) {
|
||||
maintainers.push(value);
|
||||
}
|
||||
}
|
||||
break;
|
||||
|
||||
case 'r':
|
||||
// Check for earliest unique commit marker
|
||||
if (values.length >= 2 && values[1] === 'euc') {
|
||||
earliestCommit = values[0];
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Identify GRASP servers: must appear in BOTH clone (with valid pattern) and relays
|
||||
const graspServers = [...validCloneServers].filter(server =>
|
||||
relayServers.has(server)
|
||||
);
|
||||
|
||||
// Categorize clone URLs
|
||||
const nonGraspHttpsCloneUrls = httpsCloneUrls.filter(url => {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return !graspServers.includes(hostname);
|
||||
} catch {
|
||||
return true; // Invalid URLs go to non-GRASP
|
||||
}
|
||||
});
|
||||
|
||||
// Categorize relay URLs
|
||||
const nonGraspRelays = relays.filter(url => {
|
||||
try {
|
||||
const hostname = new URL(url).hostname;
|
||||
return !graspServers.includes(hostname);
|
||||
} catch {
|
||||
return true; // Invalid URLs go to non-GRASP
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
identifier,
|
||||
name,
|
||||
description,
|
||||
webUrls,
|
||||
httpsCloneUrls,
|
||||
relays,
|
||||
earliestCommit,
|
||||
maintainers,
|
||||
graspServers,
|
||||
nonGraspHttpsCloneUrls,
|
||||
nonGraspRelays,
|
||||
event,
|
||||
};
|
||||
}
|
||||
@@ -1,4 +1,5 @@
|
||||
import { NRelay1, type NostrEvent } from '@nostrify/nostrify';
|
||||
import { parseRepositoryAnnouncement } from '@/lib/announceRepository';
|
||||
import type {
|
||||
GitHostProvider,
|
||||
GitHostConfig,
|
||||
@@ -58,31 +59,23 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
async getRepository(owner: string, repo: string): Promise<GitRepository> {
|
||||
const event = await this.queryRepo(owner, repo);
|
||||
|
||||
const getName = () => event.tags.find((t: string[]) => t[0] === 'name')?.[1] || repo;
|
||||
const getDescription = () => event.tags.find((t: string[]) => t[0] === 'description')?.[1];
|
||||
const getWebUrl = () => event.tags.find((t: string[]) => t[0] === 'web')?.[1] || '';
|
||||
const getCloneUrl = () => event.tags.find((t: string[]) => t[0] === 'clone')?.[1] || '';
|
||||
// Per NIP-34, all relays are in a single tag: ["relays", "wss://...", "wss://...", ...]
|
||||
const getRelays = () => {
|
||||
const relayTag = event.tags.find((t: string[]) => t[0] === 'relays');
|
||||
return relayTag ? relayTag.slice(1) : [];
|
||||
};
|
||||
// Parse the NIP-34 repository announcement
|
||||
const repoAnn = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Update relay to use repository's designated relays
|
||||
const repoRelays = getRelays();
|
||||
if (repoRelays.length > 0) {
|
||||
this.relayUrls = repoRelays;
|
||||
this.relay = new NRelay1(repoRelays[0]);
|
||||
if (repoAnn.relays.length > 0) {
|
||||
this.relayUrls = repoAnn.relays;
|
||||
this.relay = new NRelay1(repoAnn.relays[0]);
|
||||
}
|
||||
|
||||
return {
|
||||
owner,
|
||||
name: getName(),
|
||||
name: repoAnn.name || repo,
|
||||
fullName: `${owner}/${repo}`,
|
||||
defaultBranch: 'main', // Nostr git doesn't specify, assume main
|
||||
cloneUrl: getCloneUrl(),
|
||||
webUrl: getWebUrl(),
|
||||
description: getDescription(),
|
||||
cloneUrl: repoAnn.httpsCloneUrls[0] || '',
|
||||
webUrl: repoAnn.webUrls[0] || '',
|
||||
description: repoAnn.description,
|
||||
isPrivate: false, // All Nostr repos are public
|
||||
};
|
||||
}
|
||||
@@ -92,12 +85,12 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
// But only maintainers can apply them
|
||||
// Check if current user is listed as a maintainer
|
||||
const event = await this.queryRepo(owner, repo);
|
||||
// Per NIP-34, all maintainers are in a single tag: ["maintainers", "pubkey1", "pubkey2", ...]
|
||||
const maintainerTag = event.tags.find((t: string[]) => t[0] === 'maintainers');
|
||||
const maintainers = maintainerTag ? maintainerTag.slice(1) : [];
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(event);
|
||||
|
||||
// Repo owner is always a maintainer
|
||||
const isMaintainer = owner === this.pubkey || maintainers.includes(this.pubkey);
|
||||
const isMaintainer = owner === this.pubkey || parsed.maintainers.includes(this.pubkey);
|
||||
return isMaintainer;
|
||||
}
|
||||
|
||||
@@ -106,8 +99,9 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
// Users submit patches to the original repo
|
||||
// For compatibility with the PR flow, we return a "virtual fork"
|
||||
const repoEvent = await this.queryRepo(owner, repo);
|
||||
const cloneUrl = repoEvent.tags.find((t: string[]) => t[0] === 'clone')?.[1] || '';
|
||||
const webUrl = repoEvent.tags.find((t: string[]) => t[0] === 'web')?.[1] || '';
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// The "fork" is actually just the user's local copy
|
||||
// We'll use this to track that patches come from the user
|
||||
@@ -115,8 +109,8 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
owner: this.pubkey,
|
||||
name: repo,
|
||||
fullName: `${this.pubkey}/${repo}`,
|
||||
cloneUrl,
|
||||
webUrl,
|
||||
cloneUrl: parsed.httpsCloneUrls[0] || '',
|
||||
webUrl: parsed.webUrls[0] || '',
|
||||
parentFullName: `${owner}/${repo}`,
|
||||
};
|
||||
}
|
||||
@@ -139,8 +133,11 @@ export class NostrGitProvider implements GitHostProvider {
|
||||
const [owner, repo] = options.baseRepo.split('/');
|
||||
const repoEvent = await this.queryRepo(owner, repo);
|
||||
|
||||
// Parse the NIP-34 repository announcement
|
||||
const parsed = parseRepositoryAnnouncement(repoEvent);
|
||||
|
||||
// Get the earliest unique commit (euc) for the repository
|
||||
const euc = repoEvent.tags.find((t: string[]) => t[0] === 'r' && t[2] === 'euc')?.[1];
|
||||
const euc = parsed.earliestCommit;
|
||||
|
||||
// Create patch content from the provided body or generate a simple patch description
|
||||
const patchContent = options.body ||
|
||||
|
||||
@@ -1,219 +0,0 @@
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import type { NostrEvent } from '@nostrify/nostrify';
|
||||
import { getNgitServers } from './git';
|
||||
|
||||
// Valid test npub for GRASP URL testing
|
||||
const TEST_NPUB = 'npub1cmzxsdtwlu5m42vmqrkkcx50pc7anr5754ncmn380gmf4gcjsgms7vk7pj';
|
||||
|
||||
// Helper to create a mock repository announcement event
|
||||
function createRepoEvent(tags: string[][]): NostrEvent {
|
||||
return {
|
||||
id: 'test-id',
|
||||
pubkey: 'test-pubkey',
|
||||
created_at: Math.floor(Date.now() / 1000),
|
||||
kind: 30617,
|
||||
tags,
|
||||
content: '',
|
||||
sig: 'test-sig',
|
||||
};
|
||||
}
|
||||
|
||||
describe('getNgitServers', () => {
|
||||
it('should identify GRASP servers from clone and relays tags (NIP-34 format)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should identify GRASP servers from clone and relays tags (multiple tags format)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should require both clone and relays tags to identify GRASP server', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
// Missing relays tag for git.shakespeare.diy
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
// Missing clone tag for relay.ngit.dev
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should validate npub pattern in clone URLs', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://git.shakespeare.diy/invalid-npub/myrepo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
});
|
||||
|
||||
it('should require .git extension in clone URLs', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['relay.ngit.dev']);
|
||||
});
|
||||
|
||||
it('should handle multiple clone URLs for same server', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo1.git`],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/repo2.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle http and https protocols', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `http://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should handle ws and wss protocols', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'ws://git.shakespeare.diy/'],
|
||||
['clone', `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (separate tags)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should ignore non-GRASP clone URLs (mixed in single tag)', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://github.com/user/repo.git', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`, 'https://gitlab.com/user/repo.git'],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should return empty array when no GRASP servers found', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'https://github.com/user/repo.git'],
|
||||
['relays', 'wss://relay.nostr.band/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle invalid URLs gracefully', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', 'not-a-valid-url'],
|
||||
['relays', 'also-invalid'],
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle paths with subdirectories after npub', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/org/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle empty tags array', () => {
|
||||
const event = createRepoEvent([]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle tags with empty values', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', ''],
|
||||
['relays', ''],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual([]);
|
||||
});
|
||||
|
||||
it('should handle clone URLs with trailing slashes', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`],
|
||||
['relays', 'wss://git.shakespeare.diy/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle relay URLs without trailing slashes', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(['git.shakespeare.diy']);
|
||||
});
|
||||
|
||||
it('should handle mixed trailing slashes in clone and relay URLs', () => {
|
||||
const event = createRepoEvent([
|
||||
['clone', `https://git.shakespeare.diy/${TEST_NPUB}/myrepo.git/`, `https://relay.ngit.dev/${TEST_NPUB}/myrepo.git`],
|
||||
['relays', 'wss://git.shakespeare.diy', 'wss://relay.ngit.dev/'],
|
||||
]);
|
||||
|
||||
const servers = getNgitServers(event);
|
||||
expect(servers).toEqual(expect.arrayContaining(['git.shakespeare.diy', 'relay.ngit.dev']));
|
||||
expect(servers).toHaveLength(2);
|
||||
});
|
||||
});
|
||||
+632
-354
File diff suppressed because it is too large.
Load diff
+150
-5
@@ -1,6 +1,5 @@
|
||||
import { describe, it, expect, beforeEach } from 'vitest';
|
||||
import { LightningFSAdapter } from './LightningFSAdapter';
|
||||
import LightningFS from '@isomorphic-git/lightning-fs';
|
||||
import type { JSRuntimeFS } from './JSRuntime';
|
||||
import {
|
||||
getPlugins,
|
||||
getPluginSkills,
|
||||
@@ -10,12 +9,158 @@ import {
|
||||
isValidSkillName,
|
||||
} from './plugins';
|
||||
|
||||
// Mock filesystem for testing
|
||||
class MockFS implements JSRuntimeFS {
|
||||
private files: Map<string, string | Uint8Array> = new Map();
|
||||
private dirs: Set<string> = new Set();
|
||||
|
||||
async readFile(path: string): Promise<Uint8Array>;
|
||||
async readFile(path: string, options: 'utf8'): Promise<string>;
|
||||
async readFile(path: string, options: string): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: 'utf8' }): Promise<string>;
|
||||
async readFile(path: string, options: { encoding: string }): Promise<string>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array>;
|
||||
async readFile(path: string, options?: string | { encoding?: string }): Promise<string | Uint8Array> {
|
||||
const content = this.files.get(path);
|
||||
if (!content) throw new Error(`ENOENT: ${path}`);
|
||||
|
||||
const encoding = typeof options === 'string' ? options : options?.encoding;
|
||||
if (encoding === 'utf8') {
|
||||
return typeof content === 'string' ? content : new TextDecoder().decode(content);
|
||||
}
|
||||
return typeof content === 'string' ? new TextEncoder().encode(content) : content;
|
||||
}
|
||||
|
||||
async writeFile(path: string, data: string | Uint8Array): Promise<void> {
|
||||
this.files.set(path, data);
|
||||
// Auto-create parent directories
|
||||
const parts = path.split('/');
|
||||
for (let i = 1; i < parts.length; i++) {
|
||||
this.dirs.add(parts.slice(0, i).join('/') || '/');
|
||||
}
|
||||
}
|
||||
|
||||
async readdir(path: string): Promise<string[]>;
|
||||
async readdir(path: string, options: { withFileTypes: true }): Promise<import('./JSRuntime').DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]>;
|
||||
async readdir(path: string, options?: { withFileTypes?: boolean }): Promise<string[] | import('./JSRuntime').DirectoryEntry[]> {
|
||||
if (!this.dirs.has(path)) throw new Error(`ENOENT: ${path}`);
|
||||
|
||||
const entries = new Set<string>();
|
||||
const prefix = path === '/' ? '/' : path + '/';
|
||||
|
||||
// Check files
|
||||
for (const filePath of this.files.keys()) {
|
||||
if (filePath.startsWith(prefix)) {
|
||||
const relativePath = filePath.slice(prefix.length);
|
||||
const firstPart = relativePath.split('/')[0];
|
||||
if (firstPart) entries.add(firstPart);
|
||||
}
|
||||
}
|
||||
|
||||
// Check directories
|
||||
for (const dirPath of this.dirs) {
|
||||
if (dirPath.startsWith(prefix) && dirPath !== path) {
|
||||
const relativePath = dirPath.slice(prefix.length);
|
||||
const firstPart = relativePath.split('/')[0];
|
||||
if (firstPart) entries.add(firstPart);
|
||||
}
|
||||
}
|
||||
|
||||
const names = Array.from(entries);
|
||||
|
||||
if (options?.withFileTypes) {
|
||||
return names.map(name => {
|
||||
const fullPath = path === '/' ? `/${name}` : `${path}/${name}`;
|
||||
const isDir = this.dirs.has(fullPath);
|
||||
return {
|
||||
name,
|
||||
isDirectory: () => isDir,
|
||||
isFile: () => !isDir,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
return names;
|
||||
}
|
||||
|
||||
async mkdir(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
if (options?.recursive) {
|
||||
const parts = path.split('/');
|
||||
for (let i = 1; i <= parts.length; i++) {
|
||||
const dir = parts.slice(0, i).join('/') || '/';
|
||||
this.dirs.add(dir);
|
||||
}
|
||||
} else {
|
||||
this.dirs.add(path);
|
||||
}
|
||||
}
|
||||
|
||||
async stat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
|
||||
const isDir = this.dirs.has(path);
|
||||
const isFile = this.files.has(path);
|
||||
|
||||
if (!isDir && !isFile) throw new Error(`ENOENT: ${path}`);
|
||||
|
||||
return {
|
||||
isDirectory: () => isDir,
|
||||
isFile: () => isFile,
|
||||
};
|
||||
}
|
||||
|
||||
async rm(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
this.files.delete(path);
|
||||
this.dirs.delete(path);
|
||||
|
||||
if (options?.recursive) {
|
||||
const prefix = path + '/';
|
||||
for (const filePath of Array.from(this.files.keys())) {
|
||||
if (filePath.startsWith(prefix)) {
|
||||
this.files.delete(filePath);
|
||||
}
|
||||
}
|
||||
for (const dirPath of Array.from(this.dirs)) {
|
||||
if (dirPath.startsWith(prefix)) {
|
||||
this.dirs.delete(dirPath);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async rmdir(path: string, options?: { recursive?: boolean }): Promise<void> {
|
||||
return this.rm(path, options);
|
||||
}
|
||||
|
||||
async unlink(path: string): Promise<void> {
|
||||
this.files.delete(path);
|
||||
}
|
||||
|
||||
async rename(oldPath: string, newPath: string): Promise<void> {
|
||||
const content = this.files.get(oldPath);
|
||||
if (content) {
|
||||
this.files.set(newPath, content);
|
||||
this.files.delete(oldPath);
|
||||
}
|
||||
}
|
||||
|
||||
async lstat(path: string): Promise<{ isDirectory: () => boolean; isFile: () => boolean }> {
|
||||
return this.stat(path);
|
||||
}
|
||||
|
||||
async readlink(_path: string): Promise<string> {
|
||||
throw new Error('Symlinks not supported in MockFS');
|
||||
}
|
||||
|
||||
async symlink(_target: string, _path: string): Promise<void> {
|
||||
throw new Error('Symlinks not supported in MockFS');
|
||||
}
|
||||
}
|
||||
|
||||
describe('plugins', () => {
|
||||
let fs: LightningFSAdapter;
|
||||
let fs: MockFS;
|
||||
|
||||
beforeEach(() => {
|
||||
const lightningFS = new LightningFS('test-plugins-fs');
|
||||
fs = new LightningFSAdapter(lightningFS.promises);
|
||||
fs = new MockFS();
|
||||
});
|
||||
|
||||
describe('isValidSkillName', () => {
|
||||
|
||||
@@ -16,3 +16,56 @@ export function shuffleArray<T>(array: T[]): T[] {
|
||||
}
|
||||
return shuffled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Formats a timestamp as a relative time string (e.g., "2 hours ago", "just now")
|
||||
* @param timestamp - Unix timestamp in seconds or milliseconds, or a Date object
|
||||
* @returns Human-readable relative time string
|
||||
*/
|
||||
export function formatRelativeTime(timestamp: number | Date): string {
|
||||
const now = Date.now();
|
||||
const time = timestamp instanceof Date ? timestamp.getTime() : timestamp;
|
||||
// Handle both seconds and milliseconds timestamps
|
||||
const timestampMs = time < 10000000000 ? time * 1000 : time;
|
||||
const diffMs = now - timestampMs;
|
||||
|
||||
const diffSeconds = Math.floor(diffMs / 1000);
|
||||
const diffMinutes = Math.floor(diffMs / (1000 * 60));
|
||||
const diffHours = Math.floor(diffMs / (1000 * 60 * 60));
|
||||
const diffDays = Math.floor(diffMs / (1000 * 60 * 60 * 24));
|
||||
const diffWeeks = Math.floor(diffDays / 7);
|
||||
const diffMonths = Math.floor(diffDays / 30);
|
||||
const diffYears = Math.floor(diffDays / 365);
|
||||
|
||||
if (diffSeconds < 25) {
|
||||
return 'just now';
|
||||
} else if (diffSeconds < 35) {
|
||||
return 'half a minute ago'
|
||||
} else if (diffSeconds < 55) {
|
||||
return 'less than a minute ago'
|
||||
} else if (diffMinutes < 2) {
|
||||
return 'a minute ago';
|
||||
} else if (diffMinutes < 60) {
|
||||
return `${diffMinutes} minutes ago`;
|
||||
} else if (diffHours === 1) {
|
||||
return 'an hour ago';
|
||||
} else if (diffHours < 24) {
|
||||
return `${diffHours} hours ago`;
|
||||
} else if (diffDays === 1) {
|
||||
return '1 day ago';
|
||||
} else if (diffDays < 7) {
|
||||
return `${diffDays} days ago`;
|
||||
} else if (diffWeeks === 1) {
|
||||
return '1 week ago';
|
||||
} else if (diffWeeks < 4) {
|
||||
return `${diffWeeks} weeks ago`;
|
||||
} else if (diffMonths === 1) {
|
||||
return '1 month ago';
|
||||
} else if (diffMonths < 12) {
|
||||
return `${diffMonths} months ago`;
|
||||
} else if (diffYears === 1) {
|
||||
return '1 year ago';
|
||||
} else {
|
||||
return `${diffYears} years ago`;
|
||||
}
|
||||
}
|
||||
@@ -57,6 +57,8 @@
|
||||
"temporaryDirectoryDescription": "Filesystem path for temporary files",
|
||||
"sentryDsn": "Sentry DSN",
|
||||
"sentryDsnDescription": "Sentry Data Source Name (DSN) for error reporting. Leave empty to disable Sentry.",
|
||||
"pushReminders": "Push reminders",
|
||||
"pushRemindersDescription": "Show periodic reminders to push your code to a remote repository to prevent data loss.",
|
||||
"shareErrorReports": "Share error reports",
|
||||
"shareErrorReportsDescription": "Help improve this app by automatically sending crash and error reports.",
|
||||
"english": "English",
|
||||
|
||||
@@ -8,12 +8,14 @@ import { Label } from "@/components/ui/label";
|
||||
import { useIsMobile } from "@/hooks/useIsMobile";
|
||||
import { useNavigate } from "react-router-dom";
|
||||
import { useAppContext } from "@/hooks/useAppContext";
|
||||
import { usePushReminder } from "@/hooks/usePushReminder";
|
||||
|
||||
export function Preferences() {
|
||||
const { t } = useTranslation();
|
||||
const isMobile = useIsMobile();
|
||||
const navigate = useNavigate();
|
||||
const { config, updateConfig } = useAppContext();
|
||||
const pushReminder = usePushReminder(null);
|
||||
|
||||
return (
|
||||
<div className="p-6 space-y-6">
|
||||
@@ -73,6 +75,26 @@ export function Preferences() {
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
<Label htmlFor="push-reminders" className="text-sm font-medium">
|
||||
{t('pushReminders')}
|
||||
</Label>
|
||||
</div>
|
||||
<Switch
|
||||
id="push-reminders"
|
||||
checked={pushReminder.enabled}
|
||||
onCheckedChange={(checked) => {
|
||||
pushReminder.setEnabled(checked);
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{t('pushRemindersDescription')}
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<div className="space-y-2">
|
||||
<div className="flex items-center justify-between">
|
||||
<div className="space-y-0.5">
|
||||
|
||||
@@ -15,11 +15,14 @@ import { useNavigate } from 'react-router-dom';
|
||||
import { ActionsMenu } from '@/components/ActionsMenu';
|
||||
import { useIsMobile } from '@/hooks/useIsMobile';
|
||||
import { GitStatusIndicator } from '@/components/GitStatusIndicator';
|
||||
import { PushWarningButton } from '@/components/PushWarningButton';
|
||||
import { PushReminderDialog } from '@/components/PushReminderDialog';
|
||||
import { StarButton } from '@/components/StarButton';
|
||||
import { useBuildProject } from '@/hooks/useBuildProject';
|
||||
import { useIsProjectPreviewable } from '@/hooks/useIsProjectPreviewable';
|
||||
import { useConsoleError } from '@/hooks/useConsoleError';
|
||||
import { useAutoBuild } from '@/hooks/useAutoBuild';
|
||||
import { usePushReminder } from '@/hooks/usePushReminder';
|
||||
|
||||
export function ProjectView() {
|
||||
const { projectId } = useParams<{ projectId: string }>();
|
||||
@@ -30,6 +33,7 @@ export function ProjectView() {
|
||||
const [mobileView, setMobileView] = useState<'chat' | 'preview' | 'code'>('chat');
|
||||
const [isAILoading, setIsAILoading] = useState(false);
|
||||
const [isProjectDetailsOpen, setIsProjectDetailsOpen] = useState(false);
|
||||
const [isPushReminderOpen, setIsPushReminderOpen] = useState(false);
|
||||
|
||||
// Use console error state from provider
|
||||
const { consoleError, dismissConsoleError, clearErrors } = useConsoleError();
|
||||
@@ -43,6 +47,7 @@ export function ProjectView() {
|
||||
|
||||
const build = useBuildProject(projectId!);
|
||||
const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!);
|
||||
const pushReminder = usePushReminder(projectId || null);
|
||||
|
||||
// Enable auto-build for previewable projects
|
||||
useAutoBuild({
|
||||
@@ -105,6 +110,18 @@ export function ProjectView() {
|
||||
setIsAILoading(loading);
|
||||
};
|
||||
|
||||
// Handle message sent - increment push reminder counter
|
||||
const handleMessageSent = useCallback(() => {
|
||||
pushReminder.incrementMessages();
|
||||
}, [pushReminder]);
|
||||
|
||||
// Watch for when we should show the reminder (after state updates)
|
||||
useEffect(() => {
|
||||
if (pushReminder.shouldShowReminder && !isPushReminderOpen) {
|
||||
setIsPushReminderOpen(true);
|
||||
}
|
||||
}, [pushReminder.shouldShowReminder, isPushReminderOpen]);
|
||||
|
||||
// Handle first user interaction to enable audio context
|
||||
const handleFirstInteraction = () => {
|
||||
// This will be handled automatically by the useKeepAlive hook
|
||||
@@ -165,6 +182,7 @@ export function ProjectView() {
|
||||
<div className="flex items-center gap-2">
|
||||
{project ? (
|
||||
<>
|
||||
<PushWarningButton projectId={project.id} className="h-8" />
|
||||
<StarButton
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
@@ -227,6 +245,7 @@ export function ProjectView() {
|
||||
onNewChat={handleNewChat}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
onMessageSent={handleMessageSent}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={build.isPending}
|
||||
consoleError={consoleError}
|
||||
@@ -307,6 +326,17 @@ export function ProjectView() {
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Push Reminder Dialog */}
|
||||
{project && (
|
||||
<PushReminderDialog
|
||||
projectId={project.id}
|
||||
open={isPushReminderOpen}
|
||||
onOpenChange={setIsPushReminderOpen}
|
||||
onDisableReminders={() => pushReminder.setEnabled(false)}
|
||||
onDismiss={pushReminder.resetReminder}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
@@ -374,6 +404,7 @@ export function ProjectView() {
|
||||
<div className="flex items-center gap-2">
|
||||
{project ? (
|
||||
<>
|
||||
<PushWarningButton projectId={project.id} className="h-8" />
|
||||
<StarButton
|
||||
projectId={project.id}
|
||||
projectName={project.name}
|
||||
@@ -408,6 +439,7 @@ export function ProjectView() {
|
||||
onNewChat={handleNewChat}
|
||||
onFirstInteraction={handleFirstInteraction}
|
||||
onLoadingChange={handleAILoadingChange}
|
||||
onMessageSent={handleMessageSent}
|
||||
isLoading={isAILoading}
|
||||
isBuildLoading={build.isPending}
|
||||
consoleError={consoleError}
|
||||
@@ -461,6 +493,17 @@ export function ProjectView() {
|
||||
onProjectDeleted={handleProjectDeleted}
|
||||
/>
|
||||
)}
|
||||
|
||||
{/* Push Reminder Dialog */}
|
||||
{project && (
|
||||
<PushReminderDialog
|
||||
projectId={project.id}
|
||||
open={isPushReminderOpen}
|
||||
onOpenChange={setIsPushReminderOpen}
|
||||
onDisableReminders={() => pushReminder.setEnabled(false)}
|
||||
onDismiss={pushReminder.resetReminder}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
);
|
||||
}
|
||||
Reference in new issue
Block a user