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

useThreadActions.ts

490 lines17.3 KB

1import {
2 parseScopedThreadKey,
3 scopeProjectRef,
4 scopeThreadRef,
5} from "@t3tools/client-runtime/environment";
6import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
7import { canSettle } from "@t3tools/client-runtime/state/thread-settled";
8import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
9import * as Cause from "effect/Cause";
10import * as Schema from "effect/Schema";
11import { AsyncResult } from "effect/unstable/reactivity";
12import { useRouter } from "@tanstack/react-router";
13import { useCallback, useMemo, useRef } from "react";
14​
15import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
16import { useComposerDraftStore } from "../composerDraftStore";
17import { terminalEnvironment } from "../state/terminal";
18import { threadEnvironment } from "../state/threads";
19import { vcsEnvironment } from "../state/vcs";
20import { useNewThreadHandler } from "./useHandleNewThread";
21import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
22import { readLocalApi } from "../localApi";
23import {
24 readEnvironmentSupportsSettlement,
25 readEnvironmentThreadRefs,
26 readProject,
27 readThreadShell,
28} from "../state/entities";
29import { useTerminalUiStateStore } from "../terminalUiStateStore";
30import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
31import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
32import { stackedThreadToast, toastManager } from "../components/ui/toast";
33import { useClientSettings } from "./useSettings";
34import { useAtomCommand } from "../state/use-atom-command";
35​
36export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
37 "ThreadArchiveBlockedError",
38 {
39 environmentId: EnvironmentId,
40 threadId: ThreadId,
41 },
42) {
43 override get message(): string {
44 return "Cannot archive a running thread.";
45 }
47​
48export class ThreadSettlementUnsupportedError extends Schema.TaggedErrorClass<ThreadSettlementUnsupportedError>()(
49 "ThreadSettlementUnsupportedError",
50 {
51 environmentId: EnvironmentId,
52 threadId: ThreadId,
53 },
54) {
55 override get message(): string {
56 return "This environment's server does not support settling yet. Update the server to use Settle.";
57 }
59​
60export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSettleBlockedError>()(
61 "ThreadSettleBlockedError",
62 {
63 environmentId: EnvironmentId,
64 threadId: ThreadId,
65 },
66) {
67 override get message(): string {
68 return "This thread still needs attention. Resolve or interrupt it first, then try again.";
69 }
71​
72export function useThreadActions() {
73 const closeTerminal = useAtomCommand(terminalEnvironment.close);
74 const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
75 reportFailure: false,
76 });
77 const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
78 reportFailure: false,
79 });
80 const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
81 reportFailure: false,
82 });
83 const settleThreadMutation = useAtomCommand(threadEnvironment.settle, {
84 reportFailure: false,
85 });
86 const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
87 reportFailure: false,
88 });
89 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
90 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
91 reportFailure: false,
92 });
93 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
94 reportFailure: false,
95 });
96 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
97 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
98 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
99 const clearProjectDraftThreadById = useComposerDraftStore(
100 (store) => store.clearProjectDraftThreadById,
101 );
102 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
103 const router = useRouter();
104 const handleNewThread = useNewThreadHandler();
105 // Keep a ref so archiveThread can call handleNewThread without appearing in
106 // its dependency array — handleNewThread is inherently unstable (depends on
107 // the projects list) and would otherwise cascade new references into every
108 // sidebar row via archiveThread → attemptArchiveThread.
109 const handleNewThreadRef = useRef(handleNewThread);
110 handleNewThreadRef.current = handleNewThread;
111​
112 const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
113 const thread = readThreadShell(target);
114 if (!thread) {
115 return null;
116 }
117 return {
118 thread,
119 threadRef: target,
120 };
121 }, []);
122 const getCurrentRouteThreadRef = useCallback(() => {
123 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
124 return resolveThreadRouteRef(currentRouteParams);
125 }, [router]);
126​
127 const archiveThread = useCallback(
128 async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
129 const resolved = resolveThreadTarget(target);
130 if (!resolved) return AsyncResult.success(undefined);
131 const { thread, threadRef } = resolved;
132 if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
133 return AsyncResult.failure(
134 Cause.fail(
135 new ThreadArchiveBlockedError({
136 environmentId: threadRef.environmentId,
137 threadId: threadRef.threadId,
138 }),
139 ),
140 );
141 }
142​
143 const currentRouteThreadRef = getCurrentRouteThreadRef();
144 const shouldNavigateToDraft =
145 currentRouteThreadRef?.threadId === threadRef.threadId &&
146 currentRouteThreadRef.environmentId === threadRef.environmentId;
147 const archiveResult = await archiveThreadMutation({
148 environmentId: threadRef.environmentId,
149 input: { threadId: threadRef.threadId },
150 });
151 if (archiveResult._tag === "Failure") {
152 return archiveResult;
153 }
154 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
155 opts.onArchived?.();
156​
157 if (shouldNavigateToDraft) {
158 const navigationResult = await settlePromise(() =>
159 handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)),
160 );
161 if (navigationResult._tag === "Failure") {
162 return navigationResult;
163 }
164 return archiveResult;
165 }
166​
167 return archiveResult;
168 },
169 [archiveThreadMutation, getCurrentRouteThreadRef, resolveThreadTarget],
170 );
171​
172 const unarchiveThread = useCallback(
173 async (target: ScopedThreadRef) => {
174 const result = await unarchiveThreadMutation({
175 environmentId: target.environmentId,
176 input: { threadId: target.threadId },
177 });
178 if (result._tag === "Success") {
179 refreshArchivedThreadsForEnvironment(target.environmentId);
180 }
181 return result;
182 },
183 [unarchiveThreadMutation],
184 );
185​
186 const deleteThread = useCallback(
187 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
188 const resolved = resolveThreadTarget(target);
189 if (!resolved) {
190 // Thread not in main store (e.g. archived thread) — dispatch delete directly.
191 const result = await deleteThreadMutation({
192 environmentId: target.environmentId,
193 input: { threadId: target.threadId },
194 });
195 if (result._tag === "Success") {
196 refreshArchivedThreadsForEnvironment(target.environmentId);
197 }
198 return result;
199 }
200 const { thread, threadRef } = resolved;
201 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
202 const shell = readThreadShell(ref);
203 return shell === null ? [] : [shell];
204 });
205 const threadProject = readProject({
206 environmentId: threadRef.environmentId,
207 projectId: thread.projectId,
208 });
209 const deletedIds =
210 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
211 ? new Set<ThreadId>(
212 [...opts.deletedThreadKeys].flatMap((threadKey) => {
213 const ref = parseScopedThreadKey(threadKey);
214 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
215 }),
216 )
217 : undefined;
218 const survivingThreads =
219 deletedIds && deletedIds.size > 0
220 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
221 : threads;
222 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
223 survivingThreads,
224 threadRef.threadId,
225 );
226 const displayWorktreePath = orphanedWorktreePath
227 ? formatWorktreePathForDisplay(orphanedWorktreePath)
228 : null;
229 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
230 const localApi = readLocalApi();
231 let shouldDeleteWorktree = false;
232 if (canDeleteWorktree && localApi) {
233 const confirmationResult = await settlePromise(() =>
234 localApi.dialogs.confirm(
235 [
236 "This thread is the only one linked to this worktree:",
237 displayWorktreePath ?? orphanedWorktreePath,
238 "",
239 "Delete the worktree too?",
240 ].join("\n"),
241 ),
242 );
243 if (confirmationResult._tag === "Failure") {
244 return confirmationResult;
245 }
246 shouldDeleteWorktree = confirmationResult.value;
247 }
248​
249 if (thread.session && thread.session.status !== "stopped") {
250 await stopThreadSession({
251 environmentId: threadRef.environmentId,
252 input: { threadId: threadRef.threadId },
253 });
254 }
255​
256 await closeTerminal({
257 environmentId: threadRef.environmentId,
258 input: { threadId: threadRef.threadId, deleteHistory: true },
259 });
260​
261 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
262 const currentRouteThreadRef = getCurrentRouteThreadRef();
263 const shouldNavigateToFallback =
264 currentRouteThreadRef?.threadId === threadRef.threadId &&
265 currentRouteThreadRef.environmentId === threadRef.environmentId;
266 const fallbackThreadId = getFallbackThreadIdAfterDelete({
267 threads,
268 deletedThreadId: threadRef.threadId,
269 deletedThreadIds,
270 sortOrder: sidebarThreadSortOrder,
271 });
272 const deleteResult = await deleteThreadMutation({
273 environmentId: threadRef.environmentId,
274 input: { threadId: threadRef.threadId },
275 });
276 if (deleteResult._tag === "Failure") {
277 return deleteResult;
278 }
279 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
280 clearComposerDraftForThread(threadRef);
281 clearProjectDraftThreadById(
282 scopeProjectRef(threadRef.environmentId, thread.projectId),
283 threadRef,
284 );
285 clearTerminalUiState(threadRef);
286​
287 if (shouldNavigateToFallback) {
288 if (fallbackThreadId) {
289 const fallbackThread = readThreadShell(
290 scopeThreadRef(threadRef.environmentId, fallbackThreadId),
291 );
292 if (fallbackThread) {
293 const navigationResult = await settlePromise(() =>
294 router.navigate({
295 to: "/$environmentId/$threadId",
296 params: buildThreadRouteParams(
297 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
298 ),
299 replace: true,
300 }),
301 );
302 if (navigationResult._tag === "Failure") {
303 return navigationResult;
304 }
305 } else {
306 const navigationResult = await settlePromise(() =>
307 router.navigate({ to: "/", replace: true }),
308 );
309 if (navigationResult._tag === "Failure") {
310 return navigationResult;
311 }
312 }
313 } else {
314 const navigationResult = await settlePromise(() =>
315 router.navigate({ to: "/", replace: true }),
316 );
317 if (navigationResult._tag === "Failure") {
318 return navigationResult;
319 }
320 }
321 }
322​
323 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
324 return deleteResult;
325 }
326​
327 const removeResult = await removeWorktree({
328 environmentId: threadRef.environmentId,
329 input: {
330 cwd: threadProject.workspaceRoot,
331 path: orphanedWorktreePath,
332 force: true,
333 },
334 });
335 const refreshResult =
336 removeResult._tag === "Success"
337 ? await refreshVcsStatus({
338 environmentId: threadRef.environmentId,
339 input: { cwd: threadProject.workspaceRoot },
340 })
341 : null;
342 const cleanupFailure =
343 removeResult._tag === "Failure"
344 ? removeResult
345 : refreshResult?._tag === "Failure"
346 ? refreshResult
347 : null;
348 if (cleanupFailure) {
349 const error = squashAtomCommandFailure(cleanupFailure);
350 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
351 console.error("Failed to remove orphaned worktree after thread deletion", {
352 threadId: threadRef.threadId,
353 projectCwd: threadProject.workspaceRoot,
354 worktreePath: orphanedWorktreePath,
355 error,
356 });
357 toastManager.add(
358 stackedThreadToast({
359 type: "error",
360 title: "Thread deleted, but worktree removal failed",
361 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
362 }),
363 );
364 return cleanupFailure;
365 }
366 return deleteResult;
367 },
368 [
369 clearComposerDraftForThread,
370 clearProjectDraftThreadById,
371 clearTerminalUiState,
372 closeTerminal,
373 deleteThreadMutation,
374 getCurrentRouteThreadRef,
375 refreshVcsStatus,
376 removeWorktree,
377 router,
378 resolveThreadTarget,
379 sidebarThreadSortOrder,
380 stopThreadSession,
381 ],
382 );
383​
384 const settleThread = useCallback(
385 async (target: ScopedThreadRef) => {
386 // Version skew: never send the command to a server that predates it —
387 // the raw protocol rejection would read as a random failure.
388 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
389 return AsyncResult.failure(
390 Cause.fail(
391 new ThreadSettlementUnsupportedError({
392 environmentId: target.environmentId,
393 threadId: target.threadId,
394 }),
395 ),
396 );
397 }
398 const resolved = resolveThreadTarget(target);
399 // Settle may only target what effectiveSettled could classify as
400 // settled: not starting/running sessions, not threads waiting on
401 // approvals or user input. Anything else would hide live work.
402 if (resolved && !canSettle(resolved.thread, { now: new Date().toISOString() })) {
403 return AsyncResult.failure(
404 Cause.fail(
405 new ThreadSettleBlockedError({
406 environmentId: resolved.threadRef.environmentId,
407 threadId: resolved.threadRef.threadId,
408 }),
409 ),
410 );
411 }
412 // Settle is a high-frequency lifecycle action and stays silent — no
413 // toast.
414 return settleThreadMutation({
415 environmentId: target.environmentId,
416 input: { threadId: target.threadId },
417 });
418 },
419 [resolveThreadTarget, settleThreadMutation],
420 );
421​
422 const unsettleThread = useCallback(
423 async (target: ScopedThreadRef) => {
424 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
425 return AsyncResult.failure(
426 Cause.fail(
427 new ThreadSettlementUnsupportedError({
428 environmentId: target.environmentId,
429 threadId: target.threadId,
430 }),
431 ),
432 );
433 }
434 // reason "user" pins the thread active: auto-settle (PR merged /
435 // inactivity) stays suppressed until real activity clears the pin.
436 return unsettleThreadMutation({
437 environmentId: target.environmentId,
438 input: { threadId: target.threadId, reason: "user" },
439 });
440 },
441 [unsettleThreadMutation],
442 );
443​
444 const confirmAndDeleteThread = useCallback(
445 async (target: ScopedThreadRef) => {
446 const localApi = readLocalApi();
447 const resolved = resolveThreadTarget(target);
448​
449 if (confirmThreadDelete && localApi) {
450 const title = resolved?.thread.title ?? "this thread";
451 const confirmationResult = await settlePromise(() =>
452 localApi.dialogs.confirm(
453 [
454 `Delete thread "${title}"?`,
455 "This permanently clears conversation history for this thread.",
456 ].join("\n"),
457 ),
458 );
459 if (confirmationResult._tag === "Failure") {
460 return confirmationResult;
461 }
462 if (!confirmationResult.value) {
463 return AsyncResult.success(undefined);
464 }
465 }
466​
467 return deleteThread(target);
468 },
469 [confirmThreadDelete, deleteThread, resolveThreadTarget],
470 );
471​
472 return useMemo(
473 () => ({
474 archiveThread,
475 unarchiveThread,
476 deleteThread,
477 confirmAndDeleteThread,
478 settleThread,
479 unsettleThread,
480 }),
481 [
482 archiveThread,
483 confirmAndDeleteThread,
484 deleteThread,
485 settleThread,
486 unarchiveThread,
487 unsettleThread,
488 ],
489 );