Open History to see the last commit
1import {
2 parseScopedThreadKey,
3 scopeProjectRef,
4 scopeThreadRef,
5} from "@v12/client-runtime/environment";
6import { settlePromise, squashAtomCommandFailure } from "@v12/client-runtime/state/runtime";
7import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@v12/contracts";
8import * as Cause from "effect/Cause";
9import * as Schema from "effect/Schema";
10import { AsyncResult } from "effect/unstable/reactivity";
11import { useRouter } from "@tanstack/react-router";
12import { useCallback, useMemo, useRef } from "react";
13
14import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
15import { useComposerDraftStore } from "../composerDraftStore";
16import { terminalEnvironment } from "../state/terminal";
17import { threadEnvironment } from "../state/threads";
18import { vcsEnvironment } from "../state/vcs";
19import { useNewThreadHandler } from "./useHandleNewThread";
20import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
21import { readLocalApi } from "../localApi";
22import { readEnvironmentThreadRefs, readProject, readThreadShell } from "../state/entities";
23import { useTerminalUiStateStore } from "../terminalUiStateStore";
24import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
25import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
26import { stackedThreadToast, toastManager } from "../components/ui/toast";
27import { useClientSettings } from "./useSettings";
28import { useAtomCommand } from "../state/use-atom-command";
29
30export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
31 "ThreadArchiveBlockedError",
32 {
33 environmentId: EnvironmentId,
34 threadId: ThreadId,
35 },
36) {
37 override get message(): string {
38 return "Cannot archive a running thread.";
39 }
40}
41
42export function useThreadActions() {
43 const closeTerminal = useAtomCommand(terminalEnvironment.close);
44 const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
45 reportFailure: false,
46 });
47 const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
48 reportFailure: false,
49 });
50 const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
51 reportFailure: false,
52 });
53 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
54 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
55 reportFailure: false,
56 });
57 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
58 reportFailure: false,
59 });
60 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
61 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
62 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
63 const clearProjectDraftThreadById = useComposerDraftStore(
64 (store) => store.clearProjectDraftThreadById,
65 );
66 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
67 const router = useRouter();
68 const handleNewThread = useNewThreadHandler();
69 // Keep a ref so archiveThread can call handleNewThread without appearing in
70 // its dependency array — handleNewThread is inherently unstable (depends on
71 // the projects list) and would otherwise cascade new references into every
72 // sidebar row via archiveThread → attemptArchiveThread.
73 const handleNewThreadRef = useRef(handleNewThread);
74 handleNewThreadRef.current = handleNewThread;
75
76 const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
77 const thread = readThreadShell(target);
78 if (!thread) {
79 return null;
80 }
81 return {
82 thread,
83 threadRef: target,
84 };
85 }, []);
86 const getCurrentRouteThreadRef = useCallback(() => {
87 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
88 return resolveThreadRouteRef(currentRouteParams);
89 }, [router]);
90
91 const archiveThread = useCallback(
92 async (target: ScopedThreadRef) => {
93 const resolved = resolveThreadTarget(target);
94 if (!resolved) return AsyncResult.success(undefined);
95 const { thread, threadRef } = resolved;
96 if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
97 return AsyncResult.failure(
98 Cause.fail(
99 new ThreadArchiveBlockedError({
100 environmentId: threadRef.environmentId,
101 threadId: threadRef.threadId,
102 }),
103 ),
104 );
105 }
106
107 const currentRouteThreadRef = getCurrentRouteThreadRef();
108 const shouldNavigateToDraft =
109 currentRouteThreadRef?.threadId === threadRef.threadId &&
110 currentRouteThreadRef.environmentId === threadRef.environmentId;
111 const archiveResult = await archiveThreadMutation({
112 environmentId: threadRef.environmentId,
113 input: { threadId: threadRef.threadId },
114 });
115 if (archiveResult._tag === "Failure") {
116 return archiveResult;
117 }
118
119 if (shouldNavigateToDraft) {
120 const navigationResult = await settlePromise(() =>
121 handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)),
122 );
123 if (navigationResult._tag === "Failure") {
124 return navigationResult;
125 }
126 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
127 return archiveResult;
128 }
129
130 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
131 return archiveResult;
132 },
133 [archiveThreadMutation, getCurrentRouteThreadRef, resolveThreadTarget],
134 );
135
136 const unarchiveThread = useCallback(
137 async (target: ScopedThreadRef) => {
138 const result = await unarchiveThreadMutation({
139 environmentId: target.environmentId,
140 input: { threadId: target.threadId },
141 });
142 if (result._tag === "Success") {
143 refreshArchivedThreadsForEnvironment(target.environmentId);
144 }
145 return result;
146 },
147 [unarchiveThreadMutation],
148 );
149
150 const deleteThread = useCallback(
151 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
152 const resolved = resolveThreadTarget(target);
153 if (!resolved) {
154 // Thread not in main store (e.g. archived thread) — dispatch delete directly.
155 const result = await deleteThreadMutation({
156 environmentId: target.environmentId,
157 input: { threadId: target.threadId },
158 });
159 if (result._tag === "Success") {
160 refreshArchivedThreadsForEnvironment(target.environmentId);
161 }
162 return result;
163 }
164 const { thread, threadRef } = resolved;
165 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
166 const shell = readThreadShell(ref);
167 return shell === null ? [] : [shell];
168 });
169 const threadProject = readProject({
170 environmentId: threadRef.environmentId,
171 projectId: thread.projectId,
172 });
173 const deletedIds =
174 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
175 ? new Set<ThreadId>(
176 [...opts.deletedThreadKeys].flatMap((threadKey) => {
177 const ref = parseScopedThreadKey(threadKey);
178 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
179 }),
180 )
181 : undefined;
182 const survivingThreads =
183 deletedIds && deletedIds.size > 0
184 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
185 : threads;
186 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
187 survivingThreads,
188 threadRef.threadId,
189 );
190 const displayWorktreePath = orphanedWorktreePath
191 ? formatWorktreePathForDisplay(orphanedWorktreePath)
192 : null;
193 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
194 const localApi = readLocalApi();
195 let shouldDeleteWorktree = false;
196 if (canDeleteWorktree && localApi) {
197 const confirmationResult = await settlePromise(() =>
198 localApi.dialogs.confirm(
199 [
200 "This thread is the only one linked to this worktree:",
201 displayWorktreePath ?? orphanedWorktreePath,
202 "",
203 "Delete the worktree too?",
204 ].join("\n"),
205 ),
206 );
207 if (confirmationResult._tag === "Failure") {
208 return confirmationResult;
209 }
210 shouldDeleteWorktree = confirmationResult.value;
211 }
212
213 if (thread.session && thread.session.status !== "stopped") {
214 await stopThreadSession({
215 environmentId: threadRef.environmentId,
216 input: { threadId: threadRef.threadId },
217 });
218 }
219
220 await closeTerminal({
221 environmentId: threadRef.environmentId,
222 input: { threadId: threadRef.threadId, deleteHistory: true },
223 });
224
225 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
226 const currentRouteThreadRef = getCurrentRouteThreadRef();
227 const shouldNavigateToFallback =
228 currentRouteThreadRef?.threadId === threadRef.threadId &&
229 currentRouteThreadRef.environmentId === threadRef.environmentId;
230 const fallbackThreadId = getFallbackThreadIdAfterDelete({
231 threads,
232 deletedThreadId: threadRef.threadId,
233 deletedThreadIds,
234 sortOrder: sidebarThreadSortOrder,
235 });
236 const deleteResult = await deleteThreadMutation({
237 environmentId: threadRef.environmentId,
238 input: { threadId: threadRef.threadId },
239 });
240 if (deleteResult._tag === "Failure") {
241 return deleteResult;
242 }
243 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
244 clearComposerDraftForThread(threadRef);
245 clearProjectDraftThreadById(
246 scopeProjectRef(threadRef.environmentId, thread.projectId),
247 threadRef,
248 );
249 clearTerminalUiState(threadRef);
250
251 if (shouldNavigateToFallback) {
252 if (fallbackThreadId) {
253 const fallbackThread = readThreadShell(
254 scopeThreadRef(threadRef.environmentId, fallbackThreadId),
255 );
256 if (fallbackThread) {
257 const navigationResult = await settlePromise(() =>
258 router.navigate({
259 to: "/$environmentId/$threadId",
260 params: buildThreadRouteParams(
261 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
262 ),
263 replace: true,
264 }),
265 );
266 if (navigationResult._tag === "Failure") {
267 return navigationResult;
268 }
269 } else {
270 const navigationResult = await settlePromise(() =>
271 router.navigate({ to: "/", replace: true }),
272 );
273 if (navigationResult._tag === "Failure") {
274 return navigationResult;
275 }
276 }
277 } else {
278 const navigationResult = await settlePromise(() =>
279 router.navigate({ to: "/", replace: true }),
280 );
281 if (navigationResult._tag === "Failure") {
282 return navigationResult;
283 }
284 }
285 }
286
287 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
288 return deleteResult;
289 }
290
291 const removeResult = await removeWorktree({
292 environmentId: threadRef.environmentId,
293 input: {
294 cwd: threadProject.workspaceRoot,
295 path: orphanedWorktreePath,
296 force: true,
297 },
298 });
299 const refreshResult =
300 removeResult._tag === "Success"
301 ? await refreshVcsStatus({
302 environmentId: threadRef.environmentId,
303 input: { cwd: threadProject.workspaceRoot },
304 })
305 : null;
306 const cleanupFailure =
307 removeResult._tag === "Failure"
308 ? removeResult
309 : refreshResult?._tag === "Failure"
310 ? refreshResult
311 : null;
312 if (cleanupFailure) {
313 const error = squashAtomCommandFailure(cleanupFailure);
314 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
315 console.error("Failed to remove orphaned worktree after thread deletion", {
316 threadId: threadRef.threadId,
317 projectCwd: threadProject.workspaceRoot,
318 worktreePath: orphanedWorktreePath,
319 error,
320 });
321 toastManager.add(
322 stackedThreadToast({
323 type: "error",
324 title: "Thread deleted, but worktree removal failed",
325 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
326 }),
327 );
328 return cleanupFailure;
329 }
330 return deleteResult;
331 },
332 [
333 clearComposerDraftForThread,
334 clearProjectDraftThreadById,
335 clearTerminalUiState,
336 closeTerminal,
337 deleteThreadMutation,
338 getCurrentRouteThreadRef,
339 refreshVcsStatus,
340 removeWorktree,
341 router,
342 resolveThreadTarget,
343 sidebarThreadSortOrder,
344 stopThreadSession,
345 ],
346 );
347
348 const confirmAndDeleteThread = useCallback(
349 async (target: ScopedThreadRef) => {
350 const localApi = readLocalApi();
351 const resolved = resolveThreadTarget(target);
352
353 if (confirmThreadDelete && localApi) {
354 const title = resolved?.thread.title ?? "this thread";
355 const confirmationResult = await settlePromise(() =>
356 localApi.dialogs.confirm(
357 [
358 `Delete thread "${title}"?`,
359 "This permanently clears conversation history for this thread.",
360 ].join("\n"),
361 ),
362 );
363 if (confirmationResult._tag === "Failure") {
364 return confirmationResult;
365 }
366 if (!confirmationResult.value) {
367 return AsyncResult.success(undefined);
368 }
369 }
370
371 return deleteThread(target);
372 },
373 [confirmThreadDelete, deleteThread, resolveThreadTarget],
374 );
375
376 return useMemo(
377 () => ({
378 archiveThread,
379 unarchiveThread,
380 deleteThread,
381 confirmAndDeleteThread,
382 }),
383 [archiveThread, confirmAndDeleteThread, deleteThread, unarchiveThread],
384 );
385}