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