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

useThreadActions.ts

996 lines35.1 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/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 }
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 }
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 }
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 }
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;
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 }
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 }
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 }
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 }
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 );
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 }
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 );
221​
222/**
223 * Clears a thread's Woke marker by recording a visit at the wake time.
224 * Servers with visited tracking own the watermark (thread.visit keeps the
225 * later of the stored and supplied values, so this syncs to every device);
226 * older servers keep the browser-local watermark.
227 */
228export function useAcknowledgeThreadWoke() {
229 const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
230 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
231 return useCallback(
232 (target: ScopedThreadRef, wokeAt: string) => {
233 if (readEnvironmentSupportsVisitedTracking(target.environmentId)) {
234 void visitThreadMutation({
235 environmentId: target.environmentId,
236 input: { threadId: target.threadId, visitedAt: wokeAt },
237 });
238 return;
239 }
240 markThreadVisited(scopedThreadKey(target), wokeAt);
241 },
242 [markThreadVisited, visitThreadMutation],
243 );
245​
246export function useThreadActions() {
247 const closeTerminal = useAtomCommand(terminalEnvironment.close);
248 const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
249 reportFailure: false,
250 });
251 const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
252 reportFailure: false,
253 });
254 const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
255 reportFailure: false,
256 });
257 const settleThreadMutation = useAtomCommand(threadEnvironment.settle, {
258 reportFailure: false,
259 });
260 const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
261 reportFailure: false,
262 });
263 const pinThreadMutation = useAtomCommand(threadEnvironment.pin, {
264 reportFailure: false,
265 });
266 const unpinThreadMutation = useAtomCommand(threadEnvironment.unpin, {
267 reportFailure: false,
268 });
269 const setThreadAutoSettleMutation = useAtomCommand(threadEnvironment.setAutoSettle, {
270 reportFailure: false,
271 });
272 const reorderPinnedThreadMutation = useAtomCommand(threadEnvironment.reorderPin, {
273 reportFailure: false,
274 });
275 const reorderActiveThreadMutation = useAtomCommand(threadEnvironment.reorderActive, {
276 reportFailure: false,
277 });
278 const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
279 reportFailure: false,
280 });
281 const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
282 reportFailure: false,
283 });
284 const markThreadUnread = useMarkThreadUnread();
285 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
286 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
287 reportFailure: false,
288 });
289 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
290 reportFailure: false,
291 });
292 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
293 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
294 const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin);
295 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
296 const clearProjectDraftThreadById = useComposerDraftStore(
297 (store) => store.clearProjectDraftThreadById,
298 );
299 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
300 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
301 const router = useRouter();
302 const handleNewThread = useNewThreadHandler();
303 // Keep a ref so archiveThread can call handleNewThread without appearing in
304 // its dependency array — handleNewThread is inherently unstable (depends on
305 // the projects list) and would otherwise cascade new references into every
306 // sidebar row via archiveThread → attemptArchiveThread.
307 const handleNewThreadRef = useRef(handleNewThread);
308 handleNewThreadRef.current = handleNewThread;
309​
310 const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
311 const thread = readThreadShell(target);
312 if (!thread) {
313 return null;
314 }
315 return {
316 thread,
317 threadRef: target,
318 };
319 }, []);
320 const getCurrentRouteThreadRef = useCallback(() => {
321 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
322 return resolveThreadRouteRef(currentRouteParams);
323 }, [router]);
324​
325 const unarchiveThread = useCallback(
326 async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => {
327 ThreadUndo.invalidate("archive", scopedThreadKey(target));
328 const result = await unarchiveThreadMutation({
329 environmentId: target.environmentId,
330 input: { threadId: target.threadId },
331 });
332 if (result._tag === "Failure") {
333 return result;
334 }
335 refreshArchivedThreadsForEnvironment(target.environmentId);
336 if (opts.navigate) {
337 return settlePromise(() =>
338 router.navigate({
339 to: "/$environmentId/$threadId",
340 params: buildThreadRouteParams(target),
341 }),
342 );
343 }
344 return result;
345 },
346 [router, unarchiveThreadMutation],
347 );
348​
349 const archiveThread = useCallback(
350 async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
351 const resolved = resolveThreadTarget(target);
352 if (!resolved) return AsyncResult.success(undefined);
353 const { thread, threadRef } = resolved;
354 if (!threadRuntimeCanArchive(thread.runtime)) {
355 return AsyncResult.failure(
356 Cause.fail(
357 new ThreadArchiveBlockedError({
358 environmentId: threadRef.environmentId,
359 threadId: threadRef.threadId,
360 }),
361 ),
362 );
363 }
364​
365 const currentRouteThreadRef = getCurrentRouteThreadRef();
366 const shouldNavigateToDraft =
367 currentRouteThreadRef?.threadId === threadRef.threadId &&
368 currentRouteThreadRef.environmentId === threadRef.environmentId;
369 const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef));
370 const archiveResult = await archiveThreadMutation({
371 environmentId: threadRef.environmentId,
372 input: { threadId: threadRef.threadId },
373 });
374 if (archiveResult._tag === "Failure") {
375 action.finish();
376 return archiveResult;
377 }
378 const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
379 if (wokeAt !== null) {
380 markThreadVisited(scopedThreadKey(threadRef), wokeAt);
381 }
382 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
383 opts.onArchived?.();
384 showThreadUndoNotice({
385 action: "Archived",
386 claim: action,
387 // Undo also brings the reader back when archiving moved them to a draft.
388 undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }),
389 failureTitle: "Failed to undo archive",
390 });
391​
392 if (shouldNavigateToDraft) {
393 const navigationResult = await settlePromise(() =>
394 handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)),
395 );
396 if (navigationResult._tag === "Failure") {
397 return navigationResult;
398 }
399 return archiveResult;
400 }
401​
402 return archiveResult;
403 },
404 [
405 archiveThreadMutation,
406 getCurrentRouteThreadRef,
407 markThreadVisited,
408 resolveThreadTarget,
409 unarchiveThread,
410 ],
411 );
412​
413 const deleteThread = useCallback(
414 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
415 const resolved = resolveThreadTarget(target);
416 if (!resolved) {
417 // Thread not in main store (e.g. archived thread) — dispatch delete directly.
418 const result = await deleteThreadMutation({
419 environmentId: target.environmentId,
420 input: { threadId: target.threadId },
421 });
422 if (result._tag === "Success") {
423 refreshArchivedThreadsForEnvironment(target.environmentId);
424 }
425 return result;
426 }
427 const { thread, threadRef } = resolved;
428 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
429 const shell = readThreadShell(ref);
430 return shell === null ? [] : [shell];
431 });
432 const threadProject = readProject({
433 environmentId: threadRef.environmentId,
434 projectId: thread.projectId,
435 });
436 const deletedIds =
437 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
438 ? new Set<ThreadId>(
439 [...opts.deletedThreadKeys].flatMap((threadKey) => {
440 const ref = parseScopedThreadKey(threadKey);
441 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
442 }),
443 )
444 : undefined;
445 const survivingThreads =
446 deletedIds && deletedIds.size > 0
447 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
448 : threads;
449 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
450 survivingThreads,
451 threadRef.threadId,
452 );
453 const displayWorktreePath = orphanedWorktreePath
454 ? formatWorktreePathForDisplay(orphanedWorktreePath)
455 : null;
456 const environmentConfig = appAtomRegistry
457 .get(environmentServerConfigsAtom)
458 .get(threadRef.environmentId);
459 // A Scratch thread's folder is not a git worktree, and deleting the
460 // thread keeps its files.
461 const canDeleteWorktree =
462 orphanedWorktreePath !== null &&
463 threadProject !== null &&
464 !isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot);
465 const localApi = readLocalApi();
466 let shouldDeleteWorktree = false;
467 const environmentSettings = environmentConfig?.settings;
468 const automaticWorktreeCleanup = environmentSettings
469 ? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete
470 : false;
471 if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) {
472 const confirmationResult = await settlePromise(() =>
473 localApi.dialogs.confirm(
474 [
475 "This thread is the only one linked to this worktree:",
476 displayWorktreePath ?? orphanedWorktreePath,
477 "",
478 "Delete the worktree too?",
479 ].join("\n"),
480 { variant: "destructive" },
481 ),
482 );
483 if (confirmationResult._tag === "Failure") {
484 return confirmationResult;
485 }
486 shouldDeleteWorktree = confirmationResult.value;
487 }
488​
489 if (thread.runtime !== null) {
490 await stopThreadSession({
491 environmentId: threadRef.environmentId,
492 input: { threadId: threadRef.threadId },
493 });
494 }
495​
496 await closeTerminal({
497 environmentId: threadRef.environmentId,
498 input: { threadId: threadRef.threadId, deleteHistory: true },
499 });
500​
501 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
502 const currentRouteThreadRef = getCurrentRouteThreadRef();
503 const shouldNavigateToFallback =
504 currentRouteThreadRef?.threadId === threadRef.threadId &&
505 currentRouteThreadRef.environmentId === threadRef.environmentId;
506 const fallbackThreadId = getFallbackThreadIdAfterDelete({
507 threads,
508 deletedThreadId: threadRef.threadId,
509 deletedThreadIds,
510 sortOrder: sidebarThreadSortOrder,
511 });
512 const deleteResult = await deleteThreadMutation({
513 environmentId: threadRef.environmentId,
514 input: { threadId: threadRef.threadId },
515 });
516 if (deleteResult._tag === "Failure") {
517 return deleteResult;
518 }
519 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
520 releaseComposerDraftUploads(threadRef);
521 clearComposerDraftForThread(threadRef);
522 clearProjectDraftThreadById(
523 scopeProjectRef(threadRef.environmentId, thread.projectId),
524 threadRef,
525 );
526 clearTerminalUiState(threadRef);
527​
528 if (shouldNavigateToFallback) {
529 const fallbackThread = fallbackThreadId
530 ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId))
531 : null;
532 await navigateAfterThreadDeletion(() =>
533 fallbackThread
534 ? router.navigate({
535 to: "/$environmentId/$threadId",
536 params: buildThreadRouteParams(
537 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
538 ),
539 replace: true,
540 })
541 : router.navigate({ to: "/", replace: true }),
542 );
543 }
544​
545 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
546 return deleteResult;
547 }
548​
549 const removeResult = await removeWorktree({
550 environmentId: threadRef.environmentId,
551 input: {
552 cwd: threadProject.workspaceRoot,
553 path: orphanedWorktreePath,
554 force: true,
555 },
556 });
557 const refreshResult =
558 removeResult._tag === "Success"
559 ? await refreshVcsStatus({
560 environmentId: threadRef.environmentId,
561 input: { cwd: threadProject.workspaceRoot },
562 })
563 : null;
564 const cleanupFailure =
565 removeResult._tag === "Failure"
566 ? removeResult
567 : refreshResult?._tag === "Failure"
568 ? refreshResult
569 : null;
570 if (cleanupFailure) {
571 const removalFailed = removeResult._tag === "Failure";
572 const error = squashAtomCommandFailure(cleanupFailure);
573 const message = error instanceof Error ? error.message : "An error occurred.";
574 console.error("Worktree cleanup failed after thread deletion", {
575 threadId: threadRef.threadId,
576 projectCwd: threadProject.workspaceRoot,
577 worktreePath: orphanedWorktreePath,
578 error,
579 });
580 toastManager.add(
581 stackedThreadToast({
582 type: "error",
583 title: removalFailed
584 ? "Failed to delete worktree"
585 : "Worktree deleted, but Git status refresh failed",
586 description: removalFailed
587 ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`
588 : message,
589 }),
590 );
591 // The thread was deleted. Cleanup has its own toast; returning its
592 // failure would make callers incorrectly report a thread deletion error.
593 }
594 return deleteResult;
595 },
596 [
597 clearComposerDraftForThread,
598 clearProjectDraftThreadById,
599 clearTerminalUiState,
600 closeTerminal,
601 deleteThreadMutation,
602 getCurrentRouteThreadRef,
603 refreshVcsStatus,
604 removeWorktree,
605 router,
606 resolveThreadTarget,
607 sidebarThreadSortOrder,
608 stopThreadSession,
609 ],
610 );
611​
612 const unsettleThread = useCallback(
613 async (target: ScopedThreadRef) => {
614 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
615 return AsyncResult.failure(
616 Cause.fail(
617 new ThreadSettlementUnsupportedError({
618 environmentId: target.environmentId,
619 threadId: target.threadId,
620 }),
621 ),
622 );
623 }
624 ThreadUndo.invalidate("settle", scopedThreadKey(target));
625 // reason "user" pins the thread active: auto-settle (PR merged /
626 // inactivity) stays suppressed until real activity clears the pin.
627 return unsettleThreadMutation({
628 environmentId: target.environmentId,
629 input: { threadId: target.threadId, reason: "user" },
630 });
631 },
632 [unsettleThreadMutation],
633 );
634​
635 /** Turns automatic settlement (inactivity, merged PR) on or off for one thread. */
636 const setThreadAutoSettle = useCallback(
637 async (target: ScopedThreadRef, enabled: boolean) => {
638 if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) {
639 return AsyncResult.failure(
640 Cause.fail(
641 new ThreadAutoSettleOptOutUnsupportedError({
642 environmentId: target.environmentId,
643 threadId: target.threadId,
644 }),
645 ),
646 );
647 }
648 return setThreadAutoSettleMutation({
649 environmentId: target.environmentId,
650 input: { threadId: target.threadId, enabled },
651 });
652 },
653 [setThreadAutoSettleMutation],
654 );
655​
656 const pinThread = useCallback(
657 async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
658 // Version skew: never send the command to a server that predates it.
659 if (!readEnvironmentSupportsPinning(target.environmentId)) {
660 return AsyncResult.failure(
661 Cause.fail(
662 new ThreadPinningUnsupportedError({
663 environmentId: target.environmentId,
664 threadId: target.threadId,
665 }),
666 ),
667 );
668 }
669 // Every pin path places the thread at the top of the arranged run:
670 // callers with a better anchor (the sidebar, which knows the displayed
671 // order) pass their own key; everyone else (chat header, context menus)
672 // gets the default so the same action never places differently.
673 // orderKey rides only to servers that decode it; pre-reorder servers
674 // get the bare pin they understand and the thread stays keyless.
675 const orderKey = readEnvironmentSupportsPinReorder(target.environmentId)
676 ? (opts.orderKey ?? topOfPinnedRunOrderKey())
677 : undefined;
678 ThreadUndo.invalidate("pin", scopedThreadKey(target));
679 return pinThreadMutation({
680 environmentId: target.environmentId,
681 input: {
682 threadId: target.threadId,
683 ...(orderKey !== undefined ? { orderKey } : {}),
684 },
685 });
686 },
687 [pinThreadMutation],
688 );
689​
690 const unpinThread = useCallback(
691 async (target: ScopedThreadRef) => {
692 if (!readEnvironmentSupportsPinning(target.environmentId)) {
693 return AsyncResult.failure(
694 Cause.fail(
695 new ThreadPinningUnsupportedError({
696 environmentId: target.environmentId,
697 threadId: target.threadId,
698 }),
699 ),
700 );
701 }
702 const thread = readThreadShell(target);
703 const orderKey = thread?.pinOrderKey ?? undefined;
704 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
705 const result = await unpinThreadMutation({
706 environmentId: target.environmentId,
707 input: { threadId: target.threadId },
708 });
709 if (result._tag === "Success" && action.isCurrent()) {
710 showThreadUndoNotice({
711 action: "Unpinned",
712 claim: action,
713 undo: () => pinThread(target, orderKey === undefined ? {} : { orderKey }),
714 failureTitle: "Failed to undo unpin",
715 });
716 } else {
717 action.finish();
718 }
719 return result;
720 },
721 [pinThread, unpinThreadMutation],
722 );
723​
724 const settleThread = useCallback(
725 async (target: ScopedThreadRef) => {
726 // Version skew: never send the command to a server that predates it —
727 // the raw protocol rejection would read as a random failure.
728 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
729 return AsyncResult.failure(
730 Cause.fail(
731 new ThreadSettlementUnsupportedError({
732 environmentId: target.environmentId,
733 threadId: target.threadId,
734 }),
735 ),
736 );
737 }
738 const resolved = resolveThreadTarget(target);
739 const wokeAt = resolved
740 ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
741 : null;
742 // Settling also drops the pin and the snooze server-side, so Undo
743 // has to put those back as well.
744 const pinOrderKey = resolved?.thread.pinnedAt != null ? resolved.thread.pinOrderKey : null;
745 const wasPinned = resolved?.thread.pinnedAt != null;
746 const snoozedUntil = resolved?.thread.snoozedUntil ?? null;
747 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
748 // treats either as a promotion that un-settles; settling supersedes them.
749 ThreadUndo.invalidate("pin", scopedThreadKey(target));
750 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
751 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
752 const result = await settleThreadMutation({
753 environmentId: target.environmentId,
754 input: { threadId: target.threadId },
755 });
756 if (result._tag !== "Success") {
757 action.finish();
758 return result;
759 }
760 if (wokeAt !== null) {
761 markThreadVisited(scopedThreadKey(target), wokeAt);
762 }
763 showThreadUndoNotice({
764 action: "Settled",
765 claim: action,
766 undo: async () => {
767 const unsettled = await unsettleThread(target);
768 if (unsettled._tag !== "Success") return unsettled;
769 if (wasPinned) {
770 const pinned = await pinThread(
771 target,
772 pinOrderKey == null ? {} : { orderKey: pinOrderKey },
773 );
774 if (pinned._tag !== "Success") return pinned;
775 }
776 if (snoozedUntil !== null) {
777 return snoozeThreadMutation({
778 environmentId: target.environmentId,
779 input: { threadId: target.threadId, snoozedUntil },
780 });
781 }
782 return unsettled;
783 },
784 failureTitle: "Failed to undo settle",
785 });
786 return result;
787 },
788 [
789 markThreadVisited,
790 pinThread,
791 resolveThreadTarget,
792 settleThreadMutation,
793 snoozeThreadMutation,
794 unsettleThread,
795 ],
796 );
797​
798 const confirmAndUnpinThread = useCallback(
799 async (target: ScopedThreadRef) => {
800 const localApi = readLocalApi();
801 const resolved = resolveThreadTarget(target);
802 const confirmationResult = await requestThreadUnpinConfirmation({
803 enabled: confirmThreadUnpin,
804 title: resolved?.thread.title ?? "this thread",
805 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
806 });
807 if (confirmationResult._tag === "Failure") {
808 return confirmationResult;
809 }
810 if (!confirmationResult.value) {
811 return AsyncResult.success(undefined);
812 }
813 return unpinThread(target);
814 },
815 [confirmThreadUnpin, resolveThreadTarget, unpinThread],
816 );
817​
818 const reorderPinnedThread = useCallback(
819 async (target: ScopedThreadRef, orderKey: string) => {
820 // Callers (the sidebar drag handler) only enable dragging on
821 // reorder-capable environments; this guard covers races around
822 // capability changes mid-drag.
823 if (!readEnvironmentSupportsPinReorder(target.environmentId)) {
824 return AsyncResult.failure(
825 Cause.fail(
826 new ThreadPinReorderUnsupportedError({
827 environmentId: target.environmentId,
828 threadId: target.threadId,
829 }),
830 ),
831 );
832 }
833 ThreadUndo.invalidate("pin", scopedThreadKey(target));
834 return reorderPinnedThreadMutation({
835 environmentId: target.environmentId,
836 input: { threadId: target.threadId, orderKey },
837 });
838 },
839 [reorderPinnedThreadMutation],
840 );
841​
842 const reorderActiveThread = useCallback(
843 async (target: ScopedThreadRef, orderKey: string) => {
844 if (!readEnvironmentSupportsActiveReorder(target.environmentId)) {
845 return AsyncResult.failure(
846 Cause.fail(
847 new ThreadActiveReorderUnsupportedError({
848 environmentId: target.environmentId,
849 threadId: target.threadId,
850 }),
851 ),
852 );
853 }
854 return reorderActiveThreadMutation({
855 environmentId: target.environmentId,
856 input: { threadId: target.threadId, orderKey },
857 });
858 },
859 [reorderActiveThreadMutation],
860 );
861​
862 const unsnoozeThread = useCallback(
863 async (target: ScopedThreadRef) => {
864 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
865 return AsyncResult.failure(
866 Cause.fail(
867 new ThreadSnoozeUnsupportedError({
868 environmentId: target.environmentId,
869 threadId: target.threadId,
870 }),
871 ),
872 );
873 }
874 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
875 return unsnoozeThreadMutation({
876 environmentId: target.environmentId,
877 input: { threadId: target.threadId, reason: "user" },
878 });
879 },
880 [unsnoozeThreadMutation],
881 );
882​
883 const snoozeThread = useCallback(
884 async (target: ScopedThreadRef, snoozedUntil: string) => {
885 // Version skew: never send the command to a server that predates it.
886 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
887 return AsyncResult.failure(
888 Cause.fail(
889 new ThreadSnoozeUnsupportedError({
890 environmentId: target.environmentId,
891 threadId: target.threadId,
892 }),
893 ),
894 );
895 }
896 const resolved = resolveThreadTarget(target);
897 // Blocked-on-you work and queued turns can't be snoozed away —
898 // client-side twin of the server invariants so the UI rejects before
899 // a round trip.
900 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
901 return AsyncResult.failure(
902 Cause.fail(
903 new ThreadSnoozeBlockedError({
904 environmentId: resolved.threadRef.environmentId,
905 threadId: resolved.threadRef.threadId,
906 }),
907 ),
908 );
909 }
910 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
911 const result = await snoozeThreadMutation({
912 environmentId: target.environmentId,
913 input: { threadId: target.threadId, snoozedUntil },
914 });
915 if (result._tag !== "Success") {
916 action.finish();
917 return result;
918 }
919 // Snooze hides the row, so keep its confirmation in the sidebar.
920 showThreadUndoNotice({
921 action: "Snoozed",
922 claim: action,
923 undo: () => unsnoozeThread(target),
924 failureTitle: "Failed to wake thread",
925 });
926 return result;
927 },
928 [resolveThreadTarget, snoozeThreadMutation, unsnoozeThread],
929 );
930​
931 const confirmAndDeleteThread = useCallback(
932 async (target: ScopedThreadRef) => {
933 const localApi = readLocalApi();
934 const resolved = resolveThreadTarget(target);
935​
936 if (confirmThreadDelete && localApi) {
937 const title = resolved?.thread.title ?? "this thread";
938 const confirmationResult = await settlePromise(() =>
939 localApi.dialogs.confirm(
940 [
941 `Delete thread "${title}"?`,
942 "This permanently clears conversation history for this thread.",
943 ].join("\n"),
944 { variant: "destructive" },
945 ),
946 );
947 if (confirmationResult._tag === "Failure") {
948 return confirmationResult;
949 }
950 if (!confirmationResult.value) {
951 return AsyncResult.success(undefined);
952 }
953 }
954​
955 return deleteThread(target);
956 },
957 [confirmThreadDelete, deleteThread, resolveThreadTarget],
958 );
959​
960 return useMemo(
961 () => ({
962 archiveThread,
963 unarchiveThread,
964 deleteThread,
965 confirmAndDeleteThread,
966 settleThread,
967 unsettleThread,
968 snoozeThread,
969 unsnoozeThread,
970 pinThread,
971 unpinThread,
972 confirmAndUnpinThread,
973 reorderPinnedThread,
974 reorderActiveThread,
975 markThreadUnread,
976 setThreadAutoSettle,
977 }),
978 [
979 archiveThread,
980 confirmAndDeleteThread,
981 confirmAndUnpinThread,
982 deleteThread,
983 markThreadUnread,
984 pinThread,
985 reorderPinnedThread,
986 reorderActiveThread,
987 setThreadAutoSettle,
988 settleThread,
989 snoozeThread,
990 unarchiveThread,
991 unpinThread,
992 unsettleThread,
993 unsnoozeThread,
994 ],
995 );