Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 0 additions & 20 deletions apps/code/src/main/services/folders/schemas.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,20 +29,6 @@ export const updateFolderAccessedInput = z.object({
folderId: z.string(),
});

export const cleanupOrphanedWorktreesInput = z.object({
mainRepoPath: z.string(),
});

export const cleanupOrphanedWorktreesOutput = z.object({
deleted: z.array(z.string()),
errors: z.array(
z.object({
path: z.string(),
error: z.string(),
}),
),
});

export type RegisteredFolder = z.infer<typeof registeredFolderWithExistsSchema>;
export type GetFoldersOutput = z.infer<typeof getFoldersOutput>;
export type AddFolderInput = z.infer<typeof addFolderInput>;
Expand All @@ -51,12 +37,6 @@ export type RemoveFolderInput = z.infer<typeof removeFolderInput>;
export type UpdateFolderAccessedInput = z.infer<
typeof updateFolderAccessedInput
>;
export type CleanupOrphanedWorktreesInput = z.infer<
typeof cleanupOrphanedWorktreesInput
>;
export type CleanupOrphanedWorktreesOutput = z.infer<
typeof cleanupOrphanedWorktreesOutput
>;

export const repositoryLookupResult = z
.object({
Expand Down
139 changes: 135 additions & 4 deletions apps/code/src/main/services/folders/service.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,137 @@ describe("FoldersService", () => {
vi.clearAllMocks();
});

describe("initialize", () => {
function createService() {
return new FoldersService(
mockRepositoryRepo as unknown as IRepositoryRepository,
mockWorkspaceRepo as unknown as IWorkspaceRepository,
mockWorktreeRepo as unknown as IWorktreeRepository,
);
}

it("removes folders that no longer exist on disk", async () => {
mockRepositoryRepo.findAll.mockReturnValue([
{
id: "folder-1",
path: "/gone/project",
lastAccessedAt: "2024-01-01T00:00:00.000Z",
createdAt: "2024-01-01T00:00:00.000Z",
updatedAt: "2024-01-01T00:00:00.000Z",
},
]);
mockExistsSync.mockReturnValue(false);
mockRepositoryRepo.findById.mockReturnValue({
id: "folder-1",
path: "/gone/project",
});
mockWorkspaceRepo.findAllByRepositoryId.mockReturnValue([]);

createService();
await vi.waitFor(() => {
expect(mockRepositoryRepo.delete).toHaveBeenCalledWith("folder-1");
});
});

it("cleans up orphaned worktrees for each existing folder", async () => {
mockRepositoryRepo.findAll.mockReturnValue([
{
id: "folder-1",
path: "/home/user/project-a",
lastAccessedAt: "2024-01-01T00:00:00.000Z",
createdAt: "2024-01-01T00:00:00.000Z",
updatedAt: "2024-01-01T00:00:00.000Z",
},
{
id: "folder-2",
path: "/home/user/project-b",
lastAccessedAt: "2024-01-01T00:00:00.000Z",
createdAt: "2024-01-01T00:00:00.000Z",
updatedAt: "2024-01-01T00:00:00.000Z",
},
]);
mockExistsSync.mockReturnValue(true);
mockWorktreeRepo.findAll.mockReturnValue([]);
mockWorktreeManager.cleanupOrphanedWorktrees.mockResolvedValue({
deleted: [],
errors: [],
});

createService();
await vi.waitFor(() => {
expect(
mockWorktreeManager.cleanupOrphanedWorktrees,
).toHaveBeenCalledTimes(2);
});
});

it("continues if one folder removal fails", async () => {
mockRepositoryRepo.findAll.mockReturnValue([
{
id: "folder-1",
path: "/gone/a",
lastAccessedAt: "2024-01-01T00:00:00.000Z",
createdAt: "2024-01-01T00:00:00.000Z",
updatedAt: "2024-01-01T00:00:00.000Z",
},
{
id: "folder-2",
path: "/gone/b",
lastAccessedAt: "2024-01-01T00:00:00.000Z",
createdAt: "2024-01-01T00:00:00.000Z",
updatedAt: "2024-01-01T00:00:00.000Z",
},
]);
mockExistsSync.mockReturnValue(false);
mockRepositoryRepo.findById
.mockReturnValueOnce({ id: "folder-1", path: "/gone/a" })
.mockReturnValueOnce({ id: "folder-2", path: "/gone/b" });
mockWorkspaceRepo.findAllByRepositoryId.mockReturnValue([]);
mockRepositoryRepo.delete
.mockImplementationOnce(() => {
throw new Error("db error");
})
.mockImplementationOnce(() => undefined);

createService();
await vi.waitFor(() => {
expect(mockRepositoryRepo.delete).toHaveBeenCalledTimes(2);
expect(mockRepositoryRepo.delete).toHaveBeenCalledWith("folder-2");
});
});

it("continues if one worktree cleanup fails", async () => {
mockRepositoryRepo.findAll.mockReturnValue([
{
id: "folder-1",
path: "/home/user/project-a",
lastAccessedAt: "2024-01-01T00:00:00.000Z",
createdAt: "2024-01-01T00:00:00.000Z",
updatedAt: "2024-01-01T00:00:00.000Z",
},
{
id: "folder-2",
path: "/home/user/project-b",
lastAccessedAt: "2024-01-01T00:00:00.000Z",
createdAt: "2024-01-01T00:00:00.000Z",
updatedAt: "2024-01-01T00:00:00.000Z",
},
]);
mockExistsSync.mockReturnValue(true);
mockWorktreeRepo.findAll.mockReturnValue([]);
mockWorktreeManager.cleanupOrphanedWorktrees
.mockRejectedValueOnce(new Error("cleanup error"))
.mockResolvedValueOnce({ deleted: [], errors: [] });

createService();
await vi.waitFor(() => {
expect(
mockWorktreeManager.cleanupOrphanedWorktrees,
).toHaveBeenCalledTimes(2);
});
});
});

describe("getFolders", () => {
it("returns empty array when no folders registered", async () => {
mockRepositoryRepo.findAll.mockReturnValue([]);
Expand Down Expand Up @@ -318,11 +449,11 @@ describe("FoldersService", () => {
errors: [],
});

const result =
await service.cleanupOrphanedWorktrees("/home/user/project");
await service.cleanupOrphanedWorktrees("/home/user/project");

expect(result.deleted).toHaveLength(1);
expect(result.errors).toHaveLength(0);
expect(mockWorktreeManager.cleanupOrphanedWorktrees).toHaveBeenCalledWith(
[],
);
});

it("excludes associated worktrees from cleanup", async () => {
Expand Down
52 changes: 43 additions & 9 deletions apps/code/src/main/services/folders/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,10 +26,7 @@ import { MAIN_TOKENS } from "../../di/tokens";
import { getMainWindow } from "../../trpc/context";
import { logger } from "../../utils/logger";
import { getWorktreeLocation } from "../settingsStore";
import type {
CleanupOrphanedWorktreesOutput,
RegisteredFolder,
} from "./schemas";
import type { RegisteredFolder } from "./schemas";

const log = logger.scope("folders-service");

Expand All @@ -42,7 +39,46 @@ export class FoldersService {
private readonly workspaceRepo: IWorkspaceRepository,
@inject(MAIN_TOKENS.WorktreeRepository)
private readonly worktreeRepo: IWorktreeRepository,
) {}
) {
this.initialize().catch((err) => {
log.error("Folders initialization failed", err);
});
}

private async initialize(): Promise<void> {
const folders = await this.getFolders();

const deletedFolders = folders.filter((f) => !f.exists);
if (deletedFolders.length > 0) {
let removed = 0;
for (const folder of deletedFolders) {
try {
await this.removeFolder(folder.id);
removed++;
} catch (err) {
log.error(`Failed to remove deleted folder ${folder.path}:`, err);
}
}
if (removed > 0) {
log.info(`Removed ${removed} deleted folder(s)`);
}
}

const existingFolders = folders.filter((f) => f.exists);
const results = await Promise.allSettled(
existingFolders.map((folder) =>
this.cleanupOrphanedWorktrees(folder.path),
),
);
for (const [i, result] of results.entries()) {
if (result.status === "rejected") {
log.error(
`Failed to cleanup orphaned worktrees for ${existingFolders[i].path}:`,
result.reason,
);
}
}
}

async getFolders(): Promise<(RegisteredFolder & { exists: boolean })[]> {
const repos = this.repositoryRepo.findAll();
Expand Down Expand Up @@ -190,16 +226,14 @@ export class FoldersService {
this.repositoryRepo.updateLastAccessed(folderId);
}

async cleanupOrphanedWorktrees(
mainRepoPath: string,
): Promise<CleanupOrphanedWorktreesOutput> {
async cleanupOrphanedWorktrees(mainRepoPath: string): Promise<void> {
const worktreeBasePath = getWorktreeLocation();
const manager = new WorktreeManager({ mainRepoPath, worktreeBasePath });

const allWorktrees = this.worktreeRepo.findAll();
const associatedWorktreePaths = allWorktrees.map((wt) => wt.path);

return await manager.cleanupOrphanedWorktrees(associatedWorktreePaths);
await manager.cleanupOrphanedWorktrees(associatedWorktreePaths);
}

getRepositoryByRemoteUrl(
Expand Down
9 changes: 0 additions & 9 deletions apps/code/src/main/trpc/routers/folders.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ import { MAIN_TOKENS } from "../../di/tokens";
import {
addFolderInput,
addFolderOutput,
cleanupOrphanedWorktreesInput,
cleanupOrphanedWorktreesOutput,
getFoldersOutput,
getRepositoryByRemoteUrlInput,
removeFolderInput,
Expand Down Expand Up @@ -41,13 +39,6 @@ export const foldersRouter = router({
return getService().updateFolderAccessed(input.folderId);
}),

cleanupOrphanedWorktrees: publicProcedure
.input(cleanupOrphanedWorktreesInput)
.output(cleanupOrphanedWorktreesOutput)
.mutation(({ input }) => {
return getService().cleanupOrphanedWorktrees(input.mainRepoPath);
}),

clearAllData: publicProcedure.mutation(() => {
return getService().clearAllData();
}),
Expand Down
52 changes: 1 addition & 51 deletions apps/code/src/renderer/features/folders/hooks/useFolders.ts
Original file line number Diff line number Diff line change
@@ -1,17 +1,12 @@
import type { RegisteredFolder } from "@main/services/folders/schemas";
import { useFocusStore } from "@renderer/stores/focusStore";
import { trpc, trpcClient, useTRPC } from "@renderer/trpc";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { logger } from "@utils/logger";
import { queryClient } from "@utils/queryClient";
import { useCallback, useEffect, useMemo, useRef } from "react";

const log = logger.scope("folders");
import { useCallback, useMemo } from "react";

export function useFolders() {
const trpcReact = useTRPC();
const queryClient = useQueryClient();
const hasInitialized = useRef(false);

const { data: folders = [], isLoading } = useQuery(
trpcReact.folders.getFolders.queryOptions(undefined, {
Expand All @@ -24,46 +19,6 @@ export function useFolders() {
[folders],
);

useEffect(() => {
if (hasInitialized.current || isLoading || folders.length === 0) return;
hasInitialized.current = true;

const deletedFolders = folders.filter((f) => f.exists === false);
if (deletedFolders.length > 0) {
Promise.all(
deletedFolders.map((folder) =>
trpcClient.folders.removeFolder
.mutate({ folderId: folder.id })
.catch((err) =>
log.error(`Failed to remove deleted folder ${folder.path}:`, err),
),
),
).then(() => {
void queryClient.invalidateQueries(
trpcReact.folders.getFolders.pathFilter(),
);
});
}

for (const folder of existingFolders) {
useFocusStore
.getState()
.restore(folder.path)
.catch((error) => {
log.error(`Failed to restore focus state for ${folder.path}:`, error);
});

trpcClient.folders.cleanupOrphanedWorktrees
.mutate({ mainRepoPath: folder.path })
.catch((error) => {
log.error(
`Failed to cleanup orphaned worktrees for ${folder.path}:`,
error,
);
});
}
}, [folders, existingFolders, isLoading, queryClient, trpcReact]);

const addFolderMutation = useMutation(
trpcReact.folders.addFolder.mutationOptions({
onSuccess: () => {
Expand Down Expand Up @@ -177,11 +132,6 @@ export const foldersApi = {
async updateFolderAccessed(folderId: string) {
return trpcClient.folders.updateFolderAccessed.mutate({ folderId });
},
async cleanupOrphanedWorktrees(mainRepoPath: string) {
return trpcClient.folders.cleanupOrphanedWorktrees.mutate({
mainRepoPath,
});
},
getFolderByPath(folders: RegisteredFolder[], path: string) {
return folders.find((f) => f.path === path);
},
Expand Down
Loading