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