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