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