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

useThreadActions.ts

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