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

useThreadActions.ts

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