Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useThreadActions.ts

295 lines10.9 KB

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