Repository navigation
refactor(desktop): centralize git-init confirmation into useOpenProject hook - #1556
Conversation
…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.
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughCentralizes 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
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
Estimated code review effort🎯 4 (Complex) | ⏱️ ~45 minutes Poem
🚥 Pre-merge checks | ✅ 2 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (2 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches
🧪 Generate unit tests (beta)
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. Comment |
There was a problem hiding this comment.
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 | 🟡 MinorUI 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
.gitare 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 initerror, not just older-Git "unknown option" failures. A permissions error or corrupted.gitdirectory would be silently retried with a plaininit, 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.
🚀 Preview Deployment🔗 Preview Links
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.
There was a problem hiding this comment.
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 | 🟡 MinorUI label is stale regardless of the auto-init vs. dialog outcome
"Drag a folder with .git or click to browse"tells users only.gitfolders 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 ofonCancelwhen the Cancel button is clicked.Clicking
AlertDialogCanceltriggers bothonClick→onCancel?.()and the dialog'sonOpenChange→onCancel?.(). The current consumer (useOpenProject) guards against double-resolution viapendingRef, so this is safe today — but it's a fragile coupling. Consider removing the explicitonClickonAlertDialogCanceland relying solely ononOpenChangeto 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:initGitAndOpenin the dependency array causes cascading recreation on every render
useMutation()returns a new object reference on each state transition (idle → pending → success/error). WithinitGitAndOpeninshowDialog's dep array (line 68), the recreation chain is:initGitAndOpenchanges →showDialogrecreates →openNewandopenFromPath(both depend onshowDialog) recreate →handleDropinStartView(depends onopenFromPath) recreates every render. UsinginitGitAndOpen.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.
| 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, | ||
| }; | ||
| } |
There was a problem hiding this comment.
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.
| {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> | ||
| ))} |
There was a problem hiding this comment.
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.
| 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], | ||
| ); |
There was a problem hiding this comment.
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.handleOpenProjectlines 49–51:catch(err)is unreachable → the error bannersetError(...)is never triggered by mutation failures.StartWorkingDialog.handleImportRepolines 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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/desktop/src/renderer/components/NewWorkspaceModal/NewWorkspaceModal.tsx (1)
98-98: Destructure and applyisPendingto guard the "Import repo" action
useOpenProject()exposesisPending(coversopenNew,openFromPath, andinitGitAndOpenpending states), but it isn't destructured here. As a result, the "Import repo"DropdownMenuItem(Line 291) has no disabled guard during an in-flightopenNew()call. This is inconsistent with howcreateWorkspace.isPendingis 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.
There was a problem hiding this comment.
🧹 Nitpick comments (1)
apps/desktop/src/renderer/react-query/projects/useOpenProject.tsx (1)
70-70: UseinitGitAndOpen.mutateAsyncinstead of the full mutation object as auseCallbackdependencyIn TanStack Query v5, the entire
useMutationresult 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 likemutateAsync. Depending on the fullinitGitAndOpenobject causesshowDialog— and transitivelyopenNew/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.
Summary
useOpenProjecthook, replacing direct mutation calls across 5 consumersneedsGitInitstatus instead of auto-initializing git, so the frontend can show a confirmation dialog firstInitGitDialogrendered in the authenticated layout, driven by a Zustand storeChanges
Backend (
projects.ts)needsGitInitstatus toOpenNewResultandFolderOutcometypesopenNew: detect non-git folders by error message and returnneedsGitInitinstead of auto-callinginitGitRepoopenFromPath: separategetGitRootandgetDefaultBranchtry/catch so only missing git root triggersneedsGitInitinitGitRepohelper (reused byinitGitAndOpenprocedure)Frontend (new files)
useOpenProjecthook: wrapsuseOpenNew,useOpenFromPath, andinitGitAndOpenwith promise-based confirmation flowInitGitDialog: pure UI component reading from Zustand store, uses regularButtoninstead ofAlertDialogActionto avoid Radix auto-close race conditiongit-init-dialog.ts: Zustand store for global dialog stateConsumer updates (5 files)
StartView,SidebarDropZone,WorkspaceSidebarFooter,NewWorkspaceModal,StartWorkingDialog— all simplified to useuseOpenProjecthookTest Plan
Summary by CodeRabbit
New Features
Improvements
Removed