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