migrate current branch to query pattern (#116)

This commit is contained in:
Will Chen
2025-05-08 22:23:00 -07:00
committed by GitHub
parent 7839d6bde9
commit b6eeaab1bb
5 changed files with 65 additions and 77 deletions

View File

@@ -22,8 +22,8 @@ import { selectedChatIdAtom } from "@/atoms/chatAtoms";
import { useChats } from "@/hooks/useChats"; import { useChats } from "@/hooks/useChats";
import { showError } from "@/lib/toast"; import { showError } from "@/lib/toast";
import { useEffect, useState } from "react"; import { useEffect, useState } from "react";
import { BranchResult } from "@/ipc/ipc_types";
import { useStreamChat } from "@/hooks/useStreamChat"; import { useStreamChat } from "@/hooks/useStreamChat";
import { useCurrentBranch } from "@/hooks/useCurrentBranch";
interface ChatHeaderProps { interface ChatHeaderProps {
isPreviewOpen: boolean; isPreviewOpen: boolean;
@@ -37,55 +37,35 @@ export function ChatHeader({
onVersionClick, onVersionClick,
}: ChatHeaderProps) { }: ChatHeaderProps) {
const appId = useAtomValue(selectedAppIdAtom); const appId = useAtomValue(selectedAppIdAtom);
const { versions, loading } = useVersions(appId); const { versions, loading: versionsLoading } = useVersions(appId);
const { navigate } = useRouter(); const { navigate } = useRouter();
const [selectedChatId, setSelectedChatId] = useAtom(selectedChatIdAtom); const [selectedChatId, setSelectedChatId] = useAtom(selectedChatIdAtom);
const { refreshChats } = useChats(appId); const { refreshChats } = useChats(appId);
const [branchInfo, setBranchInfo] = useState<BranchResult | null>(null);
const [checkingOutMain, setCheckingOutMain] = useState(false); const [checkingOutMain, setCheckingOutMain] = useState(false);
const { isStreaming } = useStreamChat(); const { isStreaming } = useStreamChat();
// Fetch the current branch when appId changes const {
branchInfo,
isLoading: branchInfoLoading,
refetchBranchInfo,
} = useCurrentBranch(appId);
useEffect(() => { useEffect(() => {
if (!appId) return; if (appId) {
refetchBranchInfo();
const fetchBranch = async () => { }
try { }, [appId, selectedChatId, isStreaming, refetchBranchInfo]);
const result = await IpcClient.getInstance().getCurrentBranch(appId);
if (result.success) {
setBranchInfo(result);
} else {
showError("Failed to get current branch: " + result.errorMessage);
}
} catch (error) {
showError(`Failed to get current branch: ${error}`);
}
};
fetchBranch();
// The use of selectedChatId and isStreaming is a hack to ensure that
// the branch info is relatively up to date.
}, [appId, selectedChatId, isStreaming]);
const handleCheckoutMainBranch = async () => { const handleCheckoutMainBranch = async () => {
if (!appId) return; if (!appId) return;
try { try {
setCheckingOutMain(true); setCheckingOutMain(true);
// Find the latest commit on main branch
// For simplicity, we'll just checkout to "main" directly
await IpcClient.getInstance().checkoutVersion({ await IpcClient.getInstance().checkoutVersion({
appId, appId,
versionId: "main", versionId: "main",
}); });
await refetchBranchInfo();
// Refresh branch info
const result = await IpcClient.getInstance().getCurrentBranch(appId);
if (result.success) {
setBranchInfo(result);
} else {
showError(result.errorMessage);
}
} catch (error) { } catch (error) {
showError(`Failed to checkout main branch: ${error}`); showError(`Failed to checkout main branch: ${error}`);
} finally { } finally {
@@ -94,36 +74,29 @@ export function ChatHeader({
}; };
const handleNewChat = async () => { const handleNewChat = async () => {
// Only create a new chat if an app is selected
if (appId) { if (appId) {
try { try {
// Create a new chat with an empty title for now
const chatId = await IpcClient.getInstance().createChat(appId); const chatId = await IpcClient.getInstance().createChat(appId);
// Navigate to the new chat
setSelectedChatId(chatId); setSelectedChatId(chatId);
navigate({ navigate({
to: "/chat", to: "/chat",
search: { id: chatId }, search: { id: chatId },
}); });
// Refresh the chat list
await refreshChats(); await refreshChats();
} catch (error) { } catch (error) {
// DO A TOAST
showError(`Failed to create new chat: ${(error as any).toString()}`); showError(`Failed to create new chat: ${(error as any).toString()}`);
} }
} else { } else {
// If no app is selected, navigate to home page
navigate({ to: "/" }); navigate({ to: "/" });
} }
}; };
// TODO: KEEP UP TO DATE WITH app_handlers.ts
// REMINDER: KEEP UP TO DATE WITH app_handlers.ts
const versionPostfix = versions.length === 10_000 ? `+` : ""; const versionPostfix = versions.length === 10_000 ? `+` : "";
// Check if we're not on the main branch const isNotMainBranch = branchInfo && branchInfo.branch !== "main";
const isNotMainBranch =
branchInfo?.success && branchInfo.data.branch !== "main"; const currentBranchName = branchInfo?.branch;
return ( return (
<div className="flex flex-col w-full @container"> <div className="flex flex-col w-full @container">
@@ -132,7 +105,7 @@ export function ChatHeader({
<div className="flex items-center gap-2 text-sm"> <div className="flex items-center gap-2 text-sm">
<GitBranch size={16} /> <GitBranch size={16} />
<span> <span>
{branchInfo?.data.branch === "<no-branch>" && ( {currentBranchName === "<no-branch>" && (
<> <>
<TooltipProvider> <TooltipProvider>
<Tooltip> <Tooltip>
@@ -153,13 +126,19 @@ export function ChatHeader({
</TooltipProvider> </TooltipProvider>
</> </>
)} )}
{currentBranchName && currentBranchName !== "<no-branch>" && (
<span>
You are on branch: <strong>{currentBranchName}</strong>.
</span>
)}
{branchInfoLoading && <span>Checking branch...</span>}
</span> </span>
</div> </div>
<Button <Button
variant="outline" variant="outline"
size="sm" size="sm"
onClick={handleCheckoutMainBranch} onClick={handleCheckoutMainBranch}
disabled={checkingOutMain} disabled={checkingOutMain || branchInfoLoading}
> >
{checkingOutMain ? "Checking out..." : "Switch to main branch"} {checkingOutMain ? "Checking out..." : "Switch to main branch"}
</Button> </Button>
@@ -182,7 +161,9 @@ export function ChatHeader({
className="hidden @6xs:flex cursor-pointer items-center gap-1 text-sm px-2 py-1 rounded-md" className="hidden @6xs:flex cursor-pointer items-center gap-1 text-sm px-2 py-1 rounded-md"
> >
<History size={16} /> <History size={16} />
{loading ? "..." : `Version ${versions.length}${versionPostfix}`} {versionsLoading
? "..."
: `Version ${versions.length}${versionPostfix}`}
</Button> </Button>
</div> </div>

View File

@@ -0,0 +1,30 @@
import { IpcClient } from "@/ipc/ipc_client";
import { useQuery } from "@tanstack/react-query";
import type { BranchResult } from "@/ipc/ipc_types";
export function useCurrentBranch(appId: number | null) {
const {
data: branchInfo,
isLoading,
refetch: refetchBranchInfo,
} = useQuery<BranchResult, Error>({
queryKey: ["currentBranch", appId],
queryFn: async (): Promise<BranchResult> => {
if (appId === null) {
// This case should ideally be handled by the `enabled` option
// but as a safeguard, and to ensure queryFn always has a valid appId if called.
throw new Error("appId is null, cannot fetch current branch.");
}
const ipcClient = IpcClient.getInstance();
return ipcClient.getCurrentBranch(appId);
},
enabled: appId !== null,
meta: { showErrorToast: false },
});
return {
branchInfo,
isLoading,
refetchBranchInfo,
};
}

View File

@@ -59,20 +59,14 @@ export function registerVersionHandlers() {
}); });
if (!app) { if (!app) {
return { throw new Error("App not found");
success: false,
errorMessage: "App not found",
};
} }
const appPath = getDyadAppPath(app.path); const appPath = getDyadAppPath(app.path);
// Return appropriate result if the app is not a git repo // Return appropriate result if the app is not a git repo
if (!fs.existsSync(path.join(appPath, ".git"))) { if (!fs.existsSync(path.join(appPath, ".git"))) {
return { throw new Error("Not a git repository");
success: false,
errorMessage: "Not a git repository",
};
} }
try { try {
@@ -83,17 +77,11 @@ export function registerVersionHandlers() {
}); });
return { return {
success: true, branch: currentBranch || "<no-branch>",
data: {
branch: currentBranch || "<no-branch>",
},
}; };
} catch (error: any) { } catch (error: any) {
logger.error(`Error getting current branch for app ${appId}:`, error); logger.error(`Error getting current branch for app ${appId}:`, error);
return { throw new Error(`Failed to get current branch: ${error.message}`);
success: false,
errorMessage: `Failed to get current branch: ${error.message}`,
};
} }
}, },
); );

View File

@@ -493,10 +493,9 @@ export class IpcClient {
// Get the current branch of an app // Get the current branch of an app
public async getCurrentBranch(appId: number): Promise<BranchResult> { public async getCurrentBranch(appId: number): Promise<BranchResult> {
const result = await this.ipcRenderer.invoke("get-current-branch", { return this.ipcRenderer.invoke("get-current-branch", {
appId, appId,
}); });
return result;
} }
// Get user settings // Get user settings

View File

@@ -76,17 +76,7 @@ export interface Version {
timestamp: number; timestamp: number;
} }
export type Result<T> = export type BranchResult = { branch: string };
| {
success: true;
data: T;
}
| {
success: false;
errorMessage: string;
};
export type BranchResult = Result<{ branch: string }>;
export interface SandboxConfig { export interface SandboxConfig {
files: Record<string, string>; files: Record<string, string>;