Skip to content

refactor(desktop): centralize git-init confirmation into useOpenProject hook - #1556

Merged
Kitenite merged 9 commits into
mainfrom
kitenite/folder-is-not-git-repo
Feb 19, 2026
Merged

Kitenite merged 9 commits into
mainfrom
kitenite/folder-is-not-git-repo

Conversation

@Kitenite

@Kitenite Kitenite commented Feb 18, 2026 •

Copy link
Copy Markdown
Member

Summary

  • Centralize all git-init confirmation logic into a single useOpenProject hook, replacing direct mutation calls across 5 consumers
  • Backend returns needsGitInit status instead of auto-initializing git, so the frontend can show a confirmation dialog first
  • Single global InitGitDialog rendered in the authenticated layout, driven by a Zustand store

Changes

Backend (projects.ts)

  • Add needsGitInit status to OpenNewResult and FolderOutcome types
  • openNew: detect non-git folders by error message and return needsGitInit instead of auto-calling initGitRepo
  • openFromPath: separate getGitRoot and getDefaultBranch try/catch so only missing git root triggers needsGitInit
  • Extract initGitRepo helper (reused by initGitAndOpen procedure)

Frontend (new files)

  • useOpenProject hook: wraps useOpenNew, useOpenFromPath, and initGitAndOpen with promise-based confirmation flow
  • InitGitDialog: pure UI component reading from Zustand store, uses regular Button instead of AlertDialogAction to avoid Radix auto-close race condition
  • git-init-dialog.ts: Zustand store for global dialog state

Consumer updates (5 files)

  • StartView, SidebarDropZone, WorkspaceSidebarFooter, NewWorkspaceModal, StartWorkingDialog — all simplified to use useOpenProject hook

Test Plan

  • Open a non-git folder → confirmation dialog appears → confirm → project opens
  • Open a git repo → opens directly without dialog
  • Multi-select mix of git/non-git → git repos open immediately, dialog for non-git ones
  • Cancel dialog → only already-opened projects are returned
  • Create workspace flow with non-git folder → dialog appears, confirm works without hanging
  • Drop non-git folder on sidebar → dialog works correctly

Summary by CodeRabbit

  • New Features

    • Unified "Open Project" hook (open new, open from path, drag‑drop) and global Git Init dialog with store.
  • Improvements

    • Batch imports show concise success feedback and auto‑select the first opened project.
    • Centralized loading/error handling and simplified flows for opening/importing projects.
  • Removed

    • Legacy per-result handling and older multi‑step Git‑init modal replaced by the unified flow.

…n dialog

Instead of showing an InitGitDialog when opening a folder that isn't a git
repository, automatically initialize git and open the project in one step.
@coderabbitai

coderabbitai Bot commented Feb 18, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Centralizes Git initialization on the server via a new initGitRepo helper; adds a unified renderer hook useOpenProject with openNew/openFromPath and an InitGitDialog backed by a Zustand store; replaces per-path result handling across UI call sites and removes the legacy StartView InitGitDialog component.

Changes

Cohort / File(s) Summary
Projects router (server)
apps/desktop/src/lib/trpc/routers/projects/projects.ts
Add initGitRepo(path) to centralize git init + initial commit; consolidate git-init logic in openNew, openFromPath, and related flows; remove FolderOutcome / OpenNewMultiResult types.
Unified open hook & public export
apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx, apps/desktop/src/renderer/react-query/projects/index.ts
Add useOpenProject hook returning { openNew, openFromPath, isPending } that coordinates open flows, invokes server APIs, and drives the git-init dialog flow; re-exported from projects index.
Init Git dialog + store (renderer)
apps/desktop/src/renderer/react-query/projects/InitGitDialog.tsx, apps/desktop/src/renderer/stores/git-init-dialog.ts
Add InitGitDialog component and useGitInitDialogStore (Zustand) to manage multi-path git-init confirmation, pending state, and callbacks; dialog rendered in authenticated layout.
Renderer call-site updates
apps/desktop/src/renderer/components/NewWorkspaceModal/NewWorkspaceModal.tsx, apps/desktop/src/renderer/routes/_authenticated/_dashboard/tasks/components/StartWorkingDialog/StartWorkingDialog.tsx, apps/desktop/src/renderer/screens/main/components/WorkspaceSidebar/WorkspaceSidebarFooter.tsx, apps/desktop/src/renderer/screens/main/components/StartView/index.tsx, apps/desktop/src/renderer/screens/main/components/WorkspaceSidebar/SidebarDropZone/SidebarDropZone.tsx
Replace useOpenNew/useOpenFromPath + processOpenNewResults mutation-based flows with useOpenProject; call sites now await openNew()/openFromPath() and handle returned project arrays or errors; remove per-result git-init toast branches and legacy result-shape handling.
Removed legacy modal
apps/desktop/src/renderer/screens/main/components/StartView/InitGitDialog.tsx
Delete the old focus-heavy StartView InitGitDialog implementation (multi-path modal); replaced by the new dialog/store flow and global InitGitDialog component.
Renderer layout
apps/desktop/src/renderer/routes/_authenticated/layout.tsx
Add global <InitGitDialog /> to the authenticated layout so the new dialog is available app-wide.
Result processing utility
apps/desktop/src/renderer/react-query/projects/processOpenNewResults.ts
Remove showGitInitToast parameter and associated toast branch; function still returns categorized outcomes but no longer triggers the git-init toast.

Sequence Diagram(s)

sequenceDiagram
  participant UI as Client UI
  participant Hook as useOpenProject
  participant Store as GitInitDialogStore
  participant Server as projects.tRPC
  participant FS as LocalFS

  UI->>Hook: call openNew() / openFromPath(path)
  Hook->>Server: openNew / openFromPath
  Server-->>Hook: response (projects | needsGitInit paths | error)
  alt needs git init
    Hook->>Store: open(paths, onConfirm, onCancel)
    Store-->>UI: render InitGitDialog (isOpen)
    UI->>Store: user confirms
    Store->>Hook: invoke onConfirm
    Hook->>Server: call initGitAndOpen (per path)
    Server->>FS: init git, create initial commit (initGitRepo)
    Server-->>Hook: project(s)
  end
  Hook-->>UI: return projects or throw error
  UI->>UI: navigate to first project
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~45 minutes

Poem

🐰 I sniffed the folders, found no git inside,
A little dialog asked if I’d abide,
One click, one hop — init and make a first commit,
Workspaces bloom, branches neat and fit,
Rabbit bounces off, the projects all sit.

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 20.00% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Title check ✅ Passed The pull request title clearly and concisely describes the main change: auto-initializing git for non-repository folders without a confirmation dialog.
Description check ✅ Passed The pull request description provides comprehensive details covering summary, backend/frontend changes, and a detailed test plan aligned with the repository template structure.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
  • 📝 Generate docstrings
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch kitenite/folder-is-not-git-repo

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@coderabbitai coderabbitai Bot left a comment

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.

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/desktop/src/renderer/screens/main/components/StartView/index.tsx (1)

215-217: ⚠️ Potential issue | 🟡 Minor

UI text is now slightly misleading after auto-init change.

The hint text says "Drag a folder with .git or click to browse", but with auto-init, folders without .git are now also supported. Consider updating the text to reflect the new behavior.

📝 Suggested text update
-										<div className="text-sm pt-3 text-muted-foreground">
-											Drag a folder with .git or click to browse
-										</div>
+										<div className="text-sm pt-3 text-muted-foreground">
+											Drag a folder or click to browse
+										</div>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/screens/main/components/StartView/index.tsx` around
lines 215 - 217, Update the explanatory text in the StartView component to
reflect auto-init behavior: replace the string "Drag a folder with .git or click
to browse" in
apps/desktop/src/renderer/screens/main/components/StartView/index.tsx (inside
the div with className "text-sm pt-3 text-muted-foreground") with wording that
accepts folders both with and without .git—e.g., mention that folders without
.git will be auto-initialized or simply say "Drag a folder or click to browse
(folders will be auto-initialized if needed)". Ensure the change targets the
literal text node in StartView.
🧹 Nitpick comments (1)
apps/desktop/src/lib/trpc/routers/projects/projects.ts (1)

74-80: Fallback catch is overly broad — may swallow real init failures.

The catch at Line 76 will fire for any git init error, not just older-Git "unknown option" failures. A permissions error or corrupted .git directory would be silently retried with a plain init, masking the real problem.

Consider narrowing the catch to only retry when the error message indicates an unsupported flag, and re-throw otherwise.

♻️ Proposed fix
 	try {
 		await git.init(["--initial-branch=main"]);
 	} catch (err) {
-		// Likely an older Git version that doesn't support --initial-branch
-		console.warn("Git init with --initial-branch failed, using fallback:", err);
-		await git.init();
+		const msg = err instanceof Error ? err.message : String(err);
+		// Only fall back for older Git versions that don't support --initial-branch
+		if (msg.includes("unknown option") || msg.includes("unrecognized option")) {
+			console.warn("Git init with --initial-branch not supported, using fallback:", msg);
+			await git.init();
+		} else {
+			throw err;
+		}
 	}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/lib/trpc/routers/projects/projects.ts` around lines 74 - 80,
The catch around the git.init(["--initial-branch=main"]) call is too broad and
may hide real failures; change it to inspect the thrown error (cast to Error and
check err.message or err.toString()) and only perform the fallback await
git.init() when the message indicates the flag is unsupported (e.g., contains
"--initial-branch" or "unknown option"/"invalid option"); otherwise re-throw the
error so genuine permission/corruption failures are surfaced. Ensure you update
the catch block surrounding git.init(...) to conditionally retry and to rethrow
for any non-unsupported-flag errors.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Outside diff comments:
In `@apps/desktop/src/renderer/screens/main/components/StartView/index.tsx`:
- Around line 215-217: Update the explanatory text in the StartView component to
reflect auto-init behavior: replace the string "Drag a folder with .git or click
to browse" in
apps/desktop/src/renderer/screens/main/components/StartView/index.tsx (inside
the div with className "text-sm pt-3 text-muted-foreground") with wording that
accepts folders both with and without .git—e.g., mention that folders without
.git will be auto-initialized or simply say "Drag a folder or click to browse
(folders will be auto-initialized if needed)". Ensure the change targets the
literal text node in StartView.

---

Nitpick comments:
In `@apps/desktop/src/lib/trpc/routers/projects/projects.ts`:
- Around line 74-80: The catch around the git.init(["--initial-branch=main"])
call is too broad and may hide real failures; change it to inspect the thrown
error (cast to Error and check err.message or err.toString()) and only perform
the fallback await git.init() when the message indicates the flag is unsupported
(e.g., contains "--initial-branch" or "unknown option"/"invalid option");
otherwise re-throw the error so genuine permission/corruption failures are
surfaced. Ensure you update the catch block surrounding git.init(...) to
conditionally retry and to rethrow for any non-unsupported-flag errors.

@github-actions

github-actions Bot commented Feb 18, 2026 •

Copy link
Copy Markdown
Contributor

🚀 Preview Deployment

🔗 Preview Links

Service Status Link
Neon Database (Neon) ✅ View Branch
Fly.io Electric (Fly.io) ✅ View App
Vercel API (Vercel) ✅ Open Preview
Vercel Web (Vercel) ✅ Open Preview
Vercel Marketing (Vercel) ✅ Open Preview
Vercel Admin (Vercel) ✅ Open Preview
Vercel Docs (Vercel) ✅ Open Preview

Preview updates automatically with new commits

Replace auto-init behavior with a confirmation dialog when opening
non-git folders. The backend now returns needsGitInit status instead of
silently initializing, and a single useOpenProject hook manages the
promise-based confirmation flow for all 5 consumers. The dialog is
rendered once in the _authenticated layout via a Zustand store.

@coderabbitai coderabbitai Bot left a comment

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.

Actionable comments posted: 4

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
apps/desktop/src/renderer/screens/main/components/StartView/index.tsx (1)

176-176: ⚠️ Potential issue | 🟡 Minor

UI label is stale regardless of the auto-init vs. dialog outcome

"Drag a folder with .git or click to browse" tells users only .git folders are valid. Under the current dialog flow (or the intended auto-init approach), any folder is accepted and git is initialized if missing. The text should reflect that — e.g. "Drag any folder or click to browse".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/screens/main/components/StartView/index.tsx` at
line 176, Update the stale UI label in the StartView component: replace the
hardcoded string "Drag a folder with .git or click to browse" (used in the
StartView JSX) with a wording that reflects the current flow such as "Drag any
folder or click to browse" so it accurately indicates any folder is accepted and
git will be initialized if missing.
🧹 Nitpick comments (2)
apps/desktop/src/renderer/react-query/projects/InitGitDialog.tsx (1)

56-62: Potential double-invocation of onCancel when the Cancel button is clicked.

Clicking AlertDialogCancel triggers both onClick → onCancel?.() and the dialog's onOpenChange → onCancel?.(). The current consumer (useOpenProject) guards against double-resolution via pendingRef, so this is safe today — but it's a fragile coupling. Consider removing the explicit onClick on AlertDialogCancel and relying solely on onOpenChange to trigger cancellation, or vice versa.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/react-query/projects/InitGitDialog.tsx` around
lines 56 - 62, The Cancel button may call onCancel twice because
AlertDialogCancel has an explicit onClick that duplicates the dialog's
onOpenChange handling; remove the onClick handler from AlertDialogCancel and
keep its disabled prop, and rely on the dialog-level onOpenChange to call
onCancel?. Leave AlertDialogAction's onClick/onConfirm behavior unchanged;
ensure the component that sets onOpenChange still calls onCancel? (e.g.,
useOpenProject) so cancellation is triggered only once.
apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx (1)

25-69: initGitAndOpen in the dependency array causes cascading recreation on every render

useMutation() returns a new object reference on each state transition (idle → pending → success/error). With initGitAndOpen in showDialog's dep array (line 68), the recreation chain is: initGitAndOpen changes → showDialog recreates → openNew and openFromPath (both depend on showDialog) recreate → handleDrop in StartView (depends on openFromPath) recreates every render. Using initGitAndOpen.mutateAsync — which is a stable reference — breaks the chain:

♻️ Proposed refactor
-	), [initGitAndOpen, utils]);
+	), [initGitAndOpen.mutateAsync, utils]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx` around
lines 25 - 69, The showDialog callback is being re-created whenever the entire
initGitAndOpen mutation object changes; change the dependency to use the stable
mutateAsync function instead of initGitAndOpen itself: remove initGitAndOpen
from the showDialog dependency array and reference initGitAndOpen.mutateAsync
inside the callback where mutateAsync({ path }) is awaited; this prevents
cascading recreation of showDialog (and downstream openNew, openFromPath,
handleDrop) while preserving the existing logic that uses useGitInitDialogStore,
pendingRef, utils.projects.getRecents.invalidate(), and the onConfirm/onCancel
flows.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@apps/desktop/src/lib/trpc/routers/projects/projects.ts`:
- Around line 588-600: The current try/catch treats any error from
getGitRoot(selectedPath) or getDefaultBranch(mainRepoPath) as "needsGitInit";
change this by calling getGitRoot(selectedPath) inside its own try/catch and
only return needsGitInit when that call fails, then call
getDefaultBranch(mainRepoPath) in a separate try/catch and handle its errors
differently (e.g., return a non-needsGitInit error response or surface the error
to the caller) so that a failure in getDefaultBranch does not cause initGitRepo
to run; update the logic around mainRepoPath and defaultBranch to reflect these
two distinct error paths and keep the existing returned shape for the
needsGitInit case tied only to getGitRoot failures.

In `@apps/desktop/src/renderer/react-query/projects/InitGitDialog.tsx`:
- Around line 26-49: The current folder-name extraction uses .split("/").pop()
which fails on Windows; update InitGitDialog.tsx to use a cross-platform
basename: import { basename } from "path" (or import path and use path.basename)
and replace paths[0]?.split("/").pop() and p.split("/").pop() with
basename(paths[0] || "") and basename(p) respectively so folder names render
correctly on all platforms.

In `@apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx`:
- Around line 31-56: The onConfirm handler sets
useGitInitDialogStore.getState().setIsPending(true) but doesn’t guarantee
cleanup if utils.projects.getRecents.invalidate() throws; wrap the post-loop
cleanup (useGitInitDialogStore.getState().close(), pendingRef.current = null,
and p.resolve(projects)) in a try/finally so cleanup always runs; specifically
modify the onConfirm async block (the onConfirm lambda in useOpenProject.tsx
that uses pendingRef.current and calls initGitAndOpen.mutateAsync) to perform
the invalidate call inside try and move the close()/pendingRef reset/resolve
into the finally, optionally rethrow or handle the invalidate error after
cleanup.
- Around line 71-155: Both openNew and openFromPath wrap mutations in new
Promise that only calls resolve, which swallows real errors; change their
Promise executors to (resolve, reject) and on actual (non-cancel) error paths
(the onError callbacks and branches where "error" in result) call reject(...)
with the underlying error or an Error describing the failure (include the error
payload from result when available) instead of resolve([])/resolve(null); keep
resolving for canceled flows and the successful branches (e.g.,
processOpenNewResults path and "project" in result) so callers' try/catch and
existing error handling (StartView.handleOpenProject,
StartWorkingDialog.handleImportRepo) can react to real failures.

---

Outside diff comments:
In `@apps/desktop/src/renderer/screens/main/components/StartView/index.tsx`:
- Line 176: Update the stale UI label in the StartView component: replace the
hardcoded string "Drag a folder with .git or click to browse" (used in the
StartView JSX) with a wording that reflects the current flow such as "Drag any
folder or click to browse" so it accurately indicates any folder is accepted and
git will be initialized if missing.

---

Nitpick comments:
In `@apps/desktop/src/renderer/react-query/projects/InitGitDialog.tsx`:
- Around line 56-62: The Cancel button may call onCancel twice because
AlertDialogCancel has an explicit onClick that duplicates the dialog's
onOpenChange handling; remove the onClick handler from AlertDialogCancel and
keep its disabled prop, and rely on the dialog-level onOpenChange to call
onCancel?. Leave AlertDialogAction's onClick/onConfirm behavior unchanged;
ensure the component that sets onOpenChange still calls onCancel? (e.g.,
useOpenProject) so cancellation is triggered only once.

In `@apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx`:
- Around line 25-69: The showDialog callback is being re-created whenever the
entire initGitAndOpen mutation object changes; change the dependency to use the
stable mutateAsync function instead of initGitAndOpen itself: remove
initGitAndOpen from the showDialog dependency array and reference
initGitAndOpen.mutateAsync inside the callback where mutateAsync({ path }) is
awaited; this prevents cascading recreation of showDialog (and downstream
openNew, openFromPath, handleDrop) while preserving the existing logic that uses
useGitInitDialogStore, pendingRef, utils.projects.getRecents.invalidate(), and
the onConfirm/onCancel flows.

Comment on lines 588 to 600
let mainRepoPath: string;
let defaultBranch: string;

try {
mainRepoPath = await getGitRoot(selectedPath);
} catch (_error) {
// Return a special response so the UI can offer to initialize git
defaultBranch = await getDefaultBranch(mainRepoPath);
} catch {
return {
canceled: false,
needsGitInit: true,
needsGitInit: true as const,
selectedPath,
};
}

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

Bug: catch-all misclassifies getDefaultBranch failures as needsGitInit.

If getGitRoot succeeds but getDefaultBranch throws (e.g., corrupted repo, permission error), the catch block returns needsGitInit: true, prompting the user to re-initialize an existing repo. While git init is idempotent, initGitRepo would also create a spurious empty "Initial commit" on the existing repository.

Separate the two calls so only getGitRoot failures trigger needsGitInit:

Proposed fix
-			let mainRepoPath: string;
-			let defaultBranch: string;
-
-			try {
-				mainRepoPath = await getGitRoot(selectedPath);
-				defaultBranch = await getDefaultBranch(mainRepoPath);
-			} catch {
-				return {
-					canceled: false,
-					needsGitInit: true as const,
-					selectedPath,
-				};
-			}
+			let mainRepoPath: string;
+			try {
+				mainRepoPath = await getGitRoot(selectedPath);
+			} catch {
+				return {
+					canceled: false,
+					needsGitInit: true as const,
+					selectedPath,
+				};
+			}
+
+			const defaultBranch = await getDefaultBranch(mainRepoPath);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/lib/trpc/routers/projects/projects.ts` around lines 588 -
600, The current try/catch treats any error from getGitRoot(selectedPath) or
getDefaultBranch(mainRepoPath) as "needsGitInit"; change this by calling
getGitRoot(selectedPath) inside its own try/catch and only return needsGitInit
when that call fails, then call getDefaultBranch(mainRepoPath) in a separate
try/catch and handle its errors differently (e.g., return a non-needsGitInit
error response or surface the error to the caller) so that a failure in
getDefaultBranch does not cause initGitRepo to run; update the logic around
mainRepoPath and defaultBranch to reflect these two distinct error paths and
keep the existing returned shape for the needsGitInit case tied only to
getGitRoot failures.

Comment on lines +26 to +49
{isSingle ? (
<p>
<span className="font-medium text-foreground">
{paths[0]?.split("/").pop()}
</span>{" "}
is not a git repository. Would you like to initialize one?
</p>
) : (
<>
<p>
The following folders are not git repositories. Would you
like to initialize them?
</p>
<ul className="list-disc pl-4 space-y-1">
{paths.map((p) => (
<li key={p}>
<span className="font-medium text-foreground">
{p.split("/").pop()}
</span>
<span className="text-xs ml-1 text-muted-foreground">
{p}
</span>
</li>
))}

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

Cross-platform path display: split("/") won't extract the folder name on Windows.

On Windows, Electron may pass paths with backslash separators (e.g., C:\Users\foo\project). Using .split("/").pop() would return the full path instead of just the folder name. Consider using a cross-platform basename extraction, or import path utilities.

Proposed fix
+// Cross-platform basename: split on both separators
+const getFolderName = (p: string) => p.split(/[\\/]/).pop() ?? p;
+
 {isSingle ? (
   <p>
     <span className="font-medium text-foreground">
-      {paths[0]?.split("/").pop()}
+      {paths[0] ? getFolderName(paths[0]) : ""}
     </span>{" "}
     is not a git repository. Would you like to initialize one?
   </p>
 ) : (
   ...
     {paths.map((p) => (
       <li key={p}>
         <span className="font-medium text-foreground">
-          {p.split("/").pop()}
+          {getFolderName(p)}
         </span>
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/react-query/projects/InitGitDialog.tsx` around
lines 26 - 49, The current folder-name extraction uses .split("/").pop() which
fails on Windows; update InitGitDialog.tsx to use a cross-platform basename:
import { basename } from "path" (or import path and use path.basename) and
replace paths[0]?.split("/").pop() and p.split("/").pop() with basename(paths[0]
|| "") and basename(p) respectively so folder names render correctly on all
platforms.

Comment on lines +71 to +155
const openNew = useCallback((): Promise<Project[]> => {
return new Promise((resolve) => {
openNewMutation.mutate(undefined, {
onSuccess: (result) => {
if (result.canceled) {
resolve([]);
return;
}

if ("error" in result) {
resolve([]);
return;
}

if ("results" in result) {
const { successes, needsGitInit } = processOpenNewResults({
results: result.results,
});

const immediateProjects = successes.map((s) => s.project);

if (needsGitInit.length > 0) {
showDialog({
paths: needsGitInit.map((n) => n.selectedPath),
immediateSuccesses: immediateProjects,
resolve,
});
return;
}

resolve(immediateProjects);
return;
}

resolve([]);
},
onError: () => {
resolve([]);
},
});
});
}, [openNewMutation, showDialog]);

const openFromPath = useCallback(
(path: string): Promise<Project | null> => {
return new Promise((resolve) => {
openFromPathMutation.mutate(
{ path },
{
onSuccess: (result) => {
if ("canceled" in result && result.canceled) {
resolve(null);
return;
}

if ("needsGitInit" in result && result.needsGitInit) {
showDialog({
paths: [result.selectedPath],
immediateSuccesses: [],
resolve: (projects) => resolve(projects[0] ?? null),
});
return;
}

if ("error" in result) {
resolve(null);
return;
}

if ("project" in result) {
resolve(result.project);
return;
}

resolve(null);
},
onError: () => {
resolve(null);
},
},
);
});
},
[openFromPathMutation, showDialog],
);

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

openNew and openFromPath always resolve — actual errors are silently swallowed

Both functions wrap mutations in new Promise(resolve => ...) and exclusively call resolve(...) — never reject(...). Every error path reaches a resolve([]) or resolve(null):

  • openNew: onError → resolve([]) (line 108), "error" in result → resolve([]) (line 82).
  • openFromPath: onError → resolve(null) (line 148), "error" in result → resolve(null) (line 136).

Downstream dead code: The try/catch blocks in consumers can never fire from these mutations:

  • StartView.handleOpenProject lines 49–51: catch(err) is unreachable → the error banner setError(...) is never triggered by mutation failures.
  • StartWorkingDialog.handleImportRepo lines 121–126: toast.error(...) is unreachable for mutation failures.

User-visible impact: When a mutation fails (e.g. missing git user.name/user.email — the exact case the PR objectives require to surface as a config error), the user sees nothing: openNew() silently returns [], nothing navigates, no error appears. Individual git-init failures in onConfirm (lines 43–48) are only console.error-logged.

Consider rejecting the promise on actual (non-cancel) errors, or routing errors through a toast/setError call before resolving:

🐛 Sketch of fix for `openNew`
 onError: () => {
-  resolve([]);
+  reject(new Error("Failed to open project"));
 },

And in consumers, the existing catch blocks then become active and can surface feedback as intended.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx` around
lines 71 - 155, Both openNew and openFromPath wrap mutations in new Promise that
only calls resolve, which swallows real errors; change their Promise executors
to (resolve, reject) and on actual (non-cancel) error paths (the onError
callbacks and branches where "error" in result) call reject(...) with the
underlying error or an Error describing the failure (include the error payload
from result when available) instead of resolve([])/resolve(null); keep resolving
for canceled flows and the successful branches (e.g., processOpenNewResults path
and "project" in result) so callers' try/catch and existing error handling
(StartView.handleOpenProject, StartWorkingDialog.handleImportRepo) can react to
real failures.

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
apps/desktop/src/renderer/components/NewWorkspaceModal/NewWorkspaceModal.tsx (1)

98-98: Destructure and apply isPending to guard the "Import repo" action

useOpenProject() exposes isPending (covers openNew, openFromPath, and initGitAndOpen pending states), but it isn't destructured here. As a result, the "Import repo" DropdownMenuItem (Line 291) has no disabled guard during an in-flight openNew() call. This is inconsistent with how createWorkspace.isPending is already used to gate the "Create Workspace" button (Line 505).

♻️ Proposed fix
-	const { openNew } = useOpenProject();
+	const { openNew, isPending: isOpenPending } = useOpenProject();
-			<DropdownMenuItem onClick={handleImportRepo}>
+			<DropdownMenuItem onClick={handleImportRepo} disabled={isOpenPending}>
 				<LuFolderOpen className="size-4" />
 				Import repo
 			</DropdownMenuItem>

Also applies to: 291-294

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/components/NewWorkspaceModal/NewWorkspaceModal.tsx`
at line 98, Destructure isPending from useOpenProject alongside openNew in
NewWorkspaceModal (i.e., const { openNew, isPending } = useOpenProject()) and
use it to disable the "Import repo" DropdownMenuItem: reference the
DropdownMenuItem that triggers openNew and add a disabled prop or guard when
isPending is true so the import action is blocked while openNew (and related
operations) are in-flight, matching the existing gating used for
createWorkspace.isPending.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In
`@apps/desktop/src/renderer/components/NewWorkspaceModal/NewWorkspaceModal.tsx`:
- Line 98: Destructure isPending from useOpenProject alongside openNew in
NewWorkspaceModal (i.e., const { openNew, isPending } = useOpenProject()) and
use it to disable the "Import repo" DropdownMenuItem: reference the
DropdownMenuItem that triggers openNew and add a disabled prop or guard when
isPending is true so the import action is blocked while openNew (and related
operations) are in-flight, matching the existing gating used for
createWorkspace.isPending.

@Kitenite Kitenite changed the title feat(desktop): auto-init git for non-repo folders without confirmation refactor(desktop): centralize git-init confirmation into useOpenProject hook Feb 19, 2026

@coderabbitai coderabbitai Bot left a comment

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.

🧹 Nitpick comments (1)
apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx (1)

70-70: Use initGitAndOpen.mutateAsync instead of the full mutation object as a useCallback dependency

In TanStack Query v5, the entire useMutation result object is not referentially stable and changes reference on every mutation state transition. The official guidance is to destructure and depend on individual stable properties like mutateAsync. Depending on the full initGitAndOpen object causes showDialog — and transitively openNew/openFromPath — to be recreated unnecessarily on each mutation state change.

♻️ Proposed fix
-	), [initGitAndOpen, utils]);
+	), [initGitAndOpen.mutateAsync, utils]);
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx` at line
70, The useCallback dependency currently includes the whole mutation object
initGitAndOpen which is not referentially stable; update the dependency array to
use initGitAndOpen.mutateAsync instead (i.e., replace initGitAndOpen with
initGitAndOpen.mutateAsync) so showDialog (and the callbacks openNew /
openFromPath that depend on it) are not recreated on every mutation state
change; ensure any references inside useCallback call the async function via
mutateAsync where needed and keep utils as before.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx`:
- Around line 73-157: Both openNew and openFromPath wrap mutations in new
Promise((resolve) => ...) and always call resolve, which swallows errors (so
caller catch paths never run); change these to call reject(...) for real errors
and the mutation onError handler, and propagate config/git-user errors by
rejecting with the error object instead of resolve([])/resolve(null). Update
openNew (referencing openNewMutation, processOpenNewResults, showDialog) and
openFromPath (openFromPathMutation, showDialog) so branches that detect "error"
or mutation onError call reject(err) (or reject(new Error(...))) and only use
resolve for successful project results; when showDialog must handle user
prompts, have it continue to call the outer resolve for success but reject for
surfaced config errors so consumer catch blocks become reachable.

---

Nitpick comments:
In `@apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx`:
- Line 70: The useCallback dependency currently includes the whole mutation
object initGitAndOpen which is not referentially stable; update the dependency
array to use initGitAndOpen.mutateAsync instead (i.e., replace initGitAndOpen
with initGitAndOpen.mutateAsync) so showDialog (and the callbacks openNew /
openFromPath that depend on it) are not recreated on every mutation state
change; ensure any references inside useCallback call the async function via
mutateAsync where needed and keep utils as before.

@Kitenite
Kitenite merged commit a24c514 into main Feb 19, 2026
11 of 13 checks passed
@Kitenite
Kitenite deleted the kitenite/folder-is-not-git-repo branch February 19, 2026 06:04

This branch was previously deployed

1 inactive deployment
preview — e9045b8b Deployed Feb 19, 2026 by Kitenite via Deploy Web #2092
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant