The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg, useGT, useMessages } from "gt-react"; |
| 2 | import { errorDisplayMessage, thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { m } from "~/i18n/messages"; |
| 4 | import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection"; |
| 5 | import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; |
| 6 | import type { Dispatch } from "react"; |
| 7 | import type { ComposerThreadTarget } from "../../composerDraftStore"; |
| 8 | import type { ComposerHandleRef } from "../../composerHandleContext"; |
| 9 | import { |
| 10 | isThreadWokeUnseen, |
| 11 | branchMismatchKey, |
| 12 | isBranchMismatchDismissedForSession, |
| 13 | shouldShowBranchMismatchBanner, |
| 14 | chatActionErrorMessage, |
| 15 | makeThreadErrorSetter, |
| 16 | } from "../ChatView.logic"; |
| 17 | import { useStableCallback } from "../../hooks/useStableCallback"; |
| 18 | import { useDeadlinePassed, useNowAfter } from "../../hooks/useDeadline"; |
| 19 | import type { usePendingThreadRequests } from "./usePendingThreadRequests"; |
| 20 | import { |
| 21 | AuthOrchestrationOperateScope, |
| 22 | AuthSourceControlWriteScope, |
| 23 | type EnvironmentId, |
| 24 | type ScopedThreadRef, |
| 25 | type ThreadId, |
| 26 | ProviderInteractionMode, |
| 27 | RuntimeMode, |
| 28 | } from "@t3tools/contracts"; |
| 29 | import { |
| 30 | effectiveSnoozed, |
| 31 | snoozeWakeLabel, |
| 32 | threadWokeAt, |
| 33 | } from "@t3tools/client-runtime/state/thread-settled"; |
| 34 | import { |
| 35 | BACKGROUND_WORK_STOP_RETRY_AFTER_MS, |
| 36 | type BackgroundWorkStopRequest, |
| 37 | isBackgroundWorkStopPending, |
| 38 | } from "@t3tools/client-runtime/state/thread-execution"; |
| 39 | import { useAcknowledgeThreadWoke, useThreadActions } from "../../hooks/useThreadActions"; |
| 40 | import { settleAndAdvance } from "../../settleAndAdvance"; |
| 41 | import type { ChatShortcutCommands } from "./useChatShortcuts"; |
| 42 | import { resolveThreadLastVisitedAt } from "../Sidebar.logic"; |
| 43 | import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 44 | import { type SetStateAction, useRef, useState } from "react"; |
| 45 | import { useNavigate, useRouter } from "@tanstack/react-router"; |
| 46 | import { |
| 47 | isAtomCommandInterrupted, |
| 48 | squashAtomCommandFailure, |
| 49 | type AtomCommandResult, |
| 50 | } from "@t3tools/client-runtime/state/runtime"; |
| 51 | import { useUiStateStore } from "../../uiStateStore"; |
| 52 | import { type ChatMessage, DEFAULT_INTERACTION_MODE } from "../../types"; |
| 53 | import { AlarmClockIcon, CheckCircle2Icon } from "lucide-react"; |
| 54 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 55 | import { titleRegenerationToast } from "../threadTitleRegenerationToast"; |
| 56 | import { newMessageId } from "~/lib/utils"; |
| 57 | import { buildThreadRouteParams } from "../../threadRoutes"; |
| 58 | import { composerDraftHasUserContent, useComposerDraftStore } from "../../composerDraftStore"; |
| 59 | import { useEnvironmentScope } from "~/state/session"; |
| 60 | import { threadEnvironment } from "../../state/threads"; |
| 61 | import { vcsEnvironment } from "../../state/vcs"; |
| 62 | import { useChildThreadInputs, readThreadShell, waitForThreadShell } from "../../state/entities"; |
| 63 | import { serverEnvironment } from "../../state/server"; |
| 64 | import { environmentShell } from "../../state/shell"; |
| 65 | import { ThreadStatusLine } from "./ThreadStatusLine"; |
| 66 | import { formatRelativeTimeLabel } from "../../timestampFormat"; |
| 67 | import { appAtomRegistry } from "../../rpc/atomRegistry"; |
| 68 | import { readEnvironmentScope } from "../../state/session"; |
| 69 | import { useAtomCommand } from "../../state/use-atom-command"; |
| 70 | import { useOrchestrationCommand } from "../../state/use-orchestration-command"; |
| 71 | import { |
| 72 | backgroundWorkNowItem, |
| 73 | childInputNowItem, |
| 74 | goalNowItem, |
| 75 | runStopNowItem, |
| 76 | } from "./ThreadActivityBanners"; |
| 77 | import { useForceStopThread } from "./useForceStopThread"; |
| 78 | import { useAtomValue } from "@effect/atom-react"; |
| 79 | import type { RunStopPresentation } from "@t3tools/client-runtime/state/thread-execution"; |
| 80 | import { Atom } from "effect/reactivity"; |
| 81 | import { environmentThreadDetails } from "../../state/threads"; |
| 82 | import { type SideThreadOpenIntent, sideThreadKindOf } from "@t3tools/client-runtime/side-thread"; |
| 83 | import { openSideThread, resolveThreadOpenRoute } from "../../lib/sideChatPane"; |
| 84 | import type { useLocalDispatchState } from "./useLocalDispatchState"; |
| 85 | const RELATED_THREAD_SHELL_WAIT_MS = 1_000; |
| 86 | |
| 87 | function actionErrorMessage(error: unknown): string { |
| 88 | return errorDisplayMessage(error, m) ?? chatActionErrorMessage(error, m); |
| 89 | } |
| 90 | const NO_RUN_STOP_ATOM = Atom.make<RunStopPresentation | null>(null).pipe( |
| 91 | Atom.withLabel("web-thread-run-stop:empty"), |
| 92 | ); |
| 93 | |
| 94 | type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>; |
| 95 | type LocalDispatchState = ReturnType<typeof useLocalDispatchState>; |
| 96 | |
| 97 | interface ThreadLifecycleInput { |
| 98 | readonly environmentId: EnvironmentId; |
| 99 | readonly routeThreadKey: string; |
| 100 | readonly currentRouteThreadKeyRef: { readonly current: string | null }; |
| 101 | readonly canOperateThread: boolean; |
| 102 | readonly clientSettingsHydrated: boolean; |
| 103 | readonly activeThread: EnvironmentThreadShell | undefined; |
| 104 | readonly activeThreadId: ThreadId | null; |
| 105 | readonly activeThreadRef: ScopedThreadRef | null; |
| 106 | /** Null until the thread's detail may load; see resolveThreadDetailRef. */ |
| 107 | readonly threadDetailRef: ScopedThreadRef | null; |
| 108 | readonly activeThreadKey: string | null; |
| 109 | readonly activeThreadShell: EnvironmentThreadShell | null; |
| 110 | /** The usage-limit recovery banner shows this snooze and its Wake now. */ |
| 111 | readonly limitRecoveryHoldsSnooze: boolean; |
| 112 | readonly activeLatestRun: EnvironmentThreadShell["latestRun"]; |
| 113 | readonly activeProjectCwd: string | null; |
| 114 | readonly serverConfig: EnvironmentServerConfig | null; |
| 115 | readonly runtimeMode: RuntimeMode; |
| 116 | readonly isWorking: boolean; |
| 117 | /** Also true while the server prepares, starts, or queues a run this client did not send. */ |
| 118 | readonly runIsLive: boolean; |
| 119 | readonly pendingBackgroundTasks: Parameters<typeof backgroundWorkNowItem>[0]["tasks"]; |
| 120 | readonly turnItems: Parameters<typeof backgroundWorkNowItem>[0]["turnItems"]; |
| 121 | readonly activePendingApproval: PendingThreadRequests["activePendingApproval"]; |
| 122 | readonly activePendingUserInput: PendingThreadRequests["activePendingUserInput"]; |
| 123 | readonly localCheckoutBranchMismatch: { |
| 124 | readonly threadBranch: string; |
| 125 | readonly currentBranch: string; |
| 126 | } | null; |
| 127 | readonly gitStatusQuery: { readonly refresh: () => void }; |
| 128 | readonly nowMinute: string; |
| 129 | readonly composerRef: ComposerHandleRef; |
| 130 | readonly composerDraftTarget: ComposerThreadTarget; |
| 131 | readonly sendInFlightRef: { current: boolean }; |
| 132 | readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>; |
| 133 | readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>; |
| 134 | readonly clearUsageLimitsFor: (threadKey: string) => void; |
| 135 | readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"]; |
| 136 | readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"]; |
| 137 | readonly scrollToEnd: (animated?: boolean) => void; |
| 138 | readonly persistThreadSettingsForNextTurn: (input: { |
| 139 | threadId: ThreadId; |
| 140 | createdAt: string; |
| 141 | branch?: string; |
| 142 | runtimeMode: RuntimeMode; |
| 143 | interactionMode: ProviderInteractionMode; |
| 144 | }) => Promise<AtomCommandResult<void, unknown>>; |
| 145 | } |
| 146 | |
| 147 | /** |
| 148 | * Thread state the chat shows and changes outside a normal send: snooze and settle with |
| 149 | * their status line, the local checkout's branch, background work, child-thread and goal |
| 150 | * banners, opening related threads, and standalone slash commands. |
| 151 | */ |
| 152 | export function useThreadLifecycle(input: ThreadLifecycleInput) { |
| 153 | const { |
| 154 | environmentId, |
| 155 | routeThreadKey, |
| 156 | currentRouteThreadKeyRef, |
| 157 | canOperateThread, |
| 158 | clientSettingsHydrated, |
| 159 | activeThread, |
| 160 | activeThreadId, |
| 161 | activeThreadRef, |
| 162 | threadDetailRef, |
| 163 | activeThreadKey, |
| 164 | activeThreadShell, |
| 165 | activeLatestRun, |
| 166 | limitRecoveryHoldsSnooze, |
| 167 | activeProjectCwd, |
| 168 | serverConfig, |
| 169 | runtimeMode, |
| 170 | isWorking, |
| 171 | runIsLive, |
| 172 | pendingBackgroundTasks, |
| 173 | turnItems, |
| 174 | activePendingApproval, |
| 175 | activePendingUserInput, |
| 176 | localCheckoutBranchMismatch, |
| 177 | gitStatusQuery, |
| 178 | nowMinute, |
| 179 | composerRef, |
| 180 | composerDraftTarget, |
| 181 | sendInFlightRef, |
| 182 | setOptimisticUserMessages, |
| 183 | setThreadError, |
| 184 | clearUsageLimitsFor, |
| 185 | beginLocalDispatch, |
| 186 | resetLocalDispatch, |
| 187 | scrollToEnd, |
| 188 | persistThreadSettingsForNextTurn, |
| 189 | } = input; |
| 190 | const gt = useGT(); |
| 191 | const messages = useMessages(); |
| 192 | const navigate = useNavigate(); |
| 193 | const router = useRouter(); |
| 194 | const { settleThread, pinThread, confirmAndUnpinThread } = useThreadActions(); |
| 195 | const canWriteSourceControl = useEnvironmentScope(environmentId, AuthSourceControlWriteScope); |
| 196 | const switchGitRef = useAtomCommand(vcsEnvironment.switchRef, { reportFailure: false }); |
| 197 | const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, { |
| 198 | reportFailure: false, |
| 199 | }); |
| 200 | const regenerateThreadTitle = useOrchestrationCommand(threadEnvironment.regenerateTitle, { |
| 201 | reportFailure: false, |
| 202 | }); |
| 203 | const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { |
| 204 | reportFailure: false, |
| 205 | }); |
| 206 | const interruptThreadTurn = useOrchestrationCommand(threadEnvironment.interruptTurn, { |
| 207 | reportFailure: false, |
| 208 | }); |
| 209 | |
| 210 | const serverConfigLoaded = serverConfig !== null; |
| 211 | const activeThreadPinned = serverConfigLoaded && activeThreadShell?.pinnedAt != null; |
| 212 | // A clock read in render would stay frozen in the compiler's cache, so the |
| 213 | // snooze checks read a snapshot that moves when the wake time changes or passes. |
| 214 | const snoozeClock = new Date( |
| 215 | useNowAfter(Date.parse(activeThreadShell?.snoozedUntil ?? "") || null), |
| 216 | ).toISOString(); |
| 217 | const activeThreadSnoozed = |
| 218 | activeThreadShell !== null && |
| 219 | serverConfigLoaded && |
| 220 | effectiveSnoozed(activeThreadShell, { now: snoozeClock }); |
| 221 | const activeThreadWokeAt = |
| 222 | activeThreadShell !== null && serverConfigLoaded |
| 223 | ? threadWokeAt(activeThreadShell, { now: snoozeClock }) |
| 224 | : null; |
| 225 | const acknowledgeThreadWoke = useAcknowledgeThreadWoke(); |
| 226 | const acknowledgeActiveThreadWoke = () => { |
| 227 | if (activeThreadRef === null || activeThreadWokeAt === null) return; |
| 228 | acknowledgeThreadWoke(activeThreadRef, activeThreadWokeAt); |
| 229 | }; |
| 230 | const acknowledgeActiveThreadWokeStable = useStableCallback(acknowledgeActiveThreadWoke); |
| 231 | const activeThreadLocalVisitedAt = useUiStateStore((store) => |
| 232 | activeThreadKey === null ? undefined : store.threadLastVisitedAtById[activeThreadKey], |
| 233 | ); |
| 234 | const activeThreadLastVisitedAt = resolveThreadLastVisitedAt( |
| 235 | activeThreadShell?.lastVisitedAt, |
| 236 | activeThreadLocalVisitedAt, |
| 237 | ); |
| 238 | const activeThreadWokeVisible = isThreadWokeUnseen({ |
| 239 | wokeAt: activeThreadWokeAt, |
| 240 | settled: activeThreadShell?.settledOverride === "settled", |
| 241 | lastVisitedAt: activeThreadLastVisitedAt, |
| 242 | latestRunCompletedAt: activeLatestRun?.completedAt ?? null, |
| 243 | }); |
| 244 | const activeThreadSettled = |
| 245 | serverConfigLoaded && activeThreadShell?.settledOverride === "settled"; |
| 246 | const unsettleThreadMutation = useOrchestrationCommand(threadEnvironment.unsettle, { |
| 247 | reportFailure: false, |
| 248 | }); |
| 249 | const [unsettlingThreadKey, setUnsettlingThreadKey] = useState<string | null>(null); |
| 250 | const isUnsettling = unsettlingThreadKey !== null && unsettlingThreadKey === activeThreadKey; |
| 251 | const handleUnsettleActiveThread = async () => { |
| 252 | if ( |
| 253 | !activeThreadRef || |
| 254 | !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) |
| 255 | ) |
| 256 | return; |
| 257 | const threadKey = scopedThreadKey(activeThreadRef); |
| 258 | setUnsettlingThreadKey(threadKey); |
| 259 | // Commands settle into a result, so this always runs. |
| 260 | const result = await unsettleThreadMutation({ |
| 261 | environmentId: activeThreadRef.environmentId, |
| 262 | input: { threadId: activeThreadRef.threadId, reason: "user" }, |
| 263 | }); |
| 264 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 265 | const error = squashAtomCommandFailure(result); |
| 266 | toastManager.add( |
| 267 | stackedThreadToast({ |
| 268 | type: "error", |
| 269 | title: m(msg("Failed to un-settle thread")), |
| 270 | description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")), |
| 271 | }), |
| 272 | ); |
| 273 | } |
| 274 | setUnsettlingThreadKey((current) => (current === threadKey ? null : current)); |
| 275 | }; |
| 276 | const handleUnsettleActiveThreadStable = useStableCallback(handleUnsettleActiveThread); |
| 277 | const unsnoozeThreadMutation = useOrchestrationCommand(threadEnvironment.unsnooze, { |
| 278 | reportFailure: false, |
| 279 | }); |
| 280 | const [unsnoozingThreadKey, setUnsnoozingThreadKey] = useState<string | null>(null); |
| 281 | const isUnsnoozing = unsnoozingThreadKey !== null && unsnoozingThreadKey === activeThreadKey; |
| 282 | const handleUnsnoozeActiveThread = async () => { |
| 283 | if ( |
| 284 | !activeThreadRef || |
| 285 | !readEnvironmentScope(activeThreadRef.environmentId, AuthOrchestrationOperateScope) |
| 286 | ) |
| 287 | return; |
| 288 | const threadKey = scopedThreadKey(activeThreadRef); |
| 289 | setUnsnoozingThreadKey(threadKey); |
| 290 | // Commands settle into a result, so this always runs. |
| 291 | const recovery = activeThreadShell?.limitRecovery; |
| 292 | const recoveryOwnsSnooze = |
| 293 | recovery?.snooze === true && |
| 294 | recovery.runId === activeThreadShell?.latestRun?.runId && |
| 295 | activeThreadShell?.snoozedUntil != null && |
| 296 | Date.parse(activeThreadShell.snoozedUntil) === Date.parse(recovery.resetAt); |
| 297 | const result = recoveryOwnsSnooze |
| 298 | ? await updateThreadMetadata({ |
| 299 | environmentId: activeThreadRef.environmentId, |
| 300 | input: { |
| 301 | threadId: activeThreadRef.threadId, |
| 302 | limitRecovery: { runId: recovery.runId, resetAt: recovery.resetAt, snooze: false }, |
| 303 | }, |
| 304 | }) |
| 305 | : await unsnoozeThreadMutation({ |
| 306 | environmentId: activeThreadRef.environmentId, |
| 307 | input: { threadId: activeThreadRef.threadId, reason: "user" }, |
| 308 | }); |
| 309 | if (result._tag === "Failure" && !isAtomCommandInterrupted(result)) { |
| 310 | const error = squashAtomCommandFailure(result); |
| 311 | toastManager.add( |
| 312 | stackedThreadToast({ |
| 313 | type: "error", |
| 314 | title: m(msg("Failed to wake thread")), |
| 315 | description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")), |
| 316 | }), |
| 317 | ); |
| 318 | } |
| 319 | setUnsnoozingThreadKey((current) => (current === threadKey ? null : current)); |
| 320 | }; |
| 321 | const handleUnsnoozeActiveThreadStable = useStableCallback(handleUnsnoozeActiveThread); |
| 322 | const [restoringBranchThreadKeys, setRestoringBranchThreadKeys] = useState<ReadonlySet<string>>( |
| 323 | () => new Set(), |
| 324 | ); |
| 325 | const isRestoringThreadBranch = |
| 326 | activeThreadKey !== null && restoringBranchThreadKeys.has(activeThreadKey); |
| 327 | const [revealedBranchMismatchKey, setRevealedBranchMismatchKey] = useState<string | null>(null); |
| 328 | const [, setBranchMismatchDismissTick] = useState(0); |
| 329 | const composerHasDraftContent = useComposerDraftStore((store) => |
| 330 | composerDraftHasUserContent(store.getComposerDraft(composerDraftTarget)), |
| 331 | ); |
| 332 | const activeBranchMismatchKey = branchMismatchKey( |
| 333 | activeThread?.id ?? null, |
| 334 | localCheckoutBranchMismatch, |
| 335 | ); |
| 336 | const showBranchMismatchBanner = shouldShowBranchMismatchBanner({ |
| 337 | hasMismatch: localCheckoutBranchMismatch !== null, |
| 338 | isDismissed: isBranchMismatchDismissedForSession(activeBranchMismatchKey), |
| 339 | composerHasContent: composerHasDraftContent, |
| 340 | wasShownForCurrentMismatch: |
| 341 | revealedBranchMismatchKey !== null && revealedBranchMismatchKey === activeBranchMismatchKey, |
| 342 | }); |
| 343 | const nextRevealedBranchMismatchKey = showBranchMismatchBanner |
| 344 | ? activeBranchMismatchKey |
| 345 | : revealedBranchMismatchKey !== activeBranchMismatchKey |
| 346 | ? null |
| 347 | : revealedBranchMismatchKey; |
| 348 | if (nextRevealedBranchMismatchKey !== revealedBranchMismatchKey) { |
| 349 | setRevealedBranchMismatchKey(nextRevealedBranchMismatchKey); |
| 350 | } |
| 351 | const handleSwitchCheckoutToThread = async () => { |
| 352 | if (!canWriteSourceControl) return; |
| 353 | if ( |
| 354 | !activeProjectCwd || |
| 355 | !activeThread || |
| 356 | !localCheckoutBranchMismatch || |
| 357 | isRestoringThreadBranch |
| 358 | ) { |
| 359 | return; |
| 360 | } |
| 361 | const threadKey = scopedThreadKey(scopeThreadRef(environmentId, activeThread.id)); |
| 362 | const finishRestore = () => |
| 363 | setRestoringBranchThreadKeys((current) => { |
| 364 | const next = new Set(current); |
| 365 | next.delete(threadKey); |
| 366 | return next; |
| 367 | }); |
| 368 | setRestoringBranchThreadKeys((current) => new Set(current).add(threadKey)); |
| 369 | const checkoutResult = await switchGitRef({ |
| 370 | environmentId, |
| 371 | input: { |
| 372 | cwd: activeProjectCwd, |
| 373 | refName: localCheckoutBranchMismatch.threadBranch, |
| 374 | }, |
| 375 | }); |
| 376 | if (checkoutResult._tag === "Failure") { |
| 377 | finishRestore(); |
| 378 | if (!isAtomCommandInterrupted(checkoutResult)) { |
| 379 | toastManager.add( |
| 380 | stackedThreadToast({ |
| 381 | type: "error", |
| 382 | title: m(msg("Failed to switch checkout")), |
| 383 | description: actionErrorMessage(squashAtomCommandFailure(checkoutResult)), |
| 384 | }), |
| 385 | ); |
| 386 | } |
| 387 | return; |
| 388 | } |
| 389 | |
| 390 | if (!readEnvironmentScope(environmentId, AuthSourceControlWriteScope)) { |
| 391 | finishRestore(); |
| 392 | return; |
| 393 | } |
| 394 | const nextBranch = checkoutResult.value.refName ?? localCheckoutBranchMismatch.threadBranch; |
| 395 | if (nextBranch !== activeThread.branch) { |
| 396 | const updateResult = await updateThreadMetadata({ |
| 397 | environmentId, |
| 398 | input: { threadId: activeThread.id, branch: nextBranch, worktreePath: null }, |
| 399 | }); |
| 400 | if (updateResult._tag === "Failure") { |
| 401 | finishRestore(); |
| 402 | if (!isAtomCommandInterrupted(updateResult)) { |
| 403 | toastManager.add( |
| 404 | stackedThreadToast({ |
| 405 | type: "error", |
| 406 | title: m(msg("Checkout switched, but the thread could not be updated")), |
| 407 | description: actionErrorMessage(squashAtomCommandFailure(updateResult)), |
| 408 | }), |
| 409 | ); |
| 410 | } |
| 411 | gitStatusQuery.refresh(); |
| 412 | return; |
| 413 | } |
| 414 | } |
| 415 | gitStatusQuery.refresh(); |
| 416 | finishRestore(); |
| 417 | if (currentRouteThreadKeyRef.current === routeThreadKey) { |
| 418 | window.requestAnimationFrame(() => { |
| 419 | if (currentRouteThreadKeyRef.current === routeThreadKey) composerRef.current?.focusAtEnd(); |
| 420 | }); |
| 421 | } |
| 422 | }; |
| 423 | const handleSwitchCheckoutToThreadStable = useStableCallback(() => { |
| 424 | void handleSwitchCheckoutToThread(); |
| 425 | }); |
| 426 | const activeBackgroundTasks = activeThread ? pendingBackgroundTasks : []; |
| 427 | const [backgroundWorkStops, setBackgroundWorkStops] = useState< |
| 428 | Record<string, BackgroundWorkStopRequest | undefined> |
| 429 | >({}); |
| 430 | const backgroundWorkStop = backgroundWorkStops[`${environmentId}:${activeThreadId}`] ?? null; |
| 431 | const isStoppingBackgroundWork = isBackgroundWorkStopPending( |
| 432 | backgroundWorkStop, |
| 433 | `${environmentId}:${activeThreadId}`, |
| 434 | pendingBackgroundTasks, |
| 435 | useDeadlinePassed(backgroundWorkStop?.retryAt ?? null), |
| 436 | ); |
| 437 | const handleStopBackgroundWork = async () => { |
| 438 | if ( |
| 439 | isStoppingBackgroundWork || |
| 440 | !activeThread || |
| 441 | !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) |
| 442 | ) |
| 443 | return; |
| 444 | const request: BackgroundWorkStopRequest = { |
| 445 | threadKey: `${environmentId}:${activeThread.id}`, |
| 446 | taskIds: pendingBackgroundTasks.map((task) => task.taskId), |
| 447 | retryAt: null, |
| 448 | }; |
| 449 | setBackgroundWorkStops((current) => ({ ...current, [request.threadKey]: request })); |
| 450 | const result = await interruptThreadTurn({ |
| 451 | environmentId, |
| 452 | input: { threadId: activeThread.id }, |
| 453 | }); |
| 454 | setBackgroundWorkStops((current) => |
| 455 | current[request.threadKey] !== request |
| 456 | ? current |
| 457 | : { |
| 458 | ...current, |
| 459 | [request.threadKey]: |
| 460 | result._tag === "Failure" |
| 461 | ? undefined |
| 462 | : { ...request, retryAt: Date.now() + BACKGROUND_WORK_STOP_RETRY_AFTER_MS }, |
| 463 | }, |
| 464 | ); |
| 465 | if (result._tag === "Failure") { |
| 466 | if (!isAtomCommandInterrupted(result)) { |
| 467 | const error = squashAtomCommandFailure(result); |
| 468 | setThreadError( |
| 469 | activeThread.id, |
| 470 | thrownErrorMessage(error, m) ?? m(msg("Failed to stop background work.")), |
| 471 | ); |
| 472 | } |
| 473 | } |
| 474 | }; |
| 475 | const handleStopBackgroundWorkStable = useStableCallback(handleStopBackgroundWork); |
| 476 | const openRelatedThreadGenerationRef = useRef(0); |
| 477 | // A task delegated to a linked environment opens there; the default is this thread's own. |
| 478 | // `intent` comes from the rows that open a subagent, and says the thread is one. |
| 479 | const onOpenRelatedThread = async ( |
| 480 | threadId: ThreadId, |
| 481 | threadEnvironmentId: EnvironmentId = environmentId, |
| 482 | intent?: SideThreadOpenIntent, |
| 483 | ) => { |
| 484 | const generation = ++openRelatedThreadGenerationRef.current; |
| 485 | const threadRef = scopeThreadRef(threadEnvironmentId, threadId); |
| 486 | const isEnvironmentLive = () => |
| 487 | appAtomRegistry.get(environmentShell.stateValueAtom(threadEnvironmentId)).status === "live"; |
| 488 | // The shell can leave idle subagent children out, so absence is not deletion there: the |
| 489 | // route decides from the thread's own detail. |
| 490 | const shellOmitsChildren = |
| 491 | appAtomRegistry.get(serverEnvironment.configValueAtom(threadEnvironmentId)) |
| 492 | ?.shellThreadFamilies === true; |
| 493 | // A just-launched child can reach this timeline before its shell syncs. |
| 494 | if (!shellOmitsChildren && isEnvironmentLive() && readThreadShell(threadRef) === null) { |
| 495 | const location = router.latestLocation; |
| 496 | await waitForThreadShell(threadRef, RELATED_THREAD_SHELL_WAIT_MS); |
| 497 | if ( |
| 498 | generation !== openRelatedThreadGenerationRef.current || |
| 499 | currentRouteThreadKeyRef.current !== routeThreadKey || |
| 500 | router.latestLocation !== location |
| 501 | ) { |
| 502 | return; |
| 503 | } |
| 504 | } |
| 505 | const shell = readThreadShell(threadRef); |
| 506 | if (shell === null ? !shellOmitsChildren && isEnvironmentLive() : shell.deletedAt != null) { |
| 507 | toastManager.add({ type: "info", title: m(msg("This thread is no longer available")) }); |
| 508 | return; |
| 509 | } |
| 510 | // A subagent or side chat opens beside this thread or in its place; its own parent, like any |
| 511 | // other thread, only in its place. |
| 512 | if ( |
| 513 | (intent !== undefined || sideThreadKindOf(shell) !== null) && |
| 514 | activeThread?.lineage.parentThreadId !== threadId |
| 515 | ) { |
| 516 | openSideThread({ |
| 517 | threadRef, |
| 518 | panelRef: activeThreadRef, |
| 519 | intent: intent ?? "primary", |
| 520 | navigate: (ref) => |
| 521 | void navigate({ to: "/$environmentId/$threadId", params: buildThreadRouteParams(ref) }), |
| 522 | }); |
| 523 | return; |
| 524 | } |
| 525 | const routeRef = resolveThreadOpenRoute(threadRef, shell); |
| 526 | if (scopedThreadKey(routeRef) === routeThreadKey) return; |
| 527 | void navigate({ |
| 528 | to: "/$environmentId/$threadId", |
| 529 | params: buildThreadRouteParams(routeRef), |
| 530 | }); |
| 531 | }; |
| 532 | const onOpenRelatedThreadStable = useStableCallback(onOpenRelatedThread); |
| 533 | const childThreadInputs = useChildThreadInputs(activeThreadRef); |
| 534 | const childInputNow = childInputNowItem( |
| 535 | { |
| 536 | childThreadInputs, |
| 537 | parentAwaitingUser: Boolean( |
| 538 | activePendingApproval || activePendingUserInput || activeThreadShell?.hasPendingUserInput, |
| 539 | ), |
| 540 | onOpenThread: onOpenRelatedThreadStable, |
| 541 | }, |
| 542 | messages, |
| 543 | ); |
| 544 | |
| 545 | const sendStandaloneCommand = async (text: string, failureMessage: string) => { |
| 546 | if (!activeThread || !clientSettingsHydrated || sendInFlightRef.current) return; |
| 547 | const context = composerRef.current?.getSendContext(); |
| 548 | if (!context?.providerAvailable) return; |
| 549 | |
| 550 | const threadId = activeThread.id; |
| 551 | const messageId = newMessageId(); |
| 552 | const createdAt = new Date().toISOString(); |
| 553 | sendInFlightRef.current = true; |
| 554 | beginLocalDispatch(); |
| 555 | setThreadError(threadId, null); |
| 556 | setOptimisticUserMessages((messages) => [ |
| 557 | ...messages, |
| 558 | { |
| 559 | id: messageId, |
| 560 | role: "user", |
| 561 | text, |
| 562 | runId: null, |
| 563 | createdAt, |
| 564 | updatedAt: createdAt, |
| 565 | streaming: false, |
| 566 | }, |
| 567 | ]); |
| 568 | scrollToEnd(); |
| 569 | // Commands settle into a result, so this always runs. |
| 570 | const settingsResult = await persistThreadSettingsForNextTurn({ |
| 571 | threadId, |
| 572 | createdAt, |
| 573 | ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}), |
| 574 | runtimeMode, |
| 575 | interactionMode: DEFAULT_INTERACTION_MODE, |
| 576 | }); |
| 577 | const result = |
| 578 | settingsResult._tag === "Failure" |
| 579 | ? settingsResult |
| 580 | : await startThreadTurn({ |
| 581 | environmentId, |
| 582 | input: { |
| 583 | threadId, |
| 584 | message: { messageId, role: "user", text, attachments: [] }, |
| 585 | modelSelection: context.selectedModelSelection, |
| 586 | runtimeMode, |
| 587 | interactionMode: DEFAULT_INTERACTION_MODE, |
| 588 | createdAt, |
| 589 | }, |
| 590 | }); |
| 591 | if (result._tag === "Failure") { |
| 592 | setOptimisticUserMessages((messages) => |
| 593 | messages.filter((message) => message.id !== messageId), |
| 594 | ); |
| 595 | resetLocalDispatch(); |
| 596 | if (!isAtomCommandInterrupted(result)) { |
| 597 | const error = squashAtomCommandFailure(result); |
| 598 | setThreadError(threadId, thrownErrorMessage(error, m) ?? failureMessage); |
| 599 | } |
| 600 | } else { |
| 601 | clearUsageLimitsFor(routeThreadKey); |
| 602 | } |
| 603 | sendInFlightRef.current = false; |
| 604 | }; |
| 605 | const sendStandaloneCommandStable = useStableCallback(sendStandaloneCommand); |
| 606 | const activeGoal = activeThreadShell?.goal ?? null; |
| 607 | const goalNow = |
| 608 | activeThread && activeGoal !== null |
| 609 | ? goalNowItem( |
| 610 | { |
| 611 | threadId: activeThread.id, |
| 612 | goal: activeGoal, |
| 613 | isWorking, |
| 614 | onSendCommand: sendStandaloneCommandStable, |
| 615 | }, |
| 616 | messages, |
| 617 | ) |
| 618 | : null; |
| 619 | |
| 620 | const forceStop = useForceStopThread(environmentId); |
| 621 | const anyRunStop = useAtomValue( |
| 622 | threadDetailRef ? environmentThreadDetails.runStopAtom(threadDetailRef) : NO_RUN_STOP_ATOM, |
| 623 | ); |
| 624 | // A background Stop matters only while that work is still pending. |
| 625 | const runStop = anyRunStop?.background && activeBackgroundTasks.length === 0 ? null : anyRunStop; |
| 626 | const runStopNow = |
| 627 | activeThread && runStop !== null |
| 628 | ? runStopNowItem({ |
| 629 | threadId: activeThread.id, |
| 630 | stop: runStop, |
| 631 | canForceStop: forceStop.canForceStop, |
| 632 | forceStopping: forceStop.stoppingThreadId === activeThread.id, |
| 633 | onForceStop: () => void forceStop.forceStopThread(activeThread.id, runStop.runId), |
| 634 | }) |
| 635 | : null; |
| 636 | const backgroundWorkNow = activeThread |
| 637 | ? backgroundWorkNowItem( |
| 638 | { |
| 639 | environmentId, |
| 640 | threadId: activeThread.id, |
| 641 | tasks: activeBackgroundTasks, |
| 642 | turnItems, |
| 643 | // Interrupt stops the active run first, not this work; the composer owns that Stop. |
| 644 | stopDisabled: runIsLive || !canOperateThread || isStoppingBackgroundWork, |
| 645 | stopping: isStoppingBackgroundWork, |
| 646 | onStop: handleStopBackgroundWorkStable, |
| 647 | onOpenThread: onOpenRelatedThreadStable, |
| 648 | }, |
| 649 | messages, |
| 650 | ) |
| 651 | : null; |
| 652 | // The relative times read the clock; nowMinute re-renders them on the minute. |
| 653 | const snoozedUntil = activeThreadShell?.snoozedUntil ?? null; |
| 654 | const settledAt = activeThreadShell?.settledAt ?? null; |
| 655 | // Same rounding as the sidebar's snoozed shelf, so both read the same hour. |
| 656 | const snoozeNow = `${nowMinute}:00.000Z`; |
| 657 | const snoozeWake = |
| 658 | snoozedUntil && Date.parse(snoozedUntil) > Date.parse(snoozeNow) |
| 659 | ? snoozeWakeLabel(snoozedUntil, { now: snoozeNow }, messages) |
| 660 | : null; |
| 661 | const threadStatusLine = activeThreadSnoozed ? ( |
| 662 | limitRecoveryHoldsSnooze ? null : ( |
| 663 | <ThreadStatusLine |
| 664 | icon={<AlarmClockIcon />} |
| 665 | label={ |
| 666 | snoozeWake |
| 667 | ? gt("Snoozed, {remaining} left", { remaining: snoozeWake }) |
| 668 | : gt("Snoozed", { $context: "thread status" }) |
| 669 | } |
| 670 | clockMinute={nowMinute} |
| 671 | actionLabel={isUnsnoozing ? gt("Waking...") : gt("Wake now")} |
| 672 | actionDisabled={!canOperateThread || isUnsnoozing} |
| 673 | onAction={() => void handleUnsnoozeActiveThreadStable()} |
| 674 | /> |
| 675 | ) |
| 676 | ) : activeThreadSettled ? ( |
| 677 | <ThreadStatusLine |
| 678 | icon={<CheckCircle2Icon />} |
| 679 | label={ |
| 680 | settledAt |
| 681 | ? gt("Settled {time}", { time: formatRelativeTimeLabel(settledAt, undefined, messages) }) |
| 682 | : gt("Settled", { $context: "thread status" }) |
| 683 | } |
| 684 | clockMinute={nowMinute} |
| 685 | actionLabel={isUnsettling ? gt("Un-settling...") : gt("Un-settle")} |
| 686 | actionDisabled={!canOperateThread || isUnsettling} |
| 687 | onAction={() => void handleUnsettleActiveThreadStable()} |
| 688 | /> |
| 689 | ) : activeThreadWokeVisible ? ( |
| 690 | <ThreadStatusLine |
| 691 | icon={<AlarmClockIcon />} |
| 692 | label={gt("Woke from snooze")} |
| 693 | actionLabel={gt("Dismiss")} |
| 694 | onAction={acknowledgeActiveThreadWokeStable} |
| 695 | /> |
| 696 | ) : null; |
| 697 | const toastThreadActionFailure = |
| 698 | (title: string) => (result: AtomCommandResult<unknown, unknown>) => { |
| 699 | if (result._tag !== "Failure" || isAtomCommandInterrupted(result)) return; |
| 700 | const error = squashAtomCommandFailure(result); |
| 701 | toastManager.add( |
| 702 | stackedThreadToast({ |
| 703 | type: "error", |
| 704 | title, |
| 705 | description: thrownErrorMessage(error, m) ?? m(msg("An error occurred.")), |
| 706 | }), |
| 707 | ); |
| 708 | }; |
| 709 | const shortcuts = { |
| 710 | "thread.settle": () => { |
| 711 | if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; |
| 712 | if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return; |
| 713 | if (activeThreadSettled) { |
| 714 | void handleUnsettleActiveThread(); |
| 715 | return; |
| 716 | } |
| 717 | if (settleAndAdvance(activeThreadRef)) return; |
| 718 | void settleThread(activeThreadRef).then( |
| 719 | toastThreadActionFailure(m(msg("Failed to settle thread"))), |
| 720 | ); |
| 721 | }, |
| 722 | "thread.pin": ({ event }) => { |
| 723 | // An open project list pins its highlighted project with this key instead. |
| 724 | if ( |
| 725 | event.target instanceof Element && |
| 726 | event.target.closest('[role="combobox"][aria-expanded="true"]') !== null |
| 727 | ) { |
| 728 | return false; |
| 729 | } |
| 730 | if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; |
| 731 | if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return; |
| 732 | void ( |
| 733 | activeThreadPinned ? confirmAndUnpinThread(activeThreadRef) : pinThread(activeThreadRef) |
| 734 | ).then( |
| 735 | toastThreadActionFailure( |
| 736 | activeThreadPinned ? m(msg("Failed to unpin thread")) : m(msg("Failed to pin thread")), |
| 737 | ), |
| 738 | ); |
| 739 | }, |
| 740 | "thread.regenerateTitle": () => { |
| 741 | if (!readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) return false; |
| 742 | if (!activeThreadShell || !activeThreadRef || !serverConfigLoaded) return; |
| 743 | if (activeThreadShell.titleRegeneration != null) return; |
| 744 | void regenerateThreadTitle({ |
| 745 | environmentId: activeThreadRef.environmentId, |
| 746 | input: { threadId: activeThreadRef.threadId }, |
| 747 | }).then((result) => { |
| 748 | const toast = titleRegenerationToast([result]); |
| 749 | if (toast) toastManager.add(toast); |
| 750 | }); |
| 751 | }, |
| 752 | } satisfies ChatShortcutCommands; |
| 753 | return { |
| 754 | shortcuts, |
| 755 | acknowledgeActiveThreadWoke, |
| 756 | activeBranchMismatchKey, |
| 757 | // A Stop that went unanswered needs the user; one in progress is the thread's work. |
| 758 | attentionNow: runStop?.state === "unresponsive" ? runStopNow : childInputNow, |
| 759 | workNow: runStop?.state === "stopping" ? runStopNow : backgroundWorkNow, |
| 760 | childInputNow, |
| 761 | goalNow, |
| 762 | handleSwitchCheckoutToThread, |
| 763 | handleSwitchCheckoutToThreadStable, |
| 764 | isRestoringThreadBranch, |
| 765 | onOpenRelatedThread, |
| 766 | onOpenRelatedThreadStable, |
| 767 | sendStandaloneCommand, |
| 768 | setBranchMismatchDismissTick, |
| 769 | showBranchMismatchBanner, |
| 770 | threadStatusLine, |
| 771 | }; |
| 772 | } |