Skip to content

fix(desktop): prevent workspace from reappearing during deletion - #705

Merged
Kitenite merged 4 commits into
mainfrom
deleting-with-open-threads
Jan 10, 2026
Merged

Kitenite merged 4 commits into
mainfrom
deleting-with-open-threads

Conversation

@Kitenite

@Kitenite Kitenite commented Jan 10, 2026 •

Copy link
Copy Markdown
Member

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 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 includes:

  • Add missing deletingAt filters to 5 procedures (reorder, getWorktreesByProject, createBranchWorkspace, openWorktree, getBranches)
  • Add getWorkspaceNotDeleting helper for operations that shouldn't work on deleting workspaces
  • Optimistic update now selects next workspace when deleting active one (prevents "no workspace" flash)
  • Rollback logic on error for smooth UX

Test plan

  • Delete a workspace and verify it doesn't reappear during deletion
  • Delete the active workspace and verify it switches to another workspace smoothly
  • Verify branches no longer show as "in use" when their workspace is being deleted
  • Verify reopening a worktree works if its workspace is mid-deletion

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Workspaces now have a "deleting" state and are hidden from the UI while removal is in progress.
  • Bug Fixes
    • Creation/open flows and status checks now ignore workspaces being deleted to avoid conflicts.
    • Failed deletions now restore visibility so workspaces don’t remain permanently hidden.
  • Chores
    • Added local database migration and schema support for tracking workspace deleting state.

✏️ Tip: You can customize this high-level summary in your review settings.

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>
@coderabbitai

coderabbitai Bot commented Jan 10, 2026 •

Copy link
Copy Markdown
Contributor

Caution

Review failed

The pull request is closed.

📝 Walkthrough

Walkthrough

Adds a soft-delete flag (deletingAt) to workspaces, updates queries/helpers to exclude workspaces being deleted, updates deletion flows to mark/clear deleting state with improved error handling, and implements optimistic client-side removal with rollback support.

Changes

Cohort / File(s) Summary
Database schema & migrations
packages/local-db/src/schema/schema.ts, packages/local-db/drizzle/0010_add_workspace_deleting_at.sql, packages/local-db/drizzle/meta/0010_snapshot.json, packages/local-db/drizzle/meta/_journal.json
Add deleting_at column / deletingAt field to workspaces; include migration, snapshot, and journal updates.
DB helpers
apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
Add getWorkspaceNotDeleting(), markWorkspaceAsDeleting(), clearWorkspaceDeletingStatus(); apply isNull(workspaces.deletingAt) filters to workspace selection queries.
Workspace procedures (queries & checks)
apps/desktop/src/lib/trpc/routers/workspaces/procedures/*
branch.ts, create.ts, git-status.ts, query.ts, status.ts, init.ts
Update queries to filter out workspaces with deletingAt (use and/isNull); replace getWorkspace with getWorkspaceNotDeleting where appropriate; adjust error messages and control flow when active workspace is missing or being deleted.
Delete flow & safety
apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
On delete, mark workspace as deleting (hide from UI), acquire project lock before teardown, improve cancellation and error handling to clear deleting status on failures, reorder cleanup to preserve cancellation visibility.
Client mutation / optimistic UI
apps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts
Implement optimistic removal from cached lists (getAll, getAllGrouped), compute/select next active workspace, add onSettled/onSuccess hooks, and restore previous cache state in onError rollback.

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
Loading

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

Poem

🐰 I mark a branch with a gentle timestamp—
not gone, just napping while the system winds.
I hide it fast so the UI stays kind,
and if things break, I'll hop and unbind.
Soft-delete keeps all my carrots fine. 🥕✨

🚥 Pre-merge checks | ✅ 3
✅ Passed checks (3 passed)
Check name Status Explanation
Title check ✅ Passed The title clearly and specifically identifies the main fix: preventing a workspace from reappearing during deletion, which aligns with the core problem described in the PR.
Description check ✅ Passed The PR description comprehensively covers the problem, solution, related changes, and test plan, matching all key sections of the template with substantive content.
Docstring Coverage ✅ Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%.

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

✨ Finishing touches
  • 📝 Generate docstrings

📜 Recent review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 7f2af35 and cd36438.

📒 Files selected for processing (1)
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/init.ts

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.

@github-actions

github-actions Bot commented Jan 10, 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

- 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>

@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: 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: createBranchWorkspace can 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() returns undefined (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: openWorktree should not allow opening while a workspace for that worktree is deleting.
With onDelete: "cascade" on workspaces.worktreeId → worktrees.id, the delete flow can remove the worktrees row and cascade-delete any newly opened workspace that reuses that worktreeId. 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 the worktrees row to avoid cascading an unexpectedly reopened workspace.
Even if UI blocks reopen, a server-side check makes this safer (especially given onDelete: "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.onMutate is ignored.
Since options is spread into the mutation config, callers may reasonably expect their onMutate to 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: Filtering workspaces.deletingAt in getWorktreesByProject looks correct; watch the N+1 pattern.
The new and(..., 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: reorder filters out deleting workspaces; consider a transaction to avoid partial updates.
If another flow marks a workspace deleting mid-reorder, you can still update its tabOrder. 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 synthesizing worktree.gitStatus with placeholders; if any UI treats that as authoritative, consider setting it to null instead.

📜 Review details

Configuration used: defaults

Review profile: CHILL

Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 09b1687 and 7332194.

📒 Files selected for processing (12)
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
  • apps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts
  • packages/local-db/drizzle/0010_add_workspace_deleting_at.sql
  • packages/local-db/drizzle/meta/0010_snapshot.json
  • packages/local-db/drizzle/meta/_journal.json
  • packages/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 using any type - 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.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
  • apps/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:fix or biome check --write

Files:

  • packages/local-db/src/schema/schema.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
  • apps/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 in src/lib/trpc
Use alias as defined in tsconfig.json when 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/observable instead of async generators, as the library explicitly checks isObservable(result) and throws an error otherwise

Files:

  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
  • apps/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.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/delete.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/utils/db-helpers.ts
  • apps/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.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/query.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
  • packages/local-db/drizzle/meta/0010_snapshot.json
  • apps/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.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/git-status.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/branch.ts
  • apps/desktop/src/lib/trpc/routers/workspaces/procedures/create.ts
  • apps/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 deletingAt timestamp 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 and and isNull operators needed for the enhanced filtering logic.


42-47: LGTM! Proper soft delete filtering.

The query correctly excludes workspaces with deletingAt set, 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 / getAllGrouped deletingAt filters look good.
This aligns with the “hide while deleting” model.

Also applies to: 89-95


121-143: getActive now returns null instead 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 clearing settings.lastActiveWorkspaceId when 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: canDelete early-return when deletingAt is 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 to getWorkspaceNotDeleting is 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: getMaxWorkspaceTabOrder excluding deleting workspaces matches the UX goal.
This prevents gaps/odd tabOrder behavior caused by “in-flight deleted” workspaces.


90-107: hideProjectIfNoWorkspaces counting 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: getBranchWorkspace now 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 on createBranchWorkspace).

apps/desktop/src/renderer/react-query/workspaces/useDeleteWorkspace.ts (1)

112-135: onSettled invalidation + rollback in onError is 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>

@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: 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 deletingAt status is cleared and the workspace reappears in the UI. However, terminals have already been killed (line 187-189) via killByWorkspaceId, 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

📥 Commits

Reviewing files that changed from the base of the PR and between 7332194 and 7f2af35.

📒 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 in src/lib/trpc
Use alias as defined in tsconfig.json when 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/observable instead of async generators, as the library explicitly checks isObservable(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 using any type - 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:fix or biome 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.deletingAt properly 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:

  1. Clearing deleting status and returning an error when teardown fails, or
  2. 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 close procedure appropriately differs from delete by 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.

@Kitenite
Kitenite merged commit 64987a8 into main Jan 10, 2026
11 of 12 checks passed
@Kitenite
Kitenite deleted the deleting-with-open-threads branch January 10, 2026 23:06

This branch was previously deployed

1 inactive deployment
preview — cd364386 Deployed Jan 10, 2026 by Kitenite via Deploy Web #804
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