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

useThreadActions.ts

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