Open History to see the last commit
1import { ThreadId } from "@t3tools/contracts";
2import { useMutation, useQueryClient } from "@tanstack/react-query";
3import { useNavigate, useParams } from "@tanstack/react-router";
4import { useCallback } from "react";
5import { useUiStateStore } from "../uiStateStore";
6
7import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
8import { useComposerDraftStore } from "../composerDraftStore";
9import { useHandleNewThread } from "./useHandleNewThread";
10import { gitRemoveWorktreeMutationOptions } from "../lib/gitReactQuery";
11import { newCommandId } from "../lib/utils";
12import { readNativeApi } from "../nativeApi";
13import { useStore } from "../store";
14import { useTerminalStateStore } from "../terminalStateStore";
15import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
16import { toastManager } from "../components/ui/toast";
17import { useSettings } from "./useSettings";
18
19export function useThreadActions() {
20 const appSettings = useSettings();
21 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
22 const clearProjectDraftThreadById = useComposerDraftStore(
23 (store) => store.clearProjectDraftThreadById,
24 );
25 const clearTerminalState = useTerminalStateStore((state) => state.clearTerminalState);
26 const routeThreadId = useParams({
27 strict: false,
28 select: (params) => (params.threadId ? ThreadId.makeUnsafe(params.threadId) : null),
29 });
30 const navigate = useNavigate();
31 const { handleNewThread } = useHandleNewThread();
32 const queryClient = useQueryClient();
33 const removeWorktreeMutation = useMutation(gitRemoveWorktreeMutationOptions({ queryClient }));
34
35 const archiveThread = useCallback(
36 async (threadId: ThreadId) => {
37 const api = readNativeApi();
38 if (!api) return;
39 const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
40 if (!thread) return;
41 if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
42 throw new Error("Cannot archive a running thread.");
43 }
44
45 await api.orchestration.dispatchCommand({
46 type: "thread.archive",
47 commandId: newCommandId(),
48 threadId,
49 });
50
51 if (routeThreadId === threadId) {
52 await handleNewThread(thread.projectId);
53 }
54 },
55 [handleNewThread, routeThreadId],
56 );
57
58 const unarchiveThread = useCallback(async (threadId: ThreadId) => {
59 const api = readNativeApi();
60 if (!api) return;
61 await api.orchestration.dispatchCommand({
62 type: "thread.unarchive",
63 commandId: newCommandId(),
64 threadId,
65 });
66 }, []);
67
68 const deleteThread = useCallback(
69 async (threadId: ThreadId, opts: { deletedThreadIds?: ReadonlySet<ThreadId> } = {}) => {
70 const api = readNativeApi();
71 if (!api) return;
72 const { projects, threads } = useStore.getState();
73 const thread = threads.find((entry) => entry.id === threadId);
74 if (!thread) return;
75 const threadProject = projects.find((project) => project.id === thread.projectId);
76 const deletedIds = opts.deletedThreadIds;
77 const survivingThreads =
78 deletedIds && deletedIds.size > 0
79 ? threads.filter((entry) => entry.id === threadId || !deletedIds.has(entry.id))
80 : threads;
81 const orphanedWorktreePath = getOrphanedWorktreePathForThread(survivingThreads, threadId);
82 const displayWorktreePath = orphanedWorktreePath
83 ? formatWorktreePathForDisplay(orphanedWorktreePath)
84 : null;
85 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
86 const shouldDeleteWorktree =
87 canDeleteWorktree &&
88 (await api.dialogs.confirm(
89 [
90 "This thread is the only one linked to this worktree:",
91 displayWorktreePath ?? orphanedWorktreePath,
92 "",
93 "Delete the worktree too?",
94 ].join("\n"),
95 ));
96
97 if (thread.session && thread.session.status !== "closed") {
98 await api.orchestration
99 .dispatchCommand({
100 type: "thread.session.stop",
101 commandId: newCommandId(),
102 threadId,
103 createdAt: new Date().toISOString(),
104 })
105 .catch(() => undefined);
106 }
107
108 try {
109 await api.terminal.close({ threadId, deleteHistory: true });
110 } catch {
111 // Terminal may already be closed.
112 }
113
114 const deletedThreadIds = opts.deletedThreadIds ?? new Set<ThreadId>();
115 const pinnedThreadIds = useUiStateStore.getState().pinnedThreadIds;
116 const shouldNavigateToFallback = routeThreadId === threadId;
117 const fallbackThreadId = getFallbackThreadIdAfterDelete({
118 threads: threads.map((entry) =>
119 Object.assign({}, entry, {
120 isPinned: pinnedThreadIds.includes(entry.id),
121 }),
122 ),
123 deletedThreadId: threadId,
124 deletedThreadIds,
125 sortOrder: appSettings.sidebarThreadSortOrder,
126 });
127 await api.orchestration.dispatchCommand({
128 type: "thread.delete",
129 commandId: newCommandId(),
130 threadId,
131 });
132 clearComposerDraftForThread(threadId);
133 clearProjectDraftThreadById(thread.projectId, thread.id);
134 clearTerminalState(threadId);
135
136 if (shouldNavigateToFallback) {
137 if (fallbackThreadId) {
138 await navigate({
139 to: "/$threadId",
140 params: { threadId: fallbackThreadId },
141 replace: true,
142 });
143 } else {
144 await navigate({ to: "/", replace: true });
145 }
146 }
147
148 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
149 return;
150 }
151
152 try {
153 await removeWorktreeMutation.mutateAsync({
154 cwd: threadProject.cwd,
155 path: orphanedWorktreePath,
156 force: true,
157 });
158 } catch (error) {
159 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
160 console.error("Failed to remove orphaned worktree after thread deletion", {
161 threadId,
162 projectCwd: threadProject.cwd,
163 worktreePath: orphanedWorktreePath,
164 error,
165 });
166 toastManager.add({
167 type: "error",
168 title: "Thread deleted, but worktree removal failed",
169 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
170 });
171 }
172 },
173 [
174 clearComposerDraftForThread,
175 clearProjectDraftThreadById,
176 clearTerminalState,
177 appSettings.sidebarThreadSortOrder,
178 navigate,
179 removeWorktreeMutation,
180 routeThreadId,
181 ],
182 );
183
184 const confirmAndDeleteThread = useCallback(
185 async (threadId: ThreadId) => {
186 const api = readNativeApi();
187 if (!api) return;
188 const thread = useStore.getState().threads.find((entry) => entry.id === threadId);
189 if (!thread) return;
190
191 if (appSettings.confirmThreadDelete) {
192 const confirmed = await api.dialogs.confirm(
193 [
194 `Delete thread "${thread.title}"?`,
195 "This permanently clears conversation history for this thread.",
196 ].join("\n"),
197 );
198 if (!confirmed) {
199 return;
200 }
201 }
202
203 await deleteThread(threadId);
204 },
205 [appSettings.confirmThreadDelete, deleteThread],
206 );
207
208 return {
209 archiveThread,
210 unarchiveThread,
211 deleteThread,
212 confirmAndDeleteThread,
213 };
214}