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

useThreadActions.ts

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