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

useThreadActions.ts

724 lines25.3 KB

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