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