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