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

useThreadActions.ts

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