Fixes #12
This commit is contained in:
Will Chen
2025-06-05 22:26:17 -07:00
committed by GitHub
parent 97ed34cf08
commit d3fbb48472
18 changed files with 6386 additions and 65 deletions

18
src/hooks/useCheckName.ts Normal file
View File

@@ -0,0 +1,18 @@
import { useQuery } from "@tanstack/react-query";
import { IpcClient } from "@/ipc/ipc_client";
export const useCheckName = (appName: string) => {
return useQuery({
queryKey: ["checkAppName", appName],
queryFn: async () => {
const result = await IpcClient.getInstance().checkAppName({ appName });
return result;
},
enabled: !!appName && !!appName.trim(),
refetchOnWindowFocus: false,
refetchOnMount: false,
refetchOnReconnect: false,
retry: false,
staleTime: 300000, // 5 minutes
});
};

17
src/hooks/useDebounce.ts Normal file
View File

@@ -0,0 +1,17 @@
import { useState, useEffect } from "react";
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}

View File

@@ -2,7 +2,12 @@ import { ipcMain } from "electron";
import { db, getDatabasePath } from "../../db";
import { apps, chats } from "../../db/schema";
import { desc, eq } from "drizzle-orm";
import type { App, CreateAppParams, RenameBranchParams } from "../ipc_types";
import type {
App,
CreateAppParams,
RenameBranchParams,
CopyAppParams,
} from "../ipc_types";
import fs from "node:fs";
import path from "node:path";
import { getDyadAppPath, getUserDataPath } from "../../paths/paths";
@@ -225,6 +230,89 @@ export function registerAppHandlers() {
},
);
handle(
"copy-app",
async (_, params: CopyAppParams): Promise<{ app: any }> => {
const { appId, newAppName, withHistory } = params;
// 1. Check if an app with the new name already exists
const existingApp = await db.query.apps.findFirst({
where: eq(apps.name, newAppName),
});
if (existingApp) {
throw new Error(`An app named "${newAppName}" already exists.`);
}
// 2. Find the original app
const originalApp = await db.query.apps.findFirst({
where: eq(apps.id, appId),
});
if (!originalApp) {
throw new Error("Original app not found.");
}
const originalAppPath = getDyadAppPath(originalApp.path);
const newAppPath = getDyadAppPath(newAppName);
// 3. Copy the app folder
try {
await fsPromises.cp(originalAppPath, newAppPath, {
recursive: true,
filter: (source: string) => {
if (!withHistory && path.basename(source) === ".git") {
return false;
}
return true;
},
});
} catch (error) {
logger.error("Failed to copy app directory:", error);
throw new Error("Failed to copy app directory.");
}
if (!withHistory) {
// Initialize git repo and create first commit
await git.init({
fs: fs,
dir: newAppPath,
defaultBranch: "main",
});
// Stage all files
await git.add({
fs: fs,
dir: newAppPath,
filepath: ".",
});
// Create initial commit
await gitCommit({
path: newAppPath,
message: "Init Dyad app",
});
}
// 4. Create a new app entry in the database
const [newDbApp] = await db
.insert(apps)
.values({
name: newAppName,
path: newAppName, // Use the new name for the path
// Explicitly set these to null because we don't want to copy them over.
// Note: we could just leave them out since they're nullable field, but this
// is to make it explicit we intentionally don't want to copy them over.
supabaseProjectId: null,
githubOrg: null,
githubRepo: null,
})
.returning();
return { app: newDbApp };
},
);
handle("get-app", async (_, appId: number): Promise<App> => {
const app = await db.query.apps.findFirst({
where: eq(apps.id, appId),

View File

@@ -31,6 +31,7 @@ import type {
ImportAppParams,
RenameBranchParams,
UserBudgetInfo,
CopyAppParams,
} from "./ipc_types";
import type { ProposalResult } from "@/lib/schemas";
import { showError } from "@/lib/toast";
@@ -465,6 +466,10 @@ export class IpcClient {
});
}
public async copyApp(params: CopyAppParams): Promise<{ app: App }> {
return this.ipcRenderer.invoke("copy-app", params);
}
// Reset all - removes all app files, settings, and drops the database
public async resetAll(): Promise<void> {
await this.ipcRenderer.invoke("reset-all");

View File

@@ -199,6 +199,12 @@ export interface ImportAppParams {
appName: string;
}
export interface CopyAppParams {
appId: number;
newAppName: string;
withHistory: boolean;
}
export interface ImportAppResult {
appId: number;
chatId: number;

View File

@@ -1,6 +1,10 @@
import { useNavigate, useRouter, useSearch } from "@tanstack/react-router";
import { useAtom, useAtomValue } from "jotai";
import { appBasePathAtom, appsListAtom } from "@/atoms/appAtoms";
import { useAtom, useAtomValue, useSetAtom } from "jotai";
import {
appBasePathAtom,
appsListAtom,
selectedAppIdAtom,
} from "@/atoms/appAtoms";
import { IpcClient } from "@/ipc/ipc_client";
import { useLoadApps } from "@/hooks/useLoadApps";
import { useState } from "react";
@@ -29,6 +33,12 @@ import {
import { GitHubConnector } from "@/components/GitHubConnector";
import { SupabaseConnector } from "@/components/SupabaseConnector";
import { showError } from "@/lib/toast";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Label } from "@/components/ui/label";
import { Loader2 } from "lucide-react";
import { invalidateAppQuery } from "@/hooks/useLoadApp";
import { useDebounce } from "@/hooks/useDebounce";
import { useCheckName } from "@/hooks/useCheckName";
export default function AppDetailsPage() {
const navigate = useNavigate();
@@ -49,6 +59,18 @@ export default function AppDetailsPage() {
const [isRenamingFolder, setIsRenamingFolder] = useState(false);
const appBasePath = useAtomValue(appBasePathAtom);
const [isCopyDialogOpen, setIsCopyDialogOpen] = useState(false);
const [newCopyAppName, setNewCopyAppName] = useState("");
const queryClient = useQueryClient();
const setSelectedAppId = useSetAtom(selectedAppIdAtom);
const debouncedNewCopyAppName = useDebounce(newCopyAppName, 150);
const { data: checkNameResult, isLoading: isCheckingName } = useCheckName(
debouncedNewCopyAppName,
);
const nameExists = checkNameResult?.exists ?? false;
// Get the appId from search params and find the corresponding app
const appId = search.appId ? Number(search.appId) : null;
const selectedApp = appId ? appsList.find((app) => app.id === appId) : null;
@@ -139,6 +161,42 @@ export default function AppDetailsPage() {
}
};
const handleAppNameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setNewCopyAppName(e.target.value);
};
const handleOpenCopyDialog = () => {
if (selectedApp) {
setNewCopyAppName(`${selectedApp.name}-copy`);
setIsCopyDialogOpen(true);
}
};
const copyAppMutation = useMutation({
mutationFn: async ({ withHistory }: { withHistory: boolean }) => {
if (!appId || !newCopyAppName.trim()) {
throw new Error("Invalid app ID or name for copying.");
}
return IpcClient.getInstance().copyApp({
appId,
newAppName: newCopyAppName,
withHistory,
});
},
onSuccess: async (data) => {
const appId = data.app.id;
setSelectedAppId(appId);
await invalidateAppQuery(queryClient, { appId });
await refreshApps();
await IpcClient.getInstance().createChat(appId);
setIsCopyDialogOpen(false);
navigate({ to: "/app-details", search: { appId } });
},
onError: (error) => {
showError(error);
},
});
if (!selectedApp) {
return (
<div className="relative min-h-screen p-8">
@@ -212,6 +270,14 @@ export default function AppDetailsPage() {
>
Rename folder
</Button>
<Button
onClick={handleOpenCopyDialog}
variant="ghost"
size="sm"
className="h-8 justify-start text-xs"
>
Copy app
</Button>
<Button
onClick={() => setIsDeleteDialogOpen(true)}
variant="ghost"
@@ -439,6 +505,123 @@ export default function AppDetailsPage() {
</DialogContent>
</Dialog>
{/* Copy App Dialog */}
{selectedApp && (
<Dialog open={isCopyDialogOpen} onOpenChange={setIsCopyDialogOpen}>
<DialogContent className="max-w-md p-4">
<DialogHeader className="pb-2">
<DialogTitle>Copy "{selectedApp.name}"</DialogTitle>
<DialogDescription className="text-sm">
<p>Create a copy of this app.</p>
<p>
Note: this does not copy over the Supabase project or GitHub
project.
</p>
</DialogDescription>
</DialogHeader>
<div className="space-y-3 my-2">
<div>
<Label htmlFor="newAppName">New app name</Label>
<div className="relative mt-1">
<Input
id="newAppName"
value={newCopyAppName}
onChange={handleAppNameChange}
placeholder="Enter new app name"
className="pr-8"
disabled={copyAppMutation.isPending}
/>
{isCheckingName && (
<div className="absolute right-2 top-1/2 -translate-y-1/2">
<Loader2 className="h-4 w-4 animate-spin text-muted-foreground" />
</div>
)}
</div>
{nameExists && (
<p className="text-xs text-yellow-600 dark:text-yellow-500 mt-1">
An app with this name already exists. Please choose
another name.
</p>
)}
</div>
<div className="space-y-2">
<Button
variant="outline"
className="w-full justify-start p-2 h-auto relative text-sm"
onClick={() =>
copyAppMutation.mutate({ withHistory: true })
}
disabled={
copyAppMutation.isPending ||
nameExists ||
!newCopyAppName.trim() ||
isCheckingName
}
>
{copyAppMutation.isPending &&
copyAppMutation.variables?.withHistory === true && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
<div className="absolute top-1 right-1">
<span className="bg-blue-100 text-blue-800 text-xs font-medium px-1.5 py-0.5 rounded dark:bg-blue-900 dark:text-blue-300 text-[10px]">
Recommended
</span>
</div>
<div className="text-left">
<p className="font-medium text-xs">
Copy app with history
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">
Copies the entire app, including the Git version
history.
</p>
</div>
</Button>
<Button
variant="outline"
className="w-full justify-start p-2 h-auto text-sm"
onClick={() =>
copyAppMutation.mutate({ withHistory: false })
}
disabled={
copyAppMutation.isPending ||
nameExists ||
!newCopyAppName.trim() ||
isCheckingName
}
>
{copyAppMutation.isPending &&
copyAppMutation.variables?.withHistory === false && (
<Loader2 className="mr-2 h-4 w-4 animate-spin" />
)}
<div className="text-left">
<p className="font-medium text-xs">
Copy app without history
</p>
<p className="text-xs text-gray-500 dark:text-gray-400">
Useful if the current app has a Git-related issue.
</p>
</div>
</Button>
</div>
</div>
<DialogFooter className="pt-2">
<Button
variant="outline"
onClick={() => setIsCopyDialogOpen(false)}
disabled={copyAppMutation.isPending}
size="sm"
>
Cancel
</Button>
</DialogFooter>
</DialogContent>
</Dialog>
)}
{/* Delete Confirmation Dialog */}
<Dialog open={isDeleteDialogOpen} onOpenChange={setIsDeleteDialogOpen}>
<DialogContent className="max-w-sm p-4">

View File

@@ -20,6 +20,7 @@ const validInvokeChannels = [
"chat:count-tokens",
"create-chat",
"create-app",
"copy-app",
"get-chat",
"get-chats",
"get-chat-logs",