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

useThreadActions.ts

1,085 lines38.1 KB

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 }
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 }
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 }
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 }
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;
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 }
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 }
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 }
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 }
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 );
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 }
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 };
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 };
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));
268​
269function clearDeletedThreadPanelState(ref: ScopedThreadRef) {
270 clearThreadPreviewState(ref);
271 useRightPanelStore.getState().removeThread(ref);
272 useDiffPanelStore.getState().removeThread(ref);
273 usePreviewMiniPlayerStore.getState().removeThread(ref);
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);
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 );
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 } = {}) => {
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 = opts.orderKey ?? topOfPinnedRunOrderKey();
796 ThreadUndo.invalidate("pin", scopedThreadKey(target));
797 // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
798 ThreadUndo.invalidate("settle", scopedThreadKey(target));
799 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
800 return pinThreadMutation({
801 environmentId: target.environmentId,
802 input: {
803 threadId: target.threadId,
804 ...(orderKey !== undefined ? { orderKey } : {}),
805 },
806 });
807 };
808​
809 const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
810 const result = await sendPin(target, opts);
811 if (result._tag === "Success") announce(m(msg("Pinned 1 thread")));
812 return result;
813 };
814​
815 const unpinThread = async (target: ScopedThreadRef) => {
816 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
817 return AsyncResult.failure(
818 Cause.fail(
819 new ThreadPinningUnsupportedError({
820 environmentId: target.environmentId,
821 threadId: target.threadId,
822 }),
823 ),
824 );
825 }
826 const thread = readThreadShell(target);
827 const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
828 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
829 const result = await unpinThreadMutation({
830 environmentId: target.environmentId,
831 input: { threadId: target.threadId },
832 });
833 if (result._tag === "Success" && action.isCurrent()) {
834 showThreadUndoNotice({
835 action: "Unpinned",
836 claim: action,
837 undo: () => runUndoPlan(target, undoPlan),
838 failureTitle: m(msg("Failed to undo unpin")),
839 });
840 } else {
841 action.finish();
842 }
843 return result;
844 };
845​
846 const settleThread = async (target: ScopedThreadRef) => {
847 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
848 return AsyncResult.failure(
849 Cause.fail(
850 new ThreadSettlementUnsupportedError({
851 environmentId: target.environmentId,
852 threadId: target.threadId,
853 }),
854 ),
855 );
856 }
857 const resolved = resolveThreadTarget(target);
858 const nowIso = new Date().toISOString();
859 const wokeAt = resolved ? threadWokeAt(resolved.thread, { now: nowIso }) : null;
860 const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
861 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
862 // treats either as a promotion that un-settles; settling supersedes them.
863 ThreadUndo.invalidate("pin", scopedThreadKey(target));
864 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
865 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
866 const result = await settleThreadMutation({
867 environmentId: target.environmentId,
868 input: { threadId: target.threadId },
869 });
870 if (result._tag !== "Success") {
871 action.finish();
872 return result;
873 }
874 if (wokeAt !== null) {
875 markThreadVisited(scopedThreadKey(target), wokeAt);
876 }
877 showThreadUndoNotice({
878 action: "Settled",
879 claim: action,
880 undo: () => runUndoPlan(target, undoPlan),
881 failureTitle: m(msg("Failed to undo settle")),
882 });
883 return result;
884 };
885​
886 const confirmAndUnpinThread = async (target: ScopedThreadRef) => {
887 const permissionFailure = threadOperationFailure(target);
888 if (permissionFailure) return permissionFailure;
889 const localApi = readLocalApi();
890 const resolved = resolveThreadTarget(target);
891 const confirmationResult = await requestThreadUnpinConfirmation({
892 enabled: confirmThreadUnpin,
893 title: resolved?.thread.title ?? null,
894 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
895 });
896 if (confirmationResult._tag === "Failure") {
897 return confirmationResult;
898 }
899 if (!confirmationResult.value) {
900 return AsyncResult.success(undefined);
901 }
902 return unpinThread(target);
903 };
904​
905 const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => {
906 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
907 return AsyncResult.failure(
908 Cause.fail(
909 new ThreadPinReorderUnsupportedError({
910 environmentId: target.environmentId,
911 threadId: target.threadId,
912 }),
913 ),
914 );
915 }
916 ThreadUndo.invalidate("pin", scopedThreadKey(target));
917 return reorderPinnedThreadMutation({
918 environmentId: target.environmentId,
919 input: { threadId: target.threadId, orderKey },
920 });
921 };
922​
923 const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => {
924 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
925 return AsyncResult.failure(
926 Cause.fail(
927 new ThreadActiveReorderUnsupportedError({
928 environmentId: target.environmentId,
929 threadId: target.threadId,
930 }),
931 ),
932 );
933 }
934 return reorderActiveThreadMutation({
935 environmentId: target.environmentId,
936 input: { threadId: target.threadId, orderKey },
937 });
938 };
939​
940 const unsnoozeThread = async (target: ScopedThreadRef) => {
941 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
942 return AsyncResult.failure(
943 Cause.fail(
944 new ThreadSnoozeUnsupportedError({
945 environmentId: target.environmentId,
946 threadId: target.threadId,
947 }),
948 ),
949 );
950 }
951 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
952 return unsnoozeThreadMutation({
953 environmentId: target.environmentId,
954 input: { threadId: target.threadId, reason: "user" },
955 });
956 };
957​
958 const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => {
959 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
960 return AsyncResult.failure(
961 Cause.fail(
962 new ThreadSnoozeUnsupportedError({
963 environmentId: target.environmentId,
964 threadId: target.threadId,
965 }),
966 ),
967 );
968 }
969 const resolved = resolveThreadTarget(target);
970 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
971 return AsyncResult.failure(
972 Cause.fail(
973 new ThreadSnoozeBlockedError({
974 environmentId: resolved.threadRef.environmentId,
975 threadId: resolved.threadRef.threadId,
976 }),
977 ),
978 );
979 }
980 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
981 const result = await snoozeThreadMutation({
982 environmentId: target.environmentId,
983 input: { threadId: target.threadId, snoozedUntil },
984 });
985 if (result._tag !== "Success") {
986 action.finish();
987 return result;
988 }
989 showThreadUndoNotice({
990 action: "Snoozed",
991 claim: action,
992 undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
993 failureTitle: m(msg("Failed to wake thread")),
994 });
995 return result;
996 };
997​
998 const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) => {
999 let cancelledOnDevice = false;
1000 return ThreadUndo.executeThreadUndo(
1001 plan,
1002 async (step) => {
1003 if (
1004 cancelledOnDevice &&
1005 !ThreadUndo.restoresAfterDeviceCancel(step, readThreadShell(target))
1006 ) {
1007 return AsyncResult.success(undefined);
1009 switch (step.action) {
1010 case "unsettle": {
1011 const result = await unsettleThread(target, step.restoreUnsettledAt);
1012 cancelledOnDevice =
1013 result._tag === "Success" && ThreadUndo.cancelledOnDevice(result.value);
1014 return result;
1016 case "unsnooze":
1017 return unsnoozeThread(target);
1018 case "pin":
1019 return sendPin(target, step.orderKey === undefined ? {} : { orderKey: step.orderKey });
1020 case "reorderActive":
1021 return reorderActiveThread(target, step.orderKey);
1022 case "snooze":
1023 return snoozeThreadMutation({
1024 environmentId: target.environmentId,
1025 input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
1026 });
1028 },
1029 (result) => result._tag === "Success",
1030 );
1031 };
1032​
1033 const confirmAndDeleteThread = async (target: ScopedThreadRef, knownTitle?: string) => {
1034 const permissionFailure = threadOperationFailure(target);
1035 if (permissionFailure) return permissionFailure;
1036 const localApi = readLocalApi();
1037 const resolved = resolveThreadTarget(target);
1038​
1039 if (confirmThreadDelete && localApi) {
1040 const title = resolved?.thread.title ?? knownTitle ?? null;
1041 const confirmationResult = await settlePromise(() =>
1042 localApi.dialogs.confirm(
1044 title === null
1045 ? m(msg('Delete thread "this thread"?'))
1046 : m(msg`Delete thread "${{ title }}"?`),
1047 m(msg("This permanently clears conversation history for this thread.")),
1048 ].join("\n"),
1049 { variant: "destructive" },
1050 ),
1051 );
1052 if (confirmationResult._tag === "Failure") {
1053 return confirmationResult;
1055 if (!confirmationResult.value) {
1056 return AsyncResult.success(undefined);
1059​
1060 return deleteThread(target);
1061 };
1062​
1063 return {
1064 archiveThread,
1065 unarchiveThread,
1066 deleteThread,
1067 confirmAndDeleteThread,
1068 settleThread,
1069 unsettleThread,
1070 snoozeThread,
1071 unsnoozeThread,
1072 pinThread,
1073 unpinThread,
1074 confirmAndUnpinThread,
1075 reorderPinnedThread,
1076 reorderActiveThread,
1077 markThreadUnread,
1078 setThreadAutoSettle,
1079 turnThreadIntoProject: (target: ScopedThreadRef) =>
1080 createProjectFromThread({
1081 environmentId: target.environmentId,
1082 input: { threadId: target.threadId },
1083 }),
1084 };