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

useThreadActions.ts

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