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