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