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

useThreadActions.ts

941 lines33.1 KB

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