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

useThreadActions.ts

1,043 lines36.9 KB

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