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