Repository navigation
fix(desktop): prevent workspace from reappearing during deletion - #705
Conversation
When deleting a workspace, it would briefly disappear (optimistic update) then reappear while deletion was in progress, because refetches during slow git operations would show the workspace still in the database. Fix by adding a `deletingAt` timestamp field that is set immediately when deletion starts. All queries now filter out workspaces with deletingAt set, so even if refetches occur during slow operations, the workspace stays hidden. Also simplified the optimistic update logic in useDeleteWorkspace from 148 lines to 56 lines by removing complex rollback tracking and manual next- workspace calculation - the server now handles this automatically. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
|
Caution Review failedThe pull request is closed. 📝 WalkthroughWalkthroughAdds a soft-delete flag ( Changes
Sequence Diagram(s)sequenceDiagram
actor User
participant UI as React UI
participant Mutation as useDeleteWorkspace
participant RPC as workspaces.delete RPC
participant DB as Database
participant Teardown as Teardown/Worktree service
User->>UI: Click "Delete workspace"
UI->>Mutation: mutate(workspaceId)
activate Mutation
Mutation->>Mutation: Optimistic: remove workspace from caches
Mutation->>UI: Update UI (optimistic)
Mutation->>RPC: call delete(workspaceId)
deactivate Mutation
activate RPC
RPC->>DB: markWorkspaceAsDeleting(workspaceId)
DB-->>RPC: ok
RPC->>RPC: acquire project lock
RPC->>Teardown: teardown/remove worktree (may fail)
alt teardown succeeds
Teardown-->>RPC: success
RPC->>DB: remove or unlink workspace associations
RPC-->>Mutation: success
else teardown fails
Teardown-->>RPC: error
RPC->>DB: clearWorkspaceDeletingStatus(workspaceId)
RPC-->>Mutation: error
end
deactivate RPC
alt RPC success
Mutation->>UI: keep optimistic state
else RPC error
Mutation->>Mutation: onError: restore previous caches
Mutation->>UI: rollback UI
end
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 3✅ Passed checks (3 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing touches
📜 Recent review detailsConfiguration used: defaults Review profile: CHILL Plan: Pro 📒 Files selected for processing (1)
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 |
🚀 Preview Deployment🔗 Preview Links
Preview updates automatically with new commits |
- Add early return in canDelete when deletion already in progress - Wrap waitForInit in try-catch to clear deletingAt on timeout, preventing workspaces from being stuck in "deleting" state - Fix hideProjectIfNoWorkspaces to check ALL workspaces (including those being deleted) to prevent premature project hiding during concurrent deletes 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (4)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts (2)
187-239:createBranchWorkspacecan fail with a confusing error when a branch workspace exists but is deleting.
If the insert conflicts due to an existing (deleting) branch workspace,getBranchWorkspace()returnsundefined(because it filters deleting), so you throw “Failed to create or find…”. Consider detecting this and returning an explicit “deletion in progress” error.Proposed fix (detect deleting branch workspace conflict)
-import { and, eq, isNull, not } from "drizzle-orm"; +import { and, eq, isNotNull, isNull, not } from "drizzle-orm"; @@ const workspace = insertResult[0] ?? getBranchWorkspace(input.projectId); if (!workspace) { - throw new Error("Failed to create or find branch workspace"); + const deletingBranchWorkspace = localDb + .select() + .from(workspaces) + .where( + and( + eq(workspaces.projectId, input.projectId), + eq(workspaces.type, "branch"), + isNotNull(workspaces.deletingAt), + ), + ) + .get(); + if (deletingBranchWorkspace) { + throw new Error( + "Branch workspace deletion already in progress. Please try again shortly.", + ); + } + throw new Error("Failed to create or find branch workspace"); }
263-304: Critical:openWorktreeshould not allow opening while a workspace for that worktree is deleting.
WithonDelete: "cascade"onworkspaces.worktreeId → worktrees.id, the delete flow can remove theworktreesrow and cascade-delete any newly opened workspace that reuses thatworktreeId. Also, the worktree may be removed from disk while “reopened”.Proposed fix (block if any workspace exists; special-case deleting)
- // Check if worktree already has an active workspace (excluding deleting ones) - const existingWorkspace = localDb + // Block reopening while deletion is in progress (or already open) + const existingWorkspace = localDb .select() .from(workspaces) - .where( - and( - eq(workspaces.worktreeId, input.worktreeId), - isNull(workspaces.deletingAt), - ), - ) + .where(eq(workspaces.worktreeId, input.worktreeId)) .get(); if (existingWorkspace) { - throw new Error("Worktree already has an active workspace"); + if (existingWorkspace.deletingAt) { + throw new Error( + "Worktree is currently being deleted. Please try again shortly.", + ); + } + throw new Error("Worktree already has an active workspace"); }apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts (1)
155-283: Consider a defensive guard before deleting theworktreesrow to avoid cascading an unexpectedly reopened workspace.
Even if UI blocks reopen, a server-side check makes this safer (especially givenonDelete: "cascade").Proposed hardening (abort if another non-deleting workspace references the same worktree)
// Proceed with DB cleanup deleteWorkspace(input.id); if (worktree) { + const stillReferenced = localDb + .select() + .from(workspaces) + .where( + and( + eq(workspaces.worktreeId, worktree.id), + isNull(workspaces.deletingAt), + ), + ) + .get(); + if (stillReferenced) { + // Another active workspace is using this worktree; don't delete it. + workspaceInitManager.clearJob(input.id); + return { + success: false, + error: + "Worktree was reopened during deletion. Please retry the deletion.", + }; + } deleteWorktreeRecord(worktree.id); }apps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts (1)
30-111: Potential regression:options.onMutateis ignored.
Sinceoptionsis spread into the mutation config, callers may reasonably expect theironMutateto run. Consider calling it and merging contexts.Proposed fix (delegate onMutate and preserve both contexts)
type DeleteContext = { @@ previousActive: ReturnType< @@ : never; + userContext?: unknown; }; @@ onMutate: async ({ id }) => { + const userContext = await options?.onMutate?.({ id } as any); await Promise.all([ utils.workspaces.getAll.cancel(), utils.workspaces.getAllGrouped.cancel(), utils.workspaces.getActive.cancel(), ]); @@ - return { previousGrouped, previousAll, previousActive } as DeleteContext; + return { + previousGrouped, + previousAll, + previousActive, + userContext, + } as DeleteContext; },
🧹 Nitpick comments (3)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts (1)
2-2: Filteringworkspaces.deletingAtingetWorktreesByProjectlooks correct; watch the N+1 pattern.
The newand(..., isNull(workspaces.deletingAt))condition matches the “hide during deletion” intent. If this endpoint runs frequently, consider replacing the per-worktree.get()with a single query/join to avoid N+1 DB calls.Also applies to: 155-166
apps/desktop/src/lib/trpc/routers/workspaces/procedures/status.ts (1)
34-78:reorderfilters out deleting workspaces; consider a transaction to avoid partial updates.
If another flow marks a workspace deleting mid-reorder, you can still update itstabOrder. A transaction (or a “where isNull(deletingAt)” on updates) would make this more robust.apps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts (1)
21-109: Optimistic removal + “pick next workspace” looks reasonable for UX.
One nit: you’re synthesizingworktree.gitStatuswith placeholders; if any UI treats that as authoritative, consider setting it tonullinstead.
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (12)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/create.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/query.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/status.tsapps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.tsapps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.tspackages/local-db/drizzle/0010_add_workspace_deleting_at.sqlpackages/local-db/drizzle/meta/0010_snapshot.jsonpackages/local-db/drizzle/meta/_journal.jsonpackages/local-db/src/schema/schema.ts
🧰 Additional context used
📓 Path-based instructions (5)
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.{ts,tsx}: Use object parameters for functions with 2+ parameters instead of positional arguments
Functions with 2+ parameters should accept a single params object with named properties for self-documentation and extensibility
Use prefixed console logging with context pattern: [domain/operation] message
Extract magic numbers and hardcoded values to named constants at module top
Use lookup objects/maps instead of repeated if (type === ...) conditionals
Avoid usinganytype - maintain type safety in TypeScript code
Never swallow errors silently - at minimum log them with context
Import from concrete files directly when possible - avoid barrel file abuse that creates circular dependencies
Avoid deep nesting (4+ levels) - use early returns, extract functions, and invert conditions
Use named properties in options objects instead of boolean parameters to avoid boolean blindness
Files:
packages/local-db/src/schema/schema.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/query.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/create.tsapps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.tsapps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use Biome for formatting and linting - run at root level with
bun run lint:fixorbiome check --write
Files:
packages/local-db/src/schema/schema.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/query.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/create.tsapps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.tsapps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/create.tsapps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.tsapps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts
apps/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use Drizzle ORM for all database operations - never use raw SQL
Files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/create.tsapps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.tsapps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts
apps/desktop/src/renderer/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Never import Node.js modules (fs, path, os, net) in renderer process or shared code - they are externalized for browser compatibility
Files:
apps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts
🧠 Learnings (6)
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to packages/db/src/**/*.ts : Schema definitions must be in packages/db/src/ using Drizzle ORM
Applied to files:
packages/local-db/src/schema/schema.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/query.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/create.tspackages/local-db/drizzle/meta/0010_snapshot.jsonapps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/**/*.{ts,tsx} : Use Drizzle ORM for all database operations - never use raw SQL
Applied to files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.tsapps/desktop/src/lib/trpc/routers/workspaces/procedures/create.tsapps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/api/**/*.{ts,tsx} : Extract business logic from tRPC procedures into utility functions when logic exceeds ~50 lines, is used by multiple procedures, or needs independent testing
Applied to files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/api/**/*.{ts,tsx} : tRPC procedures and API route handlers should validate and delegate; keep orchestrators thin
Applied to files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/main/index.ts : Load environment variables from monorepo root .env in desktop app with override: true before any imports in src/main/index.ts and electron.vite.config.ts
Applied to files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
📚 Learning: 2026-01-02T06:50:28.671Z
Learnt from: CR
Repo: superset-sh/superset PR: 0
File: AGENTS.md:0-0
Timestamp: 2026-01-02T06:50:28.671Z
Learning: Applies to apps/desktop/src/lib/electron-router-dom.ts : Do not import Node.js modules like node:path or dotenv in electron-router-dom.ts and similar shared files - they run in both main and renderer processes
Applied to files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
🧬 Code graph analysis (5)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.ts (1)
packages/local-db/src/schema/schema.ts (1)
workspaces(80-121)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts (1)
packages/local-db/src/schema/schema.ts (1)
workspaces(80-121)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts (2)
apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts (2)
markWorkspaceAsDeleting(232-238)clearWorkspaceDeletingStatus(241-247)apps/desktop/src/main/lib/workspace-init-manager.ts (1)
workspaceInitManager(302-302)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts (1)
packages/local-db/src/schema/schema.ts (1)
workspaces(80-121)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts (2)
packages/local-db/src/schema/schema.ts (1)
workspaces(80-121)apps/desktop/src/main/lib/local-db/index.ts (1)
localDb(82-82)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Deploy Marketing
- GitHub Check: Deploy API
- GitHub Check: Deploy Admin
- GitHub Check: Deploy Web
- GitHub Check: Deploy Docs
- GitHub Check: Build
🔇 Additional comments (14)
packages/local-db/src/schema/schema.ts (1)
106-108: LGTM! Well-documented soft delete implementation.The
deletingAttimestamp field is correctly defined as an optional integer, with clear documentation explaining that non-null values indicate deletion in progress and should be filtered from queries. This follows standard soft delete patterns.packages/local-db/drizzle/0010_add_workspace_deleting_at.sql (1)
1-1: LGTM! Clean migration.The migration correctly adds a nullable integer column for the soft delete timestamp.
packages/local-db/drizzle/meta/_journal.json (1)
75-81: LGTM! Proper migration tracking.The journal entry correctly tracks the new migration with proper sequencing and metadata.
apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts (2)
2-2: LGTM! Correct Drizzle ORM imports.Added
andandisNulloperators needed for the enhanced filtering logic.
42-47: LGTM! Proper soft delete filtering.The query correctly excludes workspaces with
deletingAtset, ensuring that branches from deleting workspaces are not incorrectly marked as "in use". This prevents blocking operations on branches during workspace deletion.apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.ts (2)
24-31:getAll/getAllGroupeddeletingAt filters look good.
This aligns with the “hide while deleting” model.Also applies to: 89-95
121-143:getActivenow returnsnullinstead of throwing — please verify all callers handle this.
This is a behavior change; if any UI path expects an error (or non-null), it may regress. Consider also clearingsettings.lastActiveWorkspaceIdwhen the referenced workspace is missing/deleting to avoid repeated “null active” lookups.apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts (1)
28-60:canDeleteearly-return whendeletingAtis set is sensible.
Prevents concurrent deletion flows and aligns with the new state machine.apps/desktop/src/lib/trpc/routers/workspaces/procedures/status.ts (1)
14-32: Switching togetWorkspaceNotDeletingis the right guardrail for these mutations.
Error message is also clearer for the new state.Also applies to: 80-102, 104-121
apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts (4)
28-43:getMaxWorkspaceTabOrderexcluding deleting workspaces matches the UX goal.
This prevents gaps/odd tabOrder behavior caused by “in-flight deleted” workspaces.
90-107:hideProjectIfNoWorkspacescounting deleting workspaces is the right call for concurrent deletes.
Prevents projects disappearing while deletions are still in flight.
149-162: New helpers (getWorkspaceNotDeleting,markWorkspaceAsDeleting,clearWorkspaceDeletingStatus) are clean and appropriately scoped.
They centralize the “don’t operate on deleting” rule and keep procedures simpler.Also applies to: 231-247
268-282:getBranchWorkspacenow hides deleting workspaces; ensure callers handle “deletion in progress” explicitly.
In particular, flows that rely on this returning a workspace after an insert conflict should surface a clearer “deleting” error (see comment oncreateBranchWorkspace).apps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts (1)
112-135:onSettledinvalidation + rollback inonErroris solid.
This should keep cache/UI consistent even if the delete fails after the optimistic removal.
🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
There was a problem hiding this comment.
Actionable comments posted: 1
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/lib/trpc/routers/workspaces/procedures/delete.ts (1)
187-238: Terminal state is not rolled back on deletion failure.If worktree removal fails (line 234), the
deletingAtstatus is cleared and the workspace reappears in the UI. However, terminals have already been killed (line 187-189) viakillByWorkspaceId, which permanently removes them from the session map with no restoration capability. This leaves the workspace in a partially broken state with no terminals available.While the PR objectives mention "rollback logic for smooth UX," terminal session state is not preserved or restored on error. Users will need to either manually restart terminals or retry deletion.
Consider deferring terminal termination until after successful worktree removal to ensure atomic behavior, or documenting this gap as acceptable given worktree removal failures should be rare.
🤖 Fix all issues with AI agents
In @apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts:
- Around line 161-162: The retryInit flow can begin initializeWorkspaceWorktree
for a workspace already marked deleting; add a guard in the retryInit procedure
to check workspace.deletingAt and throw an error like "Cannot retry
initialization on a workspace being deleted" before calling
initializeWorkspaceWorktree, or change getWorkspaceWithRelations to use
getWorkspaceNotDeleting so deleting workspaces are filtered out by default;
reference retryInit, initializeWorkspaceWorktree, getWorkspaceWithRelations,
getWorkspaceNotDeleting, and the deletingAt flag when implementing the fix.
📜 Review details
Configuration used: defaults
Review profile: CHILL
Plan: Pro
📒 Files selected for processing (1)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
🧰 Additional context used
📓 Path-based instructions (4)
apps/desktop/**/*.{ts,tsx}
📄 CodeRabbit inference engine (apps/desktop/AGENTS.md)
apps/desktop/**/*.{ts,tsx}: For Electron interprocess communication, ALWAYS use tRPC as defined insrc/lib/trpc
Use alias as defined intsconfig.jsonwhen possible
Prefer zustand for state management if it makes sense. Do not use effect unless absolutely necessary.
For tRPC subscriptions with trpc-electron, ALWAYS use the observable pattern from@trpc/server/observableinstead of async generators, as the library explicitly checksisObservable(result)and throws an error otherwise
Files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
**/*.{ts,tsx}: Use object parameters for functions with 2+ parameters instead of positional arguments
Functions with 2+ parameters should accept a single params object with named properties for self-documentation and extensibility
Use prefixed console logging with context pattern: [domain/operation] message
Extract magic numbers and hardcoded values to named constants at module top
Use lookup objects/maps instead of repeated if (type === ...) conditionals
Avoid usinganytype - maintain type safety in TypeScript code
Never swallow errors silently - at minimum log them with context
Import from concrete files directly when possible - avoid barrel file abuse that creates circular dependencies
Avoid deep nesting (4+ levels) - use early returns, extract functions, and invert conditions
Use named properties in options objects instead of boolean parameters to avoid boolean blindness
Files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
apps/**/*.{ts,tsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use Drizzle ORM for all database operations - never use raw SQL
Files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
**/*.{ts,tsx,js,jsx}
📄 CodeRabbit inference engine (AGENTS.md)
Use Biome for formatting and linting - run at root level with
bun run lint:fixorbiome check --write
Files:
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
🧬 Code graph analysis (1)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts (2)
apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts (3)
markWorkspaceAsDeleting(232-238)clearWorkspaceDeletingStatus(241-247)deleteWorkspace(252-254)apps/desktop/src/main/lib/workspace-init-manager.ts (1)
workspaceInitManager(302-302)
⏰ Context from checks skipped due to timeout of 90000ms. You can increase the timeout in your CodeRabbit configuration to a maximum of 15 minutes (900000ms). (6)
- GitHub Check: Deploy Marketing
- GitHub Check: Deploy Web
- GitHub Check: Deploy Docs
- GitHub Check: Deploy Admin
- GitHub Check: Deploy API
- GitHub Check: Build
🔇 Additional comments (7)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts (7)
50-59: Excellent guard against concurrent deletions.The check for
workspace.deletingAtproperly prevents multiple deletion attempts on the same workspace, providing clear feedback to the user.
77-77: Clear documentation of polling behavior.The comment accurately explains when and why git checks are skipped during polling operations.
161-184: Good immediate UI hiding and init cancellation handling.The pattern of marking the workspace as deleting immediately (line 162) effectively prevents the workspace from reappearing during slow git operations. The error handling for init cancellation is robust, with proper timeout handling and deleting-status cleanup on failure.
209-219: Verify that teardown failures should not block deletion.Teardown errors are logged but the deletion continues (no early return or deleting-status clear). This suggests teardown is "best effort" and failures shouldn't block worktree removal. However, these errors are not surfaced to the user in the response.
Confirm this is the intended behavior - that teardown failures should be logged but not prevent deletion or notify the user. If teardown is critical, consider either:
- Clearing deleting status and returning an error when teardown fails, or
- Including teardown errors in the success response (similar to
terminalWarning)
199-201: Proper locking to prevent concurrent operations.The project lock acquisition effectively prevents race conditions with concurrent initialization operations. The lock release in the finally block (line 241) ensures proper cleanup even on errors.
246-268: Proper cleanup sequence on successful deletion.The cleanup sequence is well-ordered: workspace record deletion (which removes the entire record including
deletingAt), worktree record cleanup, project hiding, active workspace update, and finally clearing the init job. The comment on line 265 correctly notes that clearing happens after cleanup to maintain cancellation signal visibility.
271-296: Close procedure correctly implements non-destructive workspace removal.The
closeprocedure appropriately differs fromdeleteby not using the deleting-status mechanism, since it performs immediate removal without slow git operations. The comment on line 284 helpfully clarifies that the worktree remains on disk.
Summary
When deleting a workspace, it would briefly disappear (optimistic update) then reappear while deletion was in progress, because refetches during slow git operations would show the workspace still in the database.
Fix: Add a
deletingAttimestamp field that is set immediately when deletion starts. All queries now filter out workspaces withdeletingAtset, so even if refetches occur during slow operations, the workspace stays hidden.Also includes:
deletingAtfilters to 5 procedures (reorder, getWorktreesByProject, createBranchWorkspace, openWorktree, getBranches)getWorkspaceNotDeletinghelper for operations that shouldn't work on deleting workspacesTest plan
🤖 Generated with Claude Code
Summary by CodeRabbit
✏️ Tip: You can customize this high-level summary in your review settings.