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 { 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 ModelSelection, |
| 7 | type RuntimeMode, |
| 8 | type ThreadId, |
| 9 | } from "@t3tools/contracts"; |
| 10 | import { scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 11 | import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations"; |
| 12 | import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 13 | import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell"; |
| 14 | import { useNavigate } from "@tanstack/react-router"; |
| 15 | import { newMessageId } from "~/lib/utils"; |
| 16 | import { collapseExpandedComposerCursor } from "../../composer-logic"; |
| 17 | import { |
| 18 | type ComposerThreadTarget, |
| 19 | composerDraftHasUserContent, |
| 20 | type DraftId, |
| 21 | useComposerDraftStore, |
| 22 | } from "../../composerDraftStore"; |
| 23 | import type { ComposerHandleRef } from "../../composerHandleContext"; |
| 24 | import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue"; |
| 25 | import type { buildMessageContext } from "../../lib/composerContextRecords"; |
| 26 | import { appAtomRegistry } from "../../rpc/atomRegistry"; |
| 27 | import { threadEnvironment } from "../../state/threads"; |
| 28 | import { useOrchestrationCommand } from "../../state/use-orchestration-command"; |
| 29 | import { buildThreadRouteParams } from "../../threadRoutes"; |
| 30 | import { DEFAULT_INTERACTION_MODE } from "../../types"; |
| 31 | import { stackedThreadToast, toastManager } from "../ui/toast"; |
| 32 | import { |
| 33 | boundAttachmentIds, |
| 34 | type ComposerSendSnapshot, |
| 35 | type makeThreadErrorSetter, |
| 36 | withMessageContext, |
| 37 | } from "../ChatView.logic"; |
| 38 | import { |
| 39 | draftFanoutSelectionsAtom, |
| 40 | draftSendState, |
| 41 | type MultipleModelTarget, |
| 42 | type prepareTurnAttachments, |
| 43 | restoreComposerDraft, |
| 44 | startFanoutThread, |
| 45 | } from "./chatViewSend"; |
| 46 | import type { useLocalDispatchState } from "./useLocalDispatchState"; |
| 47 | |
| 48 | interface MultipleModelSendInput { |
| 49 | readonly environmentId: EnvironmentId; |
| 50 | readonly routeThreadKey: string; |
| 51 | readonly currentRouteThreadKeyRef: { readonly current: string | null }; |
| 52 | readonly draftId: DraftId | null; |
| 53 | readonly composerDraftTarget: ComposerThreadTarget; |
| 54 | readonly composerRef: ComposerHandleRef; |
| 55 | readonly promptRef: { current: string }; |
| 56 | readonly runtimeMode: RuntimeMode; |
| 57 | readonly startFromOrigin: boolean; |
| 58 | readonly resetLocalDispatch: ReturnType<typeof useLocalDispatchState>["resetLocalDispatch"]; |
| 59 | readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>; |
| 60 | } |
| 61 | |
| 62 | /** |
| 63 | * Starts one background thread per selected model, each in its own worktree. Failed models |
| 64 | * stay selected and the prompt comes back, either straight into this composer or, when the |
| 65 | * user has moved on, through a "Restore prompt" toast. |
| 66 | */ |
| 67 | export function useMultipleModelSend(input: MultipleModelSendInput) { |
| 68 | const { |
| 69 | environmentId, |
| 70 | routeThreadKey, |
| 71 | currentRouteThreadKeyRef, |
| 72 | draftId, |
| 73 | composerDraftTarget, |
| 74 | composerRef, |
| 75 | promptRef, |
| 76 | runtimeMode, |
| 77 | startFromOrigin, |
| 78 | resetLocalDispatch, |
| 79 | setThreadError, |
| 80 | } = input; |
| 81 | const navigate = useNavigate(); |
| 82 | const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, { |
| 83 | reportFailure: false, |
| 84 | }); |
| 85 | const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent); |
| 86 | const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey); |
| 87 | const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainSubmissionsRef } = |
| 88 | draftSendState(routeThreadKey); |
| 89 | |
| 90 | return async ({ |
| 91 | threadId, |
| 92 | project, |
| 93 | branch, |
| 94 | selections, |
| 95 | targets, |
| 96 | sendSnapshot, |
| 97 | createdAt, |
| 98 | attachmentsPromise, |
| 99 | usesAttachmentUploads, |
| 100 | readFileBlockReason, |
| 101 | buildOutgoingMessageContext, |
| 102 | isCurrentSend, |
| 103 | draftChangedDuringPreparation, |
| 104 | }: { |
| 105 | readonly threadId: ThreadId; |
| 106 | readonly project: EnvironmentProject; |
| 107 | readonly branch: string; |
| 108 | readonly selections: ReadonlyArray<ModelSelection>; |
| 109 | readonly targets: ReadonlyArray<MultipleModelTarget>; |
| 110 | readonly sendSnapshot: ComposerSendSnapshot; |
| 111 | readonly createdAt: string; |
| 112 | readonly attachmentsPromise: ReturnType<typeof prepareTurnAttachments>; |
| 113 | readonly usesAttachmentUploads: boolean; |
| 114 | readonly readFileBlockReason: () => string | null; |
| 115 | readonly buildOutgoingMessageContext: ( |
| 116 | attachmentIds: ReadonlyArray<string>, |
| 117 | ) => ReturnType<typeof buildMessageContext>; |
| 118 | /** False once a newer send from this composer started. */ |
| 119 | readonly isCurrentSend: () => boolean; |
| 120 | readonly draftChangedDuringPreparation: () => boolean; |
| 121 | }) => { |
| 122 | const { attachments: attachmentsSnapshot, messageText } = sendSnapshot; |
| 123 | const failedSelections: ModelSelection[] = []; |
| 124 | let clearedDraft = false; |
| 125 | let releasedComposer = false; |
| 126 | let canRestoreDraft = () => false; |
| 127 | let startedCount = 0; |
| 128 | // Anything thrown here (an attachment the server can no longer take) |
| 129 | // fails every selection; the draft restore below still runs. |
| 130 | const sendResult = await settlePromise(async () => { |
| 131 | const attachments = await attachmentsPromise; |
| 132 | if (draftChangedDuringPreparation()) |
| 133 | throw new Error( |
| 134 | m(msg("Draft changed while preparing this message. Review it and send again.")), |
| 135 | ); |
| 136 | const fileBlockReason = readFileBlockReason(); |
| 137 | if (fileBlockReason !== null) throw new Error(fileBlockReason); |
| 138 | const context = buildOutgoingMessageContext( |
| 139 | boundAttachmentIds(attachments, attachmentsSnapshot), |
| 140 | ); |
| 141 | const title = deriveThreadTitleSeed( |
| 142 | { text: messageText, attachments: attachmentsSnapshot }, |
| 143 | m, |
| 144 | ); |
| 145 | promptRef.current = ""; |
| 146 | clearComposerDraftContent(composerDraftTarget); |
| 147 | composerRef.current?.resetCursorState(); |
| 148 | clearedDraft = true; |
| 149 | const clearedDraftSnapshot = useComposerDraftStore |
| 150 | .getState() |
| 151 | .getComposerDraft(composerDraftTarget); |
| 152 | const submittedSelections = appAtomRegistry.get(fanoutSelectionsAtom); |
| 153 | canRestoreDraft = () => |
| 154 | currentRouteThreadKeyRef.current === routeThreadKey && |
| 155 | isCurrentSend() && |
| 156 | useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) === |
| 157 | clearedDraftSnapshot && |
| 158 | appAtomRegistry.get(fanoutSelectionsAtom) === submittedSelections; |
| 159 | setThreadError(threadId, null); |
| 160 | const starts = Promise.all( |
| 161 | targets.map(async (target) => { |
| 162 | const started = await startFanoutThread({ |
| 163 | retryKey: JSON.stringify([ |
| 164 | routeThreadKey, |
| 165 | target.selection.instanceId, |
| 166 | target.selection.model, |
| 167 | ]), |
| 168 | model: target.selection.model, |
| 169 | uncertainSubmissions: uncertainSubmissionsRef.current, |
| 170 | start: (targetThreadId) => { |
| 171 | return startThreadTurn({ |
| 172 | environmentId, |
| 173 | input: { |
| 174 | threadId: targetThreadId, |
| 175 | message: { |
| 176 | messageId: newMessageId(), |
| 177 | role: "user", |
| 178 | attachments, |
| 179 | ...withMessageContext({ |
| 180 | text: target.text, |
| 181 | context, |
| 182 | }), |
| 183 | }, |
| 184 | modelSelection: target.selection, |
| 185 | titleSeed: title, |
| 186 | runtimeMode, |
| 187 | interactionMode: DEFAULT_INTERACTION_MODE, |
| 188 | bootstrap: { |
| 189 | createThread: { |
| 190 | projectId: project.id, |
| 191 | title, |
| 192 | modelSelection: target.selection, |
| 193 | runtimeMode, |
| 194 | interactionMode: DEFAULT_INTERACTION_MODE, |
| 195 | branch, |
| 196 | worktreePath: null, |
| 197 | createdAt: createdAt, |
| 198 | }, |
| 199 | prepareWorktree: { |
| 200 | projectCwd: project.workspaceRoot, |
| 201 | baseBranch: branch, |
| 202 | requireWorktree: true, |
| 203 | ...(startFromOrigin ? { startFromOrigin: true } : {}), |
| 204 | }, |
| 205 | runSetupScript: true, |
| 206 | }, |
| 207 | createdAt: createdAt, |
| 208 | }, |
| 209 | }); |
| 210 | }, |
| 211 | openThread: (threadId) => |
| 212 | void navigate({ |
| 213 | to: "/$environmentId/$threadId", |
| 214 | params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)), |
| 215 | }), |
| 216 | }); |
| 217 | if (started) startedCount += 1; |
| 218 | else failedSelections.push(target.selection); |
| 219 | }), |
| 220 | ); |
| 221 | sendInFlightRef.current = false; |
| 222 | resetLocalDispatch(); |
| 223 | releasedComposer = true; |
| 224 | await starts; |
| 225 | if (startedCount > 0) { |
| 226 | toastManager.add( |
| 227 | stackedThreadToast({ |
| 228 | type: "success", |
| 229 | title: m( |
| 230 | msg( |
| 231 | "{count, plural, one {Started {count} thread in background} other {Started {count} threads in background}}", |
| 232 | { count: startedCount }, |
| 233 | ), |
| 234 | ), |
| 235 | }), |
| 236 | ); |
| 237 | } |
| 238 | if (failedSelections.length === 0 && usesAttachmentUploads) { |
| 239 | releaseDraftAttachments(attachmentsSnapshot); |
| 240 | } |
| 241 | }); |
| 242 | if (sendResult._tag === "Failure") { |
| 243 | const error = squashAtomCommandFailure(sendResult); |
| 244 | failedSelections.push(...selections); |
| 245 | setThreadError(threadId, thrownErrorMessage(error, m) ?? m(msg("Failed to send messages."))); |
| 246 | } |
| 247 | const restoreFailedDraft = () => { |
| 248 | appAtomRegistry.set(fanoutSelectionsAtom, failedSelections); |
| 249 | if (clearedDraft) { |
| 250 | restoreComposerDraft(composerDraftTarget, sendSnapshot); |
| 251 | if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) { |
| 252 | promptRef.current = sendSnapshot.draftText; |
| 253 | composerRef.current.resetCursorState({ |
| 254 | cursor: collapseExpandedComposerCursor( |
| 255 | sendSnapshot.draftText, |
| 256 | sendSnapshot.draftText.length, |
| 257 | ), |
| 258 | prompt: sendSnapshot.draftText, |
| 259 | detectTrigger: true, |
| 260 | }); |
| 261 | } |
| 262 | } |
| 263 | }; |
| 264 | if (failedSelections.length > 0) { |
| 265 | if (canRestoreDraft() && composerRef.current) { |
| 266 | restoreFailedDraft(); |
| 267 | } else if (clearedDraft) { |
| 268 | const recoveryToastId = toastManager.add( |
| 269 | stackedThreadToast({ |
| 270 | type: "error", |
| 271 | title: m(msg("A background prompt could not be sent")), |
| 272 | description: m( |
| 273 | msg( |
| 274 | "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.", |
| 275 | ), |
| 276 | ), |
| 277 | timeout: 0, |
| 278 | actionProps: { |
| 279 | children: m(msg("Restore prompt")), |
| 280 | onClick: () => { |
| 281 | if ( |
| 282 | !draftId || |
| 283 | !useComposerDraftStore.getState().getDraftSession(draftId) || |
| 284 | sendInFlightRef.current || |
| 285 | composerDraftHasUserContent( |
| 286 | useComposerDraftStore.getState().getComposerDraft(composerDraftTarget), |
| 287 | ) |
| 288 | ) { |
| 289 | toastManager.update(recoveryToastId, { |
| 290 | description: m( |
| 291 | msg( |
| 292 | "Return to the original draft and send or clear its current prompt before restoring.", |
| 293 | ), |
| 294 | ), |
| 295 | }); |
| 296 | return; |
| 297 | } |
| 298 | restoreFailedDraft(); |
| 299 | void navigate({ to: "/draft/$draftId", params: { draftId } }); |
| 300 | toastManager.close(recoveryToastId); |
| 301 | }, |
| 302 | }, |
| 303 | }), |
| 304 | ); |
| 305 | } |
| 306 | } |
| 307 | if (!releasedComposer) { |
| 308 | sendInFlightRef.current = false; |
| 309 | resetLocalDispatch(); |
| 310 | } |
| 311 | }; |
| 312 | } |