mirror of
https://gitlab.com/soapbox-pub/shakespeare.git
synced 2026-12-05 16:23:36 +00:00
Add git autosync functionality
This commit is contained in:
7 files changed
+201
-51
No files matched your search
@@ -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<ChatPaneRef, ChatPaneProps>(({
|
||||
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<string>());
|
||||
@@ -159,13 +161,19 @@ export const ChatPane = forwardRef<ChatPaneRef, ChatPaneProps>(({
|
||||
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<string, Tool<unknown>> = {
|
||||
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<ChatPaneRef, ChatPaneProps>(({
|
||||
}
|
||||
|
||||
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]);
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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<boolean>(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) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div className="flex items-center gap-1.5">
|
||||
<Switch
|
||||
id="autosync"
|
||||
checked={autosync}
|
||||
onCheckedChange={handleAutosyncToggle}
|
||||
disabled={isLoadingAutosync}
|
||||
className="scale-75"
|
||||
/>
|
||||
<Label htmlFor="autosync" className="text-xs cursor-pointer font-normal text-muted-foreground">
|
||||
Automatic sync
|
||||
</Label>
|
||||
</div>
|
||||
|
||||
{error && (
|
||||
<SyncStepError
|
||||
error={error}
|
||||
|
||||
@@ -1,44 +0,0 @@
|
||||
import { useQuery } from '@tanstack/react-query';
|
||||
import { useGit } from './useGit';
|
||||
|
||||
interface GitFetchResult {
|
||||
defaultBranch: string | null;
|
||||
fetchHead: string | null;
|
||||
fetchHeadDescription: string | null;
|
||||
}
|
||||
|
||||
export function useGitFetch(dir: string | undefined, remote = 'origin') {
|
||||
const { git } = useGit();
|
||||
|
||||
const query = useQuery({
|
||||
queryKey: ['git-fetch', dir],
|
||||
queryFn: async (): Promise<GitFetchResult> => {
|
||||
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;
|
||||
}
|
||||
@@ -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<GitSyncResult> => {
|
||||
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;
|
||||
}
|
||||
@@ -12,6 +12,7 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
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<GitCommitParams> {
|
||||
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<ToolResult> {
|
||||
@@ -133,6 +135,11 @@ export class GitCommitTool implements Tool<GitCommitParams> {
|
||||
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)}`);
|
||||
|
||||
@@ -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({
|
||||
|
||||
Reference in new issue
Block a user