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

useThreadActions.ts

609 lines21.6 KB

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