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