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