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

useThreadActions.ts

1,018 lines36.0 KB

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