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