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 { threadEnvironment } from "../state/threads";
32import { vcsEnvironment } from "../state/vcs";
33import { useNewThreadHandler } from "./useHandleNewThread";
34import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
35import { releaseComposerDraftUploads } from "../lib/composerDraftUploads";
36import { readLocalApi } from "../localApi";
37import {
38 readEnvironmentSupportsAutoSettleOptOut,
39 readEnvironmentSupportsPinning,
40 readEnvironmentSupportsPinReorder,
41 readEnvironmentSupportsActiveReorder,
42 readEnvironmentSupportsSettlement,
43 readEnvironmentSupportsSnooze,
44 readEnvironmentSupportsVisitedTracking,
45 readEnvironmentThreadRefs,
46 readProject,
47 readThreadShell,
48 readThreadShells,
49} from "../state/entities";
50import { useUiStateStore } from "../uiStateStore";
51import { clearThreadPreviewState } from "../previewStateStore";
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 "./threadUndo";
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 }
73}
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 }
85}
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 }
97}
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 }
109}
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;
118}
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 }
130}
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 }
142}
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 }
154}
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 }
166}
167
168export async 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 );
186}
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 }
200}
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 (readEnvironmentSupportsVisitedTracking(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 };
218}
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 (readEnvironmentSupportsVisitedTracking(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 };
233}
234
235function threadOperationFailure(target: ScopedThreadRef) {
236 return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
237 ? null
238 : AsyncResult.failure(
239 Cause.fail(
240 new EnvironmentAuthorizationError({
241 message: "This connection cannot change threads.",
242 requiredScope: AuthOrchestrationOperateScope,
243 }),
244 ),
245 );
246}
247
248export function useThreadActions() {
249 const archiveThreadMutation = useOrchestrationCommand(threadEnvironment.archive, {
250 reportFailure: false,
251 });
252 const unarchiveThreadMutation = useOrchestrationCommand(threadEnvironment.unarchive, {
253 reportFailure: false,
254 });
255 const deleteThreadMutation = useOrchestrationCommand(threadEnvironment.delete, {
256 reportFailure: false,
257 });
258 const settleThreadMutation = useOrchestrationCommand(threadEnvironment.settle, {
259 reportFailure: false,
260 });
261 const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
262 reportFailure: false,
263 });
264 const pinThreadMutation = useOrchestrationCommand(threadEnvironment.pin, {
265 reportFailure: false,
266 });
267 const unpinThreadMutation = useOrchestrationCommand(threadEnvironment.unpin, {
268 reportFailure: false,
269 });
270 const setThreadAutoSettleMutation = useOrchestrationCommand(threadEnvironment.setAutoSettle, {
271 reportFailure: false,
272 });
273 const reorderPinnedThreadMutation = useOrchestrationCommand(threadEnvironment.reorderPin, {
274 reportFailure: false,
275 });
276 const reorderActiveThreadMutation = useOrchestrationCommand(threadEnvironment.reorderActive, {
277 reportFailure: false,
278 });
279 const snoozeThreadMutation = useOrchestrationCommand(threadEnvironment.snooze, {
280 reportFailure: false,
281 });
282 const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
283 reportFailure: false,
284 });
285 const markThreadUnread = useMarkThreadUnread();
286 const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession);
287 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
288 reportFailure: false,
289 });
290 const loadSessionState = useAtomQueryRunner(environmentSession.sessionStateAtom, {
291 reportFailure: false,
292 });
293 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
294 reportFailure: false,
295 });
296 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
297 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
298 const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin);
299 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
300 const clearProjectDraftThreadById = useComposerDraftStore(
301 (store) => store.clearProjectDraftThreadById,
302 );
303 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
304 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
305 const router = useRouter();
306 const handleNewThread = useNewThreadHandler();
307
308 const resolveThreadTarget = (target: ScopedThreadRef) => {
309 const thread = readThreadShell(target);
310 if (!thread) {
311 return null;
312 }
313 return {
314 thread,
315 threadRef: target,
316 };
317 };
318 const getCurrentRouteThreadRef = () => {
319 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
320 return resolveThreadRouteRef(currentRouteParams);
321 };
322
323 const unarchiveThread = async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => {
324 ThreadUndo.invalidate("archive", scopedThreadKey(target));
325 const result = await unarchiveThreadMutation({
326 environmentId: target.environmentId,
327 input: { threadId: target.threadId },
328 });
329 if (result._tag === "Failure") {
330 return result;
331 }
332 refreshArchivedThreadsForEnvironment(target.environmentId);
333 if (opts.navigate) {
334 return settlePromise(() =>
335 router.navigate({
336 to: "/$environmentId/$threadId",
337 params: buildThreadRouteParams(target),
338 }),
339 );
340 }
341 return result;
342 };
343
344 const archiveThread = async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
345 const resolved = resolveThreadTarget(target);
346 if (!resolved) return AsyncResult.success(undefined);
347 const { thread, threadRef } = resolved;
348 if (!threadRuntimeCanArchive(thread.runtime)) {
349 return AsyncResult.failure(
350 Cause.fail(
351 new ThreadArchiveBlockedError({
352 environmentId: threadRef.environmentId,
353 threadId: threadRef.threadId,
354 }),
355 ),
356 );
357 }
358
359 const currentRouteThreadRef = getCurrentRouteThreadRef();
360 const shouldNavigateToDraft =
361 currentRouteThreadRef?.threadId === threadRef.threadId &&
362 currentRouteThreadRef.environmentId === threadRef.environmentId;
363 const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef));
364 const archiveResult = await archiveThreadMutation({
365 environmentId: threadRef.environmentId,
366 input: { threadId: threadRef.threadId },
367 });
368 if (archiveResult._tag === "Failure") {
369 action.finish();
370 return archiveResult;
371 }
372 const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
373 if (wokeAt !== null) {
374 markThreadVisited(scopedThreadKey(threadRef), wokeAt);
375 }
376 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
377 opts.onArchived?.();
378 showThreadUndoNotice({
379 action: "Archived",
380 claim: action,
381 undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }),
382 failureTitle: "Failed to undo archive",
383 });
384
385 if (shouldNavigateToDraft) {
386 const navigationResult = await settlePromise(() =>
387 handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId)),
388 );
389 if (navigationResult._tag === "Failure") {
390 return navigationResult;
391 }
392 return archiveResult;
393 }
394
395 return archiveResult;
396 };
397
398 const deleteThread = async (
399 target: ScopedThreadRef,
400 opts: { deletedThreadKeys?: ReadonlySet<string> } = {},
401 ) => {
402 const permissionFailure = threadOperationFailure(target);
403 if (permissionFailure) return permissionFailure;
404 const resolved = resolveThreadTarget(target);
405 if (!resolved) {
406 const result = await deleteThreadMutation({
407 environmentId: target.environmentId,
408 input: { threadId: target.threadId },
409 });
410 if (result._tag === "Success") {
411 refreshArchivedThreadsForEnvironment(target.environmentId);
412 clearThreadPreviewState(target);
413 }
414 return result;
415 }
416 const { thread, threadRef } = resolved;
417 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
418 const shell = readThreadShell(ref);
419 return shell === null ? [] : [shell];
420 });
421 const threadProject = readProject({
422 environmentId: threadRef.environmentId,
423 projectId: thread.projectId,
424 });
425 const deletedIds =
426 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
427 ? new Set<ThreadId>(
428 [...opts.deletedThreadKeys].flatMap((threadKey) => {
429 const ref = parseScopedThreadKey(threadKey);
430 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
431 }),
432 )
433 : undefined;
434 const survivingThreads =
435 deletedIds && deletedIds.size > 0
436 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
437 : threads;
438 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
439 survivingThreads,
440 threadRef.threadId,
441 );
442 const displayWorktreePath = orphanedWorktreePath
443 ? formatWorktreePathForDisplay(orphanedWorktreePath)
444 : null;
445 const environmentConfig = appAtomRegistry
446 .get(environmentServerConfigsAtom)
447 .get(threadRef.environmentId);
448 const localApi = readLocalApi();
449 let canDeleteWorktree = false;
450 if (
451 orphanedWorktreePath !== null &&
452 threadProject !== null &&
453 !isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot) &&
454 localApi
455 ) {
456 const sessionResult = await loadSessionState(threadRef.environmentId);
457 const permissionFailure = threadOperationFailure(threadRef);
458 if (permissionFailure) return permissionFailure;
459 canDeleteWorktree =
460 sessionResult._tag === "Success" &&
461 sessionGrantsScope(sessionResult.value, AuthSourceControlWriteScope);
462 }
463 let shouldDeleteWorktree = false;
464 const environmentSettings = environmentConfig?.settings;
465 const automaticWorktreeCleanup = environmentSettings
466 ? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete
467 : false;
468 if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) {
469 const confirmationResult = await settlePromise(() =>
470 localApi.dialogs.confirm(
471 [
472 "This thread is the only one linked to this worktree:",
473 displayWorktreePath ?? orphanedWorktreePath,
474 "",
475 "Delete the worktree too?",
476 ].join("\n"),
477 { variant: "destructive" },
478 ),
479 );
480 if (confirmationResult._tag === "Failure") {
481 return confirmationResult;
482 }
483 shouldDeleteWorktree = confirmationResult.value;
484 }
485
486 if (thread.runtime !== null) {
487 await stopThreadSession({
488 environmentId: threadRef.environmentId,
489 input: { threadId: threadRef.threadId },
490 });
491 }
492
493 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
494 const currentRouteThreadRef = getCurrentRouteThreadRef();
495 const shouldNavigateToFallback =
496 currentRouteThreadRef?.threadId === threadRef.threadId &&
497 currentRouteThreadRef.environmentId === threadRef.environmentId;
498 const fallbackThreadId = getFallbackThreadIdAfterDelete({
499 threads,
500 deletedThreadId: threadRef.threadId,
501 deletedThreadIds,
502 sortOrder: sidebarThreadSortOrder,
503 });
504 const deleteResult = await deleteThreadMutation({
505 environmentId: threadRef.environmentId,
506 input: { threadId: threadRef.threadId },
507 });
508 if (deleteResult._tag === "Failure") {
509 return deleteResult;
510 }
511 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
512 releaseComposerDraftUploads(threadRef);
513 clearComposerDraftForThread(threadRef);
514 clearProjectDraftThreadById(
515 scopeProjectRef(threadRef.environmentId, thread.projectId),
516 threadRef,
517 );
518 clearTerminalUiState(threadRef);
519 clearThreadPreviewState(threadRef);
520
521 if (shouldNavigateToFallback) {
522 const fallbackThread = fallbackThreadId
523 ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId))
524 : null;
525 await navigateAfterThreadDeletion(() =>
526 fallbackThread
527 ? router.navigate({
528 to: "/$environmentId/$threadId",
529 params: buildThreadRouteParams(
530 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
531 ),
532 replace: true,
533 })
534 : router.navigate({ to: "/", replace: true }),
535 );
536 }
537
538 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
539 return deleteResult;
540 }
541
542 const removeResult = readEnvironmentScope(threadRef.environmentId, AuthSourceControlWriteScope)
543 ? await removeWorktree({
544 environmentId: threadRef.environmentId,
545 input: {
546 cwd: threadProject.workspaceRoot,
547 path: orphanedWorktreePath,
548 force: true,
549 },
550 })
551 : AsyncResult.failure(
552 Cause.fail(
553 new EnvironmentAuthorizationError({
554 message: "This connection can no longer remove worktrees.",
555 requiredScope: AuthSourceControlWriteScope,
556 }),
557 ),
558 );
559 const refreshResult =
560 removeResult._tag === "Success"
561 ? await refreshVcsStatus({
562 environmentId: threadRef.environmentId,
563 input: { cwd: threadProject.workspaceRoot },
564 })
565 : null;
566 const cleanupFailure =
567 removeResult._tag === "Failure"
568 ? removeResult
569 : refreshResult?._tag === "Failure"
570 ? refreshResult
571 : null;
572 if (cleanupFailure) {
573 const removalFailed = removeResult._tag === "Failure";
574 const error = squashAtomCommandFailure(cleanupFailure);
575 const message = error instanceof Error ? error.message : "An error occurred.";
576 console.error("Worktree cleanup failed after thread deletion", {
577 threadId: threadRef.threadId,
578 projectCwd: threadProject.workspaceRoot,
579 worktreePath: orphanedWorktreePath,
580 error,
581 });
582 toastManager.add(
583 stackedThreadToast({
584 type: "error",
585 title: removalFailed
586 ? "Failed to delete worktree"
587 : "Worktree deleted, but Git status refresh failed",
588 description: removalFailed
589 ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`
590 : message,
591 }),
592 );
593 // The thread was deleted. Cleanup has its own toast; returning its
594 // failure would make callers incorrectly report a thread deletion error.
595 }
596 return deleteResult;
597 };
598
599 const unsettleThread = async (target: ScopedThreadRef) => {
600 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
601 return AsyncResult.failure(
602 Cause.fail(
603 new ThreadSettlementUnsupportedError({
604 environmentId: target.environmentId,
605 threadId: target.threadId,
606 }),
607 ),
608 );
609 }
610 ThreadUndo.invalidate("settle", scopedThreadKey(target));
611 // reason "user" pins the thread active: auto-settle (PR merged /
612 // inactivity) stays suppressed until real activity clears the pin.
613 return unsettleThreadMutation({
614 environmentId: target.environmentId,
615 input: { threadId: target.threadId, reason: "user" },
616 });
617 };
618
619 const setThreadAutoSettle = async (target: ScopedThreadRef, enabled: boolean) => {
620 if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) {
621 return AsyncResult.failure(
622 Cause.fail(
623 new ThreadAutoSettleOptOutUnsupportedError({
624 environmentId: target.environmentId,
625 threadId: target.threadId,
626 }),
627 ),
628 );
629 }
630 return setThreadAutoSettleMutation({
631 environmentId: target.environmentId,
632 input: { threadId: target.threadId, enabled },
633 });
634 };
635
636 const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
637 if (!readEnvironmentSupportsPinning(target.environmentId)) {
638 return AsyncResult.failure(
639 Cause.fail(
640 new ThreadPinningUnsupportedError({
641 environmentId: target.environmentId,
642 threadId: target.threadId,
643 }),
644 ),
645 );
646 }
647 // orderKey rides only to servers that decode it; pre-reorder servers get the bare pin they
648 // understand and the thread stays keyless.
649 const orderKey = readEnvironmentSupportsPinReorder(target.environmentId)
650 ? (opts.orderKey ?? topOfPinnedRunOrderKey())
651 : undefined;
652 ThreadUndo.invalidate("pin", scopedThreadKey(target));
653 return pinThreadMutation({
654 environmentId: target.environmentId,
655 input: {
656 threadId: target.threadId,
657 ...(orderKey !== undefined ? { orderKey } : {}),
658 },
659 });
660 };
661
662 const unpinThread = async (target: ScopedThreadRef) => {
663 if (!readEnvironmentSupportsPinning(target.environmentId)) {
664 return AsyncResult.failure(
665 Cause.fail(
666 new ThreadPinningUnsupportedError({
667 environmentId: target.environmentId,
668 threadId: target.threadId,
669 }),
670 ),
671 );
672 }
673 const thread = readThreadShell(target);
674 const orderKey = thread?.pinOrderKey ?? undefined;
675 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
676 const result = await unpinThreadMutation({
677 environmentId: target.environmentId,
678 input: { threadId: target.threadId },
679 });
680 if (result._tag === "Success" && action.isCurrent()) {
681 showThreadUndoNotice({
682 action: "Unpinned",
683 claim: action,
684 undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }),
685 failureTitle: "Failed to undo unpin",
686 });
687 } else {
688 action.finish();
689 }
690 return result;
691 };
692
693 const settleThread = async (target: ScopedThreadRef) => {
694 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
695 return AsyncResult.failure(
696 Cause.fail(
697 new ThreadSettlementUnsupportedError({
698 environmentId: target.environmentId,
699 threadId: target.threadId,
700 }),
701 ),
702 );
703 }
704 const resolved = resolveThreadTarget(target);
705 const wokeAt = resolved
706 ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
707 : null;
708 // Settling also drops the pin and the snooze server-side, so Undo
709 // has to put those back as well.
710 const pinOrderKey = resolved?.thread.pinnedAt != null ? resolved.thread.pinOrderKey : null;
711 const wasPinned = resolved?.thread.pinnedAt != null;
712 const snoozedUntil = resolved?.thread.snoozedUntil ?? null;
713 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
714 // treats either as a promotion that un-settles; settling supersedes them.
715 ThreadUndo.invalidate("pin", scopedThreadKey(target));
716 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
717 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
718 const result = await settleThreadMutation({
719 environmentId: target.environmentId,
720 input: { threadId: target.threadId },
721 });
722 if (result._tag !== "Success") {
723 action.finish();
724 return result;
725 }
726 if (wokeAt !== null) {
727 markThreadVisited(scopedThreadKey(target), wokeAt);
728 }
729 showThreadUndoNotice({
730 action: "Settled",
731 claim: action,
732 undo: async () => {
733 const unsettled = await unsettleThread(target);
734 if (unsettled._tag !== "Success") return unsettled;
735 if (wasPinned) {
736 const pinned = await pinThread(
737 target,
738 pinOrderKey == null ? {} : { orderKey: pinOrderKey },
739 );
740 if (pinned._tag !== "Success") return pinned;
741 }
742 if (snoozedUntil !== null) {
743 return snoozeThreadMutation({
744 environmentId: target.environmentId,
745 input: { threadId: target.threadId, snoozedUntil },
746 });
747 }
748 return unsettled;
749 },
750 failureTitle: "Failed to undo settle",
751 });
752 return result;
753 };
754
755 const confirmAndUnpinThread = async (target: ScopedThreadRef) => {
756 const permissionFailure = threadOperationFailure(target);
757 if (permissionFailure) return permissionFailure;
758 const localApi = readLocalApi();
759 const resolved = resolveThreadTarget(target);
760 const confirmationResult = await requestThreadUnpinConfirmation({
761 enabled: confirmThreadUnpin,
762 title: resolved?.thread.title ?? "this thread",
763 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
764 });
765 if (confirmationResult._tag === "Failure") {
766 return confirmationResult;
767 }
768 if (!confirmationResult.value) {
769 return AsyncResult.success(undefined);
770 }
771 return unpinThread(target);
772 };
773
774 const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => {
775 if (!readEnvironmentSupportsPinReorder(target.environmentId)) {
776 return AsyncResult.failure(
777 Cause.fail(
778 new ThreadPinReorderUnsupportedError({
779 environmentId: target.environmentId,
780 threadId: target.threadId,
781 }),
782 ),
783 );
784 }
785 ThreadUndo.invalidate("pin", scopedThreadKey(target));
786 return reorderPinnedThreadMutation({
787 environmentId: target.environmentId,
788 input: { threadId: target.threadId, orderKey },
789 });
790 };
791
792 const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => {
793 if (!readEnvironmentSupportsActiveReorder(target.environmentId)) {
794 return AsyncResult.failure(
795 Cause.fail(
796 new ThreadActiveReorderUnsupportedError({
797 environmentId: target.environmentId,
798 threadId: target.threadId,
799 }),
800 ),
801 );
802 }
803 return reorderActiveThreadMutation({
804 environmentId: target.environmentId,
805 input: { threadId: target.threadId, orderKey },
806 });
807 };
808
809 const unsnoozeThread = async (target: ScopedThreadRef) => {
810 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
811 return AsyncResult.failure(
812 Cause.fail(
813 new ThreadSnoozeUnsupportedError({
814 environmentId: target.environmentId,
815 threadId: target.threadId,
816 }),
817 ),
818 );
819 }
820 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
821 return unsnoozeThreadMutation({
822 environmentId: target.environmentId,
823 input: { threadId: target.threadId, reason: "user" },
824 });
825 };
826
827 const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => {
828 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
829 return AsyncResult.failure(
830 Cause.fail(
831 new ThreadSnoozeUnsupportedError({
832 environmentId: target.environmentId,
833 threadId: target.threadId,
834 }),
835 ),
836 );
837 }
838 const resolved = resolveThreadTarget(target);
839 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
840 return AsyncResult.failure(
841 Cause.fail(
842 new ThreadSnoozeBlockedError({
843 environmentId: resolved.threadRef.environmentId,
844 threadId: resolved.threadRef.threadId,
845 }),
846 ),
847 );
848 }
849 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
850 const result = await snoozeThreadMutation({
851 environmentId: target.environmentId,
852 input: { threadId: target.threadId, snoozedUntil },
853 });
854 if (result._tag !== "Success") {
855 action.finish();
856 return result;
857 }
858 showThreadUndoNotice({
859 action: "Snoozed",
860 claim: action,
861 undo: () => unsnoozeThread(target),
862 failureTitle: "Failed to wake thread",
863 });
864 return result;
865 };
866
867 const confirmAndDeleteThread = async (target: ScopedThreadRef) => {
868 const permissionFailure = threadOperationFailure(target);
869 if (permissionFailure) return permissionFailure;
870 const localApi = readLocalApi();
871 const resolved = resolveThreadTarget(target);
872
873 if (confirmThreadDelete && localApi) {
874 const title = resolved?.thread.title ?? "this thread";
875 const confirmationResult = await settlePromise(() =>
876 localApi.dialogs.confirm(
877 [
878 `Delete thread "${title}"?`,
879 "This permanently clears conversation history for this thread.",
880 ].join("\n"),
881 { variant: "destructive" },
882 ),
883 );
884 if (confirmationResult._tag === "Failure") {
885 return confirmationResult;
886 }
887 if (!confirmationResult.value) {
888 return AsyncResult.success(undefined);
889 }
890 }
891
892 return deleteThread(target);
893 };
894
895 return {
896 archiveThread,
897 unarchiveThread,
898 deleteThread,
899 confirmAndDeleteThread,
900 settleThread,
901 unsettleThread,
902 snoozeThread,
903 unsnoozeThread,
904 pinThread,
905 unpinThread,
906 confirmAndUnpinThread,
907 reorderPinnedThread,
908 reorderActiveThread,
909 markThreadUnread,
910 setThreadAutoSettle,
911 };
912}