diff --git a/AGENTS.md b/AGENTS.md index 953dbea9..31a03366 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 diff --git a/src/components/GitDialog.tsx b/src/components/GitDialog.tsx index 92189d06..8884cbc2 100644 --- a/src/components/GitDialog.tsx +++ b/src/components/GitDialog.tsx @@ -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 {syncStatus.text} + + {/* Last Fetched Info - inline with sync status */} + {gitStatus.remotes.length > 0 && gitFetchData?.fetchedAt && ( + <> + + ยท {formatFetchTime(gitFetchData.fetchedAt)} + + + + )} {gitStatus.remotes.length > 0 && ( diff --git a/src/components/ai/GitHistoryDialog.tsx b/src/components/ai/GitHistoryDialog.tsx index 60079e62..edad41a1 100644 --- a/src/components/ai/GitHistoryDialog.tsx +++ b/src/components/ai/GitHistoryDialog.tsx @@ -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 { diff --git a/src/hooks/useGitFetch.test.tsx b/src/hooks/useGitFetch.test.tsx new file mode 100644 index 00000000..2a14cead --- /dev/null +++ b/src/hooks/useGitFetch.test.tsx @@ -0,0 +1,133 @@ +import { describe, it, expect, vi, beforeEach, afterEach } 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', () => { + beforeEach(() => { + vi.useFakeTimers(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('returns null state when projectId is null', async () => { + const { result } = renderHook(() => useGitFetch(null), { + wrapper: TestApp, + }); + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true); + }); + + expect(result.current.data).toEqual({ + defaultBranch: null, + defaultBranchOid: null, + currentBranch: null, + currentBranchOid: null, + fetchedAt: expect.any(Number), + hasChanges: false, + remoteUrl: null, + }); + }); + + 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 when data is stale', async () => { + const { result } = renderHook(() => useGitFetch('test-project'), { + wrapper: TestApp, + }); + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true); + }); + + const firstFetchTime = result.current.data?.fetchedAt; + + // Advance time to make data stale + vi.advanceTimersByTime(31000); + + // Manually trigger refetch + await result.current.refetch(); + + await waitFor(() => { + expect(result.current.data?.fetchedAt).toBeGreaterThan(firstFetchTime || 0); + }); + }); + + it('automatically refetches every 60 seconds', async () => { + const { result } = renderHook(() => useGitFetch('test-project'), { + wrapper: TestApp, + }); + + await waitFor(() => { + expect(result.current.isSuccess).toBe(true); + }); + + const firstFetchTime = result.current.data?.fetchedAt || 0; + + // Advance time by 60 seconds + vi.advanceTimersByTime(60000); + + await waitFor(() => { + expect(result.current.data?.fetchedAt).toBeGreaterThan(firstFetchTime); + }); + }); +}); diff --git a/src/hooks/useGitFetch.ts b/src/hooks/useGitFetch.ts new file mode 100644 index 00000000..152106e4 --- /dev/null +++ b/src/hooks/useGitFetch.ts @@ -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 => { + 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; +} diff --git a/src/lib/utils.ts b/src/lib/utils.ts index bc146526..bac620ff 100644 --- a/src/lib/utils.ts +++ b/src/lib/utils.ts @@ -16,3 +16,56 @@ export function shuffleArray(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`; + } +}