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

useThreadActions.ts

1,014 lines35.8 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 { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
10import {
11 AuthOrchestrationOperateScope,
12 AuthSourceControlWriteScope,
13 EnvironmentAuthorizationError,
14 EnvironmentId,
15 type ScopedThreadRef,
16 ThreadId,
17 sessionGrantsScope,
18} from "@t3tools/contracts";
19import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
20import * as Cause from "effect/Cause";
21import * as Schema from "effect/Schema";
22import { AsyncResult } from "effect/reactivity";
23import { useRouter } from "@tanstack/react-router";
24​
25import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic";
26import { useComposerDraftStore } from "../composerDraftStore";
27import { environmentSession, readEnvironmentScope } from "../state/session";
28import { appAtomRegistry } from "../rpc/atomRegistry";
29import { environmentServerConfigsAtom } from "../state/server";
30import { isScratchProject } from "@t3tools/client-runtime/state/projects";
31import { orchestrationEnvironment } from "../state/orchestration";
32import { projectEnvironment } from "../state/projects";
33import { threadEnvironment } from "../state/threads";
34import { vcsEnvironment } from "../state/vcs";
35import { useNewThreadHandler } from "./useHandleNewThread";
36import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
37import { releaseComposerDraftUploads } from "../lib/composerDraftUploads";
38import { readLocalApi } from "../localApi";
39import {
40 readEnvironmentServerConfigLoaded,
41 readEnvironmentSupportsAutoSettleOptOut,
42 readEnvironmentThreadRefs,
43 readProject,
44 readThreadShell,
45 readThreadShells,
46} from "../state/entities";
47import { useUiStateStore } from "../uiStateStore";
48import { useDiffPanelStore } from "../diffPanelStore";
49import { usePreviewMiniPlayerStore } from "../previewMiniPlayerStore";
50import { clearThreadPreviewState } from "../previewStateStore";
51import { useRightPanelStore } from "../rightPanelStore";
52import { useTerminalUiStateStore } from "../terminalUiStateStore";
53import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
54import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
55import { stackedThreadToast, toastManager } from "../components/ui/toast";
56import { useClientSettings } from "./useSettings";
57import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
58import { showThreadUndoNotice } from "./showThreadUndoNotice";
59import { useAtomCommand } from "../state/use-atom-command";
60import { useOrchestrationCommand } from "../state/use-orchestration-command";
61import { useAtomQueryRunner } from "../state/use-atom-query-runner";
62​
63export class ThreadArchiveBlockedError extends Schema.TaggedError<ThreadArchiveBlockedError>()(
64 "ThreadArchiveBlockedError",
65 {
66 environmentId: EnvironmentId,
67 threadId: ThreadId,
68 },
69) {
70 override get message(): string {
71 return "Cannot archive while the provider is active.";
72 }
74​
75export class ThreadSettlementUnsupportedError extends Schema.TaggedError<ThreadSettlementUnsupportedError>()(
76 "ThreadSettlementUnsupportedError",
77 {
78 environmentId: EnvironmentId,
79 threadId: ThreadId,
80 },
81) {
82 override get message(): string {
83 return "This environment's server does not support settling yet. Update the server to use Settle.";
84 }
86​
87export class ThreadSnoozeUnsupportedError extends Schema.TaggedError<ThreadSnoozeUnsupportedError>()(
88 "ThreadSnoozeUnsupportedError",
89 {
90 environmentId: EnvironmentId,
91 threadId: ThreadId,
92 },
93) {
94 override get message(): string {
95 return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
96 }
98​
99export class ThreadSnoozeBlockedError extends Schema.TaggedError<ThreadSnoozeBlockedError>()(
100 "ThreadSnoozeBlockedError",
101 {
102 environmentId: EnvironmentId,
103 threadId: ThreadId,
104 },
105) {
106 override get message(): string {
107 return "This thread is waiting on you. Respond to the pending request before snoozing it.";
108 }
110​
111function topOfPinnedRunOrderKey(): string | undefined {
112 let firstKey: string | null = null;
113 for (const shell of readThreadShells()) {
114 if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
115 if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
116 }
117 return pinOrderKeyBetween(null, firstKey) ?? undefined;
119​
120export class ThreadAutoSettleOptOutUnsupportedError extends Schema.TaggedError<ThreadAutoSettleOptOutUnsupportedError>()(
121 "ThreadAutoSettleOptOutUnsupportedError",
122 {
123 environmentId: EnvironmentId,
124 threadId: ThreadId,
125 },
126) {
127 override get message(): string {
128 return "This environment's server does not support turning auto-settle off per thread yet. Update the server to use it.";
129 }
131​
132export class ThreadPinningUnsupportedError extends Schema.TaggedError<ThreadPinningUnsupportedError>()(
133 "ThreadPinningUnsupportedError",
134 {
135 environmentId: EnvironmentId,
136 threadId: ThreadId,
137 },
138) {
139 override get message(): string {
140 return "This environment's server does not support pinning yet. Update the server to use Pin.";
141 }
143​
144export class ThreadPinReorderUnsupportedError extends Schema.TaggedError<ThreadPinReorderUnsupportedError>()(
145 "ThreadPinReorderUnsupportedError",
146 {
147 environmentId: EnvironmentId,
148 threadId: ThreadId,
149 },
150) {
151 override get message(): string {
152 return "This environment's server does not support reordering pinned threads yet. Update the server to reorder pins.";
153 }
155​
156export class ThreadActiveReorderUnsupportedError extends Schema.TaggedError<ThreadActiveReorderUnsupportedError>()(
157 "ThreadActiveReorderUnsupportedError",
158 {
159 environmentId: EnvironmentId,
160 threadId: ThreadId,
161 },
162) {
163 override get message(): string {
164 return "Update this environment's server to reorder active threads.";
165 }
167​
168async function requestThreadUnpinConfirmation(input: {
169 enabled: boolean;
170 title: string;
171 confirm: ((message: string) => Promise<boolean>) | null;
172}) {
173 const { confirm } = input;
174 if (!input.enabled || confirm === null) {
175 return AsyncResult.success(true);
176 }
177​
178 return settlePromise(() =>
179 confirm(
180 [
181 `Unpin thread "${input.title}"?`,
182 "This will move the thread out of your pinned section.",
183 ].join("\n"),
184 ),
185 );
187​
188export async function navigateAfterThreadDeletion(navigate: () => Promise<void>) {
189 const result = await settlePromise(navigate);
190 if (result._tag === "Failure") {
191 const error = squashAtomCommandFailure(result);
192 toastManager.add(
193 stackedThreadToast({
194 type: "error",
195 title: "Thread deleted, but navigation failed",
196 description: error instanceof Error ? error.message : "An error occurred.",
197 }),
198 );
199 }
201​
202function useMarkThreadUnread() {
203 const markThreadUnreadMutation = useAtomCommand(threadEnvironment.markUnread, {
204 reportFailure: false,
205 });
206 const markThreadUnreadLocal = useUiStateStore((state) => state.markThreadUnread);
207 return (target: ScopedThreadRef) => {
208 if (readEnvironmentServerConfigLoaded(target.environmentId)) {
209 void markThreadUnreadMutation({
210 environmentId: target.environmentId,
211 input: { threadId: target.threadId },
212 });
213 return;
214 }
215 const thread = readThreadShell(target);
216 markThreadUnreadLocal(scopedThreadKey(target), thread?.latestRun?.completedAt);
217 };
219​
220export function useAcknowledgeThreadWoke() {
221 const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
222 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
223 return (target: ScopedThreadRef, wokeAt: string) => {
224 if (readEnvironmentServerConfigLoaded(target.environmentId)) {
225 void visitThreadMutation({
226 environmentId: target.environmentId,
227 input: { threadId: target.threadId, visitedAt: wokeAt },
228 });
229 return;
230 }
231 markThreadVisited(scopedThreadKey(target), wokeAt);
232 };
234​
235// These Undos restore a thread's place in the list, which archiving or deleting it ends.
236const LIST_PLACEMENT_UNDO_KINDS = ["settle", "snooze", "pin"];
237​
238function expireThreadUndos(target: ScopedThreadRef, kinds: readonly string[]) {
239 for (const kind of kinds) ThreadUndo.invalidate(kind, scopedThreadKey(target));
241​
242function clearDeletedThreadPanelState(ref: ScopedThreadRef) {
243 clearThreadPreviewState(ref);
244 useRightPanelStore.getState().removeThread(ref);
245 useDiffPanelStore.getState().removeThread(ref);
246 usePreviewMiniPlayerStore.getState().removeThread(ref);
248​
249/** A No project thread that already has its own folder, on a server that can promote it. */
250export function canTurnThreadIntoProject(threadRef: ScopedThreadRef): boolean {
251 const thread = readThreadShell(threadRef);
252 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId);
253 if (!thread?.worktreePath || config?.environment.capabilities.threadProjectFromScratch !== true) {
254 return false;
255 }
256 const project = readProject({
257 environmentId: threadRef.environmentId,
258 projectId: thread.projectId,
259 });
260 return project !== null && isScratchProject(project, config.scratchWorkspaceRoot);
262​
263function threadOperationFailure(target: ScopedThreadRef) {
264 return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
265 ? null
266 : AsyncResult.failure(
267 Cause.fail(
268 new EnvironmentAuthorizationError({
269 message: "This connection cannot change threads.",
270 requiredScope: AuthOrchestrationOperateScope,
271 }),
272 ),
273 );
275​
276export function useThreadActions() {
277 const archiveThreadMutation = useOrchestrationCommand(threadEnvironment.archive, {
278 reportFailure: false,
279 });
280 const unarchiveThreadMutation = useOrchestrationCommand(threadEnvironment.unarchive, {
281 reportFailure: false,
282 });
283 const deleteThreadMutation = useOrchestrationCommand(threadEnvironment.delete, {
284 reportFailure: false,
285 });
286 const settleThreadMutation = useOrchestrationCommand(threadEnvironment.settle, {
287 reportFailure: false,
288 });
289 const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
290 reportFailure: false,
291 });
292 const pinThreadMutation = useOrchestrationCommand(threadEnvironment.pin, {
293 reportFailure: false,
294 });
295 const unpinThreadMutation = useOrchestrationCommand(threadEnvironment.unpin, {
296 reportFailure: false,
297 });
298 const setThreadAutoSettleMutation = useOrchestrationCommand(threadEnvironment.setAutoSettle, {
299 reportFailure: false,
300 });
301 const reorderPinnedThreadMutation = useOrchestrationCommand(threadEnvironment.reorderPin, {
302 reportFailure: false,
303 });
304 const reorderActiveThreadMutation = useOrchestrationCommand(threadEnvironment.reorderActive, {
305 reportFailure: false,
306 });
307 const snoozeThreadMutation = useOrchestrationCommand(threadEnvironment.snooze, {
308 reportFailure: false,
309 });
310 const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
311 reportFailure: false,
312 });
313 const markThreadUnread = useMarkThreadUnread();
314 const createProjectFromThread = useAtomCommand(projectEnvironment.createFromThread, {
315 reportFailure: false,
316 });
317 const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession);
318 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
319 reportFailure: false,
320 });
321 const loadSessionState = useAtomQueryRunner(environmentSession.sessionStateAtom, {
322 reportFailure: false,
323 });
324 const loadWorktreeThreadIds = useAtomQueryRunner(orchestrationEnvironment.worktreeThreadIds, {
325 reportFailure: false,
326 refresh: true,
327 });
328 const loadThreadFamily = useAtomQueryRunner(orchestrationEnvironment.threadFamily, {
329 reportFailure: false,
330 refresh: true,
331 });
332 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
333 reportFailure: false,
334 });
335 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
336 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
337 const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin);
338 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
339 const clearProjectDraftThreadById = useComposerDraftStore(
340 (store) => store.clearProjectDraftThreadById,
341 );
342 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
343 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
344 const router = useRouter();
345 const handleNewThread = useNewThreadHandler();
346​
347 const resolveThreadTarget = (target: ScopedThreadRef) => {
348 const thread = readThreadShell(target);
349 if (!thread) {
350 return null;
351 }
352 return {
353 thread,
354 threadRef: target,
355 };
356 };
357 const getCurrentRouteThreadRef = () => {
358 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
359 return resolveThreadRouteRef(currentRouteParams);
360 };
361​
362 const unarchiveThread = async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => {
363 ThreadUndo.invalidate("archive", scopedThreadKey(target));
364 const result = await unarchiveThreadMutation({
365 environmentId: target.environmentId,
366 input: { threadId: target.threadId },
367 });
368 if (result._tag === "Failure") {
369 return result;
370 }
371 refreshArchivedThreadsForEnvironment(target.environmentId);
372 if (opts.navigate) {
373 return settlePromise(() =>
374 router.navigate({
375 to: "/$environmentId/$threadId",
376 params: buildThreadRouteParams(target),
377 }),
378 );
379 }
380 return result;
381 };
382​
383 const archiveThread = async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
384 const resolved = resolveThreadTarget(target);
385 if (!resolved) return AsyncResult.success(undefined);
386 const { thread, threadRef } = resolved;
387 if (!threadRuntimeCanArchive(thread.runtime)) {
388 return AsyncResult.failure(
389 Cause.fail(
390 new ThreadArchiveBlockedError({
391 environmentId: threadRef.environmentId,
392 threadId: threadRef.threadId,
393 }),
394 ),
395 );
396 }
397​
398 const requestingRouteHref = router.state.location.href;
399 const currentRouteThreadRef = getCurrentRouteThreadRef();
400 const shouldNavigateToDraft =
401 currentRouteThreadRef?.threadId === threadRef.threadId &&
402 currentRouteThreadRef.environmentId === threadRef.environmentId;
403 const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef));
404 const archiveResult = await archiveThreadMutation({
405 environmentId: threadRef.environmentId,
406 input: { threadId: threadRef.threadId },
407 });
408 if (archiveResult._tag === "Failure") {
409 action.finish();
410 return archiveResult;
411 }
412 expireThreadUndos(threadRef, LIST_PLACEMENT_UNDO_KINDS);
413 const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
414 if (wokeAt !== null) {
415 markThreadVisited(scopedThreadKey(threadRef), wokeAt);
416 }
417 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
418 opts.onArchived?.();
419 showThreadUndoNotice({
420 action: "Archived",
421 claim: action,
422 undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }),
423 failureTitle: "Failed to undo archive",
424 });
425​
426 if (shouldNavigateToDraft && router.state.location.href === requestingRouteHref) {
427 const navigationResult = await settlePromise(() =>
428 handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId)),
429 );
430 if (navigationResult._tag === "Failure") {
431 return navigationResult;
432 }
433 return archiveResult;
434 }
435​
436 return archiveResult;
437 };
438​
439 const deleteThread = async (
440 target: ScopedThreadRef,
441 opts: { deletedThreadKeys?: ReadonlySet<string> } = {},
442 ) => {
443 const permissionFailure = threadOperationFailure(target);
444 if (permissionFailure) return permissionFailure;
445 const resolved = resolveThreadTarget(target);
446 if (!resolved) {
447 let threads = readEnvironmentThreadRefs(target.environmentId).flatMap((ref) => {
448 const shell = readThreadShell(ref);
449 return shell === null ? [] : [{ id: shell.id, lineage: shell.lineage }];
450 });
451 if (
452 appAtomRegistry.get(environmentServerConfigsAtom).get(target.environmentId)
453 ?.shellThreadFamilies
454 ) {
455 const family = await loadThreadFamily({
456 environmentId: target.environmentId,
457 input: { threadId: target.threadId },
458 });
459 if (family._tag === "Success") threads = [...family.value.threads];
460 }
461 const result = await deleteThreadMutation({
462 environmentId: target.environmentId,
463 input: { threadId: target.threadId },
464 });
465 if (result._tag === "Success") {
466 for (const ref of [
467 target,
468 ...threads
469 .filter(
470 (entry) =>
471 entry.lineage.sideChat === true && entry.lineage.parentThreadId === target.threadId,
472 )
473 .map((entry) => scopeThreadRef(target.environmentId, entry.id)),
474 ]) {
475 releaseComposerDraftUploads(ref);
476 clearComposerDraftForThread(ref);
477 }
478 expireThreadUndos(target, [...LIST_PLACEMENT_UNDO_KINDS, "archive"]);
479 refreshArchivedThreadsForEnvironment(target.environmentId);
480 clearTerminalUiState(target);
481 clearDeletedThreadPanelState(target);
482 }
483 return result;
484 }
485 const { thread, threadRef } = resolved;
486 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
487 const shell = readThreadShell(ref);
488 return shell === null ? [] : [shell];
489 });
490 const threadProject = readProject({
491 environmentId: threadRef.environmentId,
492 projectId: thread.projectId,
493 });
494 const deletedIds =
495 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
496 ? new Set<ThreadId>(
497 [...opts.deletedThreadKeys].flatMap((threadKey) => {
498 const ref = parseScopedThreadKey(threadKey);
499 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
500 }),
501 )
502 : undefined;
503 const survivingThreads =
504 deletedIds && deletedIds.size > 0
505 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
506 : threads;
507 const environmentConfig = appAtomRegistry
508 .get(environmentServerConfigsAtom)
509 .get(threadRef.environmentId);
510 let orphanedWorktreePath = getOrphanedWorktreePathForThread(
511 survivingThreads,
512 threadRef.threadId,
513 );
514 // A shell that leaves idle subagent children out cannot prove nobody else uses the worktree,
515 // so the server's list decides. A failed read keeps the worktree.
516 if (orphanedWorktreePath !== null && environmentConfig?.shellThreadFamilies === true) {
517 const occupants = await loadWorktreeThreadIds({
518 environmentId: threadRef.environmentId,
519 input: { worktreePath: orphanedWorktreePath },
520 });
521 if (
522 occupants._tag !== "Success" ||
523 occupants.value.threadIds.some(
524 (threadId) => threadId !== threadRef.threadId && deletedIds?.has(threadId) !== true,
525 )
526 ) {
527 orphanedWorktreePath = null;
528 }
529 }
530 const displayWorktreePath = orphanedWorktreePath
531 ? formatWorktreePathForDisplay(orphanedWorktreePath)
532 : null;
533 const localApi = readLocalApi();
534 let canDeleteWorktree = false;
535 if (
536 orphanedWorktreePath !== null &&
537 threadProject !== null &&
538 !isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot) &&
539 localApi
540 ) {
541 const sessionResult = await loadSessionState(threadRef.environmentId);
542 const permissionFailure = threadOperationFailure(threadRef);
543 if (permissionFailure) return permissionFailure;
544 canDeleteWorktree =
545 sessionResult._tag === "Success" &&
546 sessionGrantsScope(sessionResult.value, AuthSourceControlWriteScope);
547 }
548 let shouldDeleteWorktree = false;
549 const environmentSettings = environmentConfig?.settings;
550 const automaticWorktreeCleanup = environmentSettings
551 ? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete
552 : false;
553 if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) {
554 const confirmationResult = await settlePromise(() =>
555 localApi.dialogs.confirm(
556 [
557 "This thread is the only one linked to this worktree:",
558 displayWorktreePath ?? orphanedWorktreePath,
559 "",
560 "Delete the worktree too?",
561 ].join("\n"),
562 { variant: "destructive" },
563 ),
564 );
565 if (confirmationResult._tag === "Failure") {
566 return confirmationResult;
567 }
568 shouldDeleteWorktree = confirmationResult.value;
569 }
570​
571 if (thread.runtime !== null) {
572 await stopThreadSession({
573 environmentId: threadRef.environmentId,
574 input: { threadId: threadRef.threadId },
575 });
576 }
577​
578 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
579 const currentRouteThreadRef = getCurrentRouteThreadRef();
580 const shouldNavigateToFallback =
581 currentRouteThreadRef?.threadId === threadRef.threadId &&
582 currentRouteThreadRef.environmentId === threadRef.environmentId;
583 const fallbackThreadId = getFallbackThreadIdAfterDelete({
584 threads,
585 deletedThreadId: threadRef.threadId,
586 deletedThreadIds,
587 sortOrder: sidebarThreadSortOrder,
588 now: new Date().toISOString(),
589 });
590 const deleteResult = await deleteThreadMutation({
591 environmentId: threadRef.environmentId,
592 input: { threadId: threadRef.threadId },
593 });
594 if (deleteResult._tag === "Failure") {
595 return deleteResult;
596 }
597 expireThreadUndos(threadRef, [...LIST_PLACEMENT_UNDO_KINDS, "archive"]);
598 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
599 releaseComposerDraftUploads(threadRef);
600 clearComposerDraftForThread(threadRef);
601 // The server deletes the thread's side chats with it.
602 for (const entry of threads) {
603 if (entry.lineage.sideChat !== true || entry.lineage.parentThreadId !== threadRef.threadId) {
604 continue;
605 }
606 const sideChatRef = scopeThreadRef(threadRef.environmentId, entry.id);
607 releaseComposerDraftUploads(sideChatRef);
608 clearComposerDraftForThread(sideChatRef);
609 }
610 clearProjectDraftThreadById(
611 scopeProjectRef(threadRef.environmentId, thread.projectId),
612 threadRef,
613 );
614 clearTerminalUiState(threadRef);
615 clearDeletedThreadPanelState(threadRef);
616​
617 if (shouldNavigateToFallback) {
618 const fallbackThread = fallbackThreadId
619 ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId))
620 : null;
621 await navigateAfterThreadDeletion(() =>
622 fallbackThread
623 ? router.navigate({
624 to: "/$environmentId/$threadId",
625 params: buildThreadRouteParams(
626 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
627 ),
628 replace: true,
629 })
630 : router.navigate({ to: "/", replace: true }),
631 );
632 }
633​
634 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
635 return deleteResult;
636 }
637​
638 const removeResult = readEnvironmentScope(threadRef.environmentId, AuthSourceControlWriteScope)
639 ? await removeWorktree({
640 environmentId: threadRef.environmentId,
641 input: {
642 cwd: threadProject.workspaceRoot,
643 path: orphanedWorktreePath,
644 force: true,
645 },
646 })
647 : AsyncResult.failure(
648 Cause.fail(
649 new EnvironmentAuthorizationError({
650 message: "This connection can no longer remove worktrees.",
651 requiredScope: AuthSourceControlWriteScope,
652 }),
653 ),
654 );
655 const refreshResult =
656 removeResult._tag === "Success"
657 ? await refreshVcsStatus({
658 environmentId: threadRef.environmentId,
659 input: { cwd: threadProject.workspaceRoot },
660 })
661 : null;
662 const cleanupFailure =
663 removeResult._tag === "Failure"
664 ? removeResult
665 : refreshResult?._tag === "Failure"
666 ? refreshResult
667 : null;
668 if (cleanupFailure) {
669 const removalFailed = removeResult._tag === "Failure";
670 const error = squashAtomCommandFailure(cleanupFailure);
671 const message = error instanceof Error ? error.message : "An error occurred.";
672 console.error("Worktree cleanup failed after thread deletion", {
673 threadId: threadRef.threadId,
674 projectCwd: threadProject.workspaceRoot,
675 worktreePath: orphanedWorktreePath,
676 error,
677 });
678 toastManager.add(
679 stackedThreadToast({
680 type: "error",
681 title: removalFailed
682 ? "Failed to delete worktree"
683 : "Worktree deleted, but Git status refresh failed",
684 description: removalFailed
685 ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`
686 : message,
687 }),
688 );
689 // Cleanup has its own toast; reporting its failure would falsely imply deletion failed.
690 }
691 return deleteResult;
692 };
693​
694 const unsettleThread = async (target: ScopedThreadRef) => {
695 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
696 return AsyncResult.failure(
697 Cause.fail(
698 new ThreadSettlementUnsupportedError({
699 environmentId: target.environmentId,
700 threadId: target.threadId,
701 }),
702 ),
703 );
704 }
705 ThreadUndo.invalidate("settle", scopedThreadKey(target));
706 // reason "user" pins active until real activity, suppressing auto-settle.
707 return unsettleThreadMutation({
708 environmentId: target.environmentId,
709 input: { threadId: target.threadId, reason: "user" },
710 });
711 };
712​
713 const setThreadAutoSettle = async (target: ScopedThreadRef, enabled: boolean) => {
714 if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) {
715 return AsyncResult.failure(
716 Cause.fail(
717 new ThreadAutoSettleOptOutUnsupportedError({
718 environmentId: target.environmentId,
719 threadId: target.threadId,
720 }),
721 ),
722 );
723 }
724 return setThreadAutoSettleMutation({
725 environmentId: target.environmentId,
726 input: { threadId: target.threadId, enabled },
727 });
728 };
729​
730 const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
731 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
732 return AsyncResult.failure(
733 Cause.fail(
734 new ThreadPinningUnsupportedError({
735 environmentId: target.environmentId,
736 threadId: target.threadId,
737 }),
738 ),
739 );
740 }
741 const orderKey = opts.orderKey ?? topOfPinnedRunOrderKey();
742 ThreadUndo.invalidate("pin", scopedThreadKey(target));
743 // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
744 ThreadUndo.invalidate("settle", scopedThreadKey(target));
745 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
746 return pinThreadMutation({
747 environmentId: target.environmentId,
748 input: {
749 threadId: target.threadId,
750 ...(orderKey !== undefined ? { orderKey } : {}),
751 },
752 });
753 };
754​
755 const unpinThread = async (target: ScopedThreadRef) => {
756 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
757 return AsyncResult.failure(
758 Cause.fail(
759 new ThreadPinningUnsupportedError({
760 environmentId: target.environmentId,
761 threadId: target.threadId,
762 }),
763 ),
764 );
765 }
766 const thread = readThreadShell(target);
767 const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
768 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
769 const result = await unpinThreadMutation({
770 environmentId: target.environmentId,
771 input: { threadId: target.threadId },
772 });
773 if (result._tag === "Success" && action.isCurrent()) {
774 showThreadUndoNotice({
775 action: "Unpinned",
776 claim: action,
777 undo: () => runUndoPlan(target, undoPlan),
778 failureTitle: "Failed to undo unpin",
779 });
780 } else {
781 action.finish();
782 }
783 return result;
784 };
785​
786 const settleThread = async (target: ScopedThreadRef) => {
787 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
788 return AsyncResult.failure(
789 Cause.fail(
790 new ThreadSettlementUnsupportedError({
791 environmentId: target.environmentId,
792 threadId: target.threadId,
793 }),
794 ),
795 );
796 }
797 const resolved = resolveThreadTarget(target);
798 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
799 const nowIso = new Date().toISOString();
800 const wokeAt = resolved ? threadWokeAt(resolved.thread, { now: nowIso }) : null;
801 const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
802 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
803 // treats either as a promotion that un-settles; settling supersedes them.
804 ThreadUndo.invalidate("pin", scopedThreadKey(target));
805 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
806 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
807 const result = await settleThreadMutation({
808 environmentId: target.environmentId,
809 input: { threadId: target.threadId },
810 });
811 if (result._tag !== "Success") {
812 action.finish();
813 return result;
814 }
815 if (wokeAt !== null) {
816 markThreadVisited(scopedThreadKey(target), wokeAt);
817 }
818 showThreadUndoNotice({
819 action: "Settled",
820 claim: action,
821 undo: () => runUndoPlan(target, undoPlan),
822 failureTitle: "Failed to undo settle",
823 });
824 return result;
825 };
826​
827 const confirmAndUnpinThread = async (target: ScopedThreadRef) => {
828 const permissionFailure = threadOperationFailure(target);
829 if (permissionFailure) return permissionFailure;
830 const localApi = readLocalApi();
831 const resolved = resolveThreadTarget(target);
832 const confirmationResult = await requestThreadUnpinConfirmation({
833 enabled: confirmThreadUnpin,
834 title: resolved?.thread.title ?? "this thread",
835 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
836 });
837 if (confirmationResult._tag === "Failure") {
838 return confirmationResult;
839 }
840 if (!confirmationResult.value) {
841 return AsyncResult.success(undefined);
842 }
843 return unpinThread(target);
844 };
845​
846 const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => {
847 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
848 return AsyncResult.failure(
849 Cause.fail(
850 new ThreadPinReorderUnsupportedError({
851 environmentId: target.environmentId,
852 threadId: target.threadId,
853 }),
854 ),
855 );
856 }
857 ThreadUndo.invalidate("pin", scopedThreadKey(target));
858 return reorderPinnedThreadMutation({
859 environmentId: target.environmentId,
860 input: { threadId: target.threadId, orderKey },
861 });
862 };
863​
864 const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => {
865 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
866 return AsyncResult.failure(
867 Cause.fail(
868 new ThreadActiveReorderUnsupportedError({
869 environmentId: target.environmentId,
870 threadId: target.threadId,
871 }),
872 ),
873 );
874 }
875 return reorderActiveThreadMutation({
876 environmentId: target.environmentId,
877 input: { threadId: target.threadId, orderKey },
878 });
879 };
880​
881 const unsnoozeThread = async (target: ScopedThreadRef) => {
882 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
883 return AsyncResult.failure(
884 Cause.fail(
885 new ThreadSnoozeUnsupportedError({
886 environmentId: target.environmentId,
887 threadId: target.threadId,
888 }),
889 ),
890 );
891 }
892 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
893 return unsnoozeThreadMutation({
894 environmentId: target.environmentId,
895 input: { threadId: target.threadId, reason: "user" },
896 });
897 };
898​
899 const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => {
900 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
901 return AsyncResult.failure(
902 Cause.fail(
903 new ThreadSnoozeUnsupportedError({
904 environmentId: target.environmentId,
905 threadId: target.threadId,
906 }),
907 ),
908 );
909 }
910 const resolved = resolveThreadTarget(target);
911 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
912 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
913 return AsyncResult.failure(
914 Cause.fail(
915 new ThreadSnoozeBlockedError({
916 environmentId: resolved.threadRef.environmentId,
917 threadId: resolved.threadRef.threadId,
918 }),
919 ),
920 );
921 }
922 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
923 const result = await snoozeThreadMutation({
924 environmentId: target.environmentId,
925 input: { threadId: target.threadId, snoozedUntil },
926 });
927 if (result._tag !== "Success") {
928 action.finish();
929 return result;
930 }
931 showThreadUndoNotice({
932 action: "Snoozed",
933 claim: action,
934 undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
935 failureTitle: "Failed to wake thread",
936 });
937 return result;
938 };
939​
940 const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) =>
941 ThreadUndo.executeThreadUndo(
942 plan,
943 async (step) => {
944 switch (step.action) {
945 case "unsettle":
946 return unsettleThread(target);
947 case "unsnooze":
948 return unsnoozeThread(target);
949 case "pin":
950 return pinThread(
951 target,
952 step.orderKey === undefined ? {} : { orderKey: step.orderKey },
953 );
954 case "snooze":
955 return snoozeThreadMutation({
956 environmentId: target.environmentId,
957 input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
958 });
959 }
960 },
961 (result) => result._tag === "Success",
962 );
963​
964 const confirmAndDeleteThread = async (target: ScopedThreadRef, knownTitle?: string) => {
965 const permissionFailure = threadOperationFailure(target);
966 if (permissionFailure) return permissionFailure;
967 const localApi = readLocalApi();
968 const resolved = resolveThreadTarget(target);
969​
970 if (confirmThreadDelete && localApi) {
971 const title = resolved?.thread.title ?? knownTitle ?? "this thread";
972 const confirmationResult = await settlePromise(() =>
973 localApi.dialogs.confirm(
974 [
975 `Delete thread "${title}"?`,
976 "This permanently clears conversation history for this thread.",
977 ].join("\n"),
978 { variant: "destructive" },
979 ),
980 );
981 if (confirmationResult._tag === "Failure") {
982 return confirmationResult;
983 }
984 if (!confirmationResult.value) {
985 return AsyncResult.success(undefined);
986 }
987 }
988​
989 return deleteThread(target);
990 };
991​
992 return {
993 archiveThread,
994 unarchiveThread,
995 deleteThread,
996 confirmAndDeleteThread,
997 settleThread,
998 unsettleThread,
999 snoozeThread,
1000 unsnoozeThread,
1001 pinThread,
1002 unpinThread,
1003 confirmAndUnpinThread,
1004 reorderPinnedThread,
1005 reorderActiveThread,
1006 markThreadUnread,
1007 setThreadAutoSettle,
1008 turnThreadIntoProject: (target: ScopedThreadRef) =>
1009 createProjectFromThread({
1010 environmentId: target.environmentId,
1011 input: { threadId: target.threadId },
1012 }),
1013 };