Focus a surviving workspace after deleting the active worktree (#5931)

Co-authored-by: brennanb2025 <brennankbenson@gmail.com>
This commit is contained in:
AJ
2026-06-24 16:11:34 -07:00
committed by GitHub
co-authored by brennanb2025
parent e55b0e1d76
commit 3f775c34c1
5 changed files with 328 additions and 1 deletions
@@ -12,6 +12,7 @@ import { getConnectionId } from '@/lib/connection-context'
import { getRuntimeGitStatus } from '@/runtime/runtime-git-client'
import { getSettingsForWorktreeRuntimeOwner } from '@/lib/worktree-runtime-owner'
import { runWorktreeDeletesInParallel } from './delete-worktree-flow'
import { prepareActiveWorktreeFocusAfterDelete } from './active-worktree-focus-after-delete'
import { getWorkspaceDeleteLineage } from './workspace-delete-lineage'
import { DeleteWorktreeLineageNotice } from './DeleteWorktreeLineageNotice'
import { DeleteWorktreeSkipConfirmOption } from './DeleteWorktreeSkipConfirmOption'
@@ -270,6 +271,7 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
// inside the dialog — it runs the destructive retry directly without
// the shared toast wrapper. Close immediately because workspace cards
// already show the deleting state while the retry runs.
const commitFocus = prepareActiveWorktreeFocusAfterDelete(worktreeId)
const deletePromise = removeWorktree(worktreeId, true)
closeModal()
deletePromise
@@ -286,6 +288,7 @@ const DeleteWorktreeDialog = React.memo(function DeleteWorktreeDialog() {
)
return
}
commitFocus()
onDeleted?.([worktreeId])
})
.catch((err: unknown) => {
@@ -0,0 +1,217 @@
import { beforeEach, describe, expect, it, vi } from 'vitest'
type SeedWorktree = { id: string; repoId: string; isMainWorktree: boolean }
const mocks = vi.hoisted(() => {
const state = {
activeView: 'terminal',
activePendingCreationId: null as string | null,
activeWorktreeId: null as string | null,
worktreesByRepo: {} as Record<string, SeedWorktree[]>,
lastVisitedAtByWorktreeId: {} as Record<string, number>,
deleteStateByWorktreeId: {} as Record<string, { isDeleting?: boolean }>,
worktreeMap: new Map<string, SeedWorktree>()
}
return { state }
})
vi.mock('@/store', () => ({
useAppStore: {
getState: () => mocks.state
}
}))
vi.mock('@/store/selectors', () => ({
getWorktreeMapFromState: () => mocks.state.worktreeMap
}))
vi.mock('@/lib/worktree-activation', () => ({
activateAndRevealWorktree: vi.fn()
}))
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
import { prepareActiveWorktreeFocusAfterDelete } from './active-worktree-focus-after-delete'
function seed(worktrees: { id: string; repoId?: string; isMainWorktree?: boolean }[]): void {
const normalized: SeedWorktree[] = worktrees.map((worktree) => ({
id: worktree.id,
repoId: worktree.repoId ?? 'repo-1',
isMainWorktree: worktree.isMainWorktree ?? false
}))
mocks.state.worktreeMap = new Map(normalized.map((worktree) => [worktree.id, worktree]))
const byRepo: Record<string, SeedWorktree[]> = {}
for (const worktree of normalized) {
;(byRepo[worktree.repoId] ??= []).push(worktree)
}
mocks.state.worktreesByRepo = byRepo
}
// Why: mirror the store reducer — once a delete resolves, the removed worktree
// is gone from the worktree map and worktreesByRepo, its lastVisited entry is
// cleared, and activeWorktreeId is nulled only when it was the deleted worktree.
function simulateDelete(worktreeId: string, nulledActive: boolean): void {
mocks.state.worktreeMap.delete(worktreeId)
for (const repoId of Object.keys(mocks.state.worktreesByRepo)) {
mocks.state.worktreesByRepo[repoId] = mocks.state.worktreesByRepo[repoId].filter(
(worktree) => worktree.id !== worktreeId
)
}
delete mocks.state.lastVisitedAtByWorktreeId[worktreeId]
if (nulledActive) {
mocks.state.activeWorktreeId = null
}
}
describe('prepareActiveWorktreeFocusAfterDelete', () => {
beforeEach(() => {
mocks.state.activeView = 'terminal'
mocks.state.activePendingCreationId = null
mocks.state.activeWorktreeId = null
mocks.state.worktreesByRepo = {}
mocks.state.lastVisitedAtByWorktreeId = {}
mocks.state.deleteStateByWorktreeId = {}
mocks.state.worktreeMap = new Map()
vi.mocked(activateAndRevealWorktree).mockClear()
})
it('focuses the most-recently-visited non-base sibling of the same project', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-a' }, { id: 'wt-b' }, { id: 'wt-del' }])
mocks.state.activeWorktreeId = 'wt-del'
mocks.state.lastVisitedAtByWorktreeId = { 'wt-a': 100, 'wt-b': 200 }
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
commit()
expect(activateAndRevealWorktree).toHaveBeenCalledWith('wt-b')
})
it('falls back to the base/primary worktree when no other workspace remains', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-del' }])
mocks.state.activeWorktreeId = 'wt-del'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
commit()
expect(activateAndRevealWorktree).toHaveBeenCalledWith('main')
})
it('stays within the deleted worktree project instead of jumping to another project', () => {
seed([
{ id: 'main-1', repoId: 'repo-1', isMainWorktree: true },
{ id: 'wt-del', repoId: 'repo-1' },
{ id: 'wt-other', repoId: 'repo-2' },
{ id: 'main-2', repoId: 'repo-2', isMainWorktree: true }
])
mocks.state.activeWorktreeId = 'wt-del'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
commit()
expect(activateAndRevealWorktree).toHaveBeenCalledWith('main-1')
})
it('does not steal focus when the deleted worktree was not the active one', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-active' }, { id: 'wt-del' }])
mocks.state.activeWorktreeId = 'wt-active'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', false)
commit()
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
})
it('does not reclaim focus when the user navigated away during the delete', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-a' }, { id: 'wt-del' }])
mocks.state.activeWorktreeId = 'wt-del'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', false)
// Why: a concurrent activation moved focus before the delete settled.
mocks.state.activeWorktreeId = 'wt-a'
commit()
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
})
it('does not steal focus when the delete starts from a non-terminal view', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-del' }])
// Why: top-level views can retain the last terminal worktree id without
// meaning the user is currently looking at that workspace.
mocks.state.activeView = 'space'
mocks.state.activeWorktreeId = 'wt-del'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
commit()
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
})
it('does not reclaim focus when the user leaves terminal view during the delete', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-del' }])
mocks.state.activeWorktreeId = 'wt-del'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
mocks.state.activeView = 'settings'
commit()
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
})
it('does not steal focus when a pending creation panel is active before delete', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-del' }])
// Why: pending creation keeps the prior worktree id while the creation
// surface owns the content area, so it is not viewing the old workspace.
mocks.state.activePendingCreationId = 'creation-1'
mocks.state.activeWorktreeId = 'wt-del'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
commit()
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
})
it('does not reclaim focus when pending creation opens during the delete', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-del' }])
mocks.state.activeWorktreeId = 'wt-del'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
mocks.state.activePendingCreationId = 'creation-1'
commit()
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
})
it('skips workspaces that are themselves mid-delete when picking a successor', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-a' }, { id: 'wt-del' }])
mocks.state.activeWorktreeId = 'wt-del'
mocks.state.lastVisitedAtByWorktreeId = { 'wt-a': 50 }
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', true)
mocks.state.deleteStateByWorktreeId = { 'wt-a': { isDeleting: true } }
commit()
expect(activateAndRevealWorktree).toHaveBeenCalledWith('main')
})
it('does not steal focus when a non-worktree workspace is active', () => {
seed([{ id: 'main', isMainWorktree: true }, { id: 'wt-del' }])
// Why: folder workspaces hold a non-worktree key in activeWorktreeId, so a
// background worktree delete must never move the user off it.
mocks.state.activeWorktreeId = 'folder:abc'
const commit = prepareActiveWorktreeFocusAfterDelete('wt-del')
simulateDelete('wt-del', false)
commit()
expect(activateAndRevealWorktree).not.toHaveBeenCalled()
})
})
@@ -0,0 +1,73 @@
import { useAppStore } from '@/store'
import { getWorktreeMapFromState } from '@/store/selectors'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
type AppStoreState = ReturnType<typeof useAppStore.getState>
// Why: after deleting the workspace the user is currently viewing, leaving the
// active workspace empty loses their place. Pick the next workspace to focus
// so a delete behaves like closing a tab — prefer another non-base/primary
// workspace of the same project (most-recently-visited first), and fall back to
// the project's base/primary workspace when no other workspace remains.
function pickNextWorktreeIdAfterDelete(
state: AppStoreState,
repoId: string,
deletedWorktreeId: string
): string | null {
const deleteState = state.deleteStateByWorktreeId
const siblings = (state.worktreesByRepo[repoId] ?? []).filter(
(worktree) => worktree.id !== deletedWorktreeId && !deleteState[worktree.id]?.isDeleting
)
const others = siblings.filter((worktree) => !worktree.isMainWorktree)
if (others.length > 0) {
const lastVisited = state.lastVisitedAtByWorktreeId
const [mostRecent] = [...others].sort(
(a, b) => (lastVisited[b.id] ?? 0) - (lastVisited[a.id] ?? 0)
)
return mostRecent.id
}
return siblings.find((worktree) => worktree.isMainWorktree)?.id ?? null
}
function focusNextWorktreeAfterActiveDelete(
deletedWorktreeId: string,
repoId: string | null,
wasViewingBeforeDelete: boolean
): void {
if (!wasViewingBeforeDelete || !repoId) {
return
}
const state = useAppStore.getState()
// Why: a concurrent activation may have already moved focus during the delete.
// Only hand off when deletion left the terminal workspace selection empty.
if (
state.activeView !== 'terminal' ||
state.activePendingCreationId !== null ||
state.activeWorktreeId !== null
) {
return
}
const nextWorktreeId = pickNextWorktreeIdAfterDelete(state, repoId, deletedWorktreeId)
if (nextWorktreeId) {
activateAndRevealWorktree(nextWorktreeId)
}
}
/**
* Capture, before a delete runs, whether the target is the workspace the user is
* currently viewing. Returns a committer to call after a successful delete: it
* focuses the next-best workspace only when the deleted one was active, so
* deleting a background workspace never steals the user's current focus.
*
* Captured up front because the worktree record (and its repoId) is gone from the
* store once the delete resolves.
*/
export function prepareActiveWorktreeFocusAfterDelete(worktreeId: string): () => void {
const state = useAppStore.getState()
const wasViewing =
state.activeView === 'terminal' &&
state.activePendingCreationId === null &&
state.activeWorktreeId === worktreeId
const repoId = getWorktreeMapFromState(state).get(worktreeId)?.repoId ?? null
return () => focusNextWorktreeAfterActiveDelete(worktreeId, repoId, wasViewing)
}
@@ -2,6 +2,7 @@ import { toast } from 'sonner'
import { useAppStore } from '@/store'
import { getWorktreeMapFromState } from '@/store/selectors'
import { activateAndRevealWorktree } from '@/lib/worktree-activation'
import { prepareActiveWorktreeFocusAfterDelete } from './active-worktree-focus-after-delete'
import { getDeleteWorktreeToastCopy } from './delete-worktree-toast'
import { getWorkspaceDeleteLineage } from './workspace-delete-lineage'
import {
@@ -19,6 +20,9 @@ type WorktreeBatchDeleteOptions = {
type WorktreeDeleteWithToastOptions = {
force?: boolean
onForceDeleted?: (worktreeId: string) => void
// Why: batch deletes suppress the per-delete focus handoff and instead focus a
// single survivor after the whole batch settles (see runWorktreeDeletesInParallel).
focusSuccessorOnDelete?: boolean
}
// Why: a failed delete almost always means the worktree still has changes
@@ -44,6 +48,12 @@ export async function runWorktreeDeletesInParallel(
targets: readonly Pick<Worktree, 'id' | 'displayName' | 'repoId' | 'path'>[],
options: WorktreeDeleteWithToastOptions = {}
): Promise<string[]> {
// Why: capture the viewed workspace before any delete runs so we can focus a
// single survivor once the batch settles, rather than per delete.
const activeWorktreeIdBefore = useAppStore.getState().activeWorktreeId
const commitBatchFocus = activeWorktreeIdBefore
? prepareActiveWorktreeFocusAfterDelete(activeWorktreeIdBefore)
: null
// Why: deletes are serialized per repo to avoid git lock races, but every
// selected/lineage workspace should show in-flight feedback immediately.
useAppStore.getState().markWorktreesDeleting(targets.map((target) => target.id))
@@ -76,7 +86,10 @@ export async function runWorktreeDeletesInParallel(
useAppStore.getState().clearWorktreeDeleteState(target.id)
continue
}
const deleted = await runWorktreeDeleteWithToast(target.id, target.displayName, options)
const deleted = await runWorktreeDeleteWithToast(target.id, target.displayName, {
...options,
focusSuccessorOnDelete: false
})
if (deleted) {
deletedInGroup.push(target.id)
} else {
@@ -89,6 +102,12 @@ export async function runWorktreeDeletesInParallel(
})
)
const deletedSet = new Set(groupResults.flat())
// Why: focus a survivor once, after the batch settles, rather than per delete —
// an intermediate focus could land on (and spawn a terminal in) a workspace this
// same batch is about to delete.
if (activeWorktreeIdBefore && deletedSet.has(activeWorktreeIdBefore)) {
commitBatchFocus?.()
}
return targets.filter((target) => deletedSet.has(target.id)).map((target) => target.id)
}
@@ -111,10 +130,17 @@ export function runWorktreeDeleteWithToast(
options: WorktreeDeleteWithToastOptions = {}
): Promise<boolean> {
const removeWorktree = useAppStore.getState().removeWorktree
const commitFocus = prepareActiveWorktreeFocusAfterDelete(worktreeId)
const focusSuccessor = options.focusSuccessorOnDelete !== false
return removeWorktree(worktreeId, options.force === true)
.then((result) => {
if (result.ok) {
// Why: keep the user on a live workspace instead of the Landing screen
// when they delete the one they were viewing.
if (focusSuccessor) {
commitFocus()
}
return true
}
const state = useAppStore.getState().deleteStateByWorktreeId[worktreeId]
@@ -135,6 +161,10 @@ export function runWorktreeDeleteWithToast(
'Force Delete'
),
onClick: () => {
// Why: recapture at click time — the user may have navigated away
// while the failed-delete toast was open, so focus only hands off
// when this is still the workspace they are viewing.
const commitForceFocus = prepareActiveWorktreeFocusAfterDelete(worktreeId)
useAppStore
.getState()
.removeWorktree(worktreeId, true)
@@ -158,6 +188,7 @@ export function runWorktreeDeleteWithToast(
)
return
}
commitForceFocus()
options.onForceDeleted?.(worktreeId)
})
.catch((err: unknown) => {
@@ -43,6 +43,7 @@ import { getHostedReviewCacheKey } from '../../store/slices/hosted-review'
import { issueCacheKey as getIssueCacheKey } from '../../store/slices/github'
import { refreshGitStatusForWorktree } from '../right-sidebar/git-status-refresh'
import { runWorktreeBatchDelete } from '../sidebar/delete-worktree-flow'
import { prepareActiveWorktreeFocusAfterDelete } from '../sidebar/active-worktree-focus-after-delete'
import { branchDisplayName } from '../sidebar/WorktreeCardHelpers'
import { Badge } from '../ui/badge'
import { Button } from '../ui/button'
@@ -1592,6 +1593,7 @@ export function WorkspaceSpaceManagerPanel(): React.JSX.Element {
(worktree: WorkspaceSpaceWorktree): void => {
// Why: Space keeps normal deletes non-force so uncommitted work is not
// discarded silently; a failed row gets this explicit recovery path.
const commitFocus = prepareActiveWorktreeFocusAfterDelete(worktree.worktreeId)
void removeWorktree(worktree.worktreeId, true)
.then((result) => {
if (!result.ok) {
@@ -1606,6 +1608,7 @@ export function WorkspaceSpaceManagerPanel(): React.JSX.Element {
)
return
}
commitFocus()
handleDeletedWorktrees([worktree.worktreeId])
})
.catch((error: unknown) => {