diff --git a/src/components/GitSyncProvider.tsx b/src/components/GitSyncProvider.tsx index b64dfa69..73839347 100644 --- a/src/components/GitSyncProvider.tsx +++ b/src/components/GitSyncProvider.tsx @@ -1,8 +1,15 @@ -import { useState, useCallback, ReactNode } from 'react'; -import { GitSyncContext, GitOperation, GitSyncState } from '@/contexts/GitSyncContext'; +import { useState, useCallback, ReactNode, useRef } from 'react'; +import { useQueryClient } from '@tanstack/react-query'; +import { GitSyncContext, GitOperation, GitSyncState, FetchResult } from '@/contexts/GitSyncContext'; +import { useGit } from '@/hooks/useGit'; export function GitSyncProvider({ children }: { children: ReactNode }) { const [syncStates, setSyncStates] = useState>(new Map()); + const queryClient = useQueryClient(); + const { git } = useGit(); + + // Track active operations to prevent concurrent operations on the same directory + const activeOperations = useRef>>(new Map()); const startOperation = useCallback((dir: string, operation: GitOperation) => { setSyncStates(prev => { @@ -68,8 +75,147 @@ export function GitSyncProvider({ children }: { children: ReactNode }) { return syncStates.get(dir)?.error; }, [syncStates]); + // Helper to invalidate git status queries + const invalidateGitStatus = useCallback((dir: string) => { + const projectId = dir.split('/').pop(); + if (projectId) { + queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); + } + }, [queryClient]); + + // Helper to ensure only one operation runs at a time per directory + const withOperationLock = useCallback(async ( + dir: string, + operation: GitOperation, + fn: () => Promise + ): Promise => { + // Check if there's already an active operation for this directory + const existingOp = activeOperations.current.get(dir); + if (existingOp) { + // Wait for the existing operation to complete first + await existingOp.catch(() => { + // Ignore errors from previous operation + }); + } + + // Start the new operation + startOperation(dir, operation); + setError(dir, null); + + const promise = fn() + .then(result => { + endOperation(dir); + activeOperations.current.delete(dir); + return result; + }) + .catch(err => { + const error = err instanceof Error ? err : new Error(`${operation} failed`); + endOperation(dir, error); + setError(dir, error); + activeOperations.current.delete(dir); + throw error; + }); + + activeOperations.current.set(dir, promise); + return promise; + }, [startOperation, endOperation, setError]); + + // Git operation: fetch + const fetch = useCallback(async (dir: string, remote = 'origin'): Promise => { + return withOperationLock(dir, 'fetch', async () => { + const fetchResult = await git.fetch({ dir, remote }); + invalidateGitStatus(dir); + return fetchResult; + }); + }, [git, withOperationLock, invalidateGitStatus]); + + // Git operation: pull + const pull = useCallback(async (dir: string, ref: string, _remote = 'origin'): Promise => { + return withOperationLock(dir, 'pull', async () => { + await git.pull({ dir, ref, singleBranch: true }); + invalidateGitStatus(dir); + }); + }, [git, withOperationLock, invalidateGitStatus]); + + // Git operation: push + const push = useCallback(async (dir: string, ref: string, remote = 'origin', force = false): Promise => { + return withOperationLock(dir, 'push', async () => { + await git.push({ dir, remote, ref, force }); + invalidateGitStatus(dir); + }); + }, [git, withOperationLock, invalidateGitStatus]); + + // Git operation: sync (pull then push) + const sync = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise => { + return withOperationLock(dir, 'pull', async () => { + // Pull first + await git.pull({ dir, ref, singleBranch: true }); + + // Then push (update operation type) + startOperation(dir, 'push'); + await git.push({ dir, remote, ref }); + + invalidateGitStatus(dir); + }); + }, [git, withOperationLock, invalidateGitStatus, startOperation]); + + // Git operation: force pull + const forcePull = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise => { + return withOperationLock(dir, 'pull', async () => { + // Step 1: Fetch latest changes from remote + await git.fetch({ + dir, + remote, + ref, + singleBranch: true, + }); + + // Step 2: Get the remote commit SHA + const remoteRef = `refs/remotes/${remote}/${ref}`; + const remoteSha = await git.resolveRef({ dir, ref: remoteRef }); + + // Step 3: Force update the current branch to point to remote + await git.writeRef({ + dir, + ref: `refs/heads/${ref}`, + value: remoteSha, + force: true, + }); + + // Step 4: Force checkout all files (overwrite local changes) + await git.checkout({ + dir, + ref, + force: true, + }); + + invalidateGitStatus(dir); + }); + }, [git, withOperationLock, invalidateGitStatus]); + + // Git operation: force push + const forcePush = useCallback(async (dir: string, ref: string, remote = 'origin'): Promise => { + return withOperationLock(dir, 'push', async () => { + await git.push({ dir, remote, ref, force: true }); + invalidateGitStatus(dir); + }); + }, [git, withOperationLock, invalidateGitStatus]); + return ( - + {children} ); diff --git a/src/components/git-sync/steps/SyncStep.tsx b/src/components/git-sync/steps/SyncStep.tsx index b85a9e71..9efdfa2b 100644 --- a/src/components/git-sync/steps/SyncStep.tsx +++ b/src/components/git-sync/steps/SyncStep.tsx @@ -45,7 +45,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { const { git } = useGit(); const { projectsPath } = useFSPaths(); const { config } = useAppContext(); - const { getState, getError, startOperation, endOperation, setError: setGlobalError } = useGitSyncState(); + const gitSync = useGitSyncState(); const dir = `${projectsPath}/${projectId}`; const ref = gitStatus?.currentBranch || 'main'; @@ -54,30 +54,26 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { const { autosync, isLoading: isLoadingAutosync, setAutosync } = useGitAutosync(dir); // Get unified sync state and error - const syncState = getState(dir); + const syncState = gitSync.getState(dir); const isSyncing = syncState?.isActive || false; const currentOperation = syncState?.operation || null; - const error = getError(dir) || null; - - // Helper to set error for this directory - const setError = useCallback((err: Error | null) => { - setGlobalError(dir, err); - }, [dir, setGlobalError]); + const error = gitSync.getError(dir) || null; const hasRemoteChanges = gitStatus?.remoteBranchExists && ((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0); const commitsAhead = gitStatus?.ahead ?? 0; const commitsBehind = gitStatus?.behind ?? 0; - // Generic git operation handler + // Helper to set error for this directory + const setError = useCallback((err: Error | null) => { + gitSync.setError(dir, err); + }, [dir, gitSync]); + + // Generic git operation handler with success feedback const executeGitOperation = useCallback(async ( - operation: 'pull' | 'push' | 'force-pull' | 'force-push', action: () => Promise ) => { if (!remoteUrl) return; - const gitOp = operation === 'force-pull' ? 'pull' : operation === 'force-push' ? 'push' : operation; - - startOperation(dir, gitOp); setError(null); setSyncSuccess(false); @@ -87,98 +83,30 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { // Show success feedback setSyncSuccess(true); setTimeout(() => setSyncSuccess(false), 2500); - - // Clear error on success - endOperation(dir); } catch (err) { console.warn(err); - const message = err instanceof Error ? err : new Error(`Failed to ${operation}`); - endOperation(dir, message); - setError(message); + // Error is already set by the provider } - - // Invalidate git status to refresh UI - queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); - }, [projectId, queryClient, remoteUrl, dir, startOperation, endOperation, setError]); + }, [remoteUrl, setError]); const handleSync = async () => { - if (!remoteUrl) return; - - setError(null); - setSyncSuccess(false); - - try { - // Pull first to get latest changes - startOperation(dir, 'pull'); - await git.pull({ dir, ref, singleBranch: true }); - endOperation(dir); - - // Then push local changes - startOperation(dir, 'push'); - await git.push({ dir, remote: 'origin', ref }); - endOperation(dir); - - // Show success feedback - setSyncSuccess(true); - setTimeout(() => setSyncSuccess(false), 2500); - } catch (err) { - console.warn(err); - const message = err instanceof Error ? err : new Error('Failed to sync'); - endOperation(dir, message); - setError(message); - } - - // Invalidate git status to refresh UI - queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); + await executeGitOperation(() => gitSync.sync(dir, ref)); }; const handlePull = async () => { - await executeGitOperation('pull', async () => { - await git.pull({ dir, ref, singleBranch: true }); - }); + await executeGitOperation(() => gitSync.pull(dir, ref)); }; const handlePush = async () => { - await executeGitOperation('push', async () => { - await git.push({ dir, remote: 'origin', ref }); - }); + await executeGitOperation(() => gitSync.push(dir, ref)); }; const handleForcePull = async () => { - await executeGitOperation('force-pull', async () => { - // Step 1: Fetch latest changes from remote - await git.fetch({ - dir, - remote: 'origin', - ref, - singleBranch: true, - }); - - // Step 2: Get the remote commit SHA - const remoteRef = `refs/remotes/origin/${ref}`; - const remoteSha = await git.resolveRef({ dir, ref: remoteRef }); - - // Step 3: Force update the current branch to point to remote - await git.writeRef({ - dir, - ref: `refs/heads/${ref}`, - value: remoteSha, - force: true, - }); - - // Step 4: Force checkout all files (overwrite local changes) - await git.checkout({ - dir, - ref, - force: true, - }); - }); + await executeGitOperation(() => gitSync.forcePull(dir, ref)); }; const handleForcePush = async () => { - await executeGitOperation('force-push', async () => { - await git.push({ dir, remote: 'origin', ref, force: true }); - }); + await executeGitOperation(() => gitSync.forcePush(dir, ref)); }; // Temporary feedback state helper diff --git a/src/contexts/GitSyncContext.ts b/src/contexts/GitSyncContext.ts index e6bd1c70..065cae14 100644 --- a/src/contexts/GitSyncContext.ts +++ b/src/contexts/GitSyncContext.ts @@ -9,13 +9,30 @@ export interface GitSyncState { error?: Error; } +export interface FetchResult { + defaultBranch: string | null; + fetchHead: string | null; + fetchHeadDescription: string | null; +} + export interface GitSyncContextValue { + // State access syncStates: Map; + getState: (dir: string) => GitSyncState | undefined; + getError: (dir: string) => Error | undefined; + + // Git operations + fetch: (dir: string, remote?: string) => Promise; + pull: (dir: string, ref: string, remote?: string) => Promise; + push: (dir: string, ref: string, remote?: string, force?: boolean) => Promise; + sync: (dir: string, ref: string, remote?: string) => Promise; + forcePull: (dir: string, ref: string, remote?: string) => Promise; + forcePush: (dir: string, ref: string, remote?: string) => Promise; + + // Internal state management (for backward compatibility during migration) startOperation: (dir: string, operation: GitOperation) => void; endOperation: (dir: string, error?: Error) => void; setError: (dir: string, error: Error | null) => void; - getState: (dir: string) => GitSyncState | undefined; - getError: (dir: string) => Error | undefined; } export const GitSyncContext = createContext(null); diff --git a/src/hooks/useGitSync.ts b/src/hooks/useGitSync.ts index 0902fcdc..6f65aaac 100644 --- a/src/hooks/useGitSync.ts +++ b/src/hooks/useGitSync.ts @@ -1,4 +1,4 @@ -import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { useQuery } from '@tanstack/react-query'; import { useGit } from './useGit'; import { useGitSyncState } from './useGitSyncState'; import { useProjectSessionStatus } from './useProjectSessionStatus'; @@ -13,8 +13,7 @@ interface GitSyncResult { export function useGitSync(dir: string | undefined, remote = 'origin') { const { git } = useGit(); - const queryClient = useQueryClient(); - const { startOperation, endOperation, setError } = useGitSyncState(); + const gitSync = useGitSyncState(); // Extract project ID from directory path const projectId = dir?.split('/').pop() || ''; @@ -50,12 +49,7 @@ export function useGitSync(dir: string | undefined, remote = 'origin') { }); // Always fetch to update remote tracking - startOperation(dir, 'fetch'); - const fetchResult = await git.fetch({ - dir, - remote, - }); - endOperation(dir); + const fetchResult = await gitSync.fetch(dir, remote); let didPull = false; let didPush = false; @@ -69,55 +63,30 @@ export function useGitSync(dir: string | undefined, remote = 'origin') { if (currentBranch) { // Pull changes from remote try { - startOperation(dir, 'pull'); - await git.pull({ - dir, - ref: currentBranch, - singleBranch: true, - }); + await gitSync.pull(dir, currentBranch, remote); didPull = true; - endOperation(dir); + // Clear any previous errors on successful pull + gitSync.setError(dir, null); } catch (pullError) { - const error = pullError instanceof Error ? pullError : new Error('Auto-pull failed'); - endOperation(dir, error); - setError(dir, error); // Pull might fail if there are conflicts or diverged branches - // Don't throw - just log and continue + // Error is already set by the provider - just log and continue console.warn('Auto-pull failed:', pullError); } // Push local changes to remote try { - startOperation(dir, 'push'); - await git.push({ - dir, - remote, - ref: currentBranch, - }); + await gitSync.push(dir, currentBranch, remote); didPush = true; - endOperation(dir); // Clear any previous errors on successful push - setError(dir, null); + gitSync.setError(dir, null); } catch (pushError) { - const error = pushError instanceof Error ? pushError : new Error('Auto-push failed'); - endOperation(dir, error); - setError(dir, error); // Push might fail if there are conflicts or no changes - // Don't throw - just log and continue + // Error is already set by the provider - just log and continue console.warn('Auto-push failed:', pushError); } - - // If we successfully synced, invalidate git status to refresh UI - if (didPull || didPush) { - const projectId = dir.split('/').pop(); - if (projectId) { - queryClient.invalidateQueries({ queryKey: ['git-status', projectId] }); - } - } } } catch (error) { - const err = error instanceof Error ? error : new Error('Auto-sync failed'); - setError(dir, err); + // Error getting current branch or other unexpected error console.warn('Auto-sync failed:', error); } } @@ -128,10 +97,8 @@ export function useGitSync(dir: string | undefined, remote = 'origin') { didPush, }; } catch (error) { - const err = error instanceof Error ? error : new Error('Git sync failed'); - endOperation(dir, err); - setError(dir, err); // Fetch/sync failed, but don't throw - just log and return null + // Error is already set by the provider console.warn('Git sync failed:', error); return { defaultBranch: null,