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

useThreadActions.ts

952 lines33.1 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";
24​
25import { getFallbackThreadIdAfterDelete, pinOrderKeyBetween } from "../components/Sidebar.logic";
26import { useComposerDraftStore } from "../composerDraftStore";
27import { environmentSession, readEnvironmentScope } from "../state/session";
28import { appAtomRegistry } from "../rpc/atomRegistry";
29import { environmentServerConfigsAtom } from "../state/server";
30import { isScratchProject } from "@t3tools/client-runtime/state/projects";
31import { orchestrationEnvironment } from "../state/orchestration";
32import { projectEnvironment } from "../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 readEnvironmentServerConfigLoaded,
41 readEnvironmentSupportsAutoSettleOptOut,
42 readEnvironmentThreadRefs,
43 readProject,
44 readThreadShell,
45 readThreadShells,
46} from "../state/entities";
47import { useUiStateStore } from "../uiStateStore";
48import { clearThreadPreviewState } from "../previewStateStore";
49import { useTerminalUiStateStore } from "../terminalUiStateStore";
50import { buildThreadRouteParams, resolveThreadRouteRef } from "../threadRoutes";
51import { formatWorktreePathForDisplay, getOrphanedWorktreePathForThread } from "../worktreeCleanup";
52import { stackedThreadToast, toastManager } from "../components/ui/toast";
53import { useClientSettings } from "./useSettings";
54import * as ThreadUndo from "@t3tools/client-runtime/state/thread-undo";
55import { showThreadUndoNotice } from "./showThreadUndoNotice";
56import { useAtomCommand } from "../state/use-atom-command";
57import { useOrchestrationCommand } from "../state/use-orchestration-command";
58import { useAtomQueryRunner } from "../state/use-atom-query-runner";
59​
60export class ThreadArchiveBlockedError extends Schema.TaggedError<ThreadArchiveBlockedError>()(
61 "ThreadArchiveBlockedError",
62 {
63 environmentId: EnvironmentId,
64 threadId: ThreadId,
65 },
66) {
67 override get message(): string {
68 return "Cannot archive while the provider is active.";
69 }
71​
72export class ThreadSettlementUnsupportedError extends Schema.TaggedError<ThreadSettlementUnsupportedError>()(
73 "ThreadSettlementUnsupportedError",
74 {
75 environmentId: EnvironmentId,
76 threadId: ThreadId,
77 },
78) {
79 override get message(): string {
80 return "This environment's server does not support settling yet. Update the server to use Settle.";
81 }
83​
84export class ThreadSnoozeUnsupportedError extends Schema.TaggedError<ThreadSnoozeUnsupportedError>()(
85 "ThreadSnoozeUnsupportedError",
86 {
87 environmentId: EnvironmentId,
88 threadId: ThreadId,
89 },
90) {
91 override get message(): string {
92 return "This environment's server does not support snoozing yet. Update the server to use Snooze.";
93 }
95​
96export class ThreadSnoozeBlockedError extends Schema.TaggedError<ThreadSnoozeBlockedError>()(
97 "ThreadSnoozeBlockedError",
98 {
99 environmentId: EnvironmentId,
100 threadId: ThreadId,
101 },
102) {
103 override get message(): string {
104 return "This thread is waiting on you. Respond to the pending request before snoozing it.";
105 }
107​
108function topOfPinnedRunOrderKey(): string | undefined {
109 let firstKey: string | null = null;
110 for (const shell of readThreadShells()) {
111 if (shell.pinnedAt == null || shell.pinOrderKey == null) continue;
112 if (firstKey === null || shell.pinOrderKey < firstKey) firstKey = shell.pinOrderKey;
113 }
114 return pinOrderKeyBetween(null, firstKey) ?? undefined;
116​
117export class ThreadAutoSettleOptOutUnsupportedError extends Schema.TaggedError<ThreadAutoSettleOptOutUnsupportedError>()(
118 "ThreadAutoSettleOptOutUnsupportedError",
119 {
120 environmentId: EnvironmentId,
121 threadId: ThreadId,
122 },
123) {
124 override get message(): string {
125 return "This environment's server does not support turning auto-settle off per thread yet. Update the server to use it.";
126 }
128​
129export class ThreadPinningUnsupportedError extends Schema.TaggedError<ThreadPinningUnsupportedError>()(
130 "ThreadPinningUnsupportedError",
131 {
132 environmentId: EnvironmentId,
133 threadId: ThreadId,
134 },
135) {
136 override get message(): string {
137 return "This environment's server does not support pinning yet. Update the server to use Pin.";
138 }
140​
141export class ThreadPinReorderUnsupportedError extends Schema.TaggedError<ThreadPinReorderUnsupportedError>()(
142 "ThreadPinReorderUnsupportedError",
143 {
144 environmentId: EnvironmentId,
145 threadId: ThreadId,
146 },
147) {
148 override get message(): string {
149 return "This environment's server does not support reordering pinned threads yet. Update the server to reorder pins.";
150 }
152​
153export class ThreadActiveReorderUnsupportedError extends Schema.TaggedError<ThreadActiveReorderUnsupportedError>()(
154 "ThreadActiveReorderUnsupportedError",
155 {
156 environmentId: EnvironmentId,
157 threadId: ThreadId,
158 },
159) {
160 override get message(): string {
161 return "Update this environment's server to reorder active threads.";
162 }
164​
165async function requestThreadUnpinConfirmation(input: {
166 enabled: boolean;
167 title: string;
168 confirm: ((message: string) => Promise<boolean>) | null;
169}) {
170 const { confirm } = input;
171 if (!input.enabled || confirm === null) {
172 return AsyncResult.success(true);
173 }
174​
175 return settlePromise(() =>
176 confirm(
177 [
178 `Unpin thread "${input.title}"?`,
179 "This will move the thread out of your pinned section.",
180 ].join("\n"),
181 ),
182 );
184​
185export async function navigateAfterThreadDeletion(navigate: () => Promise<void>) {
186 const result = await settlePromise(navigate);
187 if (result._tag === "Failure") {
188 const error = squashAtomCommandFailure(result);
189 toastManager.add(
190 stackedThreadToast({
191 type: "error",
192 title: "Thread deleted, but navigation failed",
193 description: error instanceof Error ? error.message : "An error occurred.",
194 }),
195 );
196 }
198​
199function useMarkThreadUnread() {
200 const markThreadUnreadMutation = useAtomCommand(threadEnvironment.markUnread, {
201 reportFailure: false,
202 });
203 const markThreadUnreadLocal = useUiStateStore((state) => state.markThreadUnread);
204 return (target: ScopedThreadRef) => {
205 if (readEnvironmentServerConfigLoaded(target.environmentId)) {
206 void markThreadUnreadMutation({
207 environmentId: target.environmentId,
208 input: { threadId: target.threadId },
209 });
210 return;
211 }
212 const thread = readThreadShell(target);
213 markThreadUnreadLocal(scopedThreadKey(target), thread?.latestRun?.completedAt);
214 };
216​
217export function useAcknowledgeThreadWoke() {
218 const visitThreadMutation = useAtomCommand(threadEnvironment.visit, { reportFailure: false });
219 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
220 return (target: ScopedThreadRef, wokeAt: string) => {
221 if (readEnvironmentServerConfigLoaded(target.environmentId)) {
222 void visitThreadMutation({
223 environmentId: target.environmentId,
224 input: { threadId: target.threadId, visitedAt: wokeAt },
225 });
226 return;
227 }
228 markThreadVisited(scopedThreadKey(target), wokeAt);
229 };
231​
232/** A No project thread that already has its own folder, on a server that can promote it. */
233export function canTurnThreadIntoProject(threadRef: ScopedThreadRef): boolean {
234 const thread = readThreadShell(threadRef);
235 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(threadRef.environmentId);
236 if (!thread?.worktreePath || config?.environment.capabilities.threadProjectFromScratch !== true) {
237 return false;
238 }
239 const project = readProject({
240 environmentId: threadRef.environmentId,
241 projectId: thread.projectId,
242 });
243 return project !== null && isScratchProject(project, config.scratchWorkspaceRoot);
245​
246function threadOperationFailure(target: ScopedThreadRef) {
247 return readEnvironmentScope(target.environmentId, AuthOrchestrationOperateScope)
248 ? null
249 : AsyncResult.failure(
250 Cause.fail(
251 new EnvironmentAuthorizationError({
252 message: "This connection cannot change threads.",
253 requiredScope: AuthOrchestrationOperateScope,
254 }),
255 ),
256 );
258​
259export function useThreadActions() {
260 const archiveThreadMutation = useOrchestrationCommand(threadEnvironment.archive, {
261 reportFailure: false,
262 });
263 const unarchiveThreadMutation = useOrchestrationCommand(threadEnvironment.unarchive, {
264 reportFailure: false,
265 });
266 const deleteThreadMutation = useOrchestrationCommand(threadEnvironment.delete, {
267 reportFailure: false,
268 });
269 const settleThreadMutation = useOrchestrationCommand(threadEnvironment.settle, {
270 reportFailure: false,
271 });
272 const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, {
273 reportFailure: false,
274 });
275 const pinThreadMutation = useOrchestrationCommand(threadEnvironment.pin, {
276 reportFailure: false,
277 });
278 const unpinThreadMutation = useOrchestrationCommand(threadEnvironment.unpin, {
279 reportFailure: false,
280 });
281 const setThreadAutoSettleMutation = useOrchestrationCommand(threadEnvironment.setAutoSettle, {
282 reportFailure: false,
283 });
284 const reorderPinnedThreadMutation = useOrchestrationCommand(threadEnvironment.reorderPin, {
285 reportFailure: false,
286 });
287 const reorderActiveThreadMutation = useOrchestrationCommand(threadEnvironment.reorderActive, {
288 reportFailure: false,
289 });
290 const snoozeThreadMutation = useOrchestrationCommand(threadEnvironment.snooze, {
291 reportFailure: false,
292 });
293 const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, {
294 reportFailure: false,
295 });
296 const markThreadUnread = useMarkThreadUnread();
297 const createProjectFromThread = useAtomCommand(projectEnvironment.createFromThread, {
298 reportFailure: false,
299 });
300 const stopThreadSession = useOrchestrationCommand(threadEnvironment.stopSession);
301 const removeWorktree = useAtomCommand(vcsEnvironment.removeWorktree, {
302 reportFailure: false,
303 });
304 const loadSessionState = useAtomQueryRunner(environmentSession.sessionStateAtom, {
305 reportFailure: false,
306 });
307 const loadWorktreeThreadIds = useAtomQueryRunner(orchestrationEnvironment.worktreeThreadIds, {
308 reportFailure: false,
309 refresh: true,
310 });
311 const refreshVcsStatus = useAtomCommand(vcsEnvironment.refreshStatus, {
312 reportFailure: false,
313 });
314 const sidebarThreadSortOrder = useClientSettings((settings) => settings.sidebarThreadSortOrder);
315 const confirmThreadDelete = useClientSettings((settings) => settings.confirmThreadDelete);
316 const confirmThreadUnpin = useClientSettings((settings) => settings.confirmThreadUnpin);
317 const clearComposerDraftForThread = useComposerDraftStore((store) => store.clearDraftThread);
318 const clearProjectDraftThreadById = useComposerDraftStore(
319 (store) => store.clearProjectDraftThreadById,
320 );
321 const clearTerminalUiState = useTerminalUiStateStore((state) => state.clearTerminalUiState);
322 const markThreadVisited = useUiStateStore((state) => state.markThreadVisited);
323 const router = useRouter();
324 const handleNewThread = useNewThreadHandler();
325​
326 const resolveThreadTarget = (target: ScopedThreadRef) => {
327 const thread = readThreadShell(target);
328 if (!thread) {
329 return null;
330 }
331 return {
332 thread,
333 threadRef: target,
334 };
335 };
336 const getCurrentRouteThreadRef = () => {
337 const currentRouteParams = router.state.matches[router.state.matches.length - 1]?.params ?? {};
338 return resolveThreadRouteRef(currentRouteParams);
339 };
340​
341 const unarchiveThread = async (target: ScopedThreadRef, opts: { navigate?: boolean } = {}) => {
342 ThreadUndo.invalidate("archive", scopedThreadKey(target));
343 const result = await unarchiveThreadMutation({
344 environmentId: target.environmentId,
345 input: { threadId: target.threadId },
346 });
347 if (result._tag === "Failure") {
348 return result;
349 }
350 refreshArchivedThreadsForEnvironment(target.environmentId);
351 if (opts.navigate) {
352 return settlePromise(() =>
353 router.navigate({
354 to: "/$environmentId/$threadId",
355 params: buildThreadRouteParams(target),
356 }),
357 );
358 }
359 return result;
360 };
361​
362 const archiveThread = async (target: ScopedThreadRef, opts: { onArchived?: () => void } = {}) => {
363 const resolved = resolveThreadTarget(target);
364 if (!resolved) return AsyncResult.success(undefined);
365 const { thread, threadRef } = resolved;
366 if (!threadRuntimeCanArchive(thread.runtime)) {
367 return AsyncResult.failure(
368 Cause.fail(
369 new ThreadArchiveBlockedError({
370 environmentId: threadRef.environmentId,
371 threadId: threadRef.threadId,
372 }),
373 ),
374 );
375 }
376​
377 const currentRouteThreadRef = getCurrentRouteThreadRef();
378 const shouldNavigateToDraft =
379 currentRouteThreadRef?.threadId === threadRef.threadId &&
380 currentRouteThreadRef.environmentId === threadRef.environmentId;
381 const action = ThreadUndo.begin("archive", scopedThreadKey(threadRef));
382 const archiveResult = await archiveThreadMutation({
383 environmentId: threadRef.environmentId,
384 input: { threadId: threadRef.threadId },
385 });
386 if (archiveResult._tag === "Failure") {
387 action.finish();
388 return archiveResult;
389 }
390 const wokeAt = threadWokeAt(thread, { now: new Date().toISOString() });
391 if (wokeAt !== null) {
392 markThreadVisited(scopedThreadKey(threadRef), wokeAt);
393 }
394 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
395 opts.onArchived?.();
396 showThreadUndoNotice({
397 action: "Archived",
398 claim: action,
399 undo: () => unarchiveThread(threadRef, { navigate: shouldNavigateToDraft }),
400 failureTitle: "Failed to undo archive",
401 });
402​
403 if (shouldNavigateToDraft) {
404 const navigationResult = await settlePromise(() =>
405 handleNewThread(scopeProjectRef(thread.environmentId, thread.projectId)),
406 );
407 if (navigationResult._tag === "Failure") {
408 return navigationResult;
409 }
410 return archiveResult;
411 }
412​
413 return archiveResult;
414 };
415​
416 const deleteThread = async (
417 target: ScopedThreadRef,
418 opts: { deletedThreadKeys?: ReadonlySet<string> } = {},
419 ) => {
420 const permissionFailure = threadOperationFailure(target);
421 if (permissionFailure) return permissionFailure;
422 const resolved = resolveThreadTarget(target);
423 if (!resolved) {
424 const result = await deleteThreadMutation({
425 environmentId: target.environmentId,
426 input: { threadId: target.threadId },
427 });
428 if (result._tag === "Success") {
429 refreshArchivedThreadsForEnvironment(target.environmentId);
430 clearThreadPreviewState(target);
431 }
432 return result;
433 }
434 const { thread, threadRef } = resolved;
435 const threads = readEnvironmentThreadRefs(threadRef.environmentId).flatMap((ref) => {
436 const shell = readThreadShell(ref);
437 return shell === null ? [] : [shell];
438 });
439 const threadProject = readProject({
440 environmentId: threadRef.environmentId,
441 projectId: thread.projectId,
442 });
443 const deletedIds =
444 opts.deletedThreadKeys && opts.deletedThreadKeys.size > 0
445 ? new Set<ThreadId>(
446 [...opts.deletedThreadKeys].flatMap((threadKey) => {
447 const ref = parseScopedThreadKey(threadKey);
448 return ref && ref.environmentId === threadRef.environmentId ? [ref.threadId] : [];
449 }),
450 )
451 : undefined;
452 const survivingThreads =
453 deletedIds && deletedIds.size > 0
454 ? threads.filter((entry) => entry.id === threadRef.threadId || !deletedIds.has(entry.id))
455 : threads;
456 const environmentConfig = appAtomRegistry
457 .get(environmentServerConfigsAtom)
458 .get(threadRef.environmentId);
459 let orphanedWorktreePath = getOrphanedWorktreePathForThread(
460 survivingThreads,
461 threadRef.threadId,
462 );
463 // A shell that leaves idle subagent children out cannot prove nobody else uses the worktree,
464 // so the server's list decides. A failed read keeps the worktree.
465 if (orphanedWorktreePath !== null && environmentConfig?.shellThreadFamilies === true) {
466 const occupants = await loadWorktreeThreadIds({
467 environmentId: threadRef.environmentId,
468 input: { worktreePath: orphanedWorktreePath },
469 });
470 if (
471 occupants._tag !== "Success" ||
472 occupants.value.threadIds.some(
473 (threadId) => threadId !== threadRef.threadId && deletedIds?.has(threadId) !== true,
474 )
475 ) {
476 orphanedWorktreePath = null;
477 }
478 }
479 const displayWorktreePath = orphanedWorktreePath
480 ? formatWorktreePathForDisplay(orphanedWorktreePath)
481 : null;
482 const localApi = readLocalApi();
483 let canDeleteWorktree = false;
484 if (
485 orphanedWorktreePath !== null &&
486 threadProject !== null &&
487 !isScratchProject(threadProject, environmentConfig?.scratchWorkspaceRoot) &&
488 localApi
489 ) {
490 const sessionResult = await loadSessionState(threadRef.environmentId);
491 const permissionFailure = threadOperationFailure(threadRef);
492 if (permissionFailure) return permissionFailure;
493 canDeleteWorktree =
494 sessionResult._tag === "Success" &&
495 sessionGrantsScope(sessionResult.value, AuthSourceControlWriteScope);
496 }
497 let shouldDeleteWorktree = false;
498 const environmentSettings = environmentConfig?.settings;
499 const automaticWorktreeCleanup = environmentSettings
500 ? resolveWorktreeCleanup(environmentSettings, thread.projectId).worktreeOnDelete
501 : false;
502 if (canDeleteWorktree && localApi && !automaticWorktreeCleanup) {
503 const confirmationResult = await settlePromise(() =>
504 localApi.dialogs.confirm(
505 [
506 "This thread is the only one linked to this worktree:",
507 displayWorktreePath ?? orphanedWorktreePath,
508 "",
509 "Delete the worktree too?",
510 ].join("\n"),
511 { variant: "destructive" },
512 ),
513 );
514 if (confirmationResult._tag === "Failure") {
515 return confirmationResult;
516 }
517 shouldDeleteWorktree = confirmationResult.value;
518 }
519​
520 if (thread.runtime !== null) {
521 await stopThreadSession({
522 environmentId: threadRef.environmentId,
523 input: { threadId: threadRef.threadId },
524 });
525 }
526​
527 const deletedThreadIds = deletedIds ?? new Set<ThreadId>();
528 const currentRouteThreadRef = getCurrentRouteThreadRef();
529 const shouldNavigateToFallback =
530 currentRouteThreadRef?.threadId === threadRef.threadId &&
531 currentRouteThreadRef.environmentId === threadRef.environmentId;
532 const fallbackThreadId = getFallbackThreadIdAfterDelete({
533 threads,
534 deletedThreadId: threadRef.threadId,
535 deletedThreadIds,
536 sortOrder: sidebarThreadSortOrder,
537 });
538 const deleteResult = await deleteThreadMutation({
539 environmentId: threadRef.environmentId,
540 input: { threadId: threadRef.threadId },
541 });
542 if (deleteResult._tag === "Failure") {
543 return deleteResult;
544 }
545 refreshArchivedThreadsForEnvironment(threadRef.environmentId);
546 releaseComposerDraftUploads(threadRef);
547 clearComposerDraftForThread(threadRef);
548 clearProjectDraftThreadById(
549 scopeProjectRef(threadRef.environmentId, thread.projectId),
550 threadRef,
551 );
552 clearTerminalUiState(threadRef);
553 clearThreadPreviewState(threadRef);
554​
555 if (shouldNavigateToFallback) {
556 const fallbackThread = fallbackThreadId
557 ? readThreadShell(scopeThreadRef(threadRef.environmentId, fallbackThreadId))
558 : null;
559 await navigateAfterThreadDeletion(() =>
560 fallbackThread
561 ? router.navigate({
562 to: "/$environmentId/$threadId",
563 params: buildThreadRouteParams(
564 scopeThreadRef(fallbackThread.environmentId, fallbackThread.id),
565 ),
566 replace: true,
567 })
568 : router.navigate({ to: "/", replace: true }),
569 );
570 }
571​
572 if (!shouldDeleteWorktree || !orphanedWorktreePath || !threadProject) {
573 return deleteResult;
574 }
575​
576 const removeResult = readEnvironmentScope(threadRef.environmentId, AuthSourceControlWriteScope)
577 ? await removeWorktree({
578 environmentId: threadRef.environmentId,
579 input: {
580 cwd: threadProject.workspaceRoot,
581 path: orphanedWorktreePath,
582 force: true,
583 },
584 })
585 : AsyncResult.failure(
586 Cause.fail(
587 new EnvironmentAuthorizationError({
588 message: "This connection can no longer remove worktrees.",
589 requiredScope: AuthSourceControlWriteScope,
590 }),
591 ),
592 );
593 const refreshResult =
594 removeResult._tag === "Success"
595 ? await refreshVcsStatus({
596 environmentId: threadRef.environmentId,
597 input: { cwd: threadProject.workspaceRoot },
598 })
599 : null;
600 const cleanupFailure =
601 removeResult._tag === "Failure"
602 ? removeResult
603 : refreshResult?._tag === "Failure"
604 ? refreshResult
605 : null;
606 if (cleanupFailure) {
607 const removalFailed = removeResult._tag === "Failure";
608 const error = squashAtomCommandFailure(cleanupFailure);
609 const message = error instanceof Error ? error.message : "An error occurred.";
610 console.error("Worktree cleanup failed after thread deletion", {
611 threadId: threadRef.threadId,
612 projectCwd: threadProject.workspaceRoot,
613 worktreePath: orphanedWorktreePath,
614 error,
615 });
616 toastManager.add(
617 stackedThreadToast({
618 type: "error",
619 title: removalFailed
620 ? "Failed to delete worktree"
621 : "Worktree deleted, but Git status refresh failed",
622 description: removalFailed
623 ? `Could not remove ${displayWorktreePath ?? orphanedWorktreePath}. ${message}`
624 : message,
625 }),
626 );
627 // Cleanup has its own toast; reporting its failure would falsely imply deletion failed.
628 }
629 return deleteResult;
630 };
631​
632 const unsettleThread = async (target: ScopedThreadRef) => {
633 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
634 return AsyncResult.failure(
635 Cause.fail(
636 new ThreadSettlementUnsupportedError({
637 environmentId: target.environmentId,
638 threadId: target.threadId,
639 }),
640 ),
641 );
642 }
643 ThreadUndo.invalidate("settle", scopedThreadKey(target));
644 // reason "user" pins active until real activity, suppressing auto-settle.
645 return unsettleThreadMutation({
646 environmentId: target.environmentId,
647 input: { threadId: target.threadId, reason: "user" },
648 });
649 };
650​
651 const setThreadAutoSettle = async (target: ScopedThreadRef, enabled: boolean) => {
652 if (!readEnvironmentSupportsAutoSettleOptOut(target.environmentId)) {
653 return AsyncResult.failure(
654 Cause.fail(
655 new ThreadAutoSettleOptOutUnsupportedError({
656 environmentId: target.environmentId,
657 threadId: target.threadId,
658 }),
659 ),
660 );
661 }
662 return setThreadAutoSettleMutation({
663 environmentId: target.environmentId,
664 input: { threadId: target.threadId, enabled },
665 });
666 };
667​
668 const pinThread = async (target: ScopedThreadRef, opts: { orderKey?: string } = {}) => {
669 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
670 return AsyncResult.failure(
671 Cause.fail(
672 new ThreadPinningUnsupportedError({
673 environmentId: target.environmentId,
674 threadId: target.threadId,
675 }),
676 ),
677 );
678 }
679 const orderKey = opts.orderKey ?? topOfPinnedRunOrderKey();
680 ThreadUndo.invalidate("pin", scopedThreadKey(target));
681 // Pinning clears snooze, so older Settled or Snoozed undos would fight this pin.
682 ThreadUndo.invalidate("settle", scopedThreadKey(target));
683 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
684 return pinThreadMutation({
685 environmentId: target.environmentId,
686 input: {
687 threadId: target.threadId,
688 ...(orderKey !== undefined ? { orderKey } : {}),
689 },
690 });
691 };
692​
693 const unpinThread = async (target: ScopedThreadRef) => {
694 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
695 return AsyncResult.failure(
696 Cause.fail(
697 new ThreadPinningUnsupportedError({
698 environmentId: target.environmentId,
699 threadId: target.threadId,
700 }),
701 ),
702 );
703 }
704 const thread = readThreadShell(target);
705 const undoPlan = ThreadUndo.planThreadUndo("unpin", thread);
706 const action = ThreadUndo.begin("pin", scopedThreadKey(target));
707 const result = await unpinThreadMutation({
708 environmentId: target.environmentId,
709 input: { threadId: target.threadId },
710 });
711 if (result._tag === "Success" && action.isCurrent()) {
712 showThreadUndoNotice({
713 action: "Unpinned",
714 claim: action,
715 undo: () => runUndoPlan(target, undoPlan),
716 failureTitle: "Failed to undo unpin",
717 });
718 } else {
719 action.finish();
720 }
721 return result;
722 };
723​
724 const settleThread = async (target: ScopedThreadRef) => {
725 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
726 return AsyncResult.failure(
727 Cause.fail(
728 new ThreadSettlementUnsupportedError({
729 environmentId: target.environmentId,
730 threadId: target.threadId,
731 }),
732 ),
733 );
734 }
735 const resolved = resolveThreadTarget(target);
736 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
737 const nowIso = new Date().toISOString();
738 const wokeAt = resolved ? threadWokeAt(resolved.thread, { now: nowIso }) : null;
739 const undoPlan = ThreadUndo.planThreadUndo("settle", resolved?.thread);
740 // An older unpin/snooze Undo would re-pin or re-snooze, and the server
741 // treats either as a promotion that un-settles; settling supersedes them.
742 ThreadUndo.invalidate("pin", scopedThreadKey(target));
743 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
744 const action = ThreadUndo.begin("settle", scopedThreadKey(target));
745 const result = await settleThreadMutation({
746 environmentId: target.environmentId,
747 input: { threadId: target.threadId },
748 });
749 if (result._tag !== "Success") {
750 action.finish();
751 return result;
752 }
753 if (wokeAt !== null) {
754 markThreadVisited(scopedThreadKey(target), wokeAt);
755 }
756 showThreadUndoNotice({
757 action: "Settled",
758 claim: action,
759 undo: () => runUndoPlan(target, undoPlan),
760 failureTitle: "Failed to undo settle",
761 });
762 return result;
763 };
764​
765 const confirmAndUnpinThread = async (target: ScopedThreadRef) => {
766 const permissionFailure = threadOperationFailure(target);
767 if (permissionFailure) return permissionFailure;
768 const localApi = readLocalApi();
769 const resolved = resolveThreadTarget(target);
770 const confirmationResult = await requestThreadUnpinConfirmation({
771 enabled: confirmThreadUnpin,
772 title: resolved?.thread.title ?? "this thread",
773 confirm: localApi ? (message) => localApi.dialogs.confirm(message) : null,
774 });
775 if (confirmationResult._tag === "Failure") {
776 return confirmationResult;
777 }
778 if (!confirmationResult.value) {
779 return AsyncResult.success(undefined);
780 }
781 return unpinThread(target);
782 };
783​
784 const reorderPinnedThread = async (target: ScopedThreadRef, orderKey: string) => {
785 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
786 return AsyncResult.failure(
787 Cause.fail(
788 new ThreadPinReorderUnsupportedError({
789 environmentId: target.environmentId,
790 threadId: target.threadId,
791 }),
792 ),
793 );
794 }
795 ThreadUndo.invalidate("pin", scopedThreadKey(target));
796 return reorderPinnedThreadMutation({
797 environmentId: target.environmentId,
798 input: { threadId: target.threadId, orderKey },
799 });
800 };
801​
802 const reorderActiveThread = async (target: ScopedThreadRef, orderKey: string) => {
803 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
804 return AsyncResult.failure(
805 Cause.fail(
806 new ThreadActiveReorderUnsupportedError({
807 environmentId: target.environmentId,
808 threadId: target.threadId,
809 }),
810 ),
811 );
812 }
813 return reorderActiveThreadMutation({
814 environmentId: target.environmentId,
815 input: { threadId: target.threadId, orderKey },
816 });
817 };
818​
819 const unsnoozeThread = async (target: ScopedThreadRef) => {
820 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
821 return AsyncResult.failure(
822 Cause.fail(
823 new ThreadSnoozeUnsupportedError({
824 environmentId: target.environmentId,
825 threadId: target.threadId,
826 }),
827 ),
828 );
829 }
830 ThreadUndo.invalidate("snooze", scopedThreadKey(target));
831 return unsnoozeThreadMutation({
832 environmentId: target.environmentId,
833 input: { threadId: target.threadId, reason: "user" },
834 });
835 };
836​
837 const snoozeThread = async (target: ScopedThreadRef, snoozedUntil: string) => {
838 if (!readEnvironmentServerConfigLoaded(target.environmentId)) {
839 return AsyncResult.failure(
840 Cause.fail(
841 new ThreadSnoozeUnsupportedError({
842 environmentId: target.environmentId,
843 threadId: target.threadId,
844 }),
845 ),
846 );
847 }
848 const resolved = resolveThreadTarget(target);
849 // oxlint-disable-next-line react/purity -- runs in an event handler (oxc#27309)
850 if (resolved && !canSnooze(resolved.thread, { now: new Date().toISOString() })) {
851 return AsyncResult.failure(
852 Cause.fail(
853 new ThreadSnoozeBlockedError({
854 environmentId: resolved.threadRef.environmentId,
855 threadId: resolved.threadRef.threadId,
856 }),
857 ),
858 );
859 }
860 const action = ThreadUndo.begin("snooze", scopedThreadKey(target));
861 const result = await snoozeThreadMutation({
862 environmentId: target.environmentId,
863 input: { threadId: target.threadId, snoozedUntil },
864 });
865 if (result._tag !== "Success") {
866 action.finish();
867 return result;
868 }
869 showThreadUndoNotice({
870 action: "Snoozed",
871 claim: action,
872 undo: () => runUndoPlan(target, ThreadUndo.planThreadUndo("snooze")),
873 failureTitle: "Failed to wake thread",
874 });
875 return result;
876 };
877​
878 const runUndoPlan = (target: ScopedThreadRef, plan: ThreadUndo.ThreadUndoPlan) =>
879 ThreadUndo.executeThreadUndo(
880 plan,
881 async (step) => {
882 switch (step.action) {
883 case "unsettle":
884 return unsettleThread(target);
885 case "unsnooze":
886 return unsnoozeThread(target);
887 case "pin":
888 return pinThread(
889 target,
890 step.orderKey === undefined ? {} : { orderKey: step.orderKey },
891 );
892 case "snooze":
893 return snoozeThreadMutation({
894 environmentId: target.environmentId,
895 input: { threadId: target.threadId, snoozedUntil: step.snoozedUntil },
896 });
897 }
898 },
899 (result) => result._tag === "Success",
900 );
901​
902 const confirmAndDeleteThread = async (target: ScopedThreadRef) => {
903 const permissionFailure = threadOperationFailure(target);
904 if (permissionFailure) return permissionFailure;
905 const localApi = readLocalApi();
906 const resolved = resolveThreadTarget(target);
907​
908 if (confirmThreadDelete && localApi) {
909 const title = resolved?.thread.title ?? "this thread";
910 const confirmationResult = await settlePromise(() =>
911 localApi.dialogs.confirm(
912 [
913 `Delete thread "${title}"?`,
914 "This permanently clears conversation history for this thread.",
915 ].join("\n"),
916 { variant: "destructive" },
917 ),
918 );
919 if (confirmationResult._tag === "Failure") {
920 return confirmationResult;
921 }
922 if (!confirmationResult.value) {
923 return AsyncResult.success(undefined);
924 }
925 }
926​
927 return deleteThread(target);
928 };
929​
930 return {
931 archiveThread,
932 unarchiveThread,
933 deleteThread,
934 confirmAndDeleteThread,
935 settleThread,
936 unsettleThread,
937 snoozeThread,
938 unsnoozeThread,
939 pinThread,
940 unpinThread,
941 confirmAndUnpinThread,
942 reorderPinnedThread,
943 reorderActiveThread,
944 markThreadUnread,
945 setThreadAutoSettle,
946 turnThreadIntoProject: (target: ScopedThreadRef) =>
947 createProjectFromThread({
948 environmentId: target.environmentId,
949 input: { threadId: target.threadId },
950 }),
951 };