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

useThreadActions.ts

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