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

useThreadActions.ts

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