Files
t3code/apps/web/src/hooks/useThreadActions.ts
T
Theo BrowneandClaude Fable 5 535449600a Address PR #4026 review findings, round two
- Worktree-removal offer works after settle: archived threads leave the
  live shell store, so the orphan check re-includes the settled shell and
  click-time revalidation treats absence-from-live as still-settled
- Un-settle is only offered when there is an archive to undo: auto-settled
  rows (inactivity / merged PR, archivedAt null) get Settle instead, on
  web (hover button + context menu) and mobile (swipe + long-press menu)
- Mobile optimistic settled hold rolls back when the settle is blocked or
  fails (settleThread now reports success); web and mobile both drop holds
  on delete and un-settle so ghosts can't linger
- Archived snapshot refreshes after delete too, clearing stale settled
  rows sourced from the snapshot
- v2 mobile list renders queued offline tasks above the cards (they were
  dropped entirely, leaving a blank screen for pending-task-only projects)

On the chat.new/settings finding: not fixed here — the shortcut routes to
the v2 picker only inside chat routes by design; on /settings it falls
back to contextual create, matching v1's behavior on those routes.

Co-Authored-By: Claude Fable 5 <[email protected]>
2026-07-15 22:42:33 -07:00

580 lines
22 KiB
TypeScript

import {
parseScopedThreadKey,
scopeProjectRef,
scopeThreadRef,
} from "@t3tools/client-runtime/environment";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
import * as Cause from "effect/Cause";
import * as Schema from "effect/Schema";
import { AsyncResult } from "effect/unstable/reactivity";
import { useRouter } from "@tanstack/react-router";
import { useCallback, useMemo, useRef } from "react";
import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
import { useComposerDraftStore } from "../composerDraftStore";
import { terminalEnvironment } from "../state/terminal";
import { threadEnvironment } from "../state/threads";
import { vcsEnvironment } from "../state/vcs";
import { useNewThreadHandler } from "./useHandleNewThread";
import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
import { readLocalApi } from "../localApi";
import { readEnvironmentThreadRefs, readProject, readThreadShell } from "../state/entities";
import { useTerminalUiStateStore } from "../terminalUiStateStore";
import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
import {
canOfferWorktreeRemoval,
formatWorktreePathForDisplay,
getOrphanedWorktreePathForThread,
} from "../worktreeCleanup";
import { stackedThreadToast, toastManager } from "../components/ui/toast";
import { useClientSettings } from "./useSettings";
import { useAtomCommand } from "../state/use-atom-command";
export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
"ThreadArchiveBlockedError",
{
environmentId: EnvironmentId,
threadId: ThreadId,
},
) {
override get message(): string {
return "Cannot archive a running thread.";
}
}
export function useThreadActions() {
const closeTerminal = useAtomCommand(terminalEnvironment.close);
const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
reportFailure: false,
});
const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
reportFailure: false,
});
const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
reportFailure: false,
});
// Client-only settled model: settle/unsettle ride the pre-existing archive
// lifecycle so no server upgrade is required. See threadSettled.ts.
const settleThreadMutation = useAtomCommand(threadEnvironment.archive, {
reportFailure: false,
});
const unsettleThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
reportFailure: false,
});
const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
reportFailure: false,
});
const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
reportFailure: false,
});
const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
const clearProjectDraftThreadById = useComposerDraftStore(
(store) => store.clearProjectDraftThreadById,
);
const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
const router = useRouter();
const handleNewThread = useNewThreadHandler();
// Keep a ref so archiveThread can call handleNewThread without appearing in
// its dependency array — handleNewThread is inherently unstable (depends on
// the projects list) and would otherwise cascade new references into every
// sidebar row via archiveThread → attemptArchiveThread.
const handleNewThreadRef = useRef(handleNewThread);
handleNewThreadRef.current = handleNewThread;
const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
const thread = readThreadShell(target);
if (!thread) {
return null;
}
return {
thread,
threadRef: target,
};
}, []);
const getCurrentRouteThreadRef = useCallback(() => {
const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
return resolveThreadRouteRef(currentRouteParams);
}, [router]);
const archiveThread = useCallback(
async (target: ScopedThreadRef) => {
const resolved = resolveThreadTarget(target);
if (!resolved) return AsyncResult.success(undefined);
const { thread, threadRef } = resolved;
if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
return AsyncResult.failure(
Cause.fail(
new ThreadArchiveBlockedError({
environmentId: threadRef.environmentId,
threadId: threadRef.threadId,
}),
),
);
}
const currentRouteThreadRef = getCurrentRouteThreadRef();
const shouldNavigateToDraft =
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId;
const archiveResult = await archiveThreadMutation({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
});
if (archiveResult._tag === "Failure") {
return archiveResult;
}
if (shouldNavigateToDraft) {
const navigationResult = await settlePromise(() =>
handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)),
);
if (navigationResult._tag === "Failure") {
return navigationResult;
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
return archiveResult;
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
return archiveResult;
},
[archiveThreadMutation, getCurrentRouteThreadRef, resolveThreadTarget],
);
const unarchiveThread = useCallback(
async (target: ScopedThreadRef) => {
const result = await unarchiveThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
if (result._tag === "Success") {
refreshArchivedThreadsForEnvironment(target.environmentId);
}
return result;
},
[unarchiveThreadMutation],
);
const deleteThread = useCallback(
async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
const resolved = resolveThreadTarget(target);
if (!resolved) {
// Thread not in main store (e.g. archived thread) — dispatch delete directly.
const result = await deleteThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
if (result._tag === "Success") {
refreshArchivedThreadsForEnvironment(target.environmentId);
}
return result;
}
const { thread, threadRef } = resolved;
const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
const shell = readThreadShell(ref);
return shell === null ? [] : [shell];
});
const threadProject = readProject({
environmentId: threadRef.environmentId,
projectId: thread.projectId,
});
const deletedIds =
opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
? new Set<ThreadId>(
[...opts.deletedThreadKeys].flatMap((threadKey) => {
const ref = parseScopedThreadKey(threadKey);
return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
}),
)
: undefined;
const survivingThreads =
deletedIds && deletedIds.size > 0
? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
: threads;
const orphanedWorktreePath = getOrphanedWorktreePathForThread(
survivingThreads,
threadRef.threadId,
);
const displayWorktreePath = orphanedWorktreePath
? formatWorktreePathForDisplay(orphanedWorktreePath)
: null;
const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
const localApi = readLocalApi();
let shouldDeleteWorktree = false;
if (canDeleteWorktree && localApi) {
const confirmationResult = await settlePromise(() =>
localApi.dialogs.confirm(
[
"This thread is the only one linked to this worktree:",
displayWorktreePath ?? orphanedWorktreePath,
"",
"Delete the worktree too?",
].join("\n"),
),
);
if (confirmationResult._tag === "Failure") {
return confirmationResult;
}
shouldDeleteWorktree = confirmationResult.value;
}
if (thread.session && thread.session.status !== "stopped") {
await stopThreadSession({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
});
}
await closeTerminal({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId, deleteHistory: true },
});
const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
const currentRouteThreadRef = getCurrentRouteThreadRef();
const shouldNavigateToFallback =
currentRouteThreadRef?.threadId === threadRef.threadId &&
currentRouteThreadRef.environmentId === threadRef.environmentId;
const fallbackThreadId = getFallbackThreadIdAfterDelete({
threads,
deletedThreadId: threadRef.threadId,
deletedThreadIds,
sortOrder: sidebarThreadSortOrder,
});
const deleteResult = await deleteThreadMutation({
environmentId: threadRef.environmentId,
input: { threadId: threadRef.threadId },
});
if (deleteResult._tag === "Failure") {
return deleteResult;
}
refreshArchivedThreadsForEnvironment(threadRef.environmentId);
clearComposerDraftForThread(threadRef);
clearProjectDraftThreadById(
scopeProjectRef(threadRef.environmentId, thread.projectId),
threadRef,
);
clearTerminalUiState(threadRef);
if (shouldNavigateToFallback) {
if (fallbackThreadId) {
const fallbackThread = readThreadShell(
scopeThreadRef(threadRef.environmentId, fallbackThreadId),
);
if (fallbackThread) {
const navigationResult = await settlePromise(() =>
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;
}
}
}
if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
return deleteResult;
}
const removeResult = await removeWorktree({
environmentId: threadRef.environmentId,
input: {
cwd: threadProject.workspaceRoot,
path: orphanedWorktreePath,
force: true,
},
});
const refreshResult =
removeResult._tag === "Success"
? await refreshVcsStatus({
environmentId: threadRef.environmentId,
input: { cwd: threadProject.workspaceRoot },
})
: null;
const cleanupFailure =
removeResult._tag === "Failure"
? removeResult
: refreshResult?._tag === "Failure"
? refreshResult
: null;
if (cleanupFailure) {
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", {
threadId: threadRef.threadId,
projectCwd: threadProject.workspaceRoot,
worktreePath: orphanedWorktreePath,
error,
});
toastManager.add(
stackedThreadToast({
type: "error",
title: "Thread deleted, but worktree removal failed",
description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
}),
);
return cleanupFailure;
}
return deleteResult;
},
[
clearComposerDraftForThread,
clearProjectDraftThreadById,
clearTerminalUiState,
closeTerminal,
deleteThreadMutation,
getCurrentRouteThreadRef,
refreshVcsStatus,
removeWorktree,
router,
resolveThreadTarget,
sidebarThreadSortOrder,
stopThreadSession,
],
);
const settleThread = useCallback(
async (target: ScopedThreadRef) => {
const resolved = resolveThreadTarget(target);
// Settle rides archive, so it inherits archive's guard: never
// interrupt a thread mid-turn.
if (
resolved &&
resolved.thread.session?.status === "running" &&
resolved.thread.session.activeTurnId != null
) {
return AsyncResult.failure(
Cause.fail(
new ThreadArchiveBlockedError({
environmentId: resolved.threadRef.environmentId,
threadId: resolved.threadRef.threadId,
}),
),
);
}
const settleResult = await settleThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
if (settleResult._tag === "Failure" || !resolved) {
return settleResult;
}
// Settling is the natural moment to reclaim disk: offer (never force) a
// worktree removal when this thread is the only one using it and there is
// no unsaved or unpushed work at stake.
const { thread, threadRef } = resolved;
if (thread.worktreePath === null) {
return settleResult;
}
// Settle = archive drops the thread from the live shell store, so the
// orphan computation must re-include the shell we just settled — the
// live threads are only the OTHER worktree users.
const liveThreads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
const shell = readThreadShell(ref);
return shell === null ? [] : [shell];
});
const threads = liveThreads.some((candidate) => candidate.id === threadRef.threadId)
? liveThreads
: [...liveThreads, thread];
const orphanedWorktreePath = getOrphanedWorktreePathForThread(threads, threadRef.threadId);
const threadProject = readProject({
environmentId: threadRef.environmentId,
projectId: thread.projectId,
});
if (orphanedWorktreePath === null || threadProject === null) {
return settleResult;
}
const statusResult = await refreshVcsStatus({
environmentId: threadRef.environmentId,
input: { cwd: orphanedWorktreePath },
});
// If status cannot be verified, keep the worktree and skip the prompt.
if (statusResult._tag === "Failure" || !canOfferWorktreeRemoval(statusResult.value)) {
return settleResult;
}
const displayWorktreePath = formatWorktreePathForDisplay(orphanedWorktreePath);
toastManager.add(
stackedThreadToast({
type: "info",
title: "Thread settled",
description: `Worktree ${displayWorktreePath} is no longer used by any thread.`,
actionProps: {
children: "Remove worktree",
onClick: () => {
void (async () => {
// Re-validate at click time: the toast may be stale — the
// thread can have woken up or another thread adopted the
// worktree since the settle happened.
const currentShell = readThreadShell(threadRef);
const currentLiveThreads = readEnvironmentThreadRefs(
threadRef.environmentId,
).flatMap((ref) => {
const shell = readThreadShell(ref);
return shell === null ? [] : [shell];
});
// Archived threads leave the live store entirely, so absence
// IS the settled state; a live shell means it woke back up
// (unarchive puts it back in the stream).
const stillSettled = currentShell === null || currentShell.archivedAt != null;
const currentThreads = currentLiveThreads.some(
(candidate) => candidate.id === threadRef.threadId,
)
? currentLiveThreads
: [...currentLiveThreads, thread];
const stillOrphaned =
getOrphanedWorktreePathForThread(currentThreads, threadRef.threadId) ===
orphanedWorktreePath;
if (!stillOrphaned || !stillSettled) {
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Worktree kept",
description: "This worktree is in use again and was not removed.",
}),
);
return;
}
const currentStatusResult = await refreshVcsStatus({
environmentId: threadRef.environmentId,
input: { cwd: orphanedWorktreePath },
});
if (
currentStatusResult._tag === "Failure" ||
!canOfferWorktreeRemoval(currentStatusResult.value)
) {
toastManager.add(
stackedThreadToast({
type: "warning",
title: "Worktree kept",
description:
"This worktree has uncommitted or unpushed changes, or its status could not be verified.",
}),
);
return;
}
// force stays false as an additional guard against changes
// created between the status check and the removal request.
const removeResult = await removeWorktree({
environmentId: threadRef.environmentId,
input: {
cwd: threadProject.workspaceRoot,
path: orphanedWorktreePath,
force: false,
},
});
if (removeResult._tag === "Failure") {
const error = squashAtomCommandFailure(removeResult);
toastManager.add(
stackedThreadToast({
type: "error",
title: "Worktree removal failed",
description:
error instanceof Error ? error.message : "Could not remove the worktree.",
}),
);
return;
}
await refreshVcsStatus({
environmentId: threadRef.environmentId,
input: { cwd: threadProject.workspaceRoot },
});
})();
},
},
}),
);
return settleResult;
},
[refreshVcsStatus, removeWorktree, resolveThreadTarget, settleThreadMutation],
);
const unsettleThread = useCallback(
async (target: ScopedThreadRef) => {
// Auto-settled rows (inactivity / merged PR) are not archived; sending
// unarchive for them would be rejected by the server. There is nothing
// to undo client-side, so succeed as a no-op.
const resolved = resolveThreadTarget(target);
if (resolved && resolved.thread.archivedAt === null) {
return AsyncResult.success(undefined);
}
return unsettleThreadMutation({
environmentId: target.environmentId,
input: { threadId: target.threadId },
});
},
[resolveThreadTarget, unsettleThreadMutation],
);
const confirmAndDeleteThread = useCallback(
async (target: ScopedThreadRef) => {
const localApi = readLocalApi();
const resolved = resolveThreadTarget(target);
if (confirmThreadDelete && localApi) {
const title = resolved?.thread.title ?? "this thread";
const confirmationResult = await settlePromise(() =>
localApi.dialogs.confirm(
[
`Delete thread "${title}"?`,
"This permanently clears conversation history for this thread.",
].join("\n"),
),
);
if (confirmationResult._tag === "Failure") {
return confirmationResult;
}
if (!confirmationResult.value) {
return AsyncResult.success(undefined);
}
}
return deleteThread(target);
},
[confirmThreadDelete, deleteThread, resolveThreadTarget],
);
return useMemo(
() => ({
archiveThread,
unarchiveThread,
deleteThread,
confirmAndDeleteThread,
settleThread,
unsettleThread,
}),
[
archiveThread,
confirmAndDeleteThread,
deleteThread,
settleThread,
unarchiveThread,
unsettleThread,
],
);
}