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