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