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

useThreadActions.ts

918 lines31.6 KB

1import {
2 parseScopedThreadKey,
3 scopeProjectRef,
4 scopeThreadRef,
5 scopedThreadKey,
6} from "@t3tools/client-runtime/environment";
7import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
8import { canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
9import { threadRuntimeCanArchive } from "@t3tools/client-runtime/state/models";
10import {
11 AuthOrchestrationOperateScope,
12 AuthSourceControlWriteScope,
13 EnvironmentAuthorizationError,
14 EnvironmentId,
15 type ScopedThreadRef,
16 ThreadId,
17 sessionGrantsScope,
18} from "@t3tools/contracts";
19import { resolveWorktreeCleanup } from "@t3tools/shared/projectSettings";
20import * as Cause from "effect/Cause";
21import * as Schema from "effect/Schema";
22import { AsyncResult } from "effect/reactivity";
23import { useRouter } from "@tanstack/react-router";
24​
25import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic";
26import { useComposerDraftStore } from "../composerDraftStore";
27import { environmentSession, readEnvironmentScope } from "../state/session";
28import { appAtomRegistry } from "../rpc/atomRegistry";
29import { environmentServerConfigsAtom } from "../state/server";
30import { isScratchProject } from "@t3tools/client-runtime/state/projects";
31import { 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 }
74​
75export class ThreadSettlementUnsupportedError extends Schema.TaggedError<ThreadSettlementUnsupportedError>()(
76 "ThreadSettlementUnsupportedError",
77 {
78 environmentId: EnvironmentId,
79 threadId: ThreadId,
80 },
81) {
82 override get message(): string {
83 return "This environment's server does not support settling yet. Update the server to use Settle.";
84 }
86​
87export class ThreadSnoozeUnsupportedError extends Schema.TaggedError<ThreadSnoozeUnsupportedError>()(
88 "ThreadSnoozeUnsupportedError",
89 {
90 environmentId: EnvironmentId,
91 threadId: ThreadId,
92 },
93) {
94 override get message(): string {
95 return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
96 }
98​
99export class ThreadSnoozeBlockedError extends Schema.TaggedError<ThreadSnoozeBlockedError>()(
100 "ThreadSnoozeBlockedError",
101 {
102 environmentId: EnvironmentId,
103 threadId: ThreadId,
104 },
105) {
106 override get message(): string {
107 return "This thread is waiting on you. Respond to the pending request before snoozing it.";
108 }
110​
111function topOfPinnedRunOrderKey(): string | undefined {
112 let firstKey: string | null = null;
113 for (const shell of readThreadShells()) {
114 if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
115 if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
116 }
117 return pinOrderKeyBetween(null, firstKey) ?? undefined;
119​
120export class ThreadAutoSettleOptOutUnsupportedError extends Schema.TaggedError<ThreadAutoSettleOptOutUnsupportedError>()(
121 "ThreadAutoSettleOptOutUnsupportedError",
122 {
123 environmentId: EnvironmentId,
124 threadId: ThreadId,
125 },
126) {
127 override get message(): string {
128 return "This environment's server does not support turning auto-settle off per thread yet. Update the server to use it.";
129 }
131​
132export class ThreadPinningUnsupportedError extends Schema.TaggedError<ThreadPinningUnsupportedError>()(
133 "ThreadPinningUnsupportedError",
134 {
135 environmentId: EnvironmentId,
136 threadId: ThreadId,
137 },
138) {
139 override get message(): string {
140 return "This environment's server does not support pinning yet. Update the server to use Pin.";
141 }
143​
144export class ThreadPinReorderUnsupportedError extends Schema.TaggedError<ThreadPinReorderUnsupportedError>()(
145 "ThreadPinReorderUnsupportedError",
146 {
147 environmentId: EnvironmentId,
148 threadId: ThreadId,
149 },
150) {
151 override get message(): string {
152 return "This environment's server does not support reordering pinned threads yet. Update the server to reorder pins.";
153 }
155​
156export class ThreadActiveReorderUnsupportedError extends Schema.TaggedError<ThreadActiveReorderUnsupportedError>()(
157 "ThreadActiveReorderUnsupportedError",
158 {
159 environmentId: EnvironmentId,
160 threadId: ThreadId,
161 },
162) {
163 override get message(): string {
164 return "Update this environment's server to reorder active threads.";
165 }
167​
168async function requestThreadUnpinConfirmation(input: {
169 enabled: boolean;
170 title: string;
171 confirm: ((message: string) => Promise<boolean>) | null;
172}) {
173 const { confirm } = input;
174 if (!input.enabled || confirm === null) {
175 return AsyncResult.success(true);
176 }
177​
178 return settlePromise(() =>
179 confirm(
180 [
181 `Unpin thread "${input.title}"?`,
182 "This will move the thread out of your pinned section.",
183 ].join("\n"),
184 ),
185 );
187​
188export async function navigateAfterThreadDeletion(navigate: () => Promise<void>) {
189 const result = await settlePromise(navigate);
190 if (result._tag === "Failure") {
191 const error = squashAtomCommandFailure(result);
192 toastManager.add(
193 stackedThreadToast({
194 type: "error",
195 title: "Thread deleted, but navigation failed",
196 description: error instanceof Error ? error.message : "An error occurred.",
197 }),
198 );
199 }
201​
202function useMarkThreadUnread() {
203 const markThreadUnreadMutation = useAtomCommand(threadEnvironment.markUnread, {
204 reportFailure: false,
205 });
206 const markThreadUnreadLocal = useUiStateStore((state) => state.markThreadUnread);
207 return (target: ScopedThreadRef) => {
208 if (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 };
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 };
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 );
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 // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
654 ThreadUndo.invalidate("settle", scopedThreadKey(target));
655 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
656 return pinThreadMutation({
657 environmentId: target.environmentId,
658 input: {
659 threadId: target.threadId,
660 ...(orderKey !== undefined ? { orderKey } : {}),
661 },
662 });
663 };
664​
665 const unpinThread = async (target: ScopedThreadRef) => {
666 if (!readEnvironmentSupportsPinning(target.environmentId)) {
667 return AsyncResult.failure(
668 Cause.fail(
669 new ThreadPinningUnsupportedError({
670 environmentId: target.environmentId,
671 threadId: target.threadId,
672 }),
673 ),
674 );
675 }
676 const thread = readThreadShell(target);
677 const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
678 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
679 const result = await unpinThreadMutation({
680 environmentId: target.environmentId,
681 input: { threadId: target.threadId },
682 });
683 if (result._tag === "Success" && action.isCurrent()) {
684 showThreadUndoNotice({
685 action: "Unpinned",
686 claim: action,
687 undo: () => runUndoPlan(target, undoPlan),
688 failureTitle: "Failed to undo unpin",
689 });
690 } else {
691 action.finish();
692 }
693 return result;
694 };
695​
696 const settleThread = async (target: ScopedThreadRef) => {
697 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
698 return AsyncResult.failure(
699 Cause.fail(
700 new ThreadSettlementUnsupportedError({
701 environmentId: target.environmentId,
702 threadId: target.threadId,
703 }),
704 ),
705 );
706 }
707 const resolved = resolveThreadTarget(target);
708 const wokeAt = resolved
709 ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
710 : null;
711 const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
712 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
713 // treats either as a promotion that un-settles; settling supersedes them.
714 ThreadUndo.invalidate("pin", scopedThreadKey(target));
715 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
716 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
717 const result = await settleThreadMutation({
718 environmentId: target.environmentId,
719 input: { threadId: target.threadId },
720 });
721 if (result._tag !== "Success") {
722 action.finish();
723 return result;
724 }
725 if (wokeAt !== null) {
726 markThreadVisited(scopedThreadKey(target), wokeAt);
727 }
728 showThreadUndoNotice({
729 action: "Settled",
730 claim: action,
731 undo: () => runUndoPlan(target, undoPlan),
732 failureTitle: "Failed to undo settle",
733 });
734 return result;
735 };
736​
737 const confirmAndUnpinThread = async (target: ScopedThreadRef) => {
738 const permissionFailure = threadOperationFailure(target);
739 if (permissionFailure) return permissionFailure;
740 const localApi = readLocalApi();
741 const resolved = resolveThreadTarget(target);
742 const confirmationResult = await requestThreadUnpinConfirmation({
743 enabled: confirmThreadUnpin,
744 title: resolved?.thread.title ?? "this thread",
745 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
746 });
747 if (confirmationResult._tag === "Failure") {
748 return confirmationResult;
749 }
750 if (!confirmationResult.value) {
751 return AsyncResult.success(undefined);
752 }
753 return unpinThread(target);
754 };
755​
756 const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => {
757 if (!readEnvironmentSupportsPinReorder(target.environmentId)) {
758 return AsyncResult.failure(
759 Cause.fail(
760 new ThreadPinReorderUnsupportedError({
761 environmentId: target.environmentId,
762 threadId: target.threadId,
763 }),
764 ),
765 );
766 }
767 ThreadUndo.invalidate("pin", scopedThreadKey(target));
768 return reorderPinnedThreadMutation({
769 environmentId: target.environmentId,
770 input: { threadId: target.threadId, orderKey },
771 });
772 };
773​
774 const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => {
775 if (!readEnvironmentSupportsActiveReorder(target.environmentId)) {
776 return AsyncResult.failure(
777 Cause.fail(
778 new ThreadActiveReorderUnsupportedError({
779 environmentId: target.environmentId,
780 threadId: target.threadId,
781 }),
782 ),
783 );
784 }
785 return reorderActiveThreadMutation({
786 environmentId: target.environmentId,
787 input: { threadId: target.threadId, orderKey },
788 });
789 };
790​
791 const unsnoozeThread = async (target: ScopedThreadRef) => {
792 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
793 return AsyncResult.failure(
794 Cause.fail(
795 new ThreadSnoozeUnsupportedError({
796 environmentId: target.environmentId,
797 threadId: target.threadId,
798 }),
799 ),
800 );
801 }
802 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
803 return unsnoozeThreadMutation({
804 environmentId: target.environmentId,
805 input: { threadId: target.threadId, reason: "user" },
806 });
807 };
808​
809 const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => {
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 const resolved = resolveThreadTarget(target);
821 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
822 return AsyncResult.failure(
823 Cause.fail(
824 new ThreadSnoozeBlockedError({
825 environmentId: resolved.threadRef.environmentId,
826 threadId: resolved.threadRef.threadId,
827 }),
828 ),
829 );
830 }
831 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
832 const result = await snoozeThreadMutation({
833 environmentId: target.environmentId,
834 input: { threadId: target.threadId, snoozedUntil },
835 });
836 if (result._tag !== "Success") {
837 action.finish();
838 return result;
839 }
840 showThreadUndoNotice({
841 action: "Snoozed",
842 claim: action,
843 undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
844 failureTitle: "Failed to wake thread",
845 });
846 return result;
847 };
848​
849 const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) =>
850 ThreadUndo.executeThreadUndo(
851 plan,
852 async (step) => {
853 switch (step.action) {
854 case "unsettle":
855 return unsettleThread(target);
856 case "unsnooze":
857 return unsnoozeThread(target);
858 case "pin":
859 return pinThread(
860 target,
861 step.orderKey === undefined ? {} : { orderKey: step.orderKey },
862 );
863 case "snooze":
864 return snoozeThreadMutation({
865 environmentId: target.environmentId,
866 input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
867 });
868 }
869 },
870 (result) => result._tag === "Success",
871 );
872​
873 const confirmAndDeleteThread = async (target: ScopedThreadRef) => {
874 const permissionFailure = threadOperationFailure(target);
875 if (permissionFailure) return permissionFailure;
876 const localApi = readLocalApi();
877 const resolved = resolveThreadTarget(target);
878​
879 if (confirmThreadDelete && localApi) {
880 const title = resolved?.thread.title ?? "this thread";
881 const confirmationResult = await settlePromise(() =>
882 localApi.dialogs.confirm(
883 [
884 `Delete thread "${title}"?`,
885 "This permanently clears conversation history for this thread.",
886 ].join("\n"),
887 { variant: "destructive" },
888 ),
889 );
890 if (confirmationResult._tag === "Failure") {
891 return confirmationResult;
892 }
893 if (!confirmationResult.value) {
894 return AsyncResult.success(undefined);
895 }
896 }
897​
898 return deleteThread(target);
899 };
900​
901 return {
902 archiveThread,
903 unarchiveThread,
904 deleteThread,
905 confirmAndDeleteThread,
906 settleThread,
907 unsettleThread,
908 snoozeThread,
909 unsnoozeThread,
910 pinThread,
911 unpinThread,
912 confirmAndUnpinThread,
913 reorderPinnedThread,
914 reorderActiveThread,
915 markThreadUnread,
916 setThreadAutoSettle,
917 };