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

useThreadActions.ts

292 lines10.8 KB

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