fix(web): keep bulk thread deletion going after failures (#4615)

Co-authored-by: Claude Opus 5 (1M context) <[email protected]>
Co-authored-by: Yash Singh <[email protected]>
This commit is contained in:
authored and GitHub committed 2026-09-05 06:20:48 -05:00
1 parent 39802c0611
commit bd7f7ea093
6 files changed
+191 -66

No files matched your search

+27 -15
View File
@@ -171,7 +171,10 @@ import {
SidebarMenuSubItem,
useSidebar,
} from "./ui/sidebar";
import { useThreadSelectionStore } from "../threadSelectionStore";
import {
getThreadKeysToDeselectAfterDelete,
useThreadSelectionStore,
} from "../threadSelectionStore";
import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
import {
archiveSelectedThreadEntries,
@@ -1910,26 +1913,35 @@ const SidebarProjectItem = memo(function SidebarProjectItem(props: SidebarProjec
if (!confirmed) return;
}
const deletedThreadKeys = new Set(threadKeys);
for (const { threadRef } of selectedThreadEntries) {
// Only discount batch members after their deletions succeed.
const deletedThreadKeys = new Set<string>();
let firstError: unknown = null;
for (const { threadKey, threadRef } of selectedThreadEntries) {
const result = await deleteThread(threadRef, {
deletedThreadKeys,
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete threads",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
if (isAtomCommandInterrupted(result)) break;
firstError ??= squashAtomCommandFailure(result);
continue;
}
deletedThreadKeys.add(threadKey);
}
removeFromSelection(threadKeys);
if (firstError !== null) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete threads",
description: firstError instanceof Error ? firstError.message : "An error occurred.",
}),
);
}
removeFromSelection(
getThreadKeysToDeselectAfterDelete(threadKeys, deletedThreadKeys, (threadKey) => {
const threadRef = parseScopedThreadKey(threadKey);
return threadRef !== null && readThreadShell(threadRef) !== null;
}),
);
},
[
appSettingsConfirmThreadArchive,
+28 -15
View File
@@ -25,6 +25,7 @@ import {
import { resolveSettledThreadTimestamp } from "@t3tools/client-runtime/state/thread-sort";
import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/models";
import {
parseScopedThreadKey,
scopeProjectRef,
scopeThreadRef,
scopedThreadKey,
@@ -101,7 +102,10 @@ import {
type SidebarProjectSnapshot,
} from "../sidebarProjectGrouping";
import { legacyProjectCwdPreferenceKey, useUiStateStore } from "../uiStateStore";
import { useThreadSelectionStore } from "../threadSelectionStore";
import {
getThreadKeysToDeselectAfterDelete,
useThreadSelectionStore,
} from "../threadSelectionStore";
import { useThreadActions } from "../hooks/useThreadActions";
import { useHandleNewThread } from "../hooks/useHandleNewThread";
import { isCommandPaletteOpen, openCommandPalette } from "../commandPaletteBus";
@@ -112,6 +116,7 @@ import { useLocalStorage } from "../hooks/useLocalStorage";
import { useNowMinute } from "../hooks/useNowMinute";
import { useEnvironments, usePrimaryEnvironmentId } from "../state/environments";
import {
readThreadShell,
useAllEnvironmentProjectSnapshotsReady,
useProjects,
useThreadShells,
@@ -3021,8 +3026,9 @@ export default function Sidebar() {
// right now. Selections can outlive their rows (settled-tail paging,
// thread deletion elsewhere) and the menu labels must count only what
// the actions will touch.
const threadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys].filter(
(threadKey) => threadByKeyRef.current.has(threadKey),
const selectedThreadKeys = [...useThreadSelectionStore.getState().selectedThreadKeys];
const threadKeys = selectedThreadKeys.filter((threadKey) =>
threadByKeyRef.current.has(threadKey),
);
if (threadKeys.length === 0) return;
const count = threadKeys.length;
@@ -3218,6 +3224,7 @@ export default function Sidebar() {
// really gone, or the first delete would treat still-alive batch mates
// as deleted and remove a worktree they still point at.
const deletedThreadKeys = new Set<string>();
let firstError: unknown = null;
for (const threadKey of threadKeys) {
const thread = threadByKeyRef.current.get(threadKey);
if (!thread) continue;
@@ -3225,21 +3232,27 @@ export default function Sidebar() {
deletedThreadKeys,
});
if (result._tag === "Failure") {
if (!isAtomCommandInterrupted(result)) {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete threads",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
return;
if (isAtomCommandInterrupted(result)) break;
firstError ??= squashAtomCommandFailure(result);
continue;
}
deletedThreadKeys.add(threadKey);
}
removeFromSelection(threadKeys);
if (firstError !== null) {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Failed to delete threads",
description: firstError instanceof Error ? firstError.message : "An error occurred.",
}),
);
}
removeFromSelection(
getThreadKeysToDeselectAfterDelete(selectedThreadKeys, deletedThreadKeys, (threadKey) => {
const threadRef = parseScopedThreadKey(threadKey);
return threadRef !== null && readThreadShell(threadRef) !== null;
}),
);
},
[
attemptSettle,
+35 -2
View File
@@ -1,7 +1,40 @@
import { EnvironmentId, ThreadId } from "@t3tools/contracts";
import { describe, expect, it } from "vite-plus/test";
import { afterEach, describe, expect, it, vi } from "vite-plus/test";
import { requestThreadUnpinConfirmation, ThreadArchiveBlockedError } from "./useThreadActions";
import {
navigateAfterThreadDeletion,
requestThreadUnpinConfirmation,
ThreadArchiveBlockedError,
} from "./useThreadActions";
import { toastManager } from "../components/ui/toast";
describe("navigateAfterThreadDeletion", () => {
afterEach(() => vi.restoreAllMocks());
it("reports a rejected navigation without failing the completed deletion", async () => {
const addToast = vi.spyOn(toastManager, "add").mockReturnValue("navigation-error");
await expect(
navigateAfterThreadDeletion(() => Promise.reject(new Error("route unavailable"))),
).resolves.toBeUndefined();
expect(addToast).toHaveBeenCalledOnce();
expect(addToast).toHaveBeenCalledWith(
expect.objectContaining({
title: "Thread deleted, but navigation failed",
description: "route unavailable",
}),
);
});
it("does not report an error after successful navigation", async () => {
const addToast = vi.spyOn(toastManager, "add");
await navigateAfterThreadDeletion(() => Promise.resolve());
expect(addToast).not.toHaveBeenCalled();
});
});
describe("ThreadArchiveBlockedError", () => {
it("keeps the blocked thread context with the fixed message", () => {
+35 -33
View File
@@ -144,6 +144,21 @@ export async function requestThreadUnpinConfirmation(input: {
);
}
/** Report navigation separately so a completed deletion can still finish worktree cleanup. */
export async function navigateAfterThreadDeletion(navigate: () => Promise<void>) {
const result = await settlePromise(navigate);
if (result._tag === "Failure") {
const error = squashAtomCommandFailure(result);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Thread deleted, but navigation failed",
description: error instanceof Error ? error.message : "An error occurred.",
}),
);
}
}
export function useThreadActions() {
const closeTerminal = useAtomCommand(terminalEnvironment.close);
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
@@ -383,39 +398,20 @@ export function useThreadActions() {
clearTerminalUiState(threadRef);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
const fallbackThread = readThreadShell(
scopeThreadRef(threadRef.environmentId, fallbackThreadId),
);
if (fallbackThread) {
const navigationResult = await settlePromise(() =>
router.navigate({
const fallbackThread = fallbackThreadId
? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId))
: null;
await navigateAfterThreadDeletion(() =>
fallbackThread
? router.navigate({
to: "/$environmentId/$threadId",
params: buildThreadRouteParams(
scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
),
replace: true,
}),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
} else {
const navigationResult = await settlePromise(() =>
router.navigate({ to: "/", replace: true }),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
}
} else {
const navigationResult = await settlePromise(() =>
router.navigate({ to: "/", replace: true }),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
}
})
: router.navigate({ to: "/", replace: true }),
);
}
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
@@ -444,9 +440,10 @@ export function useThreadActions() {
? refreshResult
: null;
if (cleanupFailure) {
const removalFailed = removeResult._tag === "Failure";
const error = squashAtomCommandFailure(cleanupFailure);
const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
console.error("Failed to remove orphaned worktree after thread deletion", {
const message = error instanceof Error ? error.message : "An error occurred.";
console.error("Worktree cleanup failed after thread deletion", {
threadId: threadRef.threadId,
projectCwd: threadProject.workspaceRoot,
worktreePath: orphanedWorktreePath,
@@ -455,11 +452,16 @@ export function useThreadActions() {
toastManager.add(
stackedThreadToast({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
title: removalFailed
? "Failed to delete worktree"
: "Worktree deleted, but Git status refresh failed",
description: removalFailed
? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`
: message,
}),
);
return cleanupFailure;
// The thread was deleted. Cleanup has its own toast; returning its
// failure would make callers incorrectly report a thread deletion error.
}
return deleteResult;
},
+57 -1
View File
@@ -1,7 +1,10 @@
import { ThreadId } from "@t3tools/contracts";
import { beforeEach, describe, expect, it } from "vite-plus/test";
import { useThreadSelectionStore } from "./threadSelectionStore";
import {
getThreadKeysToDeselectAfterDelete,
useThreadSelectionStore,
} from "./threadSelectionStore";
const THREAD_A = ThreadId.make("thread-a");
const THREAD_B = ThreadId.make("thread-b");
@@ -16,6 +19,59 @@ describe("threadSelectionStore", () => {
useThreadSelectionStore.getState().clearSelection();
});
describe("bulk deletion cleanup", () => {
it("clears missing selection rows and completed deletions while retaining a failed thread", () => {
const store = useThreadSelectionStore.getState();
store.toggleThread(THREAD_A);
store.toggleThread(THREAD_B);
store.toggleThread(THREAD_C);
const selected = [...useThreadSelectionStore.getState().selectedThreadKeys];
// A deleted successfully but its shell has not refreshed; B failed;
// C was deleted elsewhere and never entered this client's delete loop.
const existingThreads = new Set([THREAD_A, THREAD_B]);
store.removeFromSelection(
getThreadKeysToDeselectAfterDelete(selected, new Set([THREAD_A]), (key) =>
existingThreads.has(ThreadId.make(key)),
),
);
expect([...useThreadSelectionStore.getState().selectedThreadKeys]).toEqual([THREAD_B]);
expect(useThreadSelectionStore.getState().anchorThreadKey).toBeNull();
});
it("exits selection mode when the last selected thread disappeared elsewhere", () => {
const store = useThreadSelectionStore.getState();
store.toggleThread(THREAD_A);
store.removeFromSelection(
getThreadKeysToDeselectAfterDelete([THREAD_A], new Set(), () => false),
);
expect(useThreadSelectionStore.getState().hasSelection()).toBe(false);
expect(useThreadSelectionStore.getState().anchorThreadKey).toBeNull();
});
it("keeps unprocessed and hidden live threads and selections added while deletion was pending", () => {
const store = useThreadSelectionStore.getState();
store.toggleThread(THREAD_A);
store.toggleThread(THREAD_B);
store.toggleThread(THREAD_C);
const selected = [...useThreadSelectionStore.getState().selectedThreadKeys];
store.toggleThread(THREAD_D);
// Only A completed before interruption. B is unprocessed; C still
// has a shell even though its row is outside the rendered page.
store.removeFromSelection(
getThreadKeysToDeselectAfterDelete(selected, new Set([THREAD_A]), () => true),
);
expect([...useThreadSelectionStore.getState().selectedThreadKeys]).toEqual([
THREAD_B,
THREAD_C,
THREAD_D,
]);
expect(useThreadSelectionStore.getState().anchorThreadKey).toBe(THREAD_D);
});
});
describe("toggleThread", () => {
it("adds a thread to empty selection", () => {
useThreadSelectionStore.getState().toggleThread(THREAD_A);
+9
View File
@@ -34,6 +34,15 @@ interface ThreadSelectionStore extends ThreadSelectionState {
const EMPTY_SET = new Set<string>();
/** Clear completed deletions and missing threads, retaining failed or unprocessed threads. */
export function getThreadKeysToDeselectAfterDelete(
selectedThreadKeys: readonly string[],
deletedThreadKeys: ReadonlySet<string>,
hasThread: (threadKey: string) => boolean,
): string[] {
return selectedThreadKeys.filter((key) => deletedThreadKeys.has(key) || !hasThread(key));
}
export const useThreadSelectionStore = create<ThreadSelectionStore>((set, get) => ({
selectedThreadKeys: EMPTY_SET,
anchorThreadKey: null,