Open History to see the last commit
1import { parseScopedThreadKey, scopeProjectRef, scopeThreadRef } from "@t3tools/client-runtime";
2import { type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
3import { useQueryClient } from "@tanstack/react-query";
4import { useRouter } from "@tanstack/react-router";
5import { useCallback, useRef } from "react";
6
7import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
8import { useComposerDraftStore } from "../composerDraftStore";
9import { useNewThreadHandler } from "./useHandleNewThread";
10import { ensureEnvironmentApi, readEnvironmentApi } from "../environmentApi";
11import { invalidateGitQueries } from "../lib/gitReactQuery";
12import { newCommandId } from "../lib/utils";
13import { readLocalApi } from "../localApi";
14import {
15 selectProjectByRef,
16 selectThreadByRef,
17 selectThreadsForEnvironment,
18 useStore,
19} from "../store";
20import { useTerminalStateStore } from "../terminalStateStore";
21import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
22import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
23import { stackedThreadToast, toastManager } from "../components/ui/toast";
24import { useSettings } from "./useSettings";
25
26export function useThreadActions() {
27 const sidebarThreadSortOrder = useSettings((settings) => settings.sidebarThreadSortOrder);
28 const confirmThreadDelete = useSettings((settings) => settings.confirmThreadDelete);
29 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
30 const clearProjectDraftThreadById = useComposerDraftStore(
31 (store) => store.clearProjectDraftThreadById,
32 );
33 const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
34 const router = useRouter();
35 const { handleNewThread } = useNewThreadHandler();
36 // Keep a ref so archiveThread can call handleNewThread without appearing in
37 // its dependency array — handleNewThread is inherently unstable (depends on
38 // the projects list) and would otherwise cascade new references into every
39 // sidebar row via archiveThread → attemptArchiveThread.
40 const handleNewThreadRef = useRef(handleNewThread);
41 handleNewThreadRef.current = handleNewThread;
42 const queryClient = useQueryClient();
43
44 const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
45 const state = useStore.getState();
46 const thread = selectThreadByRef(state, target);
47 if (!thread) {
48 return null;
49 }
50 return {
51 thread,
52 threadRef: target,
53 };
54 }, []);
55 const getCurrentRouteThreadRef = useCallback(() => {
56 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
57 return resolveThreadRouteRef(currentRouteParams);
58 }, [router]);
59
60 const archiveThread = useCallback(
61 async (target: ScopedThreadRef) => {
62 const api = readEnvironmentApi(target.environmentId);
63 if (!api) return;
64 const resolved = resolveThreadTarget(target);
65 if (!resolved) return;
66 const { thread, threadRef } = resolved;
67 if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
68 throw new Error("Cannot archive a running thread.");
69 }
70
71 await api.orchestration.dispatchCommand({
72 type: "thread.archive",
73 commandId: newCommandId(),
74 threadId: threadRef.threadId,
75 });
76 const currentRouteThreadRef = getCurrentRouteThreadRef();
77
78 if (
79 currentRouteThreadRef?.threadId === threadRef.threadId &&
80 currentRouteThreadRef.environmentId === threadRef.environmentId
81 ) {
82 await handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId));
83 }
84 },
85 [getCurrentRouteThreadRef, resolveThreadTarget],
86 );
87
88 const unarchiveThread = useCallback(async (target: ScopedThreadRef) => {
89 const api = readEnvironmentApi(target.environmentId);
90 if (!api) return;
91 await api.orchestration.dispatchCommand({
92 type: "thread.unarchive",
93 commandId: newCommandId(),
94 threadId: target.threadId,
95 });
96 }, []);
97
98 const deleteThread = useCallback(
99 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
100 const api = readEnvironmentApi(target.environmentId);
101 if (!api) return;
102 const resolved = resolveThreadTarget(target);
103 if (!resolved) return;
104 const { thread, threadRef } = resolved;
105 const state = useStore.getState();
106 const threads = selectThreadsForEnvironment(state, threadRef.environmentId);
107 const threadProject = selectProjectByRef(state, {
108 environmentId: threadRef.environmentId,
109 projectId: thread.projectId,
110 });
111 const deletedIds =
112 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
113 ? new Set<ThreadId>(
114 [...opts.deletedThreadKeys].flatMap((threadKey) => {
115 const ref = parseScopedThreadKey(threadKey);
116 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
117 }),
118 )
119 : undefined;
120 const survivingThreads =
121 deletedIds && deletedIds.size > 0
122 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
123 : threads;
124 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
125 survivingThreads,
126 threadRef.threadId,
127 );
128 const displayWorktreePath = orphanedWorktreePath
129 ? formatWorktreePathForDisplay(orphanedWorktreePath)
130 : null;
131 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
132 const localApi = readLocalApi();
133 const shouldDeleteWorktree =
134 canDeleteWorktree &&
135 localApi &&
136 (await localApi.dialogs.confirm(
137 [
138 "This thread is the only one linked to this worktree:",
139 displayWorktreePath ?? orphanedWorktreePath,
140 "",
141 "Delete the worktree too?",
142 ].join("\n"),
143 ));
144
145 if (thread.session && thread.session.status !== "closed") {
146 await api.orchestration
147 .dispatchCommand({
148 type: "thread.session.stop",
149 commandId: newCommandId(),
150 threadId: threadRef.threadId,
151 createdAt: new Date().toISOString(),
152 })
153 .catch(() => undefined);
154 }
155
156 try {
157 await api.terminal.close({ threadId: threadRef.threadId, deleteHistory: true });
158 } catch {
159 // Terminal may already be closed.
160 }
161
162 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
163 const currentRouteThreadRef = getCurrentRouteThreadRef();
164 const shouldNavigateToFallback =
165 currentRouteThreadRef?.threadId === threadRef.threadId &&
166 currentRouteThreadRef.environmentId === threadRef.environmentId;
167 const fallbackThreadId = getFallbackThreadIdAfterDelete({
168 threads,
169 deletedThreadId: threadRef.threadId,
170 deletedThreadIds,
171 sortOrder: sidebarThreadSortOrder,
172 });
173 await api.orchestration.dispatchCommand({
174 type: "thread.delete",
175 commandId: newCommandId(),
176 threadId: threadRef.threadId,
177 });
178 clearComposerDraftForThread(threadRef);
179 clearProjectDraftThreadById(
180 scopeProjectRef(threadRef.environmentId, thread.projectId),
181 threadRef,
182 );
183 clearTerminalState(threadRef);
184
185 if (shouldNavigateToFallback) {
186 if (fallbackThreadId) {
187 const fallbackThread = selectThreadByRef(
188 useStore.getState(),
189 scopeThreadRef(threadRef.environmentId, fallbackThreadId),
190 );
191 if (fallbackThread) {
192 await router.navigate({
193 to: "/$environmentId/$threadId",
194 params: buildThreadRouteParams(
195 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
196 ),
197 replace: true,
198 });
199 } else {
200 await router.navigate({ to: "/", replace: true });
201 }
202 } else {
203 await router.navigate({ to: "/", replace: true });
204 }
205 }
206
207 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
208 return;
209 }
210
211 try {
212 await ensureEnvironmentApi(threadRef.environmentId).git.removeWorktree({
213 cwd: threadProject.cwd,
214 path: orphanedWorktreePath,
215 force: true,
216 });
217 await invalidateGitQueries(queryClient, {
218 environmentId: threadRef.environmentId,
219 });
220 } catch (error) {
221 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
222 console.error("Failed to remove orphaned worktree after thread deletion", {
223 threadId: threadRef.threadId,
224 projectCwd: threadProject.cwd,
225 worktreePath: orphanedWorktreePath,
226 error,
227 });
228 toastManager.add(
229 stackedThreadToast({
230 type: "error",
231 title: "Thread deleted, but worktree removal failed",
232 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
233 }),
234 );
235 }
236 },
237 [
238 clearComposerDraftForThread,
239 clearProjectDraftThreadById,
240 clearTerminalState,
241 getCurrentRouteThreadRef,
242 router,
243 queryClient,
244 resolveThreadTarget,
245 sidebarThreadSortOrder,
246 ],
247 );
248
249 const confirmAndDeleteThread = useCallback(
250 async (target: ScopedThreadRef) => {
251 const api = readEnvironmentApi(target.environmentId);
252 if (!api) return;
253 const localApi = readLocalApi();
254 const resolved = resolveThreadTarget(target);
255 if (!resolved) return;
256 const { thread } = resolved;
257
258 if (confirmThreadDelete && localApi) {
259 const confirmed = await localApi.dialogs.confirm(
260 [
261 `Delete thread "${thread.title}"?`,
262 "This permanently clears conversation history for this thread.",
263 ].join("\n"),
264 );
265 if (!confirmed) {
266 return;
267 }
268 }
269
270 await deleteThread(target);
271 },
272 [confirmThreadDelete, deleteThread, resolveThreadTarget],
273 );
274
275 return {
276 archiveThread,
277 unarchiveThread,
278 deleteThread,
279 confirmAndDeleteThread,
280 };
281}