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

useThreadActions.ts

273 lines9.7 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 } 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 { 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 const queryClient = useQueryClient();
37​
38 const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
39 const state = useStore.getState();
40 const thread = selectThreadByRef(state, target);
41 if (!thread) {
42 return null;
43 }
44 return {
45 thread,
46 threadRef: target,
47 };
48 }, []);
49 const getCurrentRouteThreadRef = useCallback(() => {
50 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
51 return resolveThreadRouteRef(currentRouteParams);
52 }, [router]);
53​
54 const archiveThread = useCallback(
55 async (target: ScopedThreadRef) => {
56 const api = readEnvironmentApi(target.environmentId);
57 if (!api) return;
58 const resolved = resolveThreadTarget(target);
59 if (!resolved) return;
60 const { thread, threadRef } = resolved;
61 if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
62 throw new Error("Cannot archive a running thread.");
63 }
64​
65 await api.orchestration.dispatchCommand({
66 type: "thread.archive",
67 commandId: newCommandId(),
68 threadId: threadRef.threadId,
69 });
70 const currentRouteThreadRef = getCurrentRouteThreadRef();
71​
72 if (
73 currentRouteThreadRef?.threadId === threadRef.threadId &&
74 currentRouteThreadRef.environmentId === threadRef.environmentId
75 ) {
76 await handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId));
77 }
78 },
79 [getCurrentRouteThreadRef, handleNewThread, resolveThreadTarget],
80 );
81​
82 const unarchiveThread = useCallback(async (target: ScopedThreadRef) => {
83 const api = readEnvironmentApi(target.environmentId);
84 if (!api) return;
85 await api.orchestration.dispatchCommand({
86 type: "thread.unarchive",
87 commandId: newCommandId(),
88 threadId: target.threadId,
89 });
90 }, []);
91​
92 const deleteThread = useCallback(
93 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
94 const api = readEnvironmentApi(target.environmentId);
95 if (!api) return;
96 const resolved = resolveThreadTarget(target);
97 if (!resolved) return;
98 const { thread, threadRef } = resolved;
99 const state = useStore.getState();
100 const threads = selectThreadsForEnvironment(state, threadRef.environmentId);
101 const threadProject = selectProjectByRef(state, {
102 environmentId: threadRef.environmentId,
103 projectId: thread.projectId,
104 });
105 const deletedIds =
106 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
107 ? new Set<ThreadId>(
108 [...opts.deletedThreadKeys].flatMap((threadKey) => {
109 const ref = parseScopedThreadKey(threadKey);
110 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
111 }),
112 )
113 : undefined;
114 const survivingThreads =
115 deletedIds && deletedIds.size > 0
116 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
117 : threads;
118 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
119 survivingThreads,
120 threadRef.threadId,
121 );
122 const displayWorktreePath = orphanedWorktreePath
123 ? formatWorktreePathForDisplay(orphanedWorktreePath)
124 : null;
125 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== undefined;
126 const localApi = readLocalApi();
127 const shouldDeleteWorktree =
128 canDeleteWorktree &&
129 localApi &&
130 (await localApi.dialogs.confirm(
131 [
132 "This thread is the only one linked to this worktree:",
133 displayWorktreePath ?? orphanedWorktreePath,
134 "",
135 "Delete the worktree too?",
136 ].join("\n"),
137 ));
138​
139 if (thread.session && thread.session.status !== "closed") {
140 await api.orchestration
141 .dispatchCommand({
142 type: "thread.session.stop",
143 commandId: newCommandId(),
144 threadId: threadRef.threadId,
145 createdAt: new Date().toISOString(),
146 })
147 .catch(() => undefined);
148 }
149​
150 try {
151 await api.terminal.close({ threadId: threadRef.threadId, deleteHistory: true });
152 } catch {
153 // Terminal may already be closed.
154 }
155​
156 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
157 const currentRouteThreadRef = getCurrentRouteThreadRef();
158 const shouldNavigateToFallback =
159 currentRouteThreadRef?.threadId === threadRef.threadId &&
160 currentRouteThreadRef.environmentId === threadRef.environmentId;
161 const fallbackThreadId = getFallbackThreadIdAfterDelete({
162 threads,
163 deletedThreadId: threadRef.threadId,
164 deletedThreadIds,
165 sortOrder: sidebarThreadSortOrder,
166 });
167 await api.orchestration.dispatchCommand({
168 type: "thread.delete",
169 commandId: newCommandId(),
170 threadId: threadRef.threadId,
171 });
172 clearComposerDraftForThread(threadRef);
173 clearProjectDraftThreadById(
174 scopeProjectRef(threadRef.environmentId, thread.projectId),
175 threadRef,
176 );
177 clearTerminalState(threadRef);
178​
179 if (shouldNavigateToFallback) {
180 if (fallbackThreadId) {
181 const fallbackThread = selectThreadByRef(
182 useStore.getState(),
183 scopeThreadRef(threadRef.environmentId, fallbackThreadId),
184 );
185 if (fallbackThread) {
186 await router.navigate({
187 to: "/$environmentId/$threadId",
188 params: buildThreadRouteParams(
189 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
190 ),
191 replace: true,
192 });
193 } else {
194 await router.navigate({ to: "/", replace: true });
195 }
196 } else {
197 await router.navigate({ to: "/", replace: true });
198 }
199 }
200​
201 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
202 return;
203 }
204​
205 try {
206 await ensureEnvironmentApi(threadRef.environmentId).git.removeWorktree({
207 cwd: threadProject.cwd,
208 path: orphanedWorktreePath,
209 force: true,
210 });
211 await invalidateGitQueries(queryClient, {
212 environmentId: threadRef.environmentId,
213 });
214 } catch (error) {
215 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
216 console.error("Failed to remove orphaned worktree after thread deletion", {
217 threadId: threadRef.threadId,
218 projectCwd: threadProject.cwd,
219 worktreePath: orphanedWorktreePath,
220 error,
221 });
222 toastManager.add({
223 type: "error",
224 title: "Thread deleted, but worktree removal failed",
225 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
226 });
227 }
228 },
229 [
230 clearComposerDraftForThread,
231 clearProjectDraftThreadById,
232 clearTerminalState,
233 getCurrentRouteThreadRef,
234 router,
235 queryClient,
236 resolveThreadTarget,
237 sidebarThreadSortOrder,
238 ],
239 );
240​
241 const confirmAndDeleteThread = useCallback(
242 async (target: ScopedThreadRef) => {
243 const api = readEnvironmentApi(target.environmentId);
244 if (!api) return;
245 const localApi = readLocalApi();
246 const resolved = resolveThreadTarget(target);
247 if (!resolved) return;
248 const { thread } = resolved;
249​
250 if (confirmThreadDelete && localApi) {
251 const confirmed = await localApi.dialogs.confirm(
252 [
253 `Delete thread "${thread.title}"?`,
254 "This permanently clears conversation history for this thread.",
255 ].join("\n"),
256 );
257 if (!confirmed) {
258 return;
259 }
260 }
261​
262 await deleteThread(target);
263 },
264 [confirmThreadDelete, deleteThread, resolveThreadTarget],
265 );
266​
267 return {
268 archiveThread,
269 unarchiveThread,
270 deleteThread,
271 confirmAndDeleteThread,
272 };