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