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