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

useThreadActions.ts

1,083 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}"?', { 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}. {message}", {
735 path: displayWorktreePath ?? orphanedWorktreePath,
736 message,
737 }),
738 )
739 : message,
740 }),
741 );
742 // Cleanup has its own toast; reporting its failure would falsely imply deletion failed.
743 }
744 return deleteResult;
745 };
746​
747 const unsettleThread = async (target: ScopedThreadRef, restoreUnsettledAt?: string | null) => {
748 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
749 return AsyncResult.failure(
750 Cause.fail(
751 new ThreadSettlementUnsupportedError({
752 environmentId: target.environmentId,
753 threadId: target.threadId,
754 }),
755 ),
756 );
757 }
758 ThreadUndo.invalidate("settle", scopedThreadKey(target));
759 // reason "user" pins active until real activity, suppressing auto-settle.
760 return unsettleThreadMutation({
761 environmentId: target.environmentId,
762 input: {
763 threadId: target.threadId,
764 reason: "user",
765 ...(restoreUnsettledAt === undefined ? {} : { restoreUnsettledAt }),
766 },
767 });
768 };
769​
770 const setThreadAutoSettle = async (target: ScopedThreadRef, enabled: boolean) => {
771 if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) {
772 return AsyncResult.failure(
773 Cause.fail(
774 new ThreadAutoSettleOptOutUnsupportedError({
775 environmentId: target.environmentId,
776 threadId: target.threadId,
777 }),
778 ),
779 );
780 }
781 return setThreadAutoSettleMutation({
782 environmentId: target.environmentId,
783 input: { threadId: target.threadId, enabled },
784 });
785 };
786​
787 const sendPin = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
788 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
789 return AsyncResult.failure(
790 Cause.fail(
791 new ThreadPinningUnsupportedError({
792 environmentId: target.environmentId,
793 threadId: target.threadId,
794 }),
795 ),
796 );
797 }
798 const orderKey = opts.orderKey ?? topOfPinnedRunOrderKey();
799 ThreadUndo.invalidate("pin", scopedThreadKey(target));
800 // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
801 ThreadUndo.invalidate("settle", scopedThreadKey(target));
802 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
803 return pinThreadMutation({
804 environmentId: target.environmentId,
805 input: {
806 threadId: target.threadId,
807 ...(orderKey !== undefined ? { orderKey } : {}),
808 },
809 });
810 };
811​
812 const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
813 const result = await sendPin(target, opts);
814 if (result._tag === "Success") announce(m(msg("Pinned 1 thread")));
815 return result;
816 };
817​
818 const unpinThread = async (target: ScopedThreadRef) => {
819 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
820 return AsyncResult.failure(
821 Cause.fail(
822 new ThreadPinningUnsupportedError({
823 environmentId: target.environmentId,
824 threadId: target.threadId,
825 }),
826 ),
827 );
828 }
829 const thread = readThreadShell(target);
830 const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
831 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
832 const result = await unpinThreadMutation({
833 environmentId: target.environmentId,
834 input: { threadId: target.threadId },
835 });
836 if (result._tag === "Success" && action.isCurrent()) {
837 showThreadUndoNotice({
838 action: "Unpinned",
839 claim: action,
840 undo: () => runUndoPlan(target, undoPlan),
841 failureTitle: m(msg("Failed to undo unpin")),
842 });
843 } else {
844 action.finish();
845 }
846 return result;
847 };
848​
849 const settleThread = async (target: ScopedThreadRef) => {
850 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
851 return AsyncResult.failure(
852 Cause.fail(
853 new ThreadSettlementUnsupportedError({
854 environmentId: target.environmentId,
855 threadId: target.threadId,
856 }),
857 ),
858 );
859 }
860 const resolved = resolveThreadTarget(target);
861 const nowIso = new Date().toISOString();
862 const wokeAt = resolved ? threadWokeAt(resolved.thread, { now: nowIso }) : null;
863 const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
864 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
865 // treats either as a promotion that un-settles; settling supersedes them.
866 ThreadUndo.invalidate("pin", scopedThreadKey(target));
867 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
868 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
869 const result = await settleThreadMutation({
870 environmentId: target.environmentId,
871 input: { threadId: target.threadId },
872 });
873 if (result._tag !== "Success") {
874 action.finish();
875 return result;
876 }
877 if (wokeAt !== null) {
878 markThreadVisited(scopedThreadKey(target), wokeAt);
879 }
880 showThreadUndoNotice({
881 action: "Settled",
882 claim: action,
883 undo: () => runUndoPlan(target, undoPlan),
884 failureTitle: m(msg("Failed to undo settle")),
885 });
886 return result;
887 };
888​
889 const confirmAndUnpinThread = async (target: ScopedThreadRef) => {
890 const permissionFailure = threadOperationFailure(target);
891 if (permissionFailure) return permissionFailure;
892 const localApi = readLocalApi();
893 const resolved = resolveThreadTarget(target);
894 const confirmationResult = await requestThreadUnpinConfirmation({
895 enabled: confirmThreadUnpin,
896 title: resolved?.thread.title ?? null,
897 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
898 });
899 if (confirmationResult._tag === "Failure") {
900 return confirmationResult;
901 }
902 if (!confirmationResult.value) {
903 return AsyncResult.success(undefined);
904 }
905 return unpinThread(target);
906 };
907​
908 const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => {
909 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
910 return AsyncResult.failure(
911 Cause.fail(
912 new ThreadPinReorderUnsupportedError({
913 environmentId: target.environmentId,
914 threadId: target.threadId,
915 }),
916 ),
917 );
918 }
919 ThreadUndo.invalidate("pin", scopedThreadKey(target));
920 return reorderPinnedThreadMutation({
921 environmentId: target.environmentId,
922 input: { threadId: target.threadId, orderKey },
923 });
924 };
925​
926 const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => {
927 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
928 return AsyncResult.failure(
929 Cause.fail(
930 new ThreadActiveReorderUnsupportedError({
931 environmentId: target.environmentId,
932 threadId: target.threadId,
933 }),
934 ),
935 );
936 }
937 return reorderActiveThreadMutation({
938 environmentId: target.environmentId,
939 input: { threadId: target.threadId, orderKey },
940 });
941 };
942​
943 const unsnoozeThread = async (target: ScopedThreadRef) => {
944 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
945 return AsyncResult.failure(
946 Cause.fail(
947 new ThreadSnoozeUnsupportedError({
948 environmentId: target.environmentId,
949 threadId: target.threadId,
950 }),
951 ),
952 );
953 }
954 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
955 return unsnoozeThreadMutation({
956 environmentId: target.environmentId,
957 input: { threadId: target.threadId, reason: "user" },
958 });
959 };
960​
961 const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => {
962 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
963 return AsyncResult.failure(
964 Cause.fail(
965 new ThreadSnoozeUnsupportedError({
966 environmentId: target.environmentId,
967 threadId: target.threadId,
968 }),
969 ),
970 );
971 }
972 const resolved = resolveThreadTarget(target);
973 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
974 return AsyncResult.failure(
975 Cause.fail(
976 new ThreadSnoozeBlockedError({
977 environmentId: resolved.threadRef.environmentId,
978 threadId: resolved.threadRef.threadId,
979 }),
980 ),
981 );
982 }
983 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
984 const result = await snoozeThreadMutation({
985 environmentId: target.environmentId,
986 input: { threadId: target.threadId, snoozedUntil },
987 });
988 if (result._tag !== "Success") {
989 action.finish();
990 return result;
991 }
992 showThreadUndoNotice({
993 action: "Snoozed",
994 claim: action,
995 undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
996 failureTitle: m(msg("Failed to wake thread")),
997 });
998 return result;
999 };
1000​
1001 const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) => {
1002 let cancelledOnDevice = false;
1003 return ThreadUndo.executeThreadUndo(
1004 plan,
1005 async (step) => {
1006 if (cancelledOnDevice) return AsyncResult.success(undefined);
1007 switch (step.action) {
1008 case "unsettle": {
1009 const result = await unsettleThread(target, step.restoreUnsettledAt);
1010 cancelledOnDevice =
1011 result._tag === "Success" && ThreadUndo.cancelledOnDevice(result.value);
1012 return result;
1014 case "unsnooze":
1015 return unsnoozeThread(target);
1016 case "pin":
1017 return sendPin(target, step.orderKey === undefined ? {} : { orderKey: step.orderKey });
1018 case "reorderActive":
1019 return reorderActiveThread(target, step.orderKey);
1020 case "snooze":
1021 return snoozeThreadMutation({
1022 environmentId: target.environmentId,
1023 input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
1024 });
1026 },
1027 (result) => result._tag === "Success",
1028 );
1029 };
1030​
1031 const confirmAndDeleteThread = async (target: ScopedThreadRef, knownTitle?: string) => {
1032 const permissionFailure = threadOperationFailure(target);
1033 if (permissionFailure) return permissionFailure;
1034 const localApi = readLocalApi();
1035 const resolved = resolveThreadTarget(target);
1036​
1037 if (confirmThreadDelete && localApi) {
1038 const title = resolved?.thread.title ?? knownTitle ?? null;
1039 const confirmationResult = await settlePromise(() =>
1040 localApi.dialogs.confirm(
1042 title === null
1043 ? m(msg('Delete thread "this thread"?'))
1044 : m(msg('Delete thread "{title}"?', { title })),
1045 m(msg("This permanently clears conversation history for this thread.")),
1046 ].join("\n"),
1047 { variant: "destructive" },
1048 ),
1049 );
1050 if (confirmationResult._tag === "Failure") {
1051 return confirmationResult;
1053 if (!confirmationResult.value) {
1054 return AsyncResult.success(undefined);
1057​
1058 return deleteThread(target);
1059 };
1060​
1061 return {
1062 archiveThread,
1063 unarchiveThread,
1064 deleteThread,
1065 confirmAndDeleteThread,
1066 settleThread,
1067 unsettleThread,
1068 snoozeThread,
1069 unsnoozeThread,
1070 pinThread,
1071 unpinThread,
1072 confirmAndUnpinThread,
1073 reorderPinnedThread,
1074 reorderActiveThread,
1075 markThreadUnread,
1076 setThreadAutoSettle,
1077 turnThreadIntoProject: (target: ScopedThreadRef) =>
1078 createProjectFromThread({
1079 environmentId: target.environmentId,
1080 input: { threadId: target.threadId },
1081 }),
1082 };