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

useThreadActions.ts

726 lines25.4 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 { variant: "destructive" },
328 ),
329 );
330 if (confirmationResult._tag === "Failure") {
331 return confirmationResult;
332 }
333 shouldDeleteWorktree = confirmationResult.value;
334 }
335​
336 if (thread.session && thread.session.status !== "stopped") {
337 await stopThreadSession({
338 environmentId: threadRef.environmentId,
339 input: { threadId: threadRef.threadId },
340 });
341 }
342​
343 await closeTerminal({
344 environmentId: threadRef.environmentId,
345 input: { threadId: threadRef.threadId, deleteHistory: true },
346 });
347​
348 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
349 const currentRouteThreadRef = getCurrentRouteThreadRef();
350 const shouldNavigateToFallback =
351 currentRouteThreadRef?.threadId === threadRef.threadId &&
352 currentRouteThreadRef.environmentId === threadRef.environmentId;
353 const fallbackThreadId = getFallbackThreadIdAfterDelete({
354 threads,
355 deletedThreadId: threadRef.threadId,
356 deletedThreadIds,
357 sortOrder: sidebarThreadSortOrder,
358 });
359 const deleteResult = await deleteThreadMutation({
360 environmentId: threadRef.environmentId,
361 input: { threadId: threadRef.threadId },
362 });
363 if (deleteResult._tag === "Failure") {
364 return deleteResult;
365 }
366 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
367 clearComposerDraftForThread(threadRef);
368 clearProjectDraftThreadById(
369 scopeProjectRef(threadRef.environmentId, thread.projectId),
370 threadRef,
371 );
372 clearTerminalUiState(threadRef);
373​
374 if (shouldNavigateToFallback) {
375 if (fallbackThreadId) {
376 const fallbackThread = readThreadShell(
377 scopeThreadRef(threadRef.environmentId, fallbackThreadId),
378 );
379 if (fallbackThread) {
380 const navigationResult = await settlePromise(() =>
381 router.navigate({
382 to: "/$environmentId/$threadId",
383 params: buildThreadRouteParams(
384 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
385 ),
386 replace: true,
387 }),
388 );
389 if (navigationResult._tag === "Failure") {
390 return navigationResult;
391 }
392 } else {
393 const navigationResult = await settlePromise(() =>
394 router.navigate({ to: "/", replace: true }),
395 );
396 if (navigationResult._tag === "Failure") {
397 return navigationResult;
398 }
399 }
400 } else {
401 const navigationResult = await settlePromise(() =>
402 router.navigate({ to: "/", replace: true }),
403 );
404 if (navigationResult._tag === "Failure") {
405 return navigationResult;
406 }
407 }
408 }
409​
410 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
411 return deleteResult;
412 }
413​
414 const removeResult = await removeWorktree({
415 environmentId: threadRef.environmentId,
416 input: {
417 cwd: threadProject.workspaceRoot,
418 path: orphanedWorktreePath,
419 force: true,
420 },
421 });
422 const refreshResult =
423 removeResult._tag === "Success"
424 ? await refreshVcsStatus({
425 environmentId: threadRef.environmentId,
426 input: { cwd: threadProject.workspaceRoot },
427 })
428 : null;
429 const cleanupFailure =
430 removeResult._tag === "Failure"
431 ? removeResult
432 : refreshResult?._tag === "Failure"
433 ? refreshResult
434 : null;
435 if (cleanupFailure) {
436 const error = squashAtomCommandFailure(cleanupFailure);
437 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
438 console.error("Failed to remove orphaned worktree after thread deletion", {
439 threadId: threadRef.threadId,
440 projectCwd: threadProject.workspaceRoot,
441 worktreePath: orphanedWorktreePath,
442 error,
443 });
444 toastManager.add(
445 stackedThreadToast({
446 type: "error",
447 title: "Thread deleted, but worktree removal failed",
448 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
449 }),
450 );
451 return cleanupFailure;
452 }
453 return deleteResult;
454 },
455 [
456 clearComposerDraftForThread,
457 clearProjectDraftThreadById,
458 clearTerminalUiState,
459 closeTerminal,
460 deleteThreadMutation,
461 getCurrentRouteThreadRef,
462 refreshVcsStatus,
463 removeWorktree,
464 router,
465 resolveThreadTarget,
466 sidebarThreadSortOrder,
467 stopThreadSession,
468 ],
469 );
470​
471 const settleThread = useCallback(
472 async (target: ScopedThreadRef) => {
473 // Version skew: never send the command to a server that predates it —
474 // the raw protocol rejection would read as a random failure.
475 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
476 return AsyncResult.failure(
477 Cause.fail(
478 new ThreadSettlementUnsupportedError({
479 environmentId: target.environmentId,
480 threadId: target.threadId,
481 }),
482 ),
483 );
484 }
485 const resolved = resolveThreadTarget(target);
486 // Settle may only target what effectiveSettled could classify as
487 // settled: not starting/running sessions, not threads waiting on
488 // approvals or user input. Anything else would hide live work.
489 if (resolved && !canSettle(resolved.thread, { now: new Date().toISOString() })) {
490 return AsyncResult.failure(
491 Cause.fail(
492 new ThreadSettleBlockedError({
493 environmentId: resolved.threadRef.environmentId,
494 threadId: resolved.threadRef.threadId,
495 }),
496 ),
497 );
498 }
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 reorderPinnedThread = useCallback(
592 async (target: ScopedThreadRef, orderKey: string) => {
593 // Callers (the sidebar drag handler) only enable dragging on
594 // reorder-capable environments; this guard covers races around
595 // capability changes mid-drag.
596 if (!readEnvironmentSupportsPinReorder(target.environmentId)) {
597 return AsyncResult.failure(
598 Cause.fail(
599 new ThreadPinReorderUnsupportedError({
600 environmentId: target.environmentId,
601 threadId: target.threadId,
602 }),
603 ),
604 );
605 }
606 return reorderPinnedThreadMutation({
607 environmentId: target.environmentId,
608 input: { threadId: target.threadId, orderKey },
609 });
610 },
611 [reorderPinnedThreadMutation],
612 );
613​
614 const snoozeThread = useCallback(
615 async (target: ScopedThreadRef, snoozedUntil: string) => {
616 // Version skew: never send the command to a server that predates it.
617 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
618 return AsyncResult.failure(
619 Cause.fail(
620 new ThreadSnoozeUnsupportedError({
621 environmentId: target.environmentId,
622 threadId: target.threadId,
623 }),
624 ),
625 );
626 }
627 const resolved = resolveThreadTarget(target);
628 // Blocked-on-you work and queued turns can't be snoozed away —
629 // client-side twin of the server invariants so the UI rejects before
630 // a round trip.
631 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
632 return AsyncResult.failure(
633 Cause.fail(
634 new ThreadSnoozeBlockedError({
635 environmentId: resolved.threadRef.environmentId,
636 threadId: resolved.threadRef.threadId,
637 }),
638 ),
639 );
640 }
641 return snoozeThreadMutation({
642 environmentId: target.environmentId,
643 input: { threadId: target.threadId, snoozedUntil },
644 });
645 },
646 [resolveThreadTarget, snoozeThreadMutation],
647 );
648​
649 const unsnoozeThread = useCallback(
650 async (target: ScopedThreadRef) => {
651 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
652 return AsyncResult.failure(
653 Cause.fail(
654 new ThreadSnoozeUnsupportedError({
655 environmentId: target.environmentId,
656 threadId: target.threadId,
657 }),
658 ),
659 );
660 }
661 return unsnoozeThreadMutation({
662 environmentId: target.environmentId,
663 input: { threadId: target.threadId, reason: "user" },
664 });
665 },
666 [unsnoozeThreadMutation],
667 );
668​
669 const confirmAndDeleteThread = useCallback(
670 async (target: ScopedThreadRef) => {
671 const localApi = readLocalApi();
672 const resolved = resolveThreadTarget(target);
673​
674 if (confirmThreadDelete && localApi) {
675 const title = resolved?.thread.title ?? "this thread";
676 const confirmationResult = await settlePromise(() =>
677 localApi.dialogs.confirm(
678 [
679 `Delete thread "${title}"?`,
680 "This permanently clears conversation history for this thread.",
681 ].join("\n"),
682 { variant: "destructive" },
683 ),
684 );
685 if (confirmationResult._tag === "Failure") {
686 return confirmationResult;
687 }
688 if (!confirmationResult.value) {
689 return AsyncResult.success(undefined);
690 }
691 }
692​
693 return deleteThread(target);
694 },
695 [confirmThreadDelete, deleteThread, resolveThreadTarget],
696 );
697​
698 return useMemo(
699 () => ({
700 archiveThread,
701 unarchiveThread,
702 deleteThread,
703 confirmAndDeleteThread,
704 settleThread,
705 unsettleThread,
706 snoozeThread,
707 unsnoozeThread,
708 pinThread,
709 unpinThread,
710 reorderPinnedThread,
711 }),
712 [
713 archiveThread,
714 confirmAndDeleteThread,
715 deleteThread,
716 pinThread,
717 reorderPinnedThread,
718 settleThread,
719 snoozeThread,
720 unarchiveThread,
721 unpinThread,
722 unsettleThread,
723 unsnoozeThread,
724 ],
725 );