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

useThreadActions.ts

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