Open History to see the last commit
1import { isClearComposerCommand, parseSideChatCommand } from "@t3tools/shared/composerTrigger";
2import { armFreshSession, disarmFreshSession, readFreshSessionArm } from "./freshSessionArms";
3import {
4 mergeDirectPreviewAnnotation,
5 resolveBackgroundDraftWorkspaceOptions,
6 shouldDockDraftHeroForSubmission,
7 buildExpiredTerminalContextToastCopy,
8 deriveComposerSendState,
9 boundAttachmentIds,
10 formatOutgoingPrompt,
11 optimisticMessageAttachments,
12 planComposerTurn,
13 sendTitleFallbackLabels,
14 snapshotComposerSend,
15 withMessageContext,
16 makeThreadErrorSetter,
17} from "../ChatView.logic";
18import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits";
19import {
20 AuthOrchestrationOperateScope,
21 DEFAULT_MODEL,
22 type EnvironmentId,
23 type ModelSelection,
24 type PreviewAnnotationPayload,
25 type ThreadId,
26 ProviderInteractionMode,
27 RuntimeMode,
28} from "@t3tools/contracts";
29import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
30import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
31import {
32 declinePendingApprovals,
33 sendApprovalFeedback,
34} from "@t3tools/client-runtime/state/thread-requests";
35import {
36 parseCodexFeedbackCommand,
37 submitCodexFeedback,
38 type CodexFeedbackSubmission,
39} from "@t3tools/client-runtime/state/threads";
40import {
41 scopedThreadKey,
42 scopeProjectRef,
43 scopeThreadRef,
44} from "@t3tools/client-runtime/environment";
45import { createModelSelection } from "@t3tools/shared/model";
46import { type SetStateAction, useLayoutEffect, useRef } from "react";
47import { flushSync } from "react-dom";
48import { useNavigate } from "@tanstack/react-router";
49import {
50 isAtomCommandInterrupted,
51 settlePromise,
52 squashAtomCommandFailure,
53 type AtomCommandResult,
54} from "@t3tools/client-runtime/state/runtime";
55import {
56 type ComposerSubmissionIntent,
57 collapseExpandedComposerCursor,
58} from "../../composer-logic";
59import { type ChatMessage, DEFAULT_INTERACTION_MODE } from "../../types";
60import { recordPromptSent } from "../GitHubStarPrompt";
61import { stackedThreadToast, toastManager } from "../ui/toast";
62import { newMessageId, newThreadId } from "~/lib/utils";
63import { useNewThreadHandler } from "../../hooks/useHandleNewThread";
64import { buildThreadRouteParams } from "../../threadRoutes";
65import {
66 beginBackgroundDraftSubmissionByRef,
67 clearBackgroundDraftSubmissionByRef,
68 finalizePromotedDraftThreadByRef,
69 markPromotedDraftThreadByRef,
70 restoreFailedDraftThread,
71 composerDraftHasUserContent,
72 type ComposerFileAttachment,
73 type ComposerImageAttachment,
74 type DraftThreadEnvMode,
75 useComposerDraftStore,
76 DraftId,
77} from "../../composerDraftStore";
78import {
79 filterTerminalContextsWithText,
80 type TerminalContextDraft,
81} from "../../lib/terminalContext";
82import { ensureInlineContextReferences } from "../../lib/composerContextReferences";
83import {
84 buildMessageContext,
85 previewAnnotationContextReference,
86} from "../../lib/composerContextRecords";
87import { environmentServerConfigsAtom } from "../../state/server";
88import { threadEnvironment } from "../../state/threads";
89import { runMobileComposerTransition } from "./draftHeroTransition";
90import { useClientSettingsHydrated } from "../../hooks/useSettings";
91import { environmentPresentations } from "../../state/presentation";
92import {
93 approvalRedirectNotice,
94 loadBalancingSendWarning,
95 multipleModelSendBlock,
96 referencedThreadContexts,
97} from "./composerSend.logic";
98import { useMultipleModelSend } from "./useMultipleModelSend";
99import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
100import {
101 awaitAttachmentUploads,
102 getUploadedAttachments,
103 readAttachmentUpload,
104 releaseDraftAttachments,
105 retryAttachmentUpload,
106 startAttachmentUpload,
107} from "../../lib/attachmentUploadQueue";
108import { appAtomRegistry } from "../../rpc/atomRegistry";
109import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
110import { useLinkedEnvironments } from "../../state/peerLinks";
111import { readEnvironmentScope } from "../../state/session";
112import { useOrchestrationCommand } from "../../state/use-orchestration-command";
113import {
114 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
115 threadContextsOutsideEnvironment,
116} from "@t3tools/shared/composerContextReferences";
117import {
118 draftSendState,
119 type MultipleModelTarget,
120 resolveMultipleModelTargets,
121 prepareTurnAttachments,
122 restoreComposerDraft,
123} from "./chatViewSend";
124import type {
125 EnvironmentProject,
126 EnvironmentThreadShell,
127} from "@t3tools/client-runtime/state/shell";
128import type { Dispatch } from "react";
129import type { ComposerThreadTarget } from "../../composerDraftStore";
130import type { ProviderInstanceEntry } from "../../providerInstances";
131import type { SessionPhase } from "../../types";
132import type { DraftSessionState } from "../../composerDraftStore";
133import type { ComposerHandleRef } from "../../composerHandleContext";
134import type { useLogicalProjectEnvironments } from "../../hooks/useLogicalProjectEnvironments";
135import type { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
136import type { useLocalDispatchState } from "./useLocalDispatchState";
137import type { usePendingThreadRequests } from "./usePendingThreadRequests";
138import type { useQueuedRunEdit } from "./useQueuedRunEdit";
139import type { useTimelineFollow } from "./useTimelineFollow";
140import type { useUsageLimitsPanel } from "./useUsageLimitsPanel";
141import type { useWorktreeSetup } from "./useWorktreeSetup";
142
143const ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE = 3;
144
145function readEnvironmentPresentation(environmentId: EnvironmentId) {
146 return appAtomRegistry.get(environmentPresentations.presentationsAtom).get(environmentId);
147}
148
149function draftHasNonPromptContent(target: ComposerThreadTarget) {
150 const draft = useComposerDraftStore.getState().getComposerDraft(target);
151 return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false;
152}
153
154type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>;
155type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
156type DraftEnvironmentRouting = ReturnType<typeof useDraftEnvironmentRouting>;
157type UsageLimitsPanel = ReturnType<typeof useUsageLimitsPanel>;
158type TimelineFollow = ReturnType<typeof useTimelineFollow>;
159
160interface ComposerSendInput {
161 readonly environmentId: EnvironmentId;
162 readonly routeThreadKey: string;
163 readonly currentRouteThreadKeyRef: { readonly current: string | null };
164 readonly draftId: DraftId | null;
165 readonly draftThread: DraftSessionState | null;
166 readonly activeThread: EnvironmentThreadShell | undefined;
167 readonly activeThreadKey: string | null;
168 readonly activeThreadBranch: string | null;
169 readonly activeProject: EnvironmentProject | null;
170 readonly activeProjectDefaultModelSelection: ModelSelection | null;
171 readonly activeMessageCount: number;
172 readonly isServerThread: boolean;
173 readonly isLocalDraftThread: boolean;
174 readonly isGitRepo: boolean;
175 readonly phase: SessionPhase;
176 readonly runtimeMode: RuntimeMode;
177 readonly sendEnvMode: DraftThreadEnvMode;
178 readonly startFromOrigin: boolean;
179 readonly localCheckoutBranchMismatch: {
180 readonly threadBranch: string;
181 readonly currentBranch: string;
182 } | null;
183 readonly logicalProjectEnvironments: ReturnType<typeof useLogicalProjectEnvironments>;
184 readonly providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry>;
185 readonly composerRef: ComposerHandleRef;
186 readonly composerDraftTarget: ComposerThreadTarget;
187 readonly promptRef: { current: string };
188 readonly composerImagesRef: { current: ComposerImageAttachment[] };
189 readonly composerFilesRef: { current: ComposerFileAttachment[] };
190 readonly composerTerminalContextsRef: { current: TerminalContextDraft[] };
191 readonly feedbackUploadsInFlightRef: { readonly current: Set<string> };
192 readonly queuedRunEdit: ReturnType<typeof useQueuedRunEdit>;
193 readonly isRevertingCheckpoint: boolean;
194 readonly threadDetailLoading: boolean;
195 readonly activeEnvironmentUnavailable: boolean;
196 readonly isSendBusy: boolean;
197 readonly sendQueuesBehindSetup: boolean;
198 readonly isDraftHeroState: boolean;
199 readonly panelAnimationsActive: boolean;
200 readonly panelAnimationDurationMs: number;
201 readonly keepFullHistory: boolean;
202 /** `/clear` can arm a fresh session on this thread. */
203 readonly freshSessionAvailable: boolean;
204 readonly resumeCompactionTokens: number | null;
205 readonly usageLimitsKey: string | null;
206 readonly usageLimitsOffered: boolean;
207 readonly openUsageLimits: UsageLimitsPanel["open"];
208 readonly clearUsageLimitsFor: UsageLimitsPanel["clearFor"];
209 readonly needsLoadBalancing: boolean;
210 readonly loadBalancing: DraftEnvironmentRouting["loadBalancing"];
211 readonly readPendingEnvironmentChange: DraftEnvironmentRouting["readPendingEnvironmentChange"];
212 readonly pendingApprovals: PendingThreadRequests["pendingApprovals"];
213 readonly respondingRequestIds: PendingThreadRequests["respondingRequestIds"];
214 readonly activePendingProgress: PendingThreadRequests["activePendingProgress"];
215 readonly onAdvanceActivePendingUserInput: PendingThreadRequests["onAdvanceActivePendingUserInput"];
216 readonly onRespondToApproval: PendingThreadRequests["onRespondToApproval"];
217 readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
218 readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
219 readonly beginWorktreeSetup: ReturnType<typeof useWorktreeSetup>["begin"];
220 readonly captureDraftHeroComposerRect: () => void;
221 readonly setDockedDraftHeroThreadKey: Dispatch<SetStateAction<string | null>>;
222 readonly setSetupQueueSendThreadKey: Dispatch<SetStateAction<string | null>>;
223 readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>;
224 /** Takes ownership of, and later releases, an optimistic message's blob previews. */
225 readonly optimisticBlobPreviews: {
226 readonly track: (message: ChatMessage) => void;
227 readonly release: (message: ChatMessage) => void;
228 };
229 readonly setFeedbackSubmissionsByThreadKey: Dispatch<
230 SetStateAction<Record<string, ReadonlyArray<CodexFeedbackSubmission>>>
231 >;
232 readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
233 readonly setKeepFullHistory: (threadKey: string, keep: boolean) => void;
234 readonly anchorNewTurn: TimelineFollow["anchorNewTurn"];
235 readonly acknowledgeActiveThreadWoke: () => void;
236 /** Resolves true once the side chat started and got the prompt. */
237 readonly onSideChat?: ((prompt: string) => Promise<boolean>) | undefined;
238 /** Refuses `/side` with this reason and keeps the draft. */
239 readonly sideChatDisabledReason: string | null;
240 readonly handleNewThreadInActiveProject: () => void;
241 readonly persistThreadSettingsForNextTurn: (input: {
242 threadId: ThreadId;
243 createdAt: string;
244 branch?: string;
245 runtimeMode: RuntimeMode;
246 interactionMode: ProviderInteractionMode;
247 }) => Promise<AtomCommandResult<void, unknown>>;
248}
249
250/**
251 * Everything the composer's send button can start: a turn on this thread or a new one,
252 * a multiple-model start, a queued or steering message, a plan follow-up or implementation
253 * thread, a feedback upload, and resuming an interrupted run. Each path restores the draft
254 * when it fails.
255 */
256export function useComposerSend(input: ComposerSendInput) {
257 const {
258 environmentId,
259 routeThreadKey,
260 currentRouteThreadKeyRef,
261 draftId,
262 draftThread,
263 activeThread,
264 activeThreadKey,
265 activeThreadBranch,
266 activeProject,
267 activeProjectDefaultModelSelection,
268 activeMessageCount,
269 isServerThread,
270 isLocalDraftThread,
271 isGitRepo,
272 phase,
273 runtimeMode,
274 sendEnvMode,
275 startFromOrigin,
276 localCheckoutBranchMismatch,
277 logicalProjectEnvironments,
278 providerInstanceEntries,
279 composerRef,
280 composerDraftTarget,
281 promptRef,
282 composerImagesRef,
283 composerFilesRef,
284 composerTerminalContextsRef,
285 feedbackUploadsInFlightRef,
286 queuedRunEdit,
287 isRevertingCheckpoint,
288 threadDetailLoading,
289 activeEnvironmentUnavailable,
290 isSendBusy,
291 sendQueuesBehindSetup,
292 isDraftHeroState,
293 panelAnimationsActive,
294 panelAnimationDurationMs,
295 keepFullHistory,
296 freshSessionAvailable,
297 resumeCompactionTokens,
298 usageLimitsKey,
299 usageLimitsOffered,
300 openUsageLimits,
301 clearUsageLimitsFor,
302 needsLoadBalancing,
303 loadBalancing,
304 readPendingEnvironmentChange,
305 pendingApprovals,
306 respondingRequestIds,
307 activePendingProgress,
308 onAdvanceActivePendingUserInput,
309 onRespondToApproval: onRespondToApprovalStable,
310 beginLocalDispatch,
311 resetLocalDispatch,
312 beginWorktreeSetup,
313 captureDraftHeroComposerRect,
314 setDockedDraftHeroThreadKey,
315 setSetupQueueSendThreadKey,
316 setOptimisticUserMessages,
317 optimisticBlobPreviews,
318 setFeedbackSubmissionsByThreadKey,
319 setThreadError,
320 setKeepFullHistory,
321 anchorNewTurn,
322 acknowledgeActiveThreadWoke,
323 onSideChat,
324 sideChatDisabledReason,
325 handleNewThreadInActiveProject,
326 persistThreadSettingsForNextTurn,
327 } = input;
328 const linkedEnvironments = useLinkedEnvironments(environmentId);
329 const handleNewThread = useNewThreadHandler();
330 const navigate = useNavigate();
331 const clientSettingsHydrated = useClientSettingsHydrated();
332 const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
333 reportFailure: false,
334 });
335 const uploadThreadFeedback = useOrchestrationCommand(threadEnvironment.uploadFeedback, {
336 reportFailure: false,
337 });
338 const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
339 const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
340 const sendToMultipleModels = useMultipleModelSend({
341 environmentId,
342 routeThreadKey,
343 currentRouteThreadKeyRef,
344 draftId,
345 composerDraftTarget,
346 composerRef,
347 promptRef,
348 runtimeMode,
349 startFromOrigin,
350 resetLocalDispatch,
351 setThreadError,
352 });
353 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
354 const composerSendGenerationRef = useRef(0);
355 const environmentUnavailableSendToastSlotRef = useRef(0);
356 // A send awaits uploads before it declines, so it reads the approvals pending by then.
357 const pendingApprovalsRef = useRef(pendingApprovals);
358 const respondingRequestIdsRef = useRef(respondingRequestIds);
359 // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- mirrors approvals into refs that an async send reads after awaiting uploads
360 useLayoutEffect(() => {
361 pendingApprovalsRef.current = pendingApprovals;
362 respondingRequestIdsRef.current = respondingRequestIds;
363 }, [pendingApprovals, respondingRequestIds]);
364
365 const onSend = async (
366 e?: { preventDefault: () => void },
367 dispatchMode: ComposerDispatchMode = "auto",
368 submissionIntent: ComposerSubmissionIntent = "foreground",
369 directAnnotation?: {
370 annotation: PreviewAnnotationPayload;
371 image: ComposerImageAttachment | null;
372 },
373 ) => {
374 e?.preventDefault();
375 // What the user pressed send on; uploads below can take a while, and a redirect must not
376 // decline approvals for a draft that changed meanwhile.
377 const promptAtSend = promptRef.current;
378 if (
379 usageLimitsOffered &&
380 usageLimitsKey !== null &&
381 !directAnnotation &&
382 !draftHasNonPromptContent(composerDraftTarget) &&
383 isUsageLimitsCommand(promptRef.current)
384 ) {
385 if (openUsageLimits()) {
386 promptRef.current = "";
387 setComposerDraftPrompt(composerDraftTarget, "");
388 composerRef.current?.resetCursorState();
389 }
390 return;
391 }
392
393 const notifyDirectAnnotationAttached = () => {
394 if (!directAnnotation) return;
395 toastManager.add(
396 stackedThreadToast({
397 type: "info",
398 title: "Annotation attached to draft",
399 description: "Sending is unavailable right now. Finish the current action, then send.",
400 }),
401 );
402 };
403 if (
404 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
405 !activeThread ||
406 (isSendBusy && !sendQueuesBehindSetup) ||
407 isRevertingCheckpoint ||
408 !clientSettingsHydrated ||
409 threadDetailLoading ||
410 readPendingEnvironmentChange() !== null ||
411 sendInFlightRef.current ||
412 feedbackUploadsInFlightRef.current.has(routeThreadKey)
413 ) {
414 notifyDirectAnnotationAttached();
415 return;
416 }
417 if (needsLoadBalancing) {
418 const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget);
419 toastManager.add({
420 type: "warning",
421 ...loadBalancingSendWarning({
422 pending: loadBalancing.pending,
423 threadContexts: draft ? referencedThreadContexts(draft) : [],
424 candidateEnvironmentIds: logicalProjectEnvironments.map(
425 (candidate) => candidate.environmentId,
426 ),
427 }),
428 });
429 return;
430 }
431 if (activeEnvironmentUnavailable) {
432 const toastSlot = environmentUnavailableSendToastSlotRef.current;
433 environmentUnavailableSendToastSlotRef.current =
434 (toastSlot + 1) % ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE;
435 toastManager.add({
436 ...stackedThreadToast({
437 type: "warning",
438 title: "Not connected: message not sent",
439 description: "Reconnecting to the environment. Try again once it is connected.",
440 }),
441 id: `chat-send-environment-unavailable:${toastSlot}`,
442 });
443 return;
444 }
445 const sendCtx = composerRef.current?.getSendContext();
446 // `/side` beats an open question and a plan follow-up, which would send the text to main.
447 const sideChatCommand =
448 sendCtx && !directAnnotation && !queuedRunEdit.isEditing
449 ? parseSideChatCommand(promptAtSend)
450 : null;
451 const answeringQuestion =
452 Boolean(activePendingProgress) && sendCtx?.answeringPendingUserInput !== false;
453 // Where side chats are unavailable, `/side` text can still be a literal answer.
454 if (sideChatDisabledReason !== null && sideChatCommand && !answeringQuestion) {
455 toastManager.add(
456 stackedThreadToast({
457 type: "warning",
458 title: "Side chat not started",
459 description: sideChatDisabledReason,
460 }),
461 );
462 return;
463 }
464 if (onSideChat && sendCtx && sideChatCommand && sideChatDisabledReason === null) {
465 if (
466 sendCtx.images.length > 0 ||
467 sendCtx.files.length > 0 ||
468 filterTerminalContextsWithText(sendCtx.terminalContexts).length > 0 ||
469 sendCtx.previewAnnotations.length > 0 ||
470 sendCtx.reviewComments.length > 0 ||
471 sendCtx.threadContexts.length > 0 ||
472 sendCtx.environmentContexts.length > 0
473 ) {
474 toastManager.add(
475 stackedThreadToast({
476 type: "warning",
477 title: "Side chats take text only",
478 description: "Remove the attachments and context, then send it again.",
479 }),
480 );
481 return;
482 }
483 const started = await onSideChat(sideChatCommand.prompt);
484 // Clear only what was sent; the user may have edited the draft or left meanwhile.
485 if (
486 started &&
487 currentRouteThreadKeyRef.current === routeThreadKey &&
488 promptRef.current === promptAtSend
489 ) {
490 promptRef.current = "";
491 setComposerDraftPrompt(composerDraftTarget, "");
492 composerRef.current?.resetCursorState();
493 }
494 return;
495 }
496 if (answeringQuestion) {
497 if (directAnnotation) {
498 notifyDirectAnnotationAttached();
499 return;
500 }
501 onAdvanceActivePendingUserInput();
502 return;
503 }
504 if (!sendCtx?.providerAvailable) {
505 notifyDirectAnnotationAttached();
506 return;
507 }
508 const multipleModelSelections = sendCtx.multipleModelSelections;
509 const approvalFeedbackTarget = pendingApprovalsRef.current.find(
510 (approval) =>
511 approval.supportsFeedback && approval.requestId === sendCtx.shownPendingApprovalIds[0],
512 );
513 const multipleModelBlock =
514 multipleModelSelections === null
515 ? null
516 : multipleModelSendBlock({
517 selectionCount: multipleModelSelections.length,
518 serverSupportsWorktreeBootstrap:
519 readEnvironmentPresentation(activeThread.environmentId)?.serverConfig?.environment
520 .capabilities.requiredWorktreeBootstrap === true,
521 isLocalDraftThread,
522 isGitRepo,
523 branch: activeThreadBranch,
524 });
525 if (multipleModelBlock === "server-outdated") {
526 setThreadError(activeThread.id, "Update this server before starting multiple models.");
527 return;
528 }
529 if (multipleModelBlock === "needs-new-git-thread") {
530 toastManager.add(
531 stackedThreadToast({
532 type: "warning",
533 title: "Choose models and a base branch",
534 description:
535 "Multiple models need a new thread in a Git project. Each gets its own worktree.",
536 }),
537 );
538 return;
539 }
540 const {
541 images: sendContextImages,
542 files: composerFiles,
543 terminalContexts: composerTerminalContexts,
544 previewAnnotations: sendContextPreviewAnnotations,
545 reviewComments: composerReviewComments,
546 threadContexts: composerThreadContexts,
547 environmentContexts: composerEnvironmentContexts,
548 selectedProvider: ctxSelectedProvider,
549 selectedModel: ctxSelectedModel,
550 selectedProviderModels: ctxSelectedProviderModels,
551 selectedPromptEffort: ctxSelectedPromptEffort,
552 selectedModelSelection: ctxSelectedModelSelection,
553 } = sendCtx;
554 const { images: composerImages, previewAnnotations: composerPreviewAnnotations } =
555 mergeDirectPreviewAnnotation({
556 images: sendContextImages,
557 fileCount: composerFiles.length,
558 previewAnnotations: sendContextPreviewAnnotations,
559 direct: directAnnotation,
560 });
561 // A direct "send annotation" writes the draft and sends in the same tick; the reference
562 // must be in the text now, not after the next render.
563 const promptForSend = directAnnotation
564 ? ensureInlineContextReferences(promptRef.current, [
565 previewAnnotationContextReference(directAnnotation.annotation),
566 ])
567 : promptRef.current;
568 const strandedThread = threadContextsOutsideEnvironment({
569 text: promptForSend,
570 records: composerThreadContexts,
571 environmentId,
572 linkedEnvironments,
573 })[0];
574 if (strandedThread) {
575 const owner =
576 readEnvironmentPresentation(strandedThread.environmentId)?.entry.target.label ??
577 "its machine";
578 toastManager.add(
579 stackedThreadToast({
580 type: "warning",
581 title: "Attached thread is on another machine",
582 description: `This machine's agent can't read "${strandedThread.title}". Remove it, or switch back to ${owner} to send.`,
583 }),
584 );
585 return;
586 }
587 if (queuedRunEdit.isEditing) {
588 // Edit mode repurposes the composer: sending saves the queued message
589 // in place instead of dispatching a new turn.
590 await queuedRunEdit.saveEdit(
591 {
592 prompt: promptForSend,
593 images: composerImages,
594 files: composerFiles,
595 terminalContexts: composerTerminalContexts,
596 reviewComments: composerReviewComments,
597 previewAnnotations: composerPreviewAnnotations,
598 threadContexts: composerThreadContexts,
599 environmentContexts: composerEnvironmentContexts,
600 },
601 setThreadError,
602 );
603 return;
604 }
605 const {
606 trimmedPrompt: trimmed,
607 sendableTerminalContexts: sendableComposerTerminalContexts,
608 expiredTerminalContextCount,
609 hasSendableContent,
610 } = deriveComposerSendState({
611 prompt: promptForSend,
612 imageCount: composerImages.length + composerFiles.length,
613 terminalContexts: composerTerminalContexts,
614 elementContextCount:
615 composerPreviewAnnotations.length +
616 composerReviewComments.length +
617 composerThreadContexts.length +
618 composerEnvironmentContexts.length,
619 });
620 const feedbackCommand =
621 ctxSelectedProvider === "codex" &&
622 composerImages.length === 0 &&
623 composerFiles.length === 0 &&
624 sendableComposerTerminalContexts.length === 0 &&
625 composerPreviewAnnotations.length === 0 &&
626 composerReviewComments.length === 0 &&
627 composerThreadContexts.length === 0 &&
628 composerEnvironmentContexts.length === 0
629 ? parseCodexFeedbackCommand(trimmed)
630 : null;
631 if (feedbackCommand && multipleModelSelections === null) {
632 if (!isServerThread || activeThread.activeProviderThreadId === null) {
633 toastManager.add(
634 stackedThreadToast({
635 type: "warning",
636 title: "Start a Codex thread first",
637 description: "Send a message before you submit feedback.",
638 }),
639 );
640 return;
641 }
642 feedbackUploadsInFlightRef.current.add(routeThreadKey);
643 await submitCodexFeedback({
644 submission: {
645 id: newMessageId(),
646 command: trimmed,
647 createdAt: new Date().toISOString(),
648 },
649 clearDraft: () => {
650 promptRef.current = "";
651 clearComposerDraftContent(composerDraftTarget);
652 composerRef.current?.resetCursorState();
653 },
654 onUpdate: (submission) => {
655 setFeedbackSubmissionsByThreadKey((current) => {
656 const existing = current[routeThreadKey] ?? [];
657 const found = existing.some((entry) => entry.id === submission.id);
658 return {
659 ...current,
660 [routeThreadKey]: found
661 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
662 : [...existing, submission],
663 };
664 });
665 },
666 upload: () =>
667 uploadThreadFeedback({
668 environmentId: activeThread.environmentId,
669 input: { threadId: activeThread.id, ...feedbackCommand },
670 }),
671 }).finally(() => {
672 feedbackUploadsInFlightRef.current.delete(routeThreadKey);
673 });
674
675 return;
676 }
677 const composerHoldsOnlyText =
678 composerImages.length === 0 &&
679 composerFiles.length === 0 &&
680 sendableComposerTerminalContexts.length === 0 &&
681 composerPreviewAnnotations.length === 0 &&
682 composerReviewComments.length === 0 &&
683 composerThreadContexts.length === 0 &&
684 composerEnvironmentContexts.length === 0;
685 if (freshSessionAvailable && composerHoldsOnlyText && isClearComposerCommand(trimmed)) {
686 armFreshSession(routeThreadKey);
687 promptRef.current = "";
688 clearComposerDraftContent(composerDraftTarget);
689 composerRef.current?.resetCursorState();
690 return;
691 }
692 // Read once: an arm made while this send is in flight belongs to the next message.
693 const freshArm = freshSessionAvailable ? readFreshSessionArm(routeThreadKey) : undefined;
694 if (!hasSendableContent) {
695 if (expiredTerminalContextCount > 0) {
696 const toastCopy = buildExpiredTerminalContextToastCopy(
697 expiredTerminalContextCount,
698 "empty",
699 );
700 toastManager.add(
701 stackedThreadToast({
702 type: "warning",
703 title: toastCopy.title,
704 description: toastCopy.description,
705 }),
706 );
707 }
708 return;
709 }
710 if (!activeProject) {
711 toastManager.add(
712 stackedThreadToast({
713 type: "warning",
714 title: "Choose a project first",
715 description: "This draft no longer points to an available project.",
716 }),
717 );
718 return;
719 }
720 const threadIdForSend = activeThread.id;
721 const sendSnapshot = snapshotComposerSend({
722 prompt: promptForSend,
723 images: composerImages,
724 files: composerFiles,
725 terminalContexts: composerTerminalContexts,
726 sendableTerminalContexts: sendableComposerTerminalContexts,
727 previewAnnotations: composerPreviewAnnotations,
728 reviewComments: composerReviewComments,
729 threadContexts: composerThreadContexts,
730 environmentContexts: composerEnvironmentContexts,
731 });
732 const {
733 files: composerFilesSnapshot,
734 attachments: composerAttachmentsSnapshot,
735 terminalContexts: composerTerminalContextsSnapshot,
736 previewAnnotations: composerPreviewAnnotationsSnapshot,
737 reviewComments: composerReviewCommentsSnapshot,
738 threadContexts: composerThreadContextsSnapshot,
739 environmentContexts: composerEnvironmentContextsSnapshot,
740 messageText: messageTextForSend,
741 } = sendSnapshot;
742 const {
743 missingWorktreeBaseBranch,
744 baseBranchForWorktree,
745 compactBeforeSend,
746 turnDispatchMode,
747 shouldQueueBehindActiveRun,
748 } = planComposerTurn({
749 messageText: messageTextForSend,
750 sendQueuesBehindSetup,
751 isServerThread,
752 activeMessageCount,
753 sendEnvMode,
754 worktreePath: activeThread.worktreePath,
755 activeThreadBranch,
756 resumeCompactionTokens,
757 keepFullHistory,
758 phase,
759 dispatchMode,
760 freshContext: freshArm !== undefined,
761 });
762 if (missingWorktreeBaseBranch) {
763 setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
764 return;
765 }
766 // Records bind attachments by the id each side knows: the local id for the optimistic
767 // row, the upload id (or local id on the data-URL path) on the wire; the server
768 // rebinds them to the persisted id.
769 const buildOutgoingMessageContext = (attachmentIds: ReadonlyArray<string>) =>
770 buildMessageContext({
771 terminalContexts: composerTerminalContextsSnapshot,
772 reviewComments: composerReviewCommentsSnapshot,
773 previewAnnotations: composerPreviewAnnotationsSnapshot,
774 threadContexts: composerThreadContextsSnapshot,
775 environmentContexts: composerEnvironmentContextsSnapshot,
776 attachments: composerAttachmentsSnapshot.map((attachment, index) => ({
777 attachment,
778 attachmentId: attachmentIds[index] ?? attachment.id,
779 })),
780 });
781 const outgoingMessageContext = buildOutgoingMessageContext(
782 composerAttachmentsSnapshot.map((attachment) => attachment.id),
783 );
784 const messageIdForSend = newMessageId();
785 const messageCreatedAt = new Date().toISOString();
786 const outgoingMessageText = formatOutgoingPrompt({
787 provider: ctxSelectedProvider,
788 model: ctxSelectedModel,
789 models: ctxSelectedProviderModels,
790 effort: ctxSelectedPromptEffort,
791 text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
792 });
793 if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) {
794 return;
795 }
796
797 const readLiveAttachmentCapabilities = () => {
798 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
799 const liveSupportsAttachmentUploads = config !== null;
800 return {
801 supportsAttachmentUploads: liveSupportsAttachmentUploads,
802 fileBlockReason: fileAttachmentCapabilityBlockReason({
803 files: composerFilesSnapshot,
804 attachmentUploadsCapabilityKnown: config !== null,
805 supportsAttachmentUploads: liveSupportsAttachmentUploads,
806 maxFileAttachmentBytes:
807 config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
808 }),
809 };
810 };
811
812 const multipleTargets: MultipleModelTarget[] = [];
813 for (const resolved of resolveMultipleModelTargets({
814 selections: multipleModelSelections ?? [],
815 providerInstanceEntries,
816 messageText: messageTextForSend,
817 })) {
818 if ("error" in resolved) {
819 setThreadError(threadIdForSend, resolved.error);
820 return;
821 }
822 if (composerRef.current?.validateProviderInput(resolved.text) === false) return;
823 multipleTargets.push(resolved);
824 }
825
826 sendInFlightRef.current = true;
827 const sendGeneration = ++composerSendGenerationRef.current;
828 const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities();
829 if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) {
830 sendInFlightRef.current = false;
831 setThreadError(threadIdForSend, attachmentCapabilitiesBeforeUpload.fileBlockReason);
832 return;
833 }
834 const turnUsesAttachmentUploads =
835 composerFilesSnapshot.length > 0
836 ? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads
837 : (readEnvironmentPresentation(environmentId)?.serverConfig ?? null) !== null;
838 if (turnUsesAttachmentUploads && composerAttachmentsSnapshot.length > 0) {
839 for (const attachment of composerAttachmentsSnapshot) {
840 const upload =
841 readAttachmentUpload(attachment.id)?.status === "failed"
842 ? retryAttachmentUpload
843 : startAttachmentUpload;
844 upload({
845 environmentId,
846 image: attachment,
847 draftTarget: composerDraftTarget,
848 });
849 }
850 await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id));
851 const attachmentCapabilitiesAfterUpload = readLiveAttachmentCapabilities();
852 if (attachmentCapabilitiesAfterUpload.fileBlockReason !== null) {
853 sendInFlightRef.current = false;
854 setThreadError(threadIdForSend, attachmentCapabilitiesAfterUpload.fileBlockReason);
855 return;
856 }
857 if (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null) {
858 sendInFlightRef.current = false;
859 setThreadError(threadIdForSend, "Retry or remove failed uploads before sending.");
860 return;
861 }
862 }
863
864 if (
865 multipleModelSelections === null &&
866 shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) &&
867 activeThreadKey
868 ) {
869 let resolveDockStarted: (() => void) | undefined;
870 const dockStarted = new Promise<void>((resolve) => {
871 resolveDockStarted = resolve;
872 });
873 const dockTransition = runMobileComposerTransition(
874 () => {
875 flushSync(() => {
876 captureDraftHeroComposerRect();
877 setDockedDraftHeroThreadKey(activeThreadKey);
878 });
879 resolveDockStarted?.();
880 },
881 {
882 active: panelAnimationsActive,
883 durationMs: panelAnimationDurationMs,
884 },
885 );
886 void dockTransition.catch(() => resolveDockStarted?.());
887 await dockStarted;
888 }
889
890 const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();
891 if (
892 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
893 attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null
894 ) {
895 sendInFlightRef.current = false;
896 setThreadError(
897 threadIdForSend,
898 attachmentCapabilitiesBeforeDispatch.fileBlockReason ??
899 "This connection cannot change threads.",
900 );
901 setDockedDraftHeroThreadKey((currentThreadKey) =>
902 currentThreadKey === activeThreadKey ? null : currentThreadKey,
903 );
904 return;
905 }
906 // A message sent while approvals are pending redirects the agent. They are declined only
907 // here, after everything above has accepted the send, so local commands and rejected
908 // drafts leave them alone. After navigating away during an upload, the shown approvals
909 // are another thread's, so this send leaves them alone too.
910 const approvalsToDecline =
911 currentRouteThreadKeyRef.current === routeThreadKey
912 ? pendingApprovalsRef.current.filter((approval) =>
913 sendCtx?.shownPendingApprovalIds.includes(approval.requestId),
914 )
915 : [];
916 if (approvalsToDecline.length > 0 || approvalFeedbackTarget !== undefined) {
917 // A draft edited since send, or a paste still landing in it, is no longer the message
918 // the user sent.
919 const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id);
920 // A direct annotation send writes its image and reference into the draft as it sends,
921 // so the live draft may still lack them; anything else differing is a real edit.
922 const annotationImageId = directAnnotation?.image?.id;
923 const attachmentIdsBeforeAnnotation = attachmentIdsAtSend.filter(
924 (id) => id !== annotationImageId,
925 );
926 const sameIds = (left: ReadonlyArray<string>, right: ReadonlyArray<string>) =>
927 left.length === right.length && left.every((id, index) => id === right[index]);
928 const draftChangedSinceSend = () => {
929 if (composerRef.current?.hasPendingAttachments() === true) return true;
930 const sendContext = composerRef.current?.getSendContext();
931 const attachmentIds = sendContext
932 ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id)
933 : attachmentIdsAtSend;
934 const promptUnchanged =
935 promptRef.current === promptAtSend || promptRef.current === promptForSend;
936 const attachmentsUnchanged =
937 sameIds(attachmentIds, attachmentIdsAtSend) ||
938 (annotationImageId !== undefined &&
939 sameIds(attachmentIds, attachmentIdsBeforeAnnotation));
940 return !promptUnchanged || !attachmentsUnchanged;
941 };
942 const draftBeforeDecline = useComposerDraftStore
943 .getState()
944 .getComposerDraft(composerDraftTarget);
945 const changedBeforeDecline = draftChangedSinceSend();
946 const pendingIdsBeforeDecline = pendingApprovalsRef.current.map(
947 (approval) => approval.requestId,
948 );
949 const approvalResponding = approvalsToDecline.some((approval) =>
950 respondingRequestIdsRef.current.includes(approval.requestId),
951 );
952 if (approvalFeedbackTarget !== undefined) {
953 if (composerAttachmentsSnapshot.length > 0 || outgoingMessageContext !== undefined) {
954 setThreadError(
955 threadIdForSend,
956 "Send approval feedback without attachments or added context.",
957 );
958 sendInFlightRef.current = false;
959 return;
960 }
961 if (
962 changedBeforeDecline ||
963 approvalResponding ||
964 currentRouteThreadKeyRef.current !== routeThreadKey
965 ) {
966 sendInFlightRef.current = false;
967 return;
968 }
969 const sent = await sendApprovalFeedback(
970 approvalFeedbackTarget,
971 messageTextForSend,
972 onRespondToApprovalStable,
973 ).catch(() => false);
974 sendInFlightRef.current = false;
975 if (
976 sent &&
977 !draftChangedSinceSend() &&
978 currentRouteThreadKeyRef.current === routeThreadKey &&
979 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
980 draftBeforeDecline
981 ) {
982 promptRef.current = "";
983 clearComposerDraftContent(composerDraftTarget);
984 composerRef.current?.resetCursorState();
985 }
986 return;
987 }
988 const declined =
989 !changedBeforeDecline &&
990 !approvalResponding &&
991 (await declinePendingApprovals(approvalsToDecline, onRespondToApprovalStable).catch(
992 () => false,
993 ));
994 const draftChanged =
995 changedBeforeDecline ||
996 draftChangedSinceSend() ||
997 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) !==
998 draftBeforeDecline;
999 // An approval that arrived during the decline would block the redirect; keep the draft so
1000 // the next send declines it too.
1001 const approvalArrived = pendingApprovalsRef.current.some(
1002 (approval) => !pendingIdsBeforeDecline.includes(approval.requestId),
1003 );
1004 if (
1005 !declined ||
1006 draftChanged ||
1007 approvalArrived ||
1008 currentRouteThreadKeyRef.current !== routeThreadKey
1009 ) {
1010 sendInFlightRef.current = false;
1011 setDockedDraftHeroThreadKey((currentThreadKey) =>
1012 currentThreadKey === activeThreadKey ? null : currentThreadKey,
1013 );
1014 const notice = approvalRedirectNotice({
1015 draftChanged,
1016 declined,
1017 approvalResponding,
1018 approvalArrived,
1019 });
1020 if (notice !== null) {
1021 toastManager.add({
1022 type: "info",
1023 title: notice,
1024 description: "Send again when it's ready.",
1025 });
1026 }
1027 return;
1028 }
1029 }
1030 if (sendQueuesBehindSetup) {
1031 setSetupQueueSendThreadKey(activeThreadKey);
1032 } else {
1033 beginLocalDispatch({
1034 preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree),
1035 submissionIntent:
1036 submissionIntent === "background" && !isLocalDraftThread
1037 ? "foreground"
1038 : submissionIntent,
1039 });
1040 beginWorktreeSetup(
1041 multipleModelSelections === null && baseBranchForWorktree
1042 ? { environmentId: activeThread.environmentId, threadId: threadIdForSend }
1043 : null,
1044 );
1045 }
1046
1047 const turnAttachmentsPromise = prepareTurnAttachments({
1048 environmentId,
1049 attachments: composerAttachmentsSnapshot,
1050 usesAttachmentUploads: turnUsesAttachmentUploads,
1051 });
1052 if (multipleModelSelections !== null) {
1053 await sendToMultipleModels({
1054 threadId: threadIdForSend,
1055 project: activeProject,
1056 branch: activeThreadBranch!,
1057 selections: multipleModelSelections,
1058 targets: multipleTargets,
1059 sendSnapshot,
1060 createdAt: messageCreatedAt,
1061 attachmentsPromise: turnAttachmentsPromise,
1062 usesAttachmentUploads: turnUsesAttachmentUploads,
1063 readFileBlockReason: () => readLiveAttachmentCapabilities().fileBlockReason,
1064 buildOutgoingMessageContext,
1065 isCurrentSend: () => composerSendGenerationRef.current === sendGeneration,
1066 });
1067 return;
1068 }
1069 const optimisticAttachments = optimisticMessageAttachments(composerAttachmentsSnapshot);
1070 if (!shouldQueueBehindActiveRun) {
1071 anchorNewTurn(
1072 scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
1073 messageIdForSend,
1074 );
1075 }
1076 const optimisticMessage: ChatMessage = {
1077 id: messageIdForSend,
1078 role: "user",
1079 text: outgoingMessageText,
1080 ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
1081 ...(outgoingMessageContext !== undefined ? { context: outgoingMessageContext } : {}),
1082 runId: null,
1083 createdAt: messageCreatedAt,
1084 updatedAt: messageCreatedAt,
1085 streaming: false,
1086 ...(shouldQueueBehindActiveRun
1087 ? { inputIntent: "queued_turn" as const }
1088 : phase === "running" && dispatchMode === "steer"
1089 ? { inputIntent: "steer" as const }
1090 : {}),
1091 };
1092 // After leaving the thread during an upload, its previews were already released and the
1093 // message is never shown, so tracking them would keep them alive past the thread.
1094 if (currentRouteThreadKeyRef.current === routeThreadKey) {
1095 optimisticBlobPreviews.track(optimisticMessage);
1096 } else {
1097 optimisticBlobPreviews.release(optimisticMessage);
1098 }
1099 setOptimisticUserMessages((existing) => [...existing, optimisticMessage]);
1100 setThreadError(threadIdForSend, null);
1101 if (expiredTerminalContextCount > 0) {
1102 const toastCopy = buildExpiredTerminalContextToastCopy(
1103 expiredTerminalContextCount,
1104 "omitted",
1105 );
1106 toastManager.add(
1107 stackedThreadToast({
1108 type: "warning",
1109 title: toastCopy.title,
1110 description: toastCopy.description,
1111 }),
1112 );
1113 }
1114 const sentDraftThreadRef = isLocalDraftThread
1115 ? scopeThreadRef(environmentId, threadIdForSend)
1116 : null;
1117 // Keep new-thread flows from reusing this draft while attachments and worktree setup settle.
1118 if (sentDraftThreadRef) markPromotedDraftThreadByRef(sentDraftThreadRef);
1119 promptRef.current = "";
1120 clearComposerDraftContent(composerDraftTarget);
1121 composerRef.current?.resetCursorState();
1122
1123 const title = deriveThreadTitleSeed({
1124 text: messageTextForSend,
1125 attachments: composerAttachmentsSnapshot,
1126 fallbackLabels: sendTitleFallbackLabels(sendSnapshot),
1127 });
1128 const threadCreateModelSelection = createModelSelection(
1129 ctxSelectedModelSelection.instanceId,
1130 ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL,
1131 ctxSelectedModelSelection.options,
1132 );
1133
1134 let failure: AtomCommandResult<unknown, unknown> | null = null;
1135
1136 if (failure === null && isServerThread) {
1137 const settingsResult = await persistThreadSettingsForNextTurn({
1138 threadId: threadIdForSend,
1139 createdAt: messageCreatedAt,
1140 ...(localCheckoutBranchMismatch
1141 ? { branch: localCheckoutBranchMismatch.currentBranch }
1142 : {}),
1143 runtimeMode,
1144 interactionMode: DEFAULT_INTERACTION_MODE,
1145 });
1146 if (settingsResult._tag === "Failure") {
1147 failure = settingsResult;
1148 }
1149 }
1150
1151 const turnAttachmentsResult = await settlePromise(async () => {
1152 const turnAttachments = await turnAttachmentsPromise;
1153 const liveFileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
1154 if (liveFileBlockReason !== null) {
1155 throw new Error(liveFileBlockReason);
1156 }
1157 return turnAttachments;
1158 });
1159 if (failure === null && turnAttachmentsResult._tag === "Failure") {
1160 failure = turnAttachmentsResult;
1161 }
1162
1163 if (failure === null && compactBeforeSend) {
1164 const compactResult = await startThreadTurn({
1165 environmentId,
1166 input: {
1167 threadId: threadIdForSend,
1168 message: {
1169 messageId: newMessageId(),
1170 role: "user",
1171 text: "/compact",
1172 attachments: [],
1173 idleCompaction: "onReturn",
1174 },
1175 modelSelection: ctxSelectedModelSelection,
1176 runtimeMode,
1177 interactionMode: DEFAULT_INTERACTION_MODE,
1178 },
1179 });
1180 if (compactResult._tag === "Failure") {
1181 failure = compactResult;
1182 }
1183 }
1184
1185 let backgroundDraftOpened = false;
1186 let turnStartSucceeded = false;
1187 if (failure === null && turnAttachmentsResult._tag === "Success") {
1188 const bootstrap =
1189 isLocalDraftThread || baseBranchForWorktree
1190 ? {
1191 ...(isLocalDraftThread
1192 ? {
1193 createThread: {
1194 projectId: activeProject.id,
1195 title,
1196 modelSelection: threadCreateModelSelection,
1197 runtimeMode,
1198 interactionMode: DEFAULT_INTERACTION_MODE,
1199 branch: activeThreadBranch,
1200 worktreePath: activeThread.worktreePath,
1201 createdAt: activeThread.createdAt,
1202 },
1203 }
1204 : {}),
1205 ...(baseBranchForWorktree
1206 ? {
1207 prepareWorktree: {
1208 projectCwd: activeProject.workspaceRoot,
1209 baseBranch: baseBranchForWorktree,
1210 ...(startFromOrigin ? { startFromOrigin: true } : {}),
1211 },
1212 runSetupScript: true,
1213 }
1214 : {}),
1215 }
1216 : undefined;
1217 const backgroundThreadRef =
1218 submissionIntent === "background" && isLocalDraftThread
1219 ? scopeThreadRef(environmentId, threadIdForSend)
1220 : null;
1221 if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef);
1222 const startPromise = startThreadTurn({
1223 environmentId,
1224 input: {
1225 threadId: threadIdForSend,
1226 message: {
1227 messageId: messageIdForSend,
1228 role: "user",
1229 attachments: turnAttachmentsResult.value,
1230 ...withMessageContext({
1231 text: outgoingMessageText,
1232 context: buildOutgoingMessageContext(
1233 boundAttachmentIds(turnAttachmentsResult.value, composerAttachmentsSnapshot),
1234 ),
1235 }),
1236 },
1237 modelSelection: ctxSelectedModelSelection,
1238 titleSeed: title,
1239 runtimeMode,
1240 interactionMode: DEFAULT_INTERACTION_MODE,
1241 dispatchMode: turnDispatchMode,
1242 ...(freshArm === undefined ? {} : { freshContext: true }),
1243 ...(bootstrap ? { bootstrap } : {}),
1244 createdAt: messageCreatedAt,
1245 },
1246 });
1247 if (backgroundThreadRef) {
1248 try {
1249 backgroundDraftOpened = Boolean(
1250 await handleNewThread(
1251 scopeProjectRef(activeProject.environmentId, activeProject.id),
1252 resolveBackgroundDraftWorkspaceOptions({
1253 envMode: sendEnvMode,
1254 branch: activeThreadBranch,
1255 startFromOrigin,
1256 }),
1257 ),
1258 );
1259 } catch (error) {
1260 clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
1261 toastManager.add(
1262 stackedThreadToast({
1263 type: "warning",
1264 title: "Could not open a fresh composer",
1265 description: error instanceof Error ? error.message : undefined,
1266 }),
1267 );
1268 }
1269 }
1270 const startResult = await startPromise;
1271 if (startResult._tag === "Failure") {
1272 failure = startResult;
1273 } else {
1274 turnStartSucceeded = true;
1275 setKeepFullHistory(routeThreadKey, false);
1276 if (freshArm !== undefined) disarmFreshSession(routeThreadKey, freshArm);
1277 clearUsageLimitsFor(routeThreadKey);
1278 if (turnUsesAttachmentUploads) {
1279 releaseDraftAttachments(composerAttachmentsSnapshot);
1280 }
1281 acknowledgeActiveThreadWoke();
1282 // A draft still on screen finalizes once its thread route takes over.
1283 if (sentDraftThreadRef) {
1284 if (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey) {
1285 finalizePromotedDraftThreadByRef(sentDraftThreadRef);
1286 } else {
1287 clearBackgroundDraftSubmissionByRef(sentDraftThreadRef);
1288 }
1289 }
1290 if (backgroundThreadRef) {
1291 if (backgroundDraftOpened) {
1292 toastManager.add(
1293 stackedThreadToast({
1294 type: "success",
1295 title: "Started in background",
1296 timeout: 5_000,
1297 actionProps: {
1298 children: "Open",
1299 onClick: () => {
1300 void navigate({
1301 to: "/$environmentId/$threadId",
1302 params: buildThreadRouteParams(backgroundThreadRef),
1303 });
1304 },
1305 },
1306 }),
1307 );
1308 }
1309 } else if (
1310 submissionIntent === "background" &&
1311 currentRouteThreadKeyRef.current === routeThreadKey
1312 ) {
1313 handleNewThreadInActiveProject();
1314 }
1315 void recordPromptSent(environmentId);
1316 }
1317 }
1318
1319 if (failure !== null) {
1320 if (isLocalDraftThread && draftId && draftThread) {
1321 restoreFailedDraftThread(
1322 draftId,
1323 draftThread,
1324 wasBootstrapThreadDeleted(squashAtomCommandFailure(failure))
1325 ? newThreadId()
1326 : threadIdForSend,
1327 );
1328 clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend));
1329 }
1330 if (
1331 !composerDraftHasUserContent(
1332 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
1333 )
1334 ) {
1335 setOptimisticUserMessages((existing) => {
1336 const next = existing.filter((message) => message.id !== messageIdForSend);
1337 return next.length === existing.length ? existing : next;
1338 });
1339 // The restored draft clones its images, so the sent copies are no longer used.
1340 optimisticBlobPreviews.release(optimisticMessage);
1341 const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot);
1342 if (currentRouteThreadKeyRef.current === routeThreadKey) {
1343 promptRef.current = messageTextForSend;
1344 composerImagesRef.current = retryComposerImages;
1345 composerFilesRef.current = composerFilesSnapshot;
1346 composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
1347 composerRef.current?.resetCursorState({
1348 cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
1349 prompt: messageTextForSend,
1350 detectTrigger: true,
1351 });
1352 }
1353 }
1354 if (!isAtomCommandInterrupted(failure)) {
1355 const error = squashAtomCommandFailure(failure);
1356 setThreadError(
1357 threadIdForSend,
1358 error instanceof Error ? error.message : "Failed to send message.",
1359 );
1360 if (
1361 draftId &&
1362 (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey)
1363 ) {
1364 toastManager.add(
1365 stackedThreadToast({
1366 type: "error",
1367 title:
1368 submissionIntent === "background"
1369 ? "Background task failed"
1370 : "Could not start thread",
1371 description: error instanceof Error ? error.message : "Failed to send message.",
1372 actionProps: {
1373 children: "Open draft",
1374 onClick: () => {
1375 void navigate({ to: "/draft/$draftId", params: { draftId } });
1376 },
1377 },
1378 }),
1379 );
1380 }
1381 }
1382 }
1383 sendInFlightRef.current = false;
1384 setSetupQueueSendThreadKey((current) => (current === activeThreadKey ? null : current));
1385 if (!turnStartSucceeded) {
1386 setDockedDraftHeroThreadKey((currentThreadKey) =>
1387 currentThreadKey === activeThreadKey ? null : currentThreadKey,
1388 );
1389 if (!sendQueuesBehindSetup) resetLocalDispatch();
1390 }
1391 };
1392
1393 return { onSend };
1394}