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

useThreadActions.ts

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