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

useThreadActions.ts

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