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 { canSettle, canSnooze, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
9import { EnvironmentId, type ScopedThreadRef, ThreadId } from "@t3tools/contracts";
10import * as Cause from "effect/Cause";
11import * as Schema from "effect/Schema";
12import { AsyncResult } from "effect/unstable/reactivity";
13import { useRouter } from "@tanstack/react-router";
14import { useCallback, useMemo, useRef } from "react";
15
16import { getFallbackThreadIdAfterDelete } from "../components/Sidebar.logic";
17import { useComposerDraftStore } from "../composerDraftStore";
18import { terminalEnvironment } from "../state/terminal";
19import { threadEnvironment } from "../state/threads";
20import { vcsEnvironment } from "../state/vcs";
21import { useNewThreadHandler } from "./useHandleNewThread";
22import { refreshArchivedThreadsForEnvironment } from "../lib/archivedThreadsState";
23import { readLocalApi } from "../localApi";
24import {
25 readEnvironmentSupportsPinning,
26 readEnvironmentSupportsSettlement,
27 readEnvironmentSupportsSnooze,
28 readEnvironmentSupportsVisitedTracking,
29 readEnvironmentThreadRefs,
30 readProject,
31 readThreadShell,
32} from "../state/entities";
33import { useUiStateStore } from "../uiStateStore";
34import { useTerminalUiStateStore } from "../terminalUiStateStore";
35import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
36import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
37import { stackedThreadToast, toastManager } from "../components/ui/toast";
38import { useClientSettings } from "./useSettings";
39import { useAtomCommand } from "../state/use-atom-command";
40
41export class ThreadArchiveBlockedError extends Schema.TaggedErrorClass<ThreadArchiveBlockedError>()(
42 "ThreadArchiveBlockedError",
43 {
44 environmentId: EnvironmentId,
45 threadId: ThreadId,
46 },
47) {
48 override get message(): string {
49 return "Cannot archive a running thread.";
50 }
51}
52
53export class ThreadSettlementUnsupportedError extends Schema.TaggedErrorClass<ThreadSettlementUnsupportedError>()(
54 "ThreadSettlementUnsupportedError",
55 {
56 environmentId: EnvironmentId,
57 threadId: ThreadId,
58 },
59) {
60 override get message(): string {
61 return "This environment's server does not support settling yet. Update the server to use Settle.";
62 }
63}
64
65export class ThreadSettleBlockedError extends Schema.TaggedErrorClass<ThreadSettleBlockedError>()(
66 "ThreadSettleBlockedError",
67 {
68 environmentId: EnvironmentId,
69 threadId: ThreadId,
70 },
71) {
72 override get message(): string {
73 return "This thread still needs attention. Resolve or interrupt it first, then try again.";
74 }
75}
76
77export class ThreadSnoozeUnsupportedError extends Schema.TaggedErrorClass<ThreadSnoozeUnsupportedError>()(
78 "ThreadSnoozeUnsupportedError",
79 {
80 environmentId: EnvironmentId,
81 threadId: ThreadId,
82 },
83) {
84 override get message(): string {
85 return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
86 }
87}
88
89export class ThreadSnoozeBlockedError extends Schema.TaggedErrorClass<ThreadSnoozeBlockedError>()(
90 "ThreadSnoozeBlockedError",
91 {
92 environmentId: EnvironmentId,
93 threadId: ThreadId,
94 },
95) {
96 override get message(): string {
97 return "This thread is waiting on you. Respond to the pending request before snoozing it.";
98 }
99}
100
101export class ThreadPinningUnsupportedError extends Schema.TaggedErrorClass<ThreadPinningUnsupportedError>()(
102 "ThreadPinningUnsupportedError",
103 {
104 environmentId: EnvironmentId,
105 threadId: ThreadId,
106 },
107) {
108 override get message(): string {
109 return "This environment's server does not support pinning yet. Update the server to use Pin.";
110 }
111}
112
113/**
114 * Marks a thread unread. Servers with visited tracking own the unread marker
115 * (thread.mark-unread rewinds the server-side visited watermark, syncing the
116 * marker to every device); older servers keep the browser-local marker.
117 */
118export function useMarkThreadUnread() {
119 const markThreadUnreadMutation = useAtomCommand(threadEnvironment.markUnread, {
120 reportFailure: false,
121 });
122 const markThreadUnreadLocal = useUiStateStore((state) => state.markThreadUnread);
123 return useCallback(
124 (target: ScopedThreadRef) => {
125 if (readEnvironmentSupportsVisitedTracking(target.environmentId)) {
126 void markThreadUnreadMutation({
127 environmentId: target.environmentId,
128 input: { threadId: target.threadId },
129 });
130 return;
131 }
132 const thread = readThreadShell(target);
133 markThreadUnreadLocal(scopedThreadKey(target), thread?.latestRun?.completedAt);
134 },
135 [markThreadUnreadLocal, markThreadUnreadMutation],
136 );
137}
138
139export function useThreadActions() {
140 const closeTerminal = useAtomCommand(terminalEnvironment.close);
141 const archiveThreadMutation = useAtomCommand(threadEnvironment.archive, {
142 reportFailure: false,
143 });
144 const unarchiveThreadMutation = useAtomCommand(threadEnvironment.unarchive, {
145 reportFailure: false,
146 });
147 const deleteThreadMutation = useAtomCommand(threadEnvironment.delete, {
148 reportFailure: false,
149 });
150 const settleThreadMutation = useAtomCommand(threadEnvironment.settle, {
151 reportFailure: false,
152 });
153 const unsettleThreadMutation = useAtomCommand(threadEnvironment.unsettle, {
154 reportFailure: false,
155 });
156 const pinThreadMutation = useAtomCommand(threadEnvironment.pin, {
157 reportFailure: false,
158 });
159 const unpinThreadMutation = useAtomCommand(threadEnvironment.unpin, {
160 reportFailure: false,
161 });
162 const snoozeThreadMutation = useAtomCommand(threadEnvironment.snooze, {
163 reportFailure: false,
164 });
165 const unsnoozeThreadMutation = useAtomCommand(threadEnvironment.unsnooze, {
166 reportFailure: false,
167 });
168 const markThreadUnread = useMarkThreadUnread();
169 const stopThreadSession = useAtomCommand(threadEnvironment.stopSession);
170 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
171 reportFailure: false,
172 });
173 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
174 reportFailure: false,
175 });
176 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
177 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
178 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
179 const clearProjectDraftThreadById = useComposerDraftStore(
180 (store) => store.clearProjectDraftThreadById,
181 );
182 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
183 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
184 const router = useRouter();
185 const handleNewThread = useNewThreadHandler();
186 // Keep a ref so archiveThread can call handleNewThread without appearing in
187 // its dependency array — handleNewThread is inherently unstable (depends on
188 // the projects list) and would otherwise cascade new references into every
189 // sidebar row via archiveThread → attemptArchiveThread.
190 const handleNewThreadRef = useRef(handleNewThread);
191 handleNewThreadRef.current = handleNewThread;
192
193 const resolveThreadTarget = useCallback((target: ScopedThreadRef) => {
194 const thread = readThreadShell(target);
195 if (!thread) {
196 return null;
197 }
198 return {
199 thread,
200 threadRef: target,
201 };
202 }, []);
203 const getCurrentRouteThreadRef = useCallback(() => {
204 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
205 return resolveThreadRouteRef(currentRouteParams);
206 }, [router]);
207
208 const archiveThread = useCallback(
209 async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
210 const resolved = resolveThreadTarget(target);
211 if (!resolved) return AsyncResult.success(undefined);
212 const { thread, threadRef } = resolved;
213 if (thread.runtime?.status === "running" && thread.runtime.activeRunId != null) {
214 return AsyncResult.failure(
215 Cause.fail(
216 new ThreadArchiveBlockedError({
217 environmentId: threadRef.environmentId,
218 threadId: threadRef.threadId,
219 }),
220 ),
221 );
222 }
223
224 const currentRouteThreadRef = getCurrentRouteThreadRef();
225 const shouldNavigateToDraft =
226 currentRouteThreadRef?.threadId === threadRef.threadId &&
227 currentRouteThreadRef.environmentId === threadRef.environmentId;
228 const archiveResult = await archiveThreadMutation({
229 environmentId: threadRef.environmentId,
230 input: { threadId: threadRef.threadId },
231 });
232 if (archiveResult._tag === "Failure") {
233 return archiveResult;
234 }
235 const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
236 if (wokeAt !== null) {
237 markThreadVisited(scopedThreadKey(threadRef), wokeAt);
238 }
239 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
240 opts.onArchived?.();
241
242 if (shouldNavigateToDraft) {
243 const navigationResult = await settlePromise(() =>
244 handleNewThreadRef.current(scopeProjectRef(thread.environmentId, thread.projectId)),
245 );
246 if (navigationResult._tag === "Failure") {
247 return navigationResult;
248 }
249 return archiveResult;
250 }
251
252 return archiveResult;
253 },
254 [archiveThreadMutation, getCurrentRouteThreadRef, markThreadVisited, resolveThreadTarget],
255 );
256
257 const unarchiveThread = useCallback(
258 async (target: ScopedThreadRef) => {
259 const result = await unarchiveThreadMutation({
260 environmentId: target.environmentId,
261 input: { threadId: target.threadId },
262 });
263 if (result._tag === "Success") {
264 refreshArchivedThreadsForEnvironment(target.environmentId);
265 }
266 return result;
267 },
268 [unarchiveThreadMutation],
269 );
270
271 const deleteThread = useCallback(
272 async (target: ScopedThreadRef, opts: { deletedThreadKeys?: ReadonlySet<string> } = {}) => {
273 const resolved = resolveThreadTarget(target);
274 if (!resolved) {
275 // Thread not in main store (e.g. archived thread) — dispatch delete directly.
276 const result = await deleteThreadMutation({
277 environmentId: target.environmentId,
278 input: { threadId: target.threadId },
279 });
280 if (result._tag === "Success") {
281 refreshArchivedThreadsForEnvironment(target.environmentId);
282 }
283 return result;
284 }
285 const { thread, threadRef } = resolved;
286 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
287 const shell = readThreadShell(ref);
288 return shell === null ? [] : [shell];
289 });
290 const threadProject = readProject({
291 environmentId: threadRef.environmentId,
292 projectId: thread.projectId,
293 });
294 const deletedIds =
295 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
296 ? new Set<ThreadId>(
297 [...opts.deletedThreadKeys].flatMap((threadKey) => {
298 const ref = parseScopedThreadKey(threadKey);
299 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
300 }),
301 )
302 : undefined;
303 const survivingThreads =
304 deletedIds && deletedIds.size > 0
305 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
306 : threads;
307 const orphanedWorktreePath = getOrphanedWorktreePathForThread(
308 survivingThreads,
309 threadRef.threadId,
310 );
311 const displayWorktreePath = orphanedWorktreePath
312 ? formatWorktreePathForDisplay(orphanedWorktreePath)
313 : null;
314 const canDeleteWorktree = orphanedWorktreePath !== null && threadProject !== null;
315 const localApi = readLocalApi();
316 let shouldDeleteWorktree = false;
317 if (canDeleteWorktree && localApi) {
318 const confirmationResult = await settlePromise(() =>
319 localApi.dialogs.confirm(
320 [
321 "This thread is the only one linked to this worktree:",
322 displayWorktreePath ?? orphanedWorktreePath,
323 "",
324 "Delete the worktree too?",
325 ].join("\n"),
326 ),
327 );
328 if (confirmationResult._tag === "Failure") {
329 return confirmationResult;
330 }
331 shouldDeleteWorktree = confirmationResult.value;
332 }
333
334 if (thread.runtime !== null) {
335 await stopThreadSession({
336 environmentId: threadRef.environmentId,
337 input: { threadId: threadRef.threadId },
338 });
339 }
340
341 await closeTerminal({
342 environmentId: threadRef.environmentId,
343 input: { threadId: threadRef.threadId, deleteHistory: true },
344 });
345
346 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
347 const currentRouteThreadRef = getCurrentRouteThreadRef();
348 const shouldNavigateToFallback =
349 currentRouteThreadRef?.threadId === threadRef.threadId &&
350 currentRouteThreadRef.environmentId === threadRef.environmentId;
351 const fallbackThreadId = getFallbackThreadIdAfterDelete({
352 threads,
353 deletedThreadId: threadRef.threadId,
354 deletedThreadIds,
355 sortOrder: sidebarThreadSortOrder,
356 });
357 const deleteResult = await deleteThreadMutation({
358 environmentId: threadRef.environmentId,
359 input: { threadId: threadRef.threadId },
360 });
361 if (deleteResult._tag === "Failure") {
362 return deleteResult;
363 }
364 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
365 clearComposerDraftForThread(threadRef);
366 clearProjectDraftThreadById(
367 scopeProjectRef(threadRef.environmentId, thread.projectId),
368 threadRef,
369 );
370 clearTerminalUiState(threadRef);
371
372 if (shouldNavigateToFallback) {
373 if (fallbackThreadId) {
374 const fallbackThread = readThreadShell(
375 scopeThreadRef(threadRef.environmentId, fallbackThreadId),
376 );
377 if (fallbackThread) {
378 const navigationResult = await settlePromise(() =>
379 router.navigate({
380 to: "/$environmentId/$threadId",
381 params: buildThreadRouteParams(
382 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
383 ),
384 replace: true,
385 }),
386 );
387 if (navigationResult._tag === "Failure") {
388 return navigationResult;
389 }
390 } else {
391 const navigationResult = await settlePromise(() =>
392 router.navigate({ to: "/", replace: true }),
393 );
394 if (navigationResult._tag === "Failure") {
395 return navigationResult;
396 }
397 }
398 } else {
399 const navigationResult = await settlePromise(() =>
400 router.navigate({ to: "/", replace: true }),
401 );
402 if (navigationResult._tag === "Failure") {
403 return navigationResult;
404 }
405 }
406 }
407
408 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
409 return deleteResult;
410 }
411
412 const removeResult = await removeWorktree({
413 environmentId: threadRef.environmentId,
414 input: {
415 cwd: threadProject.workspaceRoot,
416 path: orphanedWorktreePath,
417 force: true,
418 },
419 });
420 const refreshResult =
421 removeResult._tag === "Success"
422 ? await refreshVcsStatus({
423 environmentId: threadRef.environmentId,
424 input: { cwd: threadProject.workspaceRoot },
425 })
426 : null;
427 const cleanupFailure =
428 removeResult._tag === "Failure"
429 ? removeResult
430 : refreshResult?._tag === "Failure"
431 ? refreshResult
432 : null;
433 if (cleanupFailure) {
434 const error = squashAtomCommandFailure(cleanupFailure);
435 const message = error instanceof Error ? error.message : "Unknown error removing worktree.";
436 console.error("Failed to remove orphaned worktree after thread deletion", {
437 threadId: threadRef.threadId,
438 projectCwd: threadProject.workspaceRoot,
439 worktreePath: orphanedWorktreePath,
440 error,
441 });
442 toastManager.add(
443 stackedThreadToast({
444 type: "error",
445 title: "Thread deleted, but worktree removal failed",
446 description: `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`,
447 }),
448 );
449 return cleanupFailure;
450 }
451 return deleteResult;
452 },
453 [
454 clearComposerDraftForThread,
455 clearProjectDraftThreadById,
456 clearTerminalUiState,
457 closeTerminal,
458 deleteThreadMutation,
459 getCurrentRouteThreadRef,
460 refreshVcsStatus,
461 removeWorktree,
462 router,
463 resolveThreadTarget,
464 sidebarThreadSortOrder,
465 stopThreadSession,
466 ],
467 );
468
469 const settleThread = useCallback(
470 async (target: ScopedThreadRef) => {
471 // Version skew: never send the command to a server that predates it —
472 // the raw protocol rejection would read as a random failure.
473 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
474 return AsyncResult.failure(
475 Cause.fail(
476 new ThreadSettlementUnsupportedError({
477 environmentId: target.environmentId,
478 threadId: target.threadId,
479 }),
480 ),
481 );
482 }
483 const resolved = resolveThreadTarget(target);
484 // Settle may only target what effectiveSettled could classify as
485 // settled: not starting/running sessions, not threads waiting on
486 // approvals or user input. Anything else would hide live work.
487 if (resolved && !canSettle(resolved.thread, { now: new Date().toISOString() })) {
488 return AsyncResult.failure(
489 Cause.fail(
490 new ThreadSettleBlockedError({
491 environmentId: resolved.threadRef.environmentId,
492 threadId: resolved.threadRef.threadId,
493 }),
494 ),
495 );
496 }
497 const wokeAt = resolved
498 ? threadWokeAt(resolved.thread, { now: new Date().toISOString() })
499 : null;
500 // Settle is a high-frequency lifecycle action and stays silent — no
501 // toast.
502 const result = await settleThreadMutation({
503 environmentId: target.environmentId,
504 input: { threadId: target.threadId },
505 });
506 if (result._tag === "Success" && wokeAt !== null) {
507 markThreadVisited(scopedThreadKey(target), wokeAt);
508 }
509 return result;
510 },
511 [markThreadVisited, resolveThreadTarget, settleThreadMutation],
512 );
513
514 const unsettleThread = useCallback(
515 async (target: ScopedThreadRef) => {
516 if (!readEnvironmentSupportsSettlement(target.environmentId)) {
517 return AsyncResult.failure(
518 Cause.fail(
519 new ThreadSettlementUnsupportedError({
520 environmentId: target.environmentId,
521 threadId: target.threadId,
522 }),
523 ),
524 );
525 }
526 // reason "user" pins the thread active: auto-settle (PR merged /
527 // inactivity) stays suppressed until real activity clears the pin.
528 return unsettleThreadMutation({
529 environmentId: target.environmentId,
530 input: { threadId: target.threadId, reason: "user" },
531 });
532 },
533 [unsettleThreadMutation],
534 );
535
536 const pinThread = useCallback(
537 async (target: ScopedThreadRef) => {
538 // Version skew: never send the command to a server that predates it.
539 if (!readEnvironmentSupportsPinning(target.environmentId)) {
540 return AsyncResult.failure(
541 Cause.fail(
542 new ThreadPinningUnsupportedError({
543 environmentId: target.environmentId,
544 threadId: target.threadId,
545 }),
546 ),
547 );
548 }
549 return pinThreadMutation({
550 environmentId: target.environmentId,
551 input: { threadId: target.threadId },
552 });
553 },
554 [pinThreadMutation],
555 );
556
557 const unpinThread = useCallback(
558 async (target: ScopedThreadRef) => {
559 if (!readEnvironmentSupportsPinning(target.environmentId)) {
560 return AsyncResult.failure(
561 Cause.fail(
562 new ThreadPinningUnsupportedError({
563 environmentId: target.environmentId,
564 threadId: target.threadId,
565 }),
566 ),
567 );
568 }
569 return unpinThreadMutation({
570 environmentId: target.environmentId,
571 input: { threadId: target.threadId },
572 });
573 },
574 [unpinThreadMutation],
575 );
576
577 const snoozeThread = useCallback(
578 async (target: ScopedThreadRef, snoozedUntil: string) => {
579 // Version skew: never send the command to a server that predates it.
580 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
581 return AsyncResult.failure(
582 Cause.fail(
583 new ThreadSnoozeUnsupportedError({
584 environmentId: target.environmentId,
585 threadId: target.threadId,
586 }),
587 ),
588 );
589 }
590 const resolved = resolveThreadTarget(target);
591 // Blocked-on-you work and queued turns can't be snoozed away —
592 // client-side twin of the server invariants so the UI rejects before
593 // a round trip.
594 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
595 return AsyncResult.failure(
596 Cause.fail(
597 new ThreadSnoozeBlockedError({
598 environmentId: resolved.threadRef.environmentId,
599 threadId: resolved.threadRef.threadId,
600 }),
601 ),
602 );
603 }
604 return snoozeThreadMutation({
605 environmentId: target.environmentId,
606 input: { threadId: target.threadId, snoozedUntil },
607 });
608 },
609 [resolveThreadTarget, snoozeThreadMutation],
610 );
611
612 const unsnoozeThread = useCallback(
613 async (target: ScopedThreadRef) => {
614 if (!readEnvironmentSupportsSnooze(target.environmentId)) {
615 return AsyncResult.failure(
616 Cause.fail(
617 new ThreadSnoozeUnsupportedError({
618 environmentId: target.environmentId,
619 threadId: target.threadId,
620 }),
621 ),
622 );
623 }
624 return unsnoozeThreadMutation({
625 environmentId: target.environmentId,
626 input: { threadId: target.threadId, reason: "user" },
627 });
628 },
629 [unsnoozeThreadMutation],
630 );
631
632 const confirmAndDeleteThread = useCallback(
633 async (target: ScopedThreadRef) => {
634 const localApi = readLocalApi();
635 const resolved = resolveThreadTarget(target);
636
637 if (confirmThreadDelete && localApi) {
638 const title = resolved?.thread.title ?? "this thread";
639 const confirmationResult = await settlePromise(() =>
640 localApi.dialogs.confirm(
641 [
642 `Delete thread "${title}"?`,
643 "This permanently clears conversation history for this thread.",
644 ].join("\n"),
645 ),
646 );
647 if (confirmationResult._tag === "Failure") {
648 return confirmationResult;
649 }
650 if (!confirmationResult.value) {
651 return AsyncResult.success(undefined);
652 }
653 }
654
655 return deleteThread(target);
656 },
657 [confirmThreadDelete, deleteThread, resolveThreadTarget],
658 );
659
660 return useMemo(
661 () => ({
662 archiveThread,
663 unarchiveThread,
664 deleteThread,
665 confirmAndDeleteThread,
666 settleThread,
667 unsettleThread,
668 snoozeThread,
669 unsnoozeThread,
670 pinThread,
671 unpinThread,
672 markThreadUnread,
673 }),
674 [
675 archiveThread,
676 confirmAndDeleteThread,
677 deleteThread,
678 markThreadUnread,
679 pinThread,
680 settleThread,
681 snoozeThread,
682 unarchiveThread,
683 unpinThread,
684 unsettleThread,
685 unsnoozeThread,
686 ],
687 );
688}