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

useThreadActions.ts

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