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