diff --git a/src/components/Shakespeare/ChatPane.tsx b/src/components/Shakespeare/ChatPane.tsx index 9034e77a..f65afe90 100644 --- a/src/components/Shakespeare/ChatPane.tsx +++ b/src/components/Shakespeare/ChatPane.tsx @@ -15,6 +15,7 @@ import { useAIChat } from '@/hooks/useAIChat'; import { useProviderModels } from '@/hooks/useProviderModels'; import { useSessionManager } from '@/hooks/useSessionManager'; import { useMCPTools } from '@/hooks/useMCPTools'; +import { useQueryClient } from '@tanstack/react-query'; import { AIMessageItem } from '@/components/AIMessageItem'; import { ToolCallDisplay } from '@/components/ToolCallDisplay'; import { TextEditorViewTool } from '@/lib/tools/TextEditorViewTool'; @@ -87,6 +88,7 @@ export const ChatPane = forwardRef(({ const { models } = useProviderModels(); const { config } = useAppContext(); const { projectsPath, tmpPath, pluginsPath } = useFSPaths(); + const queryClient = useQueryClient(); const [showScrollToBottom, setShowScrollToBottom] = useState(false); const [isDragOver, setIsDragOver] = useState(false); const [scrolledProjects] = useState(() => new Set()); @@ -159,13 +161,19 @@ export const ChatPane = forwardRef(({ sessionManager.emit('fileChanged', projectId, filePath); }, [sessionManager, projectId]); + // Callback to trigger sync after git commits + const handleCommit = useCallback(() => { + // Invalidate the git-sync query to trigger an immediate sync + queryClient.invalidateQueries({ queryKey: ['git-sync', cwd] }); + }, [queryClient, cwd]); + // Fetch MCP tools const { tools: mcpOpenAITools, clients: mcpClients } = useMCPTools(); // Separate built-in tools from MCP tools for clarity const builtInTools = useMemo(() => { const tools: Record> = { - git_commit: new GitCommitTool(fs, cwd, git), + git_commit: new GitCommitTool(fs, cwd, git, { onCommit: handleCommit }), text_editor_view: new TextEditorViewTool(fs, cwd, { projectsPath }), text_editor_write: new TextEditorWriteTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), text_editor_str_replace: new TextEditorStrReplaceTool(fs, cwd, { projectsPath, tmpPath, onFileChanged: handleFileChanged }), @@ -234,7 +242,7 @@ export const ChatPane = forwardRef(({ } return tools; - }, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged]); + }, [fs, git, cwd, user, projectsPath, tmpPath, pluginsPath, config.corsProxy, settings, aiSettings, models, handleFileChanged, handleCommit]); // MCP tools wrapped for execution const mcpToolWrappers = useMemo(() => createMCPTools(mcpClients), [mcpClients]); diff --git a/src/components/git-sync/steps/ConfigureRepoStep.tsx b/src/components/git-sync/steps/ConfigureRepoStep.tsx index e72651fc..bd6c6a36 100644 --- a/src/components/git-sync/steps/ConfigureRepoStep.tsx +++ b/src/components/git-sync/steps/ConfigureRepoStep.tsx @@ -193,6 +193,13 @@ export function ConfigureRepoStep({ }); } + // Enable autosync by default after successfully setting up the remote + await git.setConfig({ + dir, + path: 'shakespeare.autosync', + value: 'true', + }); + // Refresh git status before showing success await refetchGitStatus(); // Show success state diff --git a/src/components/git-sync/steps/SyncStep.tsx b/src/components/git-sync/steps/SyncStep.tsx index 3eb24954..3a64cf13 100644 --- a/src/components/git-sync/steps/SyncStep.tsx +++ b/src/components/git-sync/steps/SyncStep.tsx @@ -1,8 +1,10 @@ -import { useState, useCallback } from 'react'; +import { useState, useCallback, useEffect } from 'react'; import { Zap, Copy, Check, RefreshCw, EllipsisVertical, CloudOff, ExternalLink, ChevronDown, ArrowDown, ArrowUp, LoaderCircle, History } from 'lucide-react'; import { Button } from '@/components/ui/button'; import { Input } from '@/components/ui/input'; import { Label } from '@/components/ui/label'; +import { Switch } from '@/components/ui/switch'; +import { useQueryClient } from '@tanstack/react-query'; import { DropdownMenu, DropdownMenuContent, @@ -41,6 +43,8 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { const [showForcePullDialog, setShowForcePullDialog] = useState(false); const [showForcePushDialog, setShowForcePushDialog] = useState(false); const [gitHistoryOpen, setGitHistoryOpen] = useState(false); + const [autosync, setAutosync] = useState(false); + const [isLoadingAutosync, setIsLoadingAutosync] = useState(true); const { data: gitStatus } = useGitStatus(projectId); const { settings } = useGitSettings(); @@ -55,6 +59,45 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { const commitsAhead = gitStatus?.ahead ?? 0; const commitsBehind = gitStatus?.behind ?? 0; + // Load autosync config on mount + useEffect(() => { + const loadAutosync = async () => { + try { + const value = await git.getConfig({ + dir, + path: 'shakespeare.autosync', + }); + setAutosync(value === 'true'); + } catch { + // Config not set, default to false + setAutosync(false); + } finally { + setIsLoadingAutosync(false); + } + }; + + loadAutosync(); + }, [git, dir]); + + // Handler to toggle autosync + const handleAutosyncToggle = async (checked: boolean) => { + try { + await git.setConfig({ + dir, + path: 'shakespeare.autosync', + value: String(checked), + }); + setAutosync(checked); + + // If enabling autosync, trigger an immediate sync + if (checked) { + queryClient.invalidateQueries({ queryKey: ['git-sync', dir] }); + } + } catch (error) { + console.error('Failed to set autosync config:', error); + } + }; + // Generic git operation handler const executeGitOperation = useCallback(async ( operation: GitOperation, @@ -306,6 +349,19 @@ export function SyncStep({ projectId, remoteUrl }: SyncStepProps) { +
+ + +
+ {error && ( => { - const remotes = await git.listRemotes({ dir }); - const hasOrigin = !!remotes.find(r => r.remote === remote); - - if (dir && hasOrigin) { - try { - return await git.fetch({ - dir, - remote, - }); - } catch (error) { - // Fetch failed, but don't throw - just log and return null - console.warn('Git fetch failed:', error); - } - } - - return { - defaultBranch: null, - fetchHead: null, - fetchHeadDescription: null, - }; - }, - enabled: !!dir, - refetchInterval: 60000, // Fetch every 60 seconds - staleTime: 30000, // Consider data stale after 30 seconds - retry: false, // Don't retry on failure - }); - - return query; -} diff --git a/src/hooks/useGitSync.ts b/src/hooks/useGitSync.ts new file mode 100644 index 00000000..43a096b7 --- /dev/null +++ b/src/hooks/useGitSync.ts @@ -0,0 +1,116 @@ +import { useQuery, useQueryClient } from '@tanstack/react-query'; +import { useGit } from './useGit'; + +interface GitSyncResult { + defaultBranch: string | null; + fetchHead: string | null; + fetchHeadDescription: string | null; + didPull?: boolean; + didPush?: boolean; +} + +export function useGitSync(dir: string | undefined, remote = 'origin') { + const { git } = useGit(); + const queryClient = useQueryClient(); + + const query = useQuery({ + queryKey: ['git-sync', dir], + queryFn: async (): Promise => { + const remotes = await git.listRemotes({ dir }); + const hasOrigin = !!remotes.find(r => r.remote === remote); + + if (!dir || !hasOrigin) { + return { + defaultBranch: null, + fetchHead: null, + fetchHeadDescription: null, + }; + } + + try { + // Check if autosync is enabled + const autosync = await git.getConfig({ + dir, + path: 'shakespeare.autosync', + }); + + // Always fetch to update remote tracking + const fetchResult = await git.fetch({ + dir, + remote, + }); + + let didPull = false; + let didPush = false; + + // If autosync is enabled, perform pull and push + if (autosync === 'true') { + try { + // Get current branch + const currentBranch = await git.currentBranch({ dir }); + + if (currentBranch) { + // Pull changes from remote + try { + await git.pull({ + dir, + ref: currentBranch, + singleBranch: true, + }); + didPull = true; + } catch (pullError) { + // Pull might fail if there are conflicts or diverged branches + // Don't throw - just log and continue + console.warn('Auto-pull failed:', pullError); + } + + // Push local changes to remote + try { + await git.push({ + dir, + remote, + ref: currentBranch, + }); + didPush = true; + } catch (pushError) { + // Push might fail if there are conflicts or no changes + // Don't throw - 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) { + console.warn('Auto-sync failed:', error); + } + } + + return { + ...fetchResult, + didPull, + didPush, + }; + } catch (error) { + // Fetch/sync failed, but don't throw - just log and return null + console.warn('Git sync failed:', error); + return { + defaultBranch: null, + fetchHead: null, + fetchHeadDescription: null, + }; + } + }, + enabled: !!dir, + refetchInterval: 60000, // Sync every 60 seconds + staleTime: 30000, // Consider data stale after 30 seconds + retry: false, // Don't retry on failure + }); + + return query; +} diff --git a/src/lib/tools/GitCommitTool.ts b/src/lib/tools/GitCommitTool.ts index 21145302..fd857a10 100644 --- a/src/lib/tools/GitCommitTool.ts +++ b/src/lib/tools/GitCommitTool.ts @@ -12,6 +12,7 @@ export class GitCommitTool implements Tool { private fs: JSRuntimeFS; private git: Git; private cwd: string; + private onCommit?: () => void; readonly description = "Commit changes to git with a commit message. Automatically adds all unstaged files."; @@ -19,10 +20,11 @@ export class GitCommitTool implements Tool { message: z.string().describe('Commit message text'), }); - constructor(fs: JSRuntimeFS, cwd: string, git: Git) { + constructor(fs: JSRuntimeFS, cwd: string, git: Git, options?: { onCommit?: () => void }) { this.fs = fs; this.git = git; this.cwd = cwd; + this.onCommit = options?.onCommit; } async execute(args: GitCommitParams): Promise { @@ -133,6 +135,11 @@ export class GitCommitTool implements Tool { if (modifiedFiles > 0) details += ` • ${modifiedFiles} file${modifiedFiles !== 1 ? 's' : ''} modified\n`; if (deletedFiles > 0) details += ` • ${deletedFiles} file${deletedFiles !== 1 ? 's' : ''} deleted\n`; + // Trigger sync callback if provided + if (this.onCommit) { + this.onCommit(); + } + return { content: `${summary}\n\n${details}` }; } catch (error) { throw new Error(`❌ Error committing changes: ${String(error)}`); diff --git a/src/pages/ProjectView.tsx b/src/pages/ProjectView.tsx index 7340ccd4..87b7bf81 100644 --- a/src/pages/ProjectView.tsx +++ b/src/pages/ProjectView.tsx @@ -26,7 +26,7 @@ import { useConsoleError } from '@/hooks/useConsoleError'; import { useAutoBuild } from '@/hooks/useAutoBuild'; import { useToast } from '@/hooks/useToast'; import { useFSPaths } from '@/hooks/useFSPaths'; -import { useGitFetch } from '@/hooks/useGitFetch'; +import { useGitSync } from '@/hooks/useGitSync'; import { useQueryClient } from '@tanstack/react-query'; import { cn } from '@/lib/utils'; import { useProjectSessionStatus } from '@/hooks/useProjectSessionStatus'; @@ -62,8 +62,8 @@ export function ProjectView() { const { data: isPreviewable = false } = useIsProjectPreviewable(projectId!); const { hasRunningSessions } = useProjectSessionStatus(projectId || ''); - // Automatically fetch from remote to keep git status updated - useGitFetch(projectId ? `${projectsPath}/${projectId}` : undefined); + // Automatically sync with remote to keep git status updated + useGitSync(projectId ? `${projectsPath}/${projectId}` : undefined); // Enable auto-build for previewable projects useAutoBuild({