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

useThreadActions.ts

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