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

useThreadActions.ts

1,047 lines37.5 KB

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