Hold errors in GitSyncProvider

This commit is contained in:
Alex Gleason committed 2025-12-29 16:43:47 -06:00
1 parent f9febcce1e
commit ffa65212bc
5 files changed
+98 -19

No files matched your search

+47 -3
View File
@@ -7,15 +7,55 @@ export function GitSyncProvider({ children }: { children: ReactNode }) {
const startOperation = useCallback((dir: string, operation: GitOperation) => {
setSyncStates(prev => {
const next = new Map(prev);
// Clear any previous error when starting a new operation
next.set(dir, { dir, operation, isActive: true });
return next;
});
}, []);
const endOperation = useCallback((dir: string) => {
const endOperation = useCallback((dir: string, error?: Error) => {
setSyncStates(prev => {
const next = new Map(prev);
next.delete(dir);
if (error) {
// Keep the state with the error
const currentState = prev.get(dir);
if (currentState) {
next.set(dir, { ...currentState, isActive: false, error });
}
} else {
// Remove the state if no error
next.delete(dir);
}
return next;
});
}, []);
const setError = useCallback((dir: string, error: Error | null) => {
setSyncStates(prev => {
const next = new Map(prev);
const currentState = prev.get(dir);
if (error) {
// Set or update error
if (currentState) {
next.set(dir, { ...currentState, error });
} else {
// Create a new state with just the error (no active operation)
next.set(dir, { dir, operation: 'fetch', isActive: false, error });
}
} else {
// Clear error
if (currentState) {
const { error: _, ...stateWithoutError } = currentState;
if (stateWithoutError.isActive) {
next.set(dir, stateWithoutError);
} else {
// If not active and no error, remove the state entirely
next.delete(dir);
}
}
}
return next;
});
}, []);
@@ -24,8 +64,12 @@ export function GitSyncProvider({ children }: { children: ReactNode }) {
return syncStates.get(dir);
}, [syncStates]);
const getError = useCallback((dir: string) => {
return syncStates.get(dir)?.error;
}, [syncStates]);
return (
<GitSyncContext.Provider value={{ syncStates, startOperation, endOperation, getState }}>
<GitSyncContext.Provider value={{ syncStates, startOperation, endOperation, setError, getState, getError }}>
{children}
</GitSyncContext.Provider>
);
+17 -4
View File
@@ -3,6 +3,8 @@ import { CloudUpload } from 'lucide-react';
import { Button } from '@/components/ui/button';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { useGitStatus } from '@/hooks/useGitStatus';
import { useGitSyncState } from '@/hooks/useGitSyncState';
import { useFSPaths } from '@/hooks/useFSPaths';
import { cn } from '@/lib/utils';
import { GitSyncSteps } from './GitSyncSteps';
@@ -15,9 +17,19 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const [open, setOpen] = useState(false);
const { data: gitStatus, isLoading: isGitStatusLoading } = useGitStatus(projectId);
const { getError } = useGitSyncState();
const { projectsPath } = useFSPaths();
// Determine which indicator to show (only one at a time)
const dir = `${projectsPath}/${projectId}`;
const hasError = !!getError(dir);
// Determine which indicator to show (only one at a time, in priority order)
const renderIndicator = () => {
// Red indicator: error state - highest priority
if (hasError) {
return <IndicatorDot color="red" />;
}
if (isGitStatusLoading || !gitStatus) return null;
const originRemote = gitStatus.remotes.find(r => r.name === 'origin');
@@ -25,13 +37,13 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
const { remoteBranchExists, ahead, behind, totalCommits } = gitStatus;
// Yellow indicator: unsynced changes (ahead or behind remote) - highest priority
// Yellow indicator: unsynced changes (ahead or behind remote) - second priority
const hasUnsyncedChanges = hasRemote && remoteBranchExists && (ahead > 0 || behind > 0);
if (hasUnsyncedChanges) {
return <IndicatorDot color="yellow" />;
}
// Purple indicator: no remote configured, but has commits - lower priority
// Purple indicator: no remote configured, but has commits - lowest priority
const needsRemote = !hasRemote && totalCommits >= 2;
if (needsRemote) {
return <IndicatorDot color="primary" />;
@@ -64,13 +76,14 @@ export function GitSyncButton({ projectId, className }: GitSyncButtonProps) {
);
}
function IndicatorDot({ color }: { color: 'primary' | 'yellow' }) {
function IndicatorDot({ color }: { color: 'primary' | 'yellow' | 'red' }) {
return (
<span className={cn(
"absolute top-1 right-1 h-2 w-2 rounded-full",
{
'bg-primary': color === 'primary',
'bg-yellow-500': color === 'yellow',
'bg-red-500': color === 'red',
},
)} />
);
+16 -7
View File
@@ -33,7 +33,6 @@ import { findCredentialsForRepo } from '@/lib/gitCredentials';
export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
const queryClient = useQueryClient();
const [error, setError] = useState<Error | null>(null);
const [copiedUrl, setCopiedUrl] = useState(false);
const [syncSuccess, setSyncSuccess] = useState(false);
const [isExpanded, setIsExpanded] = useState(false);
@@ -46,7 +45,7 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
const { git } = useGit();
const { projectsPath } = useFSPaths();
const { config } = useAppContext();
const { getState, startOperation, endOperation } = useGitSyncState();
const { getState, getError, startOperation, endOperation, setError: setGlobalError } = useGitSyncState();
const dir = `${projectsPath}/${projectId}`;
const ref = gitStatus?.currentBranch || 'main';
@@ -54,10 +53,16 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
// Use the new hook for autosync state
const { autosync, isLoading: isLoadingAutosync, setAutosync } = useGitAutosync(dir);
// Get unified sync state
// Get unified sync state and error
const syncState = 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 hasRemoteChanges = gitStatus?.remoteBranchExists && ((gitStatus?.ahead ?? 0) > 0 || (gitStatus?.behind ?? 0) > 0);
const commitsAhead = gitStatus?.ahead ?? 0;
@@ -82,17 +87,19 @@ 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);
} finally {
endOperation(dir);
}
// Invalidate git status to refresh UI
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
}, [projectId, queryClient, remoteUrl, dir, startOperation, endOperation]);
}, [projectId, queryClient, remoteUrl, dir, startOperation, endOperation, setError]);
const handleSync = async () => {
if (!remoteUrl) return;
@@ -115,9 +122,9 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
setSyncSuccess(true);
setTimeout(() => setSyncSuccess(false), 2500);
} catch (err) {
endOperation(dir);
console.warn(err);
const message = err instanceof Error ? err : new Error('Failed to sync');
endOperation(dir, message);
setError(message);
}
@@ -199,6 +206,8 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) {
try {
await git.deleteRemote({ dir, remote: 'origin' });
// Clear any errors when disconnecting
setError(null);
queryClient.invalidateQueries({ queryKey: ['git-status', projectId] });
} catch (err) {
const message = err instanceof Error ? err : new Error('Failed to disconnect');
+4 -1
View File
@@ -6,13 +6,16 @@ export interface GitSyncState {
dir: string;
operation: GitOperation;
isActive: boolean;
error?: Error;
}
export interface GitSyncContextValue {
syncStates: Map<string, GitSyncState>;
startOperation: (dir: string, operation: GitOperation) => void;
endOperation: (dir: string) => 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<GitSyncContextValue | null>(null);
+14 -4
View File
@@ -13,7 +13,7 @@ interface GitSyncResult {
export function useGitSync(dir: string | undefined, remote = 'origin') {
const { git } = useGit();
const queryClient = useQueryClient();
const { startOperation, endOperation } = useGitSyncState();
const { startOperation, endOperation, setError } = useGitSyncState();
const query = useQuery({
queryKey: ['git-sync', dir],
@@ -65,7 +65,9 @@ export function useGitSync(dir: string | undefined, remote = 'origin') {
didPull = true;
endOperation(dir);
} catch (pullError) {
endOperation(dir);
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
console.warn('Auto-pull failed:', pullError);
@@ -81,8 +83,12 @@ export function useGitSync(dir: string | undefined, remote = 'origin') {
});
didPush = true;
endOperation(dir);
// Clear any previous errors on successful push
setError(dir, null);
} catch (pushError) {
endOperation(dir);
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
console.warn('Auto-push failed:', pushError);
@@ -97,6 +103,8 @@ export function useGitSync(dir: string | undefined, remote = 'origin') {
}
}
} catch (error) {
const err = error instanceof Error ? error : new Error('Auto-sync failed');
setError(dir, err);
console.warn('Auto-sync failed:', error);
}
}
@@ -107,7 +115,9 @@ export function useGitSync(dir: string | undefined, remote = 'origin') {
didPush,
};
} catch (error) {
endOperation(dir);
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
console.warn('Git sync failed:', error);
return {