The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import { msg } from "gt-react"; |
| 2 | import { thrownErrorMessage } from "@t3tools/client-runtime/errors"; |
| 3 | import { m } from "~/i18n/messages"; |
| 4 | import { |
| 5 | type EnvironmentId, |
| 6 | type ProviderInteractionMode, |
| 7 | type RunId, |
| 8 | type RuntimeMode, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import type { EnvironmentThreadShell } from "@t3tools/client-runtime/state/shell"; |
| 11 | import { |
| 12 | isAtomCommandInterrupted, |
| 13 | squashAtomCommandFailure, |
| 14 | type AtomCommandResult, |
| 15 | } from "@t3tools/client-runtime/state/runtime"; |
| 16 | import { useState } from "react"; |
| 17 | import { newMessageId } from "~/lib/utils"; |
| 18 | import type { ComposerHandleRef } from "../../composerHandleContext"; |
| 19 | import { DEFAULT_INTERACTION_MODE } from "../../types"; |
| 20 | import { threadEnvironment } from "../../state/threads"; |
| 21 | import { useOrchestrationCommand } from "../../state/use-orchestration-command"; |
| 22 | import type { makeThreadErrorSetter } from "../ChatView.logic"; |
| 23 | import { draftSendState } from "./chatViewSend"; |
| 24 | import type { useTimelineFollow } from "./useTimelineFollow"; |
| 25 | import type { useUsageLimitsPanel } from "./useUsageLimitsPanel"; |
| 26 | |
| 27 | interface ComposerResumeInput { |
| 28 | readonly environmentId: EnvironmentId; |
| 29 | readonly routeThreadKey: string; |
| 30 | readonly currentRouteThreadKeyRef: { readonly current: string | null }; |
| 31 | readonly activeThread: EnvironmentThreadShell | undefined; |
| 32 | readonly resumableRunId: RunId | null; |
| 33 | readonly hasHeldQueuedRuns: boolean; |
| 34 | readonly canResume: boolean; |
| 35 | readonly isSendBusy: boolean; |
| 36 | readonly isRevertingCheckpoint: boolean; |
| 37 | readonly threadDetailLoading: boolean; |
| 38 | readonly activeEnvironmentUnavailable: boolean; |
| 39 | readonly runtimeMode: RuntimeMode; |
| 40 | readonly localCheckoutBranchMismatch: { readonly currentBranch: string } | null; |
| 41 | readonly composerRef: ComposerHandleRef; |
| 42 | readonly persistThreadSettingsForNextTurn: (input: { |
| 43 | threadId: EnvironmentThreadShell["id"]; |
| 44 | createdAt: string; |
| 45 | branch?: string; |
| 46 | runtimeMode: RuntimeMode; |
| 47 | interactionMode: ProviderInteractionMode; |
| 48 | }) => Promise<AtomCommandResult<void, unknown>>; |
| 49 | readonly clearUsageLimitsFor: ReturnType<typeof useUsageLimitsPanel>["clearFor"]; |
| 50 | readonly scrollToEnd: ReturnType<typeof useTimelineFollow>["scrollToEnd"]; |
| 51 | readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>; |
| 52 | } |
| 53 | |
| 54 | /** |
| 55 | * Resumes an interrupted run and/or releases the turns held |
| 56 | * in its queue. Shares the per-route send lock with the composer's send paths. |
| 57 | */ |
| 58 | export function useComposerResume(input: ComposerResumeInput) { |
| 59 | const { |
| 60 | environmentId, |
| 61 | routeThreadKey, |
| 62 | currentRouteThreadKeyRef, |
| 63 | activeThread, |
| 64 | resumableRunId, |
| 65 | hasHeldQueuedRuns, |
| 66 | canResume, |
| 67 | isSendBusy, |
| 68 | isRevertingCheckpoint, |
| 69 | threadDetailLoading, |
| 70 | activeEnvironmentUnavailable, |
| 71 | runtimeMode, |
| 72 | localCheckoutBranchMismatch, |
| 73 | composerRef, |
| 74 | persistThreadSettingsForNextTurn, |
| 75 | clearUsageLimitsFor, |
| 76 | scrollToEnd, |
| 77 | setThreadError, |
| 78 | } = input; |
| 79 | const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { |
| 80 | reportFailure: false, |
| 81 | }); |
| 82 | const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, { |
| 83 | reportFailure: false, |
| 84 | }); |
| 85 | const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>( |
| 86 | () => new Set(), |
| 87 | ); |
| 88 | const isResuming = resumingThreadKeys.has(routeThreadKey); |
| 89 | const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey); |
| 90 | |
| 91 | const onResume = async () => { |
| 92 | if ( |
| 93 | !activeThread || |
| 94 | !canResume || |
| 95 | isSendBusy || |
| 96 | isResuming || |
| 97 | isRevertingCheckpoint || |
| 98 | threadDetailLoading || |
| 99 | activeEnvironmentUnavailable || |
| 100 | sendInFlightRef.current |
| 101 | ) { |
| 102 | return; |
| 103 | } |
| 104 | const threadId = activeThread.id; |
| 105 | sendInFlightRef.current = true; |
| 106 | setResumingThreadKeys((current) => new Set(current).add(routeThreadKey)); |
| 107 | setThreadError(threadId, null); |
| 108 | // Commands settle into a result, so this always runs. |
| 109 | const resume = async () => { |
| 110 | if (resumableRunId === null) { |
| 111 | return resumeThreadQueue({ environmentId, input: { threadId } }); |
| 112 | } |
| 113 | // Read before the first await: the composer follows the route, so after the user switches |
| 114 | // threads it holds the other thread's model. |
| 115 | const modelSelection = composerRef.current?.getSendContext().selectedModelSelection; |
| 116 | const createdAt = new Date().toISOString(); |
| 117 | const settingsResult = await persistThreadSettingsForNextTurn({ |
| 118 | threadId, |
| 119 | createdAt, |
| 120 | ...(localCheckoutBranchMismatch |
| 121 | ? { branch: localCheckoutBranchMismatch.currentBranch } |
| 122 | : {}), |
| 123 | runtimeMode, |
| 124 | interactionMode: DEFAULT_INTERACTION_MODE, |
| 125 | }); |
| 126 | if (settingsResult._tag === "Failure") return settingsResult; |
| 127 | const turnResult = await startThreadTurn({ |
| 128 | environmentId, |
| 129 | input: { |
| 130 | threadId, |
| 131 | manualContinuationOfRunId: resumableRunId, |
| 132 | ...(modelSelection ? { modelSelection } : {}), |
| 133 | message: { |
| 134 | messageId: newMessageId(), |
| 135 | role: "user", |
| 136 | text: "", |
| 137 | attachments: [], |
| 138 | }, |
| 139 | runtimeMode, |
| 140 | interactionMode: DEFAULT_INTERACTION_MODE, |
| 141 | dispatchMode: "start", |
| 142 | }, |
| 143 | }); |
| 144 | if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult; |
| 145 | clearUsageLimitsFor(routeThreadKey); |
| 146 | return resumeThreadQueue({ environmentId, input: { threadId } }); |
| 147 | }; |
| 148 | const result = await resume(); |
| 149 | if (result._tag === "Failure") { |
| 150 | if (!isAtomCommandInterrupted(result)) { |
| 151 | const error = squashAtomCommandFailure(result); |
| 152 | setThreadError( |
| 153 | threadId, |
| 154 | thrownErrorMessage(error, m) ?? m(msg("Could not resume thread.")), |
| 155 | ); |
| 156 | } |
| 157 | } else { |
| 158 | clearUsageLimitsFor(routeThreadKey); |
| 159 | if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd(); |
| 160 | } |
| 161 | sendInFlightRef.current = false; |
| 162 | setResumingThreadKeys((current) => { |
| 163 | const next = new Set(current); |
| 164 | next.delete(routeThreadKey); |
| 165 | return next; |
| 166 | }); |
| 167 | }; |
| 168 | |
| 169 | return { onResume, isResuming }; |
| 170 | } |