Open History to see the last commit
1import {
2 parseScopedThreadKey,
3 scopeProjectRef,
4 scopeThreadRef,
5 scopedThreadKey,
6} from "@t3tools/client-runtime/environment";
7import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
9import { 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 }
73}
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 }
85}
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 }
97}
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 }
109}
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;
118}
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 }
130}
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 }
142}
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 }
154}
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 }
166}
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 );
186}
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 }
200}
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 };
218}
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 };
233}
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));
240}
241
242function clearDeletedThreadPanelState(ref: ScopedThreadRef) {
243 clearThreadPreviewState(ref);
244 useRightPanelStore.getState().removeThread(ref);
245 useDiffPanelStore.getState().removeThread(ref);
246 usePreviewMiniPlayerStore.getState().removeThread(ref);
247}
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);
261}
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 );
274}
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 refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
329 reportFailure: false,
330 });
331 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
332 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
333 const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin);
334 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
335 const clearProjectDraftThreadById = useComposerDraftStore(
336 (store) => store.clearProjectDraftThreadById,
337 );
338 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
339 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
340 const router = useRouter();
341 const handleNewThread = useNewThreadHandler();
342
343 const resolveThreadTarget = (target: ScopedThreadRef) => {
344 const thread = readThreadShell(target);
345 if (!thread) {
346 return null;
347 }
348 return {
349 thread,
350 threadRef: target,
351 };
352 };
353 const getCurrentRouteThreadRef = () => {
354 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
355 return resolveThreadRouteRef(currentRouteParams);
356 };
357
358 const unarchiveThread = async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => {
359 ThreadUndo.invalidate("archive", scopedThreadKey(target));
360 const result = await unarchiveThreadMutation({
361 environmentId: target.environmentId,
362 input: { threadId: target.threadId },
363 });
364 if (result._tag === "Failure") {
365 return result;
366 }
367 refreshArchivedThreadsForEnvironment(target.environmentId);
368 if (opts.navigate) {
369 return settlePromise(() =>
370 router.navigate({
371 to: "/$environmentId/$threadId",
372 params: buildThreadRouteParams(target),
373 }),
374 );
375 }
376 return result;
377 };
378
379 const archiveThread = async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
380 const resolved = resolveThreadTarget(target);
381 if (!resolved) return AsyncResult.success(undefined);
382 const { thread, threadRef } = resolved;
383 if (!threadRuntimeCanArchive(thread.runtime)) {
384 return AsyncResult.failure(
385 Cause.fail(
386 new ThreadArchiveBlockedError({
387 environmentId: threadRef.environmentId,
388 threadId: threadRef.threadId,
389 }),
390 ),
391 );
392 }
393
394 const requestingRouteHref = router.state.location.href;
395 const currentRouteThreadRef = getCurrentRouteThreadRef();
396 const shouldNavigateToDraft =
397 currentRouteThreadRef?.threadId === threadRef.threadId &&
398 currentRouteThreadRef.environmentId === threadRef.environmentId;
399 const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef));
400 const archiveResult = await archiveThreadMutation({
401 environmentId: threadRef.environmentId,
402 input: { threadId: threadRef.threadId },
403 });
404 if (archiveResult._tag === "Failure") {
405 action.finish();
406 return archiveResult;
407 }
408 expireThreadUndos(threadRef, LIST_PLACEMENT_UNDO_KINDS);
409 const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
410 if (wokeAt !== null) {
411 markThreadVisited(scopedThreadKey(threadRef), wokeAt);
412 }
413 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
414 opts.onArchived?.();
415 showThreadUndoNotice({
416 action: "Archived",
417 claim: action,
418 undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }),
419 failureTitle: "Failed to undo archive",
420 });
421
422 if (shouldNavigateToDraft && router.state.location.href === requestingRouteHref) {
423 const navigationResult = await settlePromise(() =>
424 handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId)),
425 );
426 if (navigationResult._tag === "Failure") {
427 return navigationResult;
428 }
429 return archiveResult;
430 }
431
432 return archiveResult;
433 };
434
435 const deleteThread = async (
436 target: ScopedThreadRef,
437 opts: { deletedThreadKeys?: ReadonlySet<string> } = {},
438 ) => {
439 const permissionFailure = threadOperationFailure(target);
440 if (permissionFailure) return permissionFailure;
441 const resolved = resolveThreadTarget(target);
442 if (!resolved) {
443 const result = await deleteThreadMutation({
444 environmentId: target.environmentId,
445 input: { threadId: target.threadId },
446 });
447 if (result._tag === "Success") {
448 expireThreadUndos(target, [...LIST_PLACEMENT_UNDO_KINDS, "archive"]);
449 refreshArchivedThreadsForEnvironment(target.environmentId);
450 clearDeletedThreadPanelState(target);
451 }
452 return result;
453 }
454 const { thread, threadRef } = resolved;
455 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
456 const shell = readThreadShell(ref);
457 return shell === null ? [] : [shell];
458 });
459 const threadProject = readProject({
460 environmentId: threadRef.environmentId,
461 projectId: thread.projectId,
462 });
463 const deletedIds =
464 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
465 ? new Set<ThreadId>(
466 [...opts.deletedThreadKeys].flatMap((threadKey) => {
467 const ref = parseScopedThreadKey(threadKey);
468 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
469 }),
470 )
471 : undefined;
472 const survivingThreads =
473 deletedIds && deletedIds.size > 0
474 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
475 : threads;
476 const environmentConfig = appAtomRegistry
477 .get(environmentServerConfigsAtom)
478 .get(threadRef.environmentId);
479 let orphanedWorktreePath = getOrphanedWorktreePathForThread(
480 survivingThreads,
481 threadRef.threadId,
482 );
483 // A shell that leaves idle subagent children out cannot prove nobody else uses the worktree,
484 // so the server's list decides. A failed read keeps the worktree.
485 if (orphanedWorktreePath !== null && environmentConfig?.shellThreadFamilies === true) {
486 const occupants = await loadWorktreeThreadIds({
487 environmentId: threadRef.environmentId,
488 input: { worktreePath: orphanedWorktreePath },
489 });
490 if (
491 occupants._tag !== "Success" ||
492 occupants.value.threadIds.some(
493 (threadId) => threadId !== threadRef.threadId && deletedIds?.has(threadId) !== true,
494 )
495 ) {
496 orphanedWorktreePath = null;
497 }
498 }
499 const displayWorktreePath = orphanedWorktreePath
500 ? formatWorktreePathForDisplay(orphanedWorktreePath)
501 : null;
502 const localApi = readLocalApi();
503 let canDeleteWorktree = false;
504 if (
505 orphanedWorktreePath !== null &&
506 threadProject !== null &&
507 !isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot) &&
508 localApi
509 ) {
510 const sessionResult = await loadSessionState(threadRef.environmentId);
511 const permissionFailure = threadOperationFailure(threadRef);
512 if (permissionFailure) return permissionFailure;
513 canDeleteWorktree =
514 sessionResult._tag === "Success" &&
515 sessionGrantsScope(sessionResult.value, AuthSourceControlWriteScope);
516 }
517 let shouldDeleteWorktree = false;
518 const environmentSettings = environmentConfig?.settings;
519 const automaticWorktreeCleanup = environmentSettings
520 ? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete
521 : false;
522 if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) {
523 const confirmationResult = await settlePromise(() =>
524 localApi.dialogs.confirm(
525 [
526 "This thread is the only one linked to this worktree:",
527 displayWorktreePath ?? orphanedWorktreePath,
528 "",
529 "Delete the worktree too?",
530 ].join("\n"),
531 { variant: "destructive" },
532 ),
533 );
534 if (confirmationResult._tag === "Failure") {
535 return confirmationResult;
536 }
537 shouldDeleteWorktree = confirmationResult.value;
538 }
539
540 if (thread.runtime !== null) {
541 await stopThreadSession({
542 environmentId: threadRef.environmentId,
543 input: { threadId: threadRef.threadId },
544 });
545 }
546
547 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
548 const currentRouteThreadRef = getCurrentRouteThreadRef();
549 const shouldNavigateToFallback =
550 currentRouteThreadRef?.threadId === threadRef.threadId &&
551 currentRouteThreadRef.environmentId === threadRef.environmentId;
552 const fallbackThreadId = getFallbackThreadIdAfterDelete({
553 threads,
554 deletedThreadId: threadRef.threadId,
555 deletedThreadIds,
556 sortOrder: sidebarThreadSortOrder,
557 now: new Date().toISOString(),
558 });
559 const deleteResult = await deleteThreadMutation({
560 environmentId: threadRef.environmentId,
561 input: { threadId: threadRef.threadId },
562 });
563 if (deleteResult._tag === "Failure") {
564 return deleteResult;
565 }
566 expireThreadUndos(threadRef, [...LIST_PLACEMENT_UNDO_KINDS, "archive"]);
567 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
568 releaseComposerDraftUploads(threadRef);
569 clearComposerDraftForThread(threadRef);
570 clearProjectDraftThreadById(
571 scopeProjectRef(threadRef.environmentId, thread.projectId),
572 threadRef,
573 );
574 clearTerminalUiState(threadRef);
575 clearDeletedThreadPanelState(threadRef);
576
577 if (shouldNavigateToFallback) {
578 const fallbackThread = fallbackThreadId
579 ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId))
580 : null;
581 await navigateAfterThreadDeletion(() =>
582 fallbackThread
583 ? router.navigate({
584 to: "/$environmentId/$threadId",
585 params: buildThreadRouteParams(
586 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
587 ),
588 replace: true,
589 })
590 : router.navigate({ to: "/", replace: true }),
591 );
592 }
593
594 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
595 return deleteResult;
596 }
597
598 const removeResult = readEnvironmentScope(threadRef.environmentId, AuthSourceControlWriteScope)
599 ? await removeWorktree({
600 environmentId: threadRef.environmentId,
601 input: {
602 cwd: threadProject.workspaceRoot,
603 path: orphanedWorktreePath,
604 force: true,
605 },
606 })
607 : AsyncResult.failure(
608 Cause.fail(
609 new EnvironmentAuthorizationError({
610 message: "This connection can no longer remove worktrees.",
611 requiredScope: AuthSourceControlWriteScope,
612 }),
613 ),
614 );
615 const refreshResult =
616 removeResult._tag === "Success"
617 ? await refreshVcsStatus({
618 environmentId: threadRef.environmentId,
619 input: { cwd: threadProject.workspaceRoot },
620 })
621 : null;
622 const cleanupFailure =
623 removeResult._tag === "Failure"
624 ? removeResult
625 : refreshResult?._tag === "Failure"
626 ? refreshResult
627 : null;
628 if (cleanupFailure) {
629 const removalFailed = removeResult._tag === "Failure";
630 const error = squashAtomCommandFailure(cleanupFailure);
631 const message = error instanceof Error ? error.message : "An error occurred.";
632 console.error("Worktree cleanup failed after thread deletion", {
633 threadId: threadRef.threadId,
634 projectCwd: threadProject.workspaceRoot,
635 worktreePath: orphanedWorktreePath,
636 error,
637 });
638 toastManager.add(
639 stackedThreadToast({
640 type: "error",
641 title: removalFailed
642 ? "Failed to delete worktree"
643 : "Worktree deleted, but Git status refresh failed",
644 description: removalFailed
645 ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`
646 : message,
647 }),
648 );
649 // Cleanup has its own toast; reporting its failure would falsely imply deletion failed.
650 }
651 return deleteResult;
652 };
653
654 const unsettleThread = async (target: ScopedThreadRef) => {
655 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
656 return AsyncResult.failure(
657 Cause.fail(
658 new ThreadSettlementUnsupportedError({
659 environmentId: target.environmentId,
660 threadId: target.threadId,
661 }),
662 ),
663 );
664 }
665 ThreadUndo.invalidate("settle", scopedThreadKey(target));
666 // reason "user" pins active until real activity, suppressing auto-settle.
667 return unsettleThreadMutation({
668 environmentId: target.environmentId,
669 input: { threadId: target.threadId, reason: "user" },
670 });
671 };
672
673 const setThreadAutoSettle = async (target: ScopedThreadRef, enabled: boolean) => {
674 if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) {
675 return AsyncResult.failure(
676 Cause.fail(
677 new ThreadAutoSettleOptOutUnsupportedError({
678 environmentId: target.environmentId,
679 threadId: target.threadId,
680 }),
681 ),
682 );
683 }
684 return setThreadAutoSettleMutation({
685 environmentId: target.environmentId,
686 input: { threadId: target.threadId, enabled },
687 });
688 };
689
690 const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
691 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
692 return AsyncResult.failure(
693 Cause.fail(
694 new ThreadPinningUnsupportedError({
695 environmentId: target.environmentId,
696 threadId: target.threadId,
697 }),
698 ),
699 );
700 }
701 const orderKey = opts.orderKey ?? topOfPinnedRunOrderKey();
702 ThreadUndo.invalidate("pin", scopedThreadKey(target));
703 // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
704 ThreadUndo.invalidate("settle", scopedThreadKey(target));
705 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
706 return pinThreadMutation({
707 environmentId: target.environmentId,
708 input: {
709 threadId: target.threadId,
710 ...(orderKey !== undefined ? { orderKey } : {}),
711 },
712 });
713 };
714
715 const unpinThread = async (target: ScopedThreadRef) => {
716 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
717 return AsyncResult.failure(
718 Cause.fail(
719 new ThreadPinningUnsupportedError({
720 environmentId: target.environmentId,
721 threadId: target.threadId,
722 }),
723 ),
724 );
725 }
726 const thread = readThreadShell(target);
727 const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
728 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
729 const result = await unpinThreadMutation({
730 environmentId: target.environmentId,
731 input: { threadId: target.threadId },
732 });
733 if (result._tag === "Success" && action.isCurrent()) {
734 showThreadUndoNotice({
735 action: "Unpinned",
736 claim: action,
737 undo: () => runUndoPlan(target, undoPlan),
738 failureTitle: "Failed to undo unpin",
739 });
740 } else {
741 action.finish();
742 }
743 return result;
744 };
745
746 const settleThread = async (target: ScopedThreadRef) => {
747 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
748 return AsyncResult.failure(
749 Cause.fail(
750 new ThreadSettlementUnsupportedError({
751 environmentId: target.environmentId,
752 threadId: target.threadId,
753 }),
754 ),
755 );
756 }
757 const resolved = resolveThreadTarget(target);
758 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
759 const nowIso = new Date().toISOString();
760 const wokeAt = resolved ? threadWokeAt(resolved.thread, { now: nowIso }) : null;
761 const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
762 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
763 // treats either as a promotion that un-settles; settling supersedes them.
764 ThreadUndo.invalidate("pin", scopedThreadKey(target));
765 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
766 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
767 const result = await settleThreadMutation({
768 environmentId: target.environmentId,
769 input: { threadId: target.threadId },
770 });
771 if (result._tag !== "Success") {
772 action.finish();
773 return result;
774 }
775 if (wokeAt !== null) {
776 markThreadVisited(scopedThreadKey(target), wokeAt);
777 }
778 showThreadUndoNotice({
779 action: "Settled",
780 claim: action,
781 undo: () => runUndoPlan(target, undoPlan),
782 failureTitle: "Failed to undo settle",
783 });
784 return result;
785 };
786
787 const confirmAndUnpinThread = async (target: ScopedThreadRef) => {
788 const permissionFailure = threadOperationFailure(target);
789 if (permissionFailure) return permissionFailure;
790 const localApi = readLocalApi();
791 const resolved = resolveThreadTarget(target);
792 const confirmationResult = await requestThreadUnpinConfirmation({
793 enabled: confirmThreadUnpin,
794 title: resolved?.thread.title ?? "this thread",
795 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
796 });
797 if (confirmationResult._tag === "Failure") {
798 return confirmationResult;
799 }
800 if (!confirmationResult.value) {
801 return AsyncResult.success(undefined);
802 }
803 return unpinThread(target);
804 };
805
806 const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => {
807 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
808 return AsyncResult.failure(
809 Cause.fail(
810 new ThreadPinReorderUnsupportedError({
811 environmentId: target.environmentId,
812 threadId: target.threadId,
813 }),
814 ),
815 );
816 }
817 ThreadUndo.invalidate("pin", scopedThreadKey(target));
818 return reorderPinnedThreadMutation({
819 environmentId: target.environmentId,
820 input: { threadId: target.threadId, orderKey },
821 });
822 };
823
824 const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => {
825 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
826 return AsyncResult.failure(
827 Cause.fail(
828 new ThreadActiveReorderUnsupportedError({
829 environmentId: target.environmentId,
830 threadId: target.threadId,
831 }),
832 ),
833 );
834 }
835 return reorderActiveThreadMutation({
836 environmentId: target.environmentId,
837 input: { threadId: target.threadId, orderKey },
838 });
839 };
840
841 const unsnoozeThread = async (target: ScopedThreadRef) => {
842 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
843 return AsyncResult.failure(
844 Cause.fail(
845 new ThreadSnoozeUnsupportedError({
846 environmentId: target.environmentId,
847 threadId: target.threadId,
848 }),
849 ),
850 );
851 }
852 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
853 return unsnoozeThreadMutation({
854 environmentId: target.environmentId,
855 input: { threadId: target.threadId, reason: "user" },
856 });
857 };
858
859 const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => {
860 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
861 return AsyncResult.failure(
862 Cause.fail(
863 new ThreadSnoozeUnsupportedError({
864 environmentId: target.environmentId,
865 threadId: target.threadId,
866 }),
867 ),
868 );
869 }
870 const resolved = resolveThreadTarget(target);
871 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
872 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
873 return AsyncResult.failure(
874 Cause.fail(
875 new ThreadSnoozeBlockedError({
876 environmentId: resolved.threadRef.environmentId,
877 threadId: resolved.threadRef.threadId,
878 }),
879 ),
880 );
881 }
882 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
883 const result = await snoozeThreadMutation({
884 environmentId: target.environmentId,
885 input: { threadId: target.threadId, snoozedUntil },
886 });
887 if (result._tag !== "Success") {
888 action.finish();
889 return result;
890 }
891 showThreadUndoNotice({
892 action: "Snoozed",
893 claim: action,
894 undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
895 failureTitle: "Failed to wake thread",
896 });
897 return result;
898 };
899
900 const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) =>
901 ThreadUndo.executeThreadUndo(
902 plan,
903 async (step) => {
904 switch (step.action) {
905 case "unsettle":
906 return unsettleThread(target);
907 case "unsnooze":
908 return unsnoozeThread(target);
909 case "pin":
910 return pinThread(
911 target,
912 step.orderKey === undefined ? {} : { orderKey: step.orderKey },
913 );
914 case "snooze":
915 return snoozeThreadMutation({
916 environmentId: target.environmentId,
917 input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
918 });
919 }
920 },
921 (result) => result._tag === "Success",
922 );
923
924 const confirmAndDeleteThread = async (target: ScopedThreadRef) => {
925 const permissionFailure = threadOperationFailure(target);
926 if (permissionFailure) return permissionFailure;
927 const localApi = readLocalApi();
928 const resolved = resolveThreadTarget(target);
929
930 if (confirmThreadDelete && localApi) {
931 const title = resolved?.thread.title ?? "this thread";
932 const confirmationResult = await settlePromise(() =>
933 localApi.dialogs.confirm(
934 [
935 `Delete thread "${title}"?`,
936 "This permanently clears conversation history for this thread.",
937 ].join("\n"),
938 { variant: "destructive" },
939 ),
940 );
941 if (confirmationResult._tag === "Failure") {
942 return confirmationResult;
943 }
944 if (!confirmationResult.value) {
945 return AsyncResult.success(undefined);
946 }
947 }
948
949 return deleteThread(target);
950 };
951
952 return {
953 archiveThread,
954 unarchiveThread,
955 deleteThread,
956 confirmAndDeleteThread,
957 settleThread,
958 unsettleThread,
959 snoozeThread,
960 unsnoozeThread,
961 pinThread,
962 unpinThread,
963 confirmAndUnpinThread,
964 reorderPinnedThread,
965 reorderActiveThread,
966 markThreadUnread,
967 setThreadAutoSettle,
968 turnThreadIntoProject: (target: ScopedThreadRef) =>
969 createProjectFromThread({
970 environmentId: target.environmentId,
971 input: { threadId: target.threadId },
972 }),
973 };
974}