Open History to see the last commit
1import {
2 parseScopedThreadKey,
3 scopeProjectRef,
4 scopeThreadRef,
5 scopedThreadKey,
6} from "@t3tools/client-runtime/environment";
7import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
9import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Schema from "effect/Schema";
12import { AsyncResult } from "effect/unstable/reactivity";
13import { useRouter } from "@tanstack/react-router";
14import { useCallback, useMemo, useRef } from "react";
15
16import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic";
17import { useComposerDraftStore } from "../composerDraftStore";
18import { terminalEnvironment } from "../state/terminal";
19import { threadEnvironment } from "../state/threads";
20import { vcsEnvironment } from "../state/vcs";
21import { useNewThreadHandler } from "./useHandleNewThread";
22import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
23import { releaseComposerDraftUploads } from "../lib/composerDraftUploads";
24import { readLocalApi } from "../localApi";
25import {
26 readEnvironmentSupportsPinning,
27 readEnvironmentSupportsPinReorder,
28 readEnvironmentSupportsSettlement,
29 readEnvironmentSupportsSnooze,
30 readEnvironmentThreadRefs,
31 readProject,
32 readThreadShell,
33 readThreadShells,
34} from "../state/entities";
35import { useTerminalUiStateStore } from "../terminalUiStateStore";
36import { useUiStateStore } from "../uiStateStore";
37import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
38import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
39import { stackedThreadToast, toastManager } from "../components/ui/toast";
40import { useClientSettings } from "./useSettings";
41import { useAtomCommand } from "../state/use-atom-command";
42
43export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
44 "ThreadArchiveBlockedError",
45 {
46 environmentId: EnvironmentId,
47 threadId: ThreadId,
48 },
49) {
50 override get message(): string {
51 return "Cannot archive a running thread.";
52 }
53}
54
55export class ThreadSettlementUnsupportedError extends Schema.TaggedErrorClass<ThreadSettlementUnsupportedError>()(
56 "ThreadSettlementUnsupportedError",
57 {
58 environmentId: EnvironmentId,
59 threadId: ThreadId,
60 },
61) {
62 override get message(): string {
63 return "This environment's server does not support settling yet. Update the server to use Settle.";
64 }
65}
66
67export class ThreadSnoozeUnsupportedError extends Schema.TaggedErrorClass<ThreadSnoozeUnsupportedError>()(
68 "ThreadSnoozeUnsupportedError",
69 {
70 environmentId: EnvironmentId,
71 threadId: ThreadId,
72 },
73) {
74 override get message(): string {
75 return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
76 }
77}
78
79export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass<ThreadSnoozeBlockedError>()(
80 "ThreadSnoozeBlockedError",
81 {
82 environmentId: EnvironmentId,
83 threadId: ThreadId,
84 },
85) {
86 override get message(): string {
87 return "This thread is waiting on you. Respond to the pending request before snoozing it.";
88 }
89}
90
91/** Key that sorts before every arranged pinned thread, so a fresh pin lands
92 at the top of the run. Undefined (keyless, sorts with the legacy block)
93 when key math can't produce one — pinning must never fail on placement. */
94function topOfPinnedRunOrderKey(): string | undefined {
95 let firstKey: string | null = null;
96 for (const shell of readThreadShells()) {
97 if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
98 if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
99 }
100 return pinOrderKeyBetween(null, firstKey) ?? undefined;
101}
102
103export class ThreadPinningUnsupportedError extends Schema.TaggedErrorClass<ThreadPinningUnsupportedError>()(
104 "ThreadPinningUnsupportedError",
105 {
106 environmentId: EnvironmentId,
107 threadId: ThreadId,
108 },
109) {
110 override get message(): string {
111 return "This environment's server does not support pinning yet. Update the server to use Pin.";
112 }
113}
114
115export class ThreadPinReorderUnsupportedError extends Schema.TaggedErrorClass<ThreadPinReorderUnsupportedError>()(
116 "ThreadPinReorderUnsupportedError",
117 {
118 environmentId: EnvironmentId,
119 threadId: ThreadId,
120 },
121) {
122 override get message(): string {
123 return "This environment's server does not support reordering pinned threads yet. Update the server to reorder pins.";
124 }
125}
126
127export async function requestThreadUnpinConfirmation(input: {
128 enabled: boolean;
129 title: string;
130 confirm: ((message: string) => Promise<boolean>) | null;
131}) {
132 const { confirm } = input;
133 if (!input.enabled || confirm === null) {
134 return AsyncResult.success(true);
135 }
136
137 return settlePromise(() =>
138 confirm(
139 [
140 `Unpin thread "${input.title}"?`,
141 "This will move the thread out of your pinned section.",
142 ].join("\n"),
143 ),
144 );
145}
146
147/** Report navigation separately so a completed deletion can still finish worktree cleanup. */
148export async function navigateAfterThreadDeletion(navigate: () => Promise<void>) {
149 const result = await settlePromise(navigate);
150 if (result._tag === "Failure") {
151 const error = squashAtomCommandFailure(result);
152 toastManager.add(
153 stackedThreadToast({
154 type: "error",
155 title: "Thread deleted, but navigation failed",
156 description: error instanceof Error ? error.message : "An error occurred.",
157 }),
158 );
159 }
160}
161
162export function useThreadActions() {
163 const closeTerminal = useAtomCommand(terminalEnvironment.close);
164 const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
165 reportFailure: false,
166 });
167 const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
168 reportFailure: false,
169 });
170 const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
171 reportFailure: false,
172 });
173 const settleThreadMutation = useAtomCommand(threadEnvironment.settle, {
174 reportFailure: false,
175 });
176 const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
177 reportFailure: false,
178 });
179 const pinThreadMutation = useAtomCommand(threadEnvironment.pin, {
180 reportFailure: false,
181 });
182 const unpinThreadMutation = useAtomCommand(threadEnvironment.unpin, {
183 reportFailure: false,
184 });
185 const reorderPinnedThreadMutation = useAtomCommand(threadEnvironment.reorderPin, {
186 reportFailure: false,
187 });
188 const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
189 reportFailure: false,
190 });
191 const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
192 reportFailure: false,
193 });
194 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
195 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
196 reportFailure: false,
197 });
198 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
199 reportFailure: false,
200 });
201 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
202 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
203 const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin);
204 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
205 const clearProjectDraftThreadById = useComposerDraftStore(
206 (store) => store.clearProjectDraftThreadById,
207 );
208 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
209 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
210 const router = useRouter();
211 const handleNewThread = useNewThreadHandler();
212 // Keep a ref so archiveThread can call handleNewThread without appearing in
213 // its dependency array — handleNewThread is inherently unstable (depends on
214 // the projects list) and would otherwise cascade new references into every
215 // sidebar row via archiveThread → attemptArchiveThread.
216 const handleNewThreadRef = useRef(handleNewThread);
217 handleNewThreadRef.current = handleNewThread;
218
219 const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
220 const thread = readThreadShell(target);
221 if (!thread) {
222 return null;
223 }
224 return {
225 thread,
226 threadRef: target,
227 };
228 }, []);
229 const getCurrentRouteThreadRef = useCallback(() => {
230 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
231 return resolveThreadRouteRef(currentRouteParams);
232 }, [router]);
233
234 const archiveThread = useCallback(
235 async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
236 const resolved = resolveThreadTarget(target);
237 if (!resolved) return AsyncResult.success(undefined);
238 const { thread, threadRef } = resolved;
239 if (thread.session?.status === "running" && thread.session.activeTurnId != null) {
240 return AsyncResult.failure(
241 Cause.fail(
242 new ThreadArchiveBlockedError({
243 environmentId: threadRef.environmentId,
244 threadId: threadRef.threadId,
245 }),
246 ),
247 );
248 }
249
250 const currentRouteThreadRef = getCurrentRouteThreadRef();
251 const shouldNavigateToDraft =
252 currentRouteThreadRef?.threadId === threadRef.threadId &&
253 currentRouteThreadRef.environmentId === threadRef.environmentId;
254 const archiveResult = await archiveThreadMutation({
255 environmentId: threadRef.environmentId,
256 input: { threadId: threadRef.threadId },
257 });
258 if (archiveResult._tag === "Failure") {
259 return archiveResult;
260 }
261 const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
262 if (wokeAt !== null) {
263 markThreadVisited(scopedThreadKey(threadRef), wokeAt);
264 }
265 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
266 opts.onArchived?.();
267
268 if (shouldNavigateToDraft) {
269 const navigationResult = await settlePromise(() =>
270 handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)),
271 );
272 if (navigationResult._tag === "Failure") {
273 return navigationResult;
274 }
275 return archiveResult;
276 }
277
278 return archiveResult;
279 },
280 [archiveThreadMutation, getCurrentRouteThreadRef, markThreadVisited, resolveThreadTarget],
281 );
282
283 const unarchiveThread = useCallback(
284 async (target: ScopedThreadRef) => {
285 const result = await unarchiveThreadMutation({
286 environmentId: target.environmentId,
287 input: { threadId: target.threadId },
288 });
289 if (result._tag === "Success") {
290 refreshArchivedThreadsForEnvironment(target.environmentId);
291 }
292 return result;
293 },
294 [unarchiveThreadMutation],
295 );
296
297 const deleteThread = useCallback(
298 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
299 const resolved = resolveThreadTarget(target);
300 if (!resolved) {
301 // Thread not in main store (e.g. archived thread) — dispatch delete directly.
302 const result = await deleteThreadMutation({
303 environmentId: target.environmentId,
304 input: { threadId: target.threadId },
305 });
306 if (result._tag === "Success") {
307 refreshArchivedThreadsForEnvironment(target.environmentId);
308 }
309 return result;
310 }
311 const { thread, threadRef } = resolved;
312 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
313 const shell = readThreadShell(ref);
314 return shell === null ? [] : [shell];
315 });
316 const threadProject = readProject({
317 environmentId: threadRef.environmentId,
318 projectId: thread.projectId,
319 });
320 const deletedIds =
321 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
322 ? new Set<ThreadId>(
323 [...opts.deletedThreadKeys].flatMap((threadKey) => {
324 const ref = parseScopedThreadKey(threadKey);
325 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
326 }),
327 )
328 : undefined;
329 const survivingThreads =
330 deletedIds && deletedIds.size > 0
331 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
332 : threads;
333 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
334 survivingThreads,
335 threadRef.threadId,
336 );
337 const displayWorktreePath = orphanedWorktreePath
338 ? formatWorktreePathForDisplay(orphanedWorktreePath)
339 : null;
340 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
341 const localApi = readLocalApi();
342 let shouldDeleteWorktree = false;
343 if (canDeleteWorktree && localApi) {
344 const confirmationResult = await settlePromise(() =>
345 localApi.dialogs.confirm(
346 [
347 "This thread is the only one linked to this worktree:",
348 displayWorktreePath ?? orphanedWorktreePath,
349 "",
350 "Delete the worktree too?",
351 ].join("\n"),
352 { variant: "destructive" },
353 ),
354 );
355 if (confirmationResult._tag === "Failure") {
356 return confirmationResult;
357 }
358 shouldDeleteWorktree = confirmationResult.value;
359 }
360
361 if (thread.session && thread.session.status !== "stopped") {
362 await stopThreadSession({
363 environmentId: threadRef.environmentId,
364 input: { threadId: threadRef.threadId },
365 });
366 }
367
368 await closeTerminal({
369 environmentId: threadRef.environmentId,
370 input: { threadId: threadRef.threadId, deleteHistory: true },
371 });
372
373 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
374 const currentRouteThreadRef = getCurrentRouteThreadRef();
375 const shouldNavigateToFallback =
376 currentRouteThreadRef?.threadId === threadRef.threadId &&
377 currentRouteThreadRef.environmentId === threadRef.environmentId;
378 const fallbackThreadId = getFallbackThreadIdAfterDelete({
379 threads,
380 deletedThreadId: threadRef.threadId,
381 deletedThreadIds,
382 sortOrder: sidebarThreadSortOrder,
383 });
384 const deleteResult = await deleteThreadMutation({
385 environmentId: threadRef.environmentId,
386 input: { threadId: threadRef.threadId },
387 });
388 if (deleteResult._tag === "Failure") {
389 return deleteResult;
390 }
391 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
392 releaseComposerDraftUploads(threadRef);
393 clearComposerDraftForThread(threadRef);
394 clearProjectDraftThreadById(
395 scopeProjectRef(threadRef.environmentId, thread.projectId),
396 threadRef,
397 );
398 clearTerminalUiState(threadRef);
399
400 if (shouldNavigateToFallback) {
401 const fallbackThread = fallbackThreadId
402 ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId))
403 : null;
404 await navigateAfterThreadDeletion(() =>
405 fallbackThread
406 ? router.navigate({
407 to: "/$environmentId/$threadId",
408 params: buildThreadRouteParams(
409 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
410 ),
411 replace: true,
412 })
413 : router.navigate({ to: "/", replace: true }),
414 );
415 }
416
417 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
418 return deleteResult;
419 }
420
421 const removeResult = await removeWorktree({
422 environmentId: threadRef.environmentId,
423 input: {
424 cwd: threadProject.workspaceRoot,
425 path: orphanedWorktreePath,
426 force: true,
427 },
428 });
429 const refreshResult =
430 removeResult._tag === "Success"
431 ? await refreshVcsStatus({
432 environmentId: threadRef.environmentId,
433 input: { cwd: threadProject.workspaceRoot },
434 })
435 : null;
436 const cleanupFailure =
437 removeResult._tag === "Failure"
438 ? removeResult
439 : refreshResult?._tag === "Failure"
440 ? refreshResult
441 : null;
442 if (cleanupFailure) {
443 const removalFailed = removeResult._tag === "Failure";
444 const error = squashAtomCommandFailure(cleanupFailure);
445 const message = error instanceof Error ? error.message : "An error occurred.";
446 console.error("Worktree cleanup failed after thread deletion", {
447 threadId: threadRef.threadId,
448 projectCwd: threadProject.workspaceRoot,
449 worktreePath: orphanedWorktreePath,
450 error,
451 });
452 toastManager.add(
453 stackedThreadToast({
454 type: "error",
455 title: removalFailed
456 ? "Failed to delete worktree"
457 : "Worktree deleted, but Git status refresh failed",
458 description: removalFailed
459 ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`
460 : message,
461 }),
462 );
463 // The thread was deleted. Cleanup has its own toast; returning its
464 // failure would make callers incorrectly report a thread deletion error.
465 }
466 return deleteResult;
467 },
468 [
469 clearComposerDraftForThread,
470 clearProjectDraftThreadById,
471 clearTerminalUiState,
472 closeTerminal,
473 deleteThreadMutation,
474 getCurrentRouteThreadRef,
475 refreshVcsStatus,
476 removeWorktree,
477 router,
478 resolveThreadTarget,
479 sidebarThreadSortOrder,
480 stopThreadSession,
481 ],
482 );
483
484 const settleThread = useCallback(
485 async (target: ScopedThreadRef) => {
486 // Version skew: never send the command to a server that predates it —
487 // the raw protocol rejection would read as a random failure.
488 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
489 return AsyncResult.failure(
490 Cause.fail(
491 new ThreadSettlementUnsupportedError({
492 environmentId: target.environmentId,
493 threadId: target.threadId,
494 }),
495 ),
496 );
497 }
498 const resolved = resolveThreadTarget(target);
499 const wokeAt = resolved
500 ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
501 : null;
502 // Settle is a high-frequency lifecycle action and stays silent — no
503 // toast.
504 const result = await settleThreadMutation({
505 environmentId: target.environmentId,
506 input: { threadId: target.threadId },
507 });
508 if (result._tag === "Success" && wokeAt !== null) {
509 markThreadVisited(scopedThreadKey(target), wokeAt);
510 }
511 return result;
512 },
513 [markThreadVisited, resolveThreadTarget, settleThreadMutation],
514 );
515
516 const unsettleThread = useCallback(
517 async (target: ScopedThreadRef) => {
518 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
519 return AsyncResult.failure(
520 Cause.fail(
521 new ThreadSettlementUnsupportedError({
522 environmentId: target.environmentId,
523 threadId: target.threadId,
524 }),
525 ),
526 );
527 }
528 // reason "user" pins the thread active: auto-settle (PR merged /
529 // inactivity) stays suppressed until real activity clears the pin.
530 return unsettleThreadMutation({
531 environmentId: target.environmentId,
532 input: { threadId: target.threadId, reason: "user" },
533 });
534 },
535 [unsettleThreadMutation],
536 );
537
538 const pinThread = useCallback(
539 async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
540 // Version skew: never send the command to a server that predates it.
541 if (!readEnvironmentSupportsPinning(target.environmentId)) {
542 return AsyncResult.failure(
543 Cause.fail(
544 new ThreadPinningUnsupportedError({
545 environmentId: target.environmentId,
546 threadId: target.threadId,
547 }),
548 ),
549 );
550 }
551 // Every pin path places the thread at the top of the arranged run:
552 // callers with a better anchor (the sidebar, which knows the displayed
553 // order) pass their own key; everyone else (chat header, context menus)
554 // gets the default so the same action never places differently.
555 // orderKey rides only to servers that decode it; pre-reorder servers
556 // get the bare pin they understand and the thread stays keyless.
557 const orderKey = readEnvironmentSupportsPinReorder(target.environmentId)
558 ? (opts.orderKey ?? topOfPinnedRunOrderKey())
559 : undefined;
560 return pinThreadMutation({
561 environmentId: target.environmentId,
562 input: {
563 threadId: target.threadId,
564 ...(orderKey !== undefined ? { orderKey } : {}),
565 },
566 });
567 },
568 [pinThreadMutation],
569 );
570
571 const unpinThread = useCallback(
572 async (target: ScopedThreadRef) => {
573 if (!readEnvironmentSupportsPinning(target.environmentId)) {
574 return AsyncResult.failure(
575 Cause.fail(
576 new ThreadPinningUnsupportedError({
577 environmentId: target.environmentId,
578 threadId: target.threadId,
579 }),
580 ),
581 );
582 }
583 return unpinThreadMutation({
584 environmentId: target.environmentId,
585 input: { threadId: target.threadId },
586 });
587 },
588 [unpinThreadMutation],
589 );
590
591 const confirmAndUnpinThread = useCallback(
592 async (target: ScopedThreadRef) => {
593 const localApi = readLocalApi();
594 const resolved = resolveThreadTarget(target);
595 const confirmationResult = await requestThreadUnpinConfirmation({
596 enabled: confirmThreadUnpin,
597 title: resolved?.thread.title ?? "this thread",
598 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
599 });
600 if (confirmationResult._tag === "Failure") {
601 return confirmationResult;
602 }
603 if (!confirmationResult.value) {
604 return AsyncResult.success(undefined);
605 }
606 return unpinThread(target);
607 },
608 [confirmThreadUnpin, resolveThreadTarget, unpinThread],
609 );
610
611 const reorderPinnedThread = useCallback(
612 async (target: ScopedThreadRef, orderKey: string) => {
613 // Callers (the sidebar drag handler) only enable dragging on
614 // reorder-capable environments; this guard covers races around
615 // capability changes mid-drag.
616 if (!readEnvironmentSupportsPinReorder(target.environmentId)) {
617 return AsyncResult.failure(
618 Cause.fail(
619 new ThreadPinReorderUnsupportedError({
620 environmentId: target.environmentId,
621 threadId: target.threadId,
622 }),
623 ),
624 );
625 }
626 return reorderPinnedThreadMutation({
627 environmentId: target.environmentId,
628 input: { threadId: target.threadId, orderKey },
629 });
630 },
631 [reorderPinnedThreadMutation],
632 );
633
634 const snoozeThread = useCallback(
635 async (target: ScopedThreadRef, snoozedUntil: string) => {
636 // Version skew: never send the command to a server that predates it.
637 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
638 return AsyncResult.failure(
639 Cause.fail(
640 new ThreadSnoozeUnsupportedError({
641 environmentId: target.environmentId,
642 threadId: target.threadId,
643 }),
644 ),
645 );
646 }
647 const resolved = resolveThreadTarget(target);
648 // Blocked-on-you work and queued turns can't be snoozed away —
649 // client-side twin of the server invariants so the UI rejects before
650 // a round trip.
651 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
652 return AsyncResult.failure(
653 Cause.fail(
654 new ThreadSnoozeBlockedError({
655 environmentId: resolved.threadRef.environmentId,
656 threadId: resolved.threadRef.threadId,
657 }),
658 ),
659 );
660 }
661 return snoozeThreadMutation({
662 environmentId: target.environmentId,
663 input: { threadId: target.threadId, snoozedUntil },
664 });
665 },
666 [resolveThreadTarget, snoozeThreadMutation],
667 );
668
669 const unsnoozeThread = useCallback(
670 async (target: ScopedThreadRef) => {
671 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
672 return AsyncResult.failure(
673 Cause.fail(
674 new ThreadSnoozeUnsupportedError({
675 environmentId: target.environmentId,
676 threadId: target.threadId,
677 }),
678 ),
679 );
680 }
681 return unsnoozeThreadMutation({
682 environmentId: target.environmentId,
683 input: { threadId: target.threadId, reason: "user" },
684 });
685 },
686 [unsnoozeThreadMutation],
687 );
688
689 const confirmAndDeleteThread = useCallback(
690 async (target: ScopedThreadRef) => {
691 const localApi = readLocalApi();
692 const resolved = resolveThreadTarget(target);
693
694 if (confirmThreadDelete && localApi) {
695 const title = resolved?.thread.title ?? "this thread";
696 const confirmationResult = await settlePromise(() =>
697 localApi.dialogs.confirm(
698 [
699 `Delete thread "${title}"?`,
700 "This permanently clears conversation history for this thread.",
701 ].join("\n"),
702 { variant: "destructive" },
703 ),
704 );
705 if (confirmationResult._tag === "Failure") {
706 return confirmationResult;
707 }
708 if (!confirmationResult.value) {
709 return AsyncResult.success(undefined);
710 }
711 }
712
713 return deleteThread(target);
714 },
715 [confirmThreadDelete, deleteThread, resolveThreadTarget],
716 );
717
718 return useMemo(
719 () => ({
720 archiveThread,
721 unarchiveThread,
722 deleteThread,
723 confirmAndDeleteThread,
724 settleThread,
725 unsettleThread,
726 snoozeThread,
727 unsnoozeThread,
728 pinThread,
729 unpinThread,
730 confirmAndUnpinThread,
731 reorderPinnedThread,
732 }),
733 [
734 archiveThread,
735 confirmAndDeleteThread,
736 confirmAndUnpinThread,
737 deleteThread,
738 pinThread,
739 reorderPinnedThread,
740 settleThread,
741 snoozeThread,
742 unarchiveThread,
743 unpinThread,
744 unsettleThread,
745 unsnoozeThread,
746 ],
747 );
748}