@devries-cameron20 / t3code-1 / commits / ac23b74df8
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

refactor(web): multiple-model sends live in their own hook (#23094)

Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>

Julius Marminge committed Oct 21, 2026 at 14:25 UTC ac23b74df83d95f98419f3ade6103054a54daec1
4 files changed +364 -211
apps/web/src/components/ChatView.tsx
-1
@@ -3032,7 +3032,6 @@ export default function ChatView(props: ChatViewProps) {
3032 setSetupQueueSendThreadKey,
3033 setOptimisticUserMessages,
3034 setFeedbackSubmissionsByThreadKey,
3035 - setMultipleModelSelections,
3035 setThreadError,
3036 setKeepFullHistory,
3037 anchorNewTurn,
apps/web/src/components/chat/chatViewSend.ts
+37
@@ -17,6 +17,7 @@ import {
17 type AtomCommandResult,
18 } from "@t3tools/client-runtime/state/runtime";
19 import { readLocalApi } from "../../localApi";
20 +import { getUploadedAttachments } from "../../lib/attachmentUploadQueue";
21 import { findRevertCheckpoint } from "../../session-logic";
22 import { type ChatMessage } from "../../types";
23 import { randomUUID } from "~/lib/utils";
@@ -38,6 +39,7 @@ import {
39 resolveComposerInteractionMode,
40 cloneComposerImageForRetry,
41 type ComposerSendSnapshot,
42 + readFileAsDataUrl,
43 prepareRevertedMessageAttachments,
44 waitForRevertedMessage,
45 } from "../ChatView.logic";
@@ -326,3 +328,38 @@ export function resolveMultipleModelTargets(input: {
328 };
329 });
330 }
331 +
332 +/**
333 + * The attachments a turn sends: the server's upload records when it takes uploads, otherwise
334 + * images inlined as data URLs. Rejects when an attachment cannot go out.
335 + */
336 +export function prepareTurnAttachments(input: {
337 + readonly environmentId: EnvironmentId;
338 + readonly attachments: ReadonlyArray<ComposerImageAttachment | ComposerFileAttachment>;
339 + readonly usesAttachmentUploads: boolean;
340 +}) {
341 + const { environmentId, usesAttachmentUploads } = input;
342 + return Promise.all(
343 + input.attachments.map(async (attachment) => {
344 + if (usesAttachmentUploads) {
345 + const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
346 + if (!uploaded) {
347 + throw new Error(`Attachment '${attachment.name}' did not finish uploading.`);
348 + }
349 + return uploaded;
350 + }
351 + if (attachment.type !== "image") {
352 + throw new Error("This server does not support file attachments.");
353 + }
354 + return {
355 + type: "image" as const,
356 + id: attachment.id,
357 + name: attachment.name,
358 + mimeType: attachment.mimeType,
359 + sizeBytes: attachment.sizeBytes,
360 + dataUrl: await readFileAsDataUrl(attachment.file),
361 + ...(attachment.source ? { source: attachment.source } : {}),
362 + };
363 + }),
364 + );
365 +}
apps/web/src/components/chat/useComposerSend.ts
+34 -210
@@ -5,7 +5,6 @@ import {
5 restorePlanFollowUpComposer,
6 buildExpiredTerminalContextToastCopy,
7 deriveComposerSendState,
8 - readFileAsDataUrl,
8 revokeUserMessagePreviewUrls,
9 boundAttachmentIds,
10 formatOutgoingPrompt,
@@ -84,6 +83,7 @@ import { environmentServerConfigsAtom } from "../../state/server";
83 import { threadEnvironment } from "../../state/threads";
84 import { runMobileComposerTransition } from "./draftHeroTransition";
85 import { usePlanFollowUpSend } from "./useProposedPlanSend";
86 +import { useMultipleModelSend } from "./useMultipleModelSend";
87 import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
88 import {
89 awaitAttachmentUploads,
@@ -102,12 +102,11 @@ import {
102 threadContextsOutsideEnvironment,
103 } from "@t3tools/shared/composerContextReferences";
104 import {
105 - draftFanoutSelectionsAtom,
105 draftSendState,
106 type MultipleModelTarget,
107 resolveMultipleModelTargets,
108 + prepareTurnAttachments,
109 restoreComposerDraft,
110 - startFanoutThread,
110 } from "./chatViewSend";
111 import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
112 import type {
@@ -215,9 +214,6 @@ interface ComposerSendInput {
214 readonly setFeedbackSubmissionsByThreadKey: Dispatch<
215 SetStateAction<Record<string, ReadonlyArray<CodexFeedbackSubmission>>>
216 >;
218 - readonly setMultipleModelSelections: (
219 - selections: SetStateAction<ReadonlyArray<ModelSelection> | null>,
220 - ) => void;
217 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
218 readonly setKeepFullHistory: (threadKey: string, keep: boolean) => void;
219 readonly anchorNewTurn: TimelineFollow["anchorNewTurn"];
@@ -310,7 +306,6 @@ export function useComposerSend(input: ComposerSendInput) {
306 setSetupQueueSendThreadKey,
307 setOptimisticUserMessages,
308 setFeedbackSubmissionsByThreadKey,
313 - setMultipleModelSelections,
309 setThreadError,
310 setKeepFullHistory,
311 anchorNewTurn,
@@ -337,6 +332,19 @@ export function useComposerSend(input: ComposerSendInput) {
332 const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments);
333 const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
334 const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
335 + const sendToMultipleModels = useMultipleModelSend({
336 + environmentId,
337 + routeThreadKey,
338 + currentRouteThreadKeyRef,
339 + draftId,
340 + composerDraftTarget,
341 + composerRef,
342 + promptRef,
343 + runtimeMode,
344 + startFromOrigin,
345 + resetLocalDispatch,
346 + setThreadError,
347 + });
348 const submitPlanFollowUp = usePlanFollowUpSend({
349 environmentId,
350 routeThreadKey,
@@ -356,10 +364,7 @@ export function useComposerSend(input: ComposerSendInput) {
364 anchorNewTurn,
365 persistThreadSettingsForNextTurn,
366 });
359 - const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
360 - const readMultipleModelSelections = () => appAtomRegistry.get(fanoutSelectionsAtom);
361 - const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainMultipleSubmissionsRef } =
362 - draftSendState(routeThreadKey);
367 + const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
368 const composerSendGenerationRef = useRef(0);
369 const environmentUnavailableSendToastSlotRef = useRef(0);
370 // A send awaits uploads before it declines, so it reads the approvals pending by then.
@@ -1029,207 +1034,26 @@ export function useComposerSend(input: ComposerSendInput) {
1034 );
1035 }
1036
1032 - const turnAttachmentsPromise = Promise.all(
1033 - composerAttachmentsSnapshot.map(async (attachment) => {
1034 - if (turnUsesAttachmentUploads) {
1035 - const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
1036 - if (!uploaded) {
1037 - throw new Error(`Attachment '${attachment.name}' did not finish uploading.`);
1038 - }
1039 - return uploaded;
1040 - }
1041 - if (attachment.type !== "image") {
1042 - throw new Error("This server does not support file attachments.");
1043 - }
1044 - return {
1045 - type: "image" as const,
1046 - id: attachment.id,
1047 - name: attachment.name,
1048 - mimeType: attachment.mimeType,
1049 - sizeBytes: attachment.sizeBytes,
1050 - dataUrl: await readFileAsDataUrl(attachment.file),
1051 - ...(attachment.source ? { source: attachment.source } : {}),
1052 - };
1053 - }),
1054 - );
1037 + const turnAttachmentsPromise = prepareTurnAttachments({
1038 + environmentId,
1039 + attachments: composerAttachmentsSnapshot,
1040 + usesAttachmentUploads: turnUsesAttachmentUploads,
1041 + });
1042 if (multipleModelSelections !== null) {
1056 - const failedSelections: ModelSelection[] = [];
1057 - let clearedDraft = false;
1058 - let releasedComposer = false;
1059 - let canRestoreDraft = () => false;
1060 - let startedCount = 0;
1061 - // Anything thrown here (an attachment the server can no longer take)
1062 - // fails every selection; the draft restore below still runs.
1063 - const sendResult = await settlePromise(async () => {
1064 - const attachments = await turnAttachmentsPromise;
1065 - const fileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
1066 - if (fileBlockReason !== null) throw new Error(fileBlockReason);
1067 - const context = buildOutgoingMessageContext(
1068 - boundAttachmentIds(attachments, composerAttachmentsSnapshot),
1069 - );
1070 - const title = deriveThreadTitleSeed({
1071 - text: messageTextForSend,
1072 - attachments: composerAttachmentsSnapshot,
1073 - });
1074 - promptRef.current = "";
1075 - clearComposerDraftContent(composerDraftTarget);
1076 - composerRef.current?.resetCursorState();
1077 - clearedDraft = true;
1078 - const clearedDraftSnapshot = useComposerDraftStore
1079 - .getState()
1080 - .getComposerDraft(composerDraftTarget);
1081 - const submittedSelections = readMultipleModelSelections();
1082 - canRestoreDraft = () =>
1083 - currentRouteThreadKeyRef.current === routeThreadKey &&
1084 - composerSendGenerationRef.current === sendGeneration &&
1085 - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
1086 - clearedDraftSnapshot &&
1087 - readMultipleModelSelections() === submittedSelections;
1088 - setThreadError(threadIdForSend, null);
1089 - const starts = Promise.all(
1090 - multipleTargets.map(async (target) => {
1091 - const started = await startFanoutThread({
1092 - retryKey: JSON.stringify([
1093 - routeThreadKey,
1094 - target.selection.instanceId,
1095 - target.selection.model,
1096 - ]),
1097 - model: target.selection.model,
1098 - uncertainSubmissions: uncertainMultipleSubmissionsRef.current,
1099 - start: (targetThreadId) => {
1100 - const supportsInlineMessageContext =
1101 - appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
1102 - .capabilities.inlineMessageContext === true;
1103 - return startThreadTurn({
1104 - environmentId,
1105 - input: {
1106 - threadId: targetThreadId,
1107 - message: {
1108 - messageId: newMessageId(),
1109 - role: "user",
1110 - attachments,
1111 - ...withMessageContext({
1112 - text: target.text,
1113 - context,
1114 - supportsInlineMessageContext,
1115 - }),
1116 - },
1117 - modelSelection: target.selection,
1118 - titleSeed: title,
1119 - runtimeMode,
1120 - interactionMode: target.interactionMode,
1121 - bootstrap: {
1122 - createThread: {
1123 - projectId: activeProject.id,
1124 - title,
1125 - modelSelection: target.selection,
1126 - runtimeMode,
1127 - interactionMode: target.interactionMode,
1128 - branch: activeThreadBranch,
1129 - worktreePath: null,
1130 - createdAt: messageCreatedAt,
1131 - },
1132 - prepareWorktree: {
1133 - projectCwd: activeProject.workspaceRoot,
1134 - baseBranch: activeThreadBranch!,
1135 - requireWorktree: true,
1136 - ...(startFromOrigin ? { startFromOrigin: true } : {}),
1137 - },
1138 - runSetupScript: true,
1139 - },
1140 - createdAt: messageCreatedAt,
1141 - },
1142 - });
1143 - },
1144 - openThread: (threadId) =>
1145 - void navigate({
1146 - to: "/$environmentId/$threadId",
1147 - params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
1148 - }),
1149 - });
1150 - if (started) startedCount += 1;
1151 - else failedSelections.push(target.selection);
1152 - }),
1153 - );
1154 - sendInFlightRef.current = false;
1155 - resetLocalDispatch();
1156 - releasedComposer = true;
1157 - await starts;
1158 - if (startedCount > 0) {
1159 - toastManager.add(
1160 - stackedThreadToast({
1161 - type: "success",
1162 - title: `Started ${startedCount} ${startedCount === 1 ? "thread" : "threads"} in background`,
1163 - }),
1164 - );
1165 - }
1166 - if (failedSelections.length === 0 && turnUsesAttachmentUploads) {
1167 - releaseDraftAttachments(composerAttachmentsSnapshot);
1168 - }
1043 + await sendToMultipleModels({
1044 + threadId: threadIdForSend,
1045 + project: activeProject,
1046 + branch: activeThreadBranch!,
1047 + selections: multipleModelSelections,
1048 + targets: multipleTargets,
1049 + sendSnapshot,
1050 + createdAt: messageCreatedAt,
1051 + attachmentsPromise: turnAttachmentsPromise,
1052 + usesAttachmentUploads: turnUsesAttachmentUploads,
1053 + readFileBlockReason: () => readLiveAttachmentCapabilities().fileBlockReason,
1054 + buildOutgoingMessageContext,
1055 + isCurrentSend: () => composerSendGenerationRef.current === sendGeneration,
1056 });
1170 - if (sendResult._tag === "Failure") {
1171 - const error = squashAtomCommandFailure(sendResult);
1172 - failedSelections.push(...multipleModelSelections);
1173 - setThreadError(
1174 - threadIdForSend,
1175 - error instanceof Error ? error.message : "Failed to send messages.",
1176 - );
1177 - }
1178 - const restoreFailedDraft = () => {
1179 - setMultipleModelSelections(failedSelections);
1180 - if (clearedDraft) {
1181 - restoreComposerDraft(composerDraftTarget, sendSnapshot);
1182 - if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) {
1183 - promptRef.current = messageTextForSend;
1184 - composerRef.current.resetCursorState({
1185 - cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
1186 - prompt: messageTextForSend,
1187 - detectTrigger: true,
1188 - });
1189 - }
1190 - }
1191 - };
1192 - if (failedSelections.length > 0) {
1193 - if (canRestoreDraft() && composerRef.current) {
1194 - restoreFailedDraft();
1195 - } else if (clearedDraft) {
1196 - const recoveryToastId = toastManager.add(
1197 - stackedThreadToast({
1198 - type: "error",
1199 - title: "A background prompt could not be sent",
1200 - description:
1201 - "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.",
1202 - timeout: 0,
1203 - actionProps: {
1204 - children: "Restore prompt",
1205 - onClick: () => {
1206 - if (
1207 - !draftId ||
1208 - !useComposerDraftStore.getState().getDraftSession(draftId) ||
1209 - sendInFlightRef.current ||
1210 - composerDraftHasUserContent(
1211 - useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
1212 - )
1213 - ) {
1214 - toastManager.update(recoveryToastId, {
1215 - description:
1216 - "Return to the original draft and send or clear its current prompt before restoring.",
1217 - });
1218 - return;
1219 - }
1220 - restoreFailedDraft();
1221 - void navigate({ to: "/draft/$draftId", params: { draftId } });
1222 - toastManager.close(recoveryToastId);
1223 - },
1224 - },
1225 - }),
1226 - );
1227 - }
1228 - }
1229 - if (!releasedComposer) {
1230 - sendInFlightRef.current = false;
1231 - resetLocalDispatch();
1232 - }
1057 return;
1058 }
1059 const optimisticAttachments = optimisticMessageAttachments(composerAttachmentsSnapshot);
apps/web/src/components/chat/useMultipleModelSend.ts new
+293
@@ -0,0 +1,293 @@
1 +import {
2 + type EnvironmentId,
3 + type ModelSelection,
4 + type RuntimeMode,
5 + type ThreadId,
6 +} from "@t3tools/contracts";
7 +import { scopeThreadRef } from "@t3tools/client-runtime/environment";
8 +import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
9 +import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
10 +import type { EnvironmentProject } from "@t3tools/client-runtime/state/shell";
11 +import { useNavigate } from "@tanstack/react-router";
12 +import { newMessageId } from "~/lib/utils";
13 +import { collapseExpandedComposerCursor } from "../../composer-logic";
14 +import {
15 + type ComposerThreadTarget,
16 + composerDraftHasUserContent,
17 + type DraftId,
18 + useComposerDraftStore,
19 +} from "../../composerDraftStore";
20 +import type { ComposerHandleRef } from "../../composerHandleContext";
21 +import { releaseDraftAttachments } from "../../lib/attachmentUploadQueue";
22 +import type { buildMessageContext } from "../../lib/composerContextRecords";
23 +import { appAtomRegistry } from "../../rpc/atomRegistry";
24 +import { environmentServerConfigsAtom } from "../../state/server";
25 +import { threadEnvironment } from "../../state/threads";
26 +import { useOrchestrationCommand } from "../../state/use-orchestration-command";
27 +import { buildThreadRouteParams } from "../../threadRoutes";
28 +import { stackedThreadToast, toastManager } from "../ui/toast";
29 +import {
30 + boundAttachmentIds,
31 + type ComposerSendSnapshot,
32 + type makeThreadErrorSetter,
33 + withMessageContext,
34 +} from "../ChatView.logic";
35 +import {
36 + draftFanoutSelectionsAtom,
37 + draftSendState,
38 + type MultipleModelTarget,
39 + type prepareTurnAttachments,
40 + restoreComposerDraft,
41 + startFanoutThread,
42 +} from "./chatViewSend";
43 +import type { useLocalDispatchState } from "./useLocalDispatchState";
44 +
45 +interface MultipleModelSendInput {
46 + readonly environmentId: EnvironmentId;
47 + readonly routeThreadKey: string;
48 + readonly currentRouteThreadKeyRef: { readonly current: string | null };
49 + readonly draftId: DraftId | null;
50 + readonly composerDraftTarget: ComposerThreadTarget;
51 + readonly composerRef: ComposerHandleRef;
52 + readonly promptRef: { current: string };
53 + readonly runtimeMode: RuntimeMode;
54 + readonly startFromOrigin: boolean;
55 + readonly resetLocalDispatch: ReturnType<typeof useLocalDispatchState>["resetLocalDispatch"];
56 + readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
57 +}
58 +
59 +/**
60 + * Starts one background thread per selected model, each in its own worktree. Failed models
61 + * stay selected and the prompt comes back, either straight into this composer or, when the
62 + * user has moved on, through a "Restore prompt" toast.
63 + */
64 +export function useMultipleModelSend(input: MultipleModelSendInput) {
65 + const {
66 + environmentId,
67 + routeThreadKey,
68 + currentRouteThreadKeyRef,
69 + draftId,
70 + composerDraftTarget,
71 + composerRef,
72 + promptRef,
73 + runtimeMode,
74 + startFromOrigin,
75 + resetLocalDispatch,
76 + setThreadError,
77 + } = input;
78 + const navigate = useNavigate();
79 + const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
80 + reportFailure: false,
81 + });
82 + const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
83 + const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
84 + const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainSubmissionsRef } =
85 + draftSendState(routeThreadKey);
86 +
87 + return async ({
88 + threadId,
89 + project,
90 + branch,
91 + selections,
92 + targets,
93 + sendSnapshot,
94 + createdAt,
95 + attachmentsPromise,
96 + usesAttachmentUploads,
97 + readFileBlockReason,
98 + buildOutgoingMessageContext,
99 + isCurrentSend,
100 + }: {
101 + readonly threadId: ThreadId;
102 + readonly project: EnvironmentProject;
103 + readonly branch: string;
104 + readonly selections: ReadonlyArray<ModelSelection>;
105 + readonly targets: ReadonlyArray<MultipleModelTarget>;
106 + readonly sendSnapshot: ComposerSendSnapshot;
107 + readonly createdAt: string;
108 + readonly attachmentsPromise: ReturnType<typeof prepareTurnAttachments>;
109 + readonly usesAttachmentUploads: boolean;
110 + readonly readFileBlockReason: () => string | null;
111 + readonly buildOutgoingMessageContext: (
112 + attachmentIds: ReadonlyArray<string>,
113 + ) => ReturnType<typeof buildMessageContext>;
114 + /** False once a newer send from this composer started. */
115 + readonly isCurrentSend: () => boolean;
116 + }) => {
117 + const { attachments: attachmentsSnapshot, messageText } = sendSnapshot;
118 + const failedSelections: ModelSelection[] = [];
119 + let clearedDraft = false;
120 + let releasedComposer = false;
121 + let canRestoreDraft = () => false;
122 + let startedCount = 0;
123 + // Anything thrown here (an attachment the server can no longer take)
124 + // fails every selection; the draft restore below still runs.
125 + const sendResult = await settlePromise(async () => {
126 + const attachments = await attachmentsPromise;
127 + const fileBlockReason = readFileBlockReason();
128 + if (fileBlockReason !== null) throw new Error(fileBlockReason);
129 + const context = buildOutgoingMessageContext(
130 + boundAttachmentIds(attachments, attachmentsSnapshot),
131 + );
132 + const title = deriveThreadTitleSeed({
133 + text: messageText,
134 + attachments: attachmentsSnapshot,
135 + });
136 + promptRef.current = "";
137 + clearComposerDraftContent(composerDraftTarget);
138 + composerRef.current?.resetCursorState();
139 + clearedDraft = true;
140 + const clearedDraftSnapshot = useComposerDraftStore
141 + .getState()
142 + .getComposerDraft(composerDraftTarget);
143 + const submittedSelections = appAtomRegistry.get(fanoutSelectionsAtom);
144 + canRestoreDraft = () =>
145 + currentRouteThreadKeyRef.current === routeThreadKey &&
146 + isCurrentSend() &&
147 + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
148 + clearedDraftSnapshot &&
149 + appAtomRegistry.get(fanoutSelectionsAtom) === submittedSelections;
150 + setThreadError(threadId, null);
151 + const starts = Promise.all(
152 + targets.map(async (target) => {
153 + const started = await startFanoutThread({
154 + retryKey: JSON.stringify([
155 + routeThreadKey,
156 + target.selection.instanceId,
157 + target.selection.model,
158 + ]),
159 + model: target.selection.model,
160 + uncertainSubmissions: uncertainSubmissionsRef.current,
161 + start: (targetThreadId) => {
162 + const supportsInlineMessageContext =
163 + appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
164 + .capabilities.inlineMessageContext === true;
165 + return startThreadTurn({
166 + environmentId,
167 + input: {
168 + threadId: targetThreadId,
169 + message: {
170 + messageId: newMessageId(),
171 + role: "user",
172 + attachments,
173 + ...withMessageContext({
174 + text: target.text,
175 + context,
176 + supportsInlineMessageContext,
177 + }),
178 + },
179 + modelSelection: target.selection,
180 + titleSeed: title,
181 + runtimeMode,
182 + interactionMode: target.interactionMode,
183 + bootstrap: {
184 + createThread: {
185 + projectId: project.id,
186 + title,
187 + modelSelection: target.selection,
188 + runtimeMode,
189 + interactionMode: target.interactionMode,
190 + branch,
191 + worktreePath: null,
192 + createdAt: createdAt,
193 + },
194 + prepareWorktree: {
195 + projectCwd: project.workspaceRoot,
196 + baseBranch: branch,
197 + requireWorktree: true,
198 + ...(startFromOrigin ? { startFromOrigin: true } : {}),
199 + },
200 + runSetupScript: true,
201 + },
202 + createdAt: createdAt,
203 + },
204 + });
205 + },
206 + openThread: (threadId) =>
207 + void navigate({
208 + to: "/$environmentId/$threadId",
209 + params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
210 + }),
211 + });
212 + if (started) startedCount += 1;
213 + else failedSelections.push(target.selection);
214 + }),
215 + );
216 + sendInFlightRef.current = false;
217 + resetLocalDispatch();
218 + releasedComposer = true;
219 + await starts;
220 + if (startedCount > 0) {
221 + toastManager.add(
222 + stackedThreadToast({
223 + type: "success",
224 + title: `Started ${startedCount} ${startedCount === 1 ? "thread" : "threads"} in background`,
225 + }),
226 + );
227 + }
228 + if (failedSelections.length === 0 && usesAttachmentUploads) {
229 + releaseDraftAttachments(attachmentsSnapshot);
230 + }
231 + });
232 + if (sendResult._tag === "Failure") {
233 + const error = squashAtomCommandFailure(sendResult);
234 + failedSelections.push(...selections);
235 + setThreadError(threadId, error instanceof Error ? error.message : "Failed to send messages.");
236 + }
237 + const restoreFailedDraft = () => {
238 + appAtomRegistry.set(fanoutSelectionsAtom, failedSelections);
239 + if (clearedDraft) {
240 + restoreComposerDraft(composerDraftTarget, sendSnapshot);
241 + if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) {
242 + promptRef.current = messageText;
243 + composerRef.current.resetCursorState({
244 + cursor: collapseExpandedComposerCursor(messageText, messageText.length),
245 + prompt: messageText,
246 + detectTrigger: true,
247 + });
248 + }
249 + }
250 + };
251 + if (failedSelections.length > 0) {
252 + if (canRestoreDraft() && composerRef.current) {
253 + restoreFailedDraft();
254 + } else if (clearedDraft) {
255 + const recoveryToastId = toastManager.add(
256 + stackedThreadToast({
257 + type: "error",
258 + title: "A background prompt could not be sent",
259 + description:
260 + "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.",
261 + timeout: 0,
262 + actionProps: {
263 + children: "Restore prompt",
264 + onClick: () => {
265 + if (
266 + !draftId ||
267 + !useComposerDraftStore.getState().getDraftSession(draftId) ||
268 + sendInFlightRef.current ||
269 + composerDraftHasUserContent(
270 + useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
271 + )
272 + ) {
273 + toastManager.update(recoveryToastId, {
274 + description:
275 + "Return to the original draft and send or clear its current prompt before restoring.",
276 + });
277 + return;
278 + }
279 + restoreFailedDraft();
280 + void navigate({ to: "/draft/$draftId", params: { draftId } });
281 + toastManager.close(recoveryToastId);
282 + },
283 + },
284 + }),
285 + );
286 + }
287 + }
288 + if (!releasedComposer) {
289 + sendInFlightRef.current = false;
290 + resetLocalDispatch();
291 + }
292 + };
293 +}