Skip to content
Closed
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
90 changes: 88 additions & 2 deletions apps/desktop/src/lib/trpc/routers/projects/projects.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
import { basename } from "node:path";
import { existsSync } from "node:fs";
import { homedir } from "node:os";
import { basename, join } from "node:path";
import type { BrowserWindow } from "electron";
import { dialog } from "electron";
import { db } from "main/lib/db";
import type { Project } from "main/lib/db/schemas";
import { nanoid } from "nanoid";
import { SUPERSET_DIR_NAME, WORKTREES_DIR_NAME } from "shared/constants";
import { PROJECT_COLOR_VALUES } from "shared/constants/project-colors";
import { z } from "zod";
import { publicProcedure, router } from "../..";
import { getGitRoot } from "../workspaces/utils/git";
import { getGitRoot, listWorktrees } from "../workspaces/utils/git";
import { assignRandomColor } from "./utils/colors";

export const createProjectsRouter = (window: BrowserWindow) => {
Expand Down Expand Up @@ -65,6 +68,89 @@ export const createProjectsRouter = (window: BrowserWindow) => {
// biome-ignore lint/style/noNonNullAssertion: project is assigned above, TypeScript can't see it inside callback
data.projects.push(project!);
});

// Import existing worktrees for this new project
const supersetWorktreesDir = join(
homedir(),
SUPERSET_DIR_NAME,
WORKTREES_DIR_NAME,
);

const existingWorktrees = await listWorktrees(mainRepoPath);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Wrap listWorktrees in try-catch to prevent import failures from breaking project creation.

At this point the project has already been successfully created. If listWorktrees fails (e.g., git command error, permission issues), the entire mutation throws and the user sees an error even though the project was saved. Worktree import is supplementary functionality and shouldn't cause the overall operation to fail.

-			const existingWorktrees = await listWorktrees(mainRepoPath);
+			let existingWorktrees: Awaited<ReturnType<typeof listWorktrees>> = [];
+			try {
+				existingWorktrees = await listWorktrees(mainRepoPath);
+			} catch (error) {
+				console.warn("Failed to list existing worktrees:", error);
+			}
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const existingWorktrees = await listWorktrees(mainRepoPath);
let existingWorktrees: Awaited<ReturnType<typeof listWorktrees>> = [];
try {
existingWorktrees = await listWorktrees(mainRepoPath);
} catch (error) {
console.warn("Failed to list existing worktrees:", error);
}
🤖 Prompt for AI Agents
In apps/desktop/src/lib/trpc/routers/projects/projects.ts around line 79, the
call to listWorktrees can throw and currently will bubble up causing the whole
mutation to fail even after the project was created; wrap the listWorktrees call
in a try-catch, handle errors by logging them (or reporting to a
diagnostic/error-tracking service) and fall back to an empty array or skip
worktree import so the mutation returns success; ensure the catch does not
rethrow and that any subsequent code that expects the worktree list handles the
empty fallback.


// Filter to only worktrees in the superset worktrees directory that exist on disk
const supersetWorktrees = existingWorktrees.filter(
(wt) =>
wt.path.startsWith(`${supersetWorktreesDir}/`) && existsSync(wt.path),
);
Comment on lines +82 to +85

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Cross-platform path separator mismatch.

path.join produces OS-specific separators (backslash on Windows), but the check uses a hardcoded forward slash. On Windows, supersetWorktreesDir would be something like C:\Users\...\worktrees, so startsWith(${supersetWorktreesDir}/) would never match.

+import { sep } from "node:path";
...
 				const supersetWorktrees = existingWorktrees.filter(
 					(wt) =>
-						wt.path.startsWith(`${supersetWorktreesDir}/`) && existsSync(wt.path),
+						wt.path.startsWith(`${supersetWorktreesDir}${sep}`) && existsSync(wt.path),
 				);

Alternatively, normalize both paths before comparison to handle mixed separators from git output.

📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
const supersetWorktrees = existingWorktrees.filter(
(wt) =>
wt.path.startsWith(`${supersetWorktreesDir}/`) && existsSync(wt.path),
);
import { sep } from "node:path";
const supersetWorktrees = existingWorktrees.filter(
(wt) =>
wt.path.startsWith(`${supersetWorktreesDir}${sep}`) && existsSync(wt.path),
);
🤖 Prompt for AI Agents
In apps/desktop/src/lib/trpc/routers/projects/projects.ts around lines 82-85,
the startsWith check uses a hardcoded '/' which fails on Windows; normalize both
paths and use the platform separator before comparing. Fix by normalizing or
resolving supersetWorktreesDir and wt.path (e.g., with
path.resolve/path.normalize), ensure supersetWorktreesDir ends with path.sep,
then test startsWith against that normalized directory; alternatively use
path.relative(supersetWorktreesDir, wt.path) and check it does not start with
'..' to determine containment.


if (supersetWorktrees.length > 0) {
await db.update((data) => {
for (const wt of supersetWorktrees) {
// Check if worktree already exists in db
const existingWorktree = data.worktrees.find(
(w) => w.path === wt.path,
);
if (existingWorktree) {
continue;
}

const worktreeId = nanoid();
const worktree = {
id: worktreeId,
// biome-ignore lint/style/noNonNullAssertion: project is assigned above
projectId: project!.id,
path: wt.path,
branch: wt.branch,
createdAt: Date.now(),
gitStatus: {
branch: wt.branch,
needsRebase: false,
lastRefreshed: Date.now(),
},
};
data.worktrees.push(worktree);

// Calculate next tab order for workspace
const projectWorkspaces = data.workspaces.filter(
// biome-ignore lint/style/noNonNullAssertion: project is assigned above
(w) => w.projectId === project!.id,
);
const maxTabOrder =
projectWorkspaces.length > 0
? Math.max(...projectWorkspaces.map((w) => w.tabOrder))
: -1;

const workspace = {
id: nanoid(),
// biome-ignore lint/style/noNonNullAssertion: project is assigned above
projectId: project!.id,
worktreeId,
name: wt.branch,
tabOrder: maxTabOrder + 1,
createdAt: Date.now(),
updatedAt: Date.now(),
lastOpenedAt: Date.now(),
};
data.workspaces.push(workspace);

// Mark project as active since we found workspaces
// biome-ignore lint/style/noNonNullAssertion: project is assigned above
const p = data.projects.find((proj) => proj.id === project!.id);
if (p && p.tabOrder === null) {
const activeProjects = data.projects.filter(
(proj) => proj.tabOrder !== null,
);
const maxProjectTabOrder =
activeProjects.length > 0
? // biome-ignore lint/style/noNonNullAssertion: filter guarantees tabOrder is not null
Math.max(...activeProjects.map((proj) => proj.tabOrder!))
: -1;
p.tabOrder = maxProjectTabOrder + 1;
}
}
});
}
}

return {
Expand Down
47 changes: 47 additions & 0 deletions apps/desktop/src/lib/trpc/routers/workspaces/utils/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,3 +144,50 @@ export async function checkNeedsRebase(worktreePath: string): Promise<boolean> {
]);
return Number.parseInt(behindCount.trim(), 10) > 0;
}

export interface WorktreeInfo {
path: string;
branch: string;
}

/**
* Lists all worktrees for a repository
* @param mainRepoPath - Path to the main repository
* @returns Array of worktree information (path and branch)
*/
export async function listWorktrees(
mainRepoPath: string,
): Promise<WorktreeInfo[]> {
const git = simpleGit(mainRepoPath);
const output = await git.raw(["worktree", "list", "--porcelain"]);

const worktrees: WorktreeInfo[] = [];
const lines = output.split("\n");

let currentWorktree: Partial<WorktreeInfo> = {};

for (const line of lines) {
const trimmed = line.trim();

if (trimmed.startsWith("worktree ")) {
// Start of a new worktree entry
if (currentWorktree.path && currentWorktree.branch) {
worktrees.push(currentWorktree as WorktreeInfo);
}
currentWorktree = { path: trimmed.slice("worktree ".length) };
} else if (trimmed.startsWith("branch ")) {
// Branch reference (e.g., "branch refs/heads/branch-name")
const branchRef = trimmed.slice("branch ".length);
// Extract branch name from refs/heads/branch-name
const branchName = branchRef.replace("refs/heads/", "");
currentWorktree.branch = branchName;
}
}

// Don't forget the last worktree
if (currentWorktree.path && currentWorktree.branch) {
worktrees.push(currentWorktree as WorktreeInfo);
}

return worktrees;
}
Loading