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