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 { readEnvironmentScope } from "../../state/session";
109import { useOrchestrationCommand } from "../../state/use-orchestration-command";
110import {
111 ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
112 threadContextsOutsideEnvironment,
113} from "@t3tools/shared/composerContextReferences";
114import {
115 draftSendState,
116 type MultipleModelTarget,
117 resolveMultipleModelTargets,
118 prepareTurnAttachments,
119 restoreComposerDraft,
120} from "./chatViewSend";
121import type {
122 EnvironmentProject,
123 EnvironmentThreadShell,
124} from "@t3tools/client-runtime/state/shell";
125import type { UnifiedSettings } from "@t3tools/contracts";
126import type { Dispatch } from "react";
127import type { ComposerThreadTarget } from "../../composerDraftStore";
128import type { ProviderInstanceEntry } from "../../providerInstances";
129import type { SessionPhase } from "../../types";
130import type { DraftSessionState } from "../../composerDraftStore";
131import type { ComposerHandleRef } from "../../composerHandleContext";
132import type { useLogicalProjectEnvironments } from "../../hooks/useLogicalProjectEnvironments";
133import type { LatestProposedPlanState } from "../../session-logic";
134import type { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
135import type { useLocalDispatchState } from "./useLocalDispatchState";
136import type { usePendingThreadRequests } from "./usePendingThreadRequests";
137import type { useQueuedRunEdit } from "./useQueuedRunEdit";
138import type { useTimelineFollow } from "./useTimelineFollow";
139import type { useUsageLimitsPanel } from "./useUsageLimitsPanel";
140import type { useWorktreeSetup } from "./useWorktreeSetup";
141
142const ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE = 3;
143
144const selectPlanModeEnabled = (settings: UnifiedSettings) => settings.planModeEnabled;
145
146function readEnvironmentPresentation(environmentId: EnvironmentId) {
147 return appAtomRegistry.get(environmentPresentations.presentationsAtom).get(environmentId);
148}
149
150function draftHasNonPromptContent(target: ComposerThreadTarget) {
151 const draft = useComposerDraftStore.getState().getComposerDraft(target);
152 return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false;
153}
154
155type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>;
156type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
157type DraftEnvironmentRouting = ReturnType<typeof useDraftEnvironmentRouting>;
158type UsageLimitsPanel = ReturnType<typeof useUsageLimitsPanel>;
159type TimelineFollow = ReturnType<typeof useTimelineFollow>;
160
161interface ComposerSendInput {
162 readonly environmentId: EnvironmentId;
163 readonly routeThreadKey: string;
164 readonly currentRouteThreadKeyRef: { readonly current: string | null };
165 readonly draftId: DraftId | null;
166 readonly draftThread: DraftSessionState | null;
167 readonly activeThread: EnvironmentThreadShell | undefined;
168 readonly activeThreadKey: string | null;
169 readonly activeThreadBranch: string | null;
170 readonly activeProject: EnvironmentProject | null;
171 readonly activeProjectDefaultModelSelection: ModelSelection | null;
172 readonly activeProposedPlan: LatestProposedPlanState | null;
173 readonly activeMessageCount: number;
174 readonly isServerThread: boolean;
175 readonly isLocalDraftThread: boolean;
176 readonly isGitRepo: boolean;
177 readonly phase: SessionPhase;
178 readonly runtimeMode: RuntimeMode;
179 readonly sendEnvMode: DraftThreadEnvMode;
180 readonly startFromOrigin: boolean;
181 readonly localCheckoutBranchMismatch: {
182 readonly threadBranch: string;
183 readonly currentBranch: string;
184 } | null;
185 readonly logicalProjectEnvironments: ReturnType<typeof useLogicalProjectEnvironments>;
186 readonly providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry>;
187 readonly composerRef: ComposerHandleRef;
188 readonly composerDraftTarget: ComposerThreadTarget;
189 readonly promptRef: { current: string };
190 readonly composerImagesRef: { current: ComposerImageAttachment[] };
191 readonly composerFilesRef: { current: ComposerFileAttachment[] };
192 readonly composerTerminalContextsRef: { current: TerminalContextDraft[] };
193 readonly feedbackUploadsInFlightRef: { readonly current: Set<string> };
194 readonly queuedRunEdit: ReturnType<typeof useQueuedRunEdit>;
195 readonly isConnecting: boolean;
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 isConnecting,
288 isRevertingCheckpoint,
289 threadDetailLoading,
290 activeEnvironmentUnavailable,
291 isSendBusy,
292 sendQueuesBehindSetup,
293 isDraftHeroState,
294 panelAnimationsActive,
295 panelAnimationDurationMs,
296 keepFullHistory,
297 resumeCompactionTokens,
298 showPlanFollowUpPrompt,
299 usageLimitsKey,
300 usageLimitsOffered,
301 openUsageLimits,
302 clearUsageLimitsFor,
303 needsLoadBalancing,
304 loadBalancing,
305 readPendingEnvironmentChange,
306 pendingApprovals,
307 respondingRequestIds,
308 activePendingProgress,
309 onAdvanceActivePendingUserInput,
310 onRespondToApproval: onRespondToApprovalStable,
311 beginLocalDispatch,
312 resetLocalDispatch,
313 beginWorktreeSetup,
314 captureDraftHeroComposerRect,
315 setDockedDraftHeroThreadKey,
316 setSetupQueueSendThreadKey,
317 setOptimisticUserMessages,
318 optimisticBlobPreviews,
319 setFeedbackSubmissionsByThreadKey,
320 setThreadError,
321 setKeepFullHistory,
322 anchorNewTurn,
323 acknowledgeActiveThreadWoke,
324 handleInteractionModeChange,
325 handleNewThreadInActiveProject,
326 persistThreadSettingsForNextTurn,
327 } = input;
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 clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
348 const sendToMultipleModels = useMultipleModelSend({
349 environmentId,
350 routeThreadKey,
351 currentRouteThreadKeyRef,
352 draftId,
353 composerDraftTarget,
354 composerRef,
355 promptRef,
356 runtimeMode,
357 startFromOrigin,
358 resetLocalDispatch,
359 setThreadError,
360 });
361 const submitPlanFollowUp = usePlanFollowUpSend({
362 environmentId,
363 routeThreadKey,
364 activeThread,
365 activeThreadBranch,
366 activeProposedPlan,
367 isServerThread,
368 isSendBusy,
369 isConnecting,
370 composerRef,
371 beginLocalDispatch,
372 resetLocalDispatch,
373 runtimeMode,
374 localCheckoutBranchMismatch,
375 setOptimisticUserMessages,
376 setThreadError,
377 anchorNewTurn,
378 persistThreadSettingsForNextTurn,
379 });
380 const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
381 const composerSendGenerationRef = useRef(0);
382 const environmentUnavailableSendToastSlotRef = useRef(0);
383 // A send awaits uploads before it declines, so it reads the approvals pending by then.
384 const pendingApprovalsRef = useRef(pendingApprovals);
385 const respondingRequestIdsRef = useRef(respondingRequestIds);
386 useLayoutEffect(() => {
387 pendingApprovalsRef.current = pendingApprovals;
388 respondingRequestIdsRef.current = respondingRequestIds;
389 }, [pendingApprovals, respondingRequestIds]);
390
391 const onSend = async (
392 e?: { preventDefault: () => void },
393 dispatchMode: ComposerDispatchMode = "auto",
394 submissionIntent: ComposerSubmissionIntent = "foreground",
395 directAnnotation?: {
396 annotation: PreviewAnnotationPayload;
397 image: ComposerImageAttachment | null;
398 },
399 ) => {
400 e?.preventDefault();
401 // What the user pressed send on; uploads below can take a while, and a redirect must not
402 // decline approvals for a draft that changed meanwhile.
403 const promptAtSend = promptRef.current;
404 if (
405 usageLimitsOffered &&
406 usageLimitsKey !== null &&
407 !directAnnotation &&
408 !draftHasNonPromptContent(composerDraftTarget) &&
409 isUsageLimitsCommand(promptRef.current)
410 ) {
411 if (openUsageLimits()) {
412 promptRef.current = "";
413 setComposerDraftPrompt(composerDraftTarget, "");
414 composerRef.current?.resetCursorState();
415 }
416 return;
417 }
418
419 const notifyDirectAnnotationAttached = () => {
420 if (!directAnnotation) return;
421 toastManager.add(
422 stackedThreadToast({
423 type: "info",
424 title: "Annotation attached to draft",
425 description: "Sending is unavailable right now. Finish the current action, then send.",
426 }),
427 );
428 };
429 if (
430 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
431 !activeThread ||
432 (isSendBusy && !sendQueuesBehindSetup) ||
433 isConnecting ||
434 isRevertingCheckpoint ||
435 !clientSettingsHydrated ||
436 threadDetailLoading ||
437 readPendingEnvironmentChange() !== null ||
438 sendInFlightRef.current ||
439 feedbackUploadsInFlightRef.current.has(routeThreadKey)
440 ) {
441 notifyDirectAnnotationAttached();
442 return;
443 }
444 if (needsLoadBalancing) {
445 const draft = useComposerDraftStore.getState().getComposerDraft(composerDraftTarget);
446 toastManager.add({
447 type: "warning",
448 ...loadBalancingSendWarning({
449 pending: loadBalancing.pending,
450 threadContexts: draft ? referencedThreadContexts(draft) : [],
451 candidateEnvironmentIds: logicalProjectEnvironments.map(
452 (candidate) => candidate.environmentId,
453 ),
454 }),
455 });
456 return;
457 }
458 if (activeEnvironmentUnavailable) {
459 const toastSlot = environmentUnavailableSendToastSlotRef.current;
460 environmentUnavailableSendToastSlotRef.current =
461 (toastSlot + 1) % ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE;
462 toastManager.add({
463 ...stackedThreadToast({
464 type: "warning",
465 title: "Not connected: message not sent",
466 description: "Reconnecting to the environment. Try again once it is connected.",
467 }),
468 id: `chat-send-environment-unavailable:${toastSlot}`,
469 });
470 return;
471 }
472 const sendCtx = composerRef.current?.getSendContext();
473 if (activePendingProgress && sendCtx?.answeringPendingUserInput !== false) {
474 if (directAnnotation) {
475 notifyDirectAnnotationAttached();
476 return;
477 }
478 onAdvanceActivePendingUserInput();
479 return;
480 }
481 if (!sendCtx?.providerAvailable) {
482 notifyDirectAnnotationAttached();
483 return;
484 }
485 const multipleModelSelections = sendCtx.multipleModelSelections;
486 const approvalFeedbackTarget = pendingApprovalsRef.current.find(
487 (approval) =>
488 approval.supportsFeedback && approval.requestId === sendCtx.shownPendingApprovalIds[0],
489 );
490 const multipleModelBlock =
491 multipleModelSelections === null
492 ? null
493 : multipleModelSendBlock({
494 selectionCount: multipleModelSelections.length,
495 serverSupportsWorktreeBootstrap:
496 readEnvironmentPresentation(activeThread.environmentId)?.serverConfig?.environment
497 .capabilities.requiredWorktreeBootstrap === true,
498 isLocalDraftThread,
499 isGitRepo,
500 branch: activeThreadBranch,
501 });
502 if (multipleModelBlock === "server-outdated") {
503 setThreadError(activeThread.id, "Update this server before starting multiple models.");
504 return;
505 }
506 if (multipleModelBlock === "needs-new-git-thread") {
507 toastManager.add(
508 stackedThreadToast({
509 type: "warning",
510 title: "Choose models and a base branch",
511 description:
512 "Multiple models need a new thread in a Git project. Each gets its own worktree.",
513 }),
514 );
515 return;
516 }
517 const {
518 images: sendContextImages,
519 files: composerFiles,
520 terminalContexts: composerTerminalContexts,
521 previewAnnotations: sendContextPreviewAnnotations,
522 reviewComments: composerReviewComments,
523 threadContexts: composerThreadContexts,
524 selectedProvider: ctxSelectedProvider,
525 selectedModel: ctxSelectedModel,
526 selectedProviderModels: ctxSelectedProviderModels,
527 selectedPromptEffort: ctxSelectedPromptEffort,
528 selectedModelSelection: ctxSelectedModelSelection,
529 interactionMode: sendInteractionMode,
530 interactionModeEnabled: sendInteractionModeEnabled,
531 } = sendCtx;
532 const { images: composerImages, previewAnnotations: composerPreviewAnnotations } =
533 mergeDirectPreviewAnnotation({
534 images: sendContextImages,
535 fileCount: composerFiles.length,
536 previewAnnotations: sendContextPreviewAnnotations,
537 direct: directAnnotation,
538 });
539 // A direct "send annotation" writes the draft and sends in the same tick; the reference
540 // must be in the text now, not after the next render.
541 const promptForSend = directAnnotation
542 ? ensureInlineContextReferences(promptRef.current, [
543 previewAnnotationContextReference(directAnnotation.annotation),
544 ])
545 : promptRef.current;
546 const strandedThread = threadContextsOutsideEnvironment({
547 text: promptForSend,
548 records: composerThreadContexts,
549 environmentId,
550 })[0];
551 if (strandedThread) {
552 const owner =
553 readEnvironmentPresentation(strandedThread.environmentId)?.entry.target.label ??
554 "its machine";
555 toastManager.add(
556 stackedThreadToast({
557 type: "warning",
558 title: "Attached thread is on another machine",
559 description: `This machine's agent can't read "${strandedThread.title}". Remove it, or switch back to ${owner} to send.`,
560 }),
561 );
562 return;
563 }
564 if (queuedRunEdit.isEditing) {
565 // Edit mode repurposes the composer: sending saves the queued message
566 // in place instead of dispatching a new turn.
567 await queuedRunEdit.saveEdit(
568 {
569 prompt: promptForSend,
570 images: composerImages,
571 files: composerFiles,
572 terminalContexts: composerTerminalContexts,
573 reviewComments: composerReviewComments,
574 previewAnnotations: composerPreviewAnnotations,
575 threadContexts: composerThreadContexts,
576 },
577 setThreadError,
578 );
579 return;
580 }
581 const {
582 trimmedPrompt: trimmed,
583 sendableTerminalContexts: sendableComposerTerminalContexts,
584 expiredTerminalContextCount,
585 hasSendableContent,
586 } = deriveComposerSendState({
587 prompt: promptForSend,
588 imageCount: composerImages.length + composerFiles.length,
589 terminalContexts: composerTerminalContexts,
590 elementContextCount:
591 composerPreviewAnnotations.length +
592 composerReviewComments.length +
593 composerThreadContexts.length,
594 });
595 const feedbackCommand =
596 ctxSelectedProvider === "codex" &&
597 composerImages.length === 0 &&
598 composerFiles.length === 0 &&
599 sendableComposerTerminalContexts.length === 0 &&
600 composerPreviewAnnotations.length === 0 &&
601 composerReviewComments.length === 0 &&
602 composerThreadContexts.length === 0
603 ? parseCodexFeedbackCommand(trimmed)
604 : null;
605 if (feedbackCommand && multipleModelSelections === null) {
606 if (!isServerThread || activeThread.activeProviderThreadId === null) {
607 toastManager.add(
608 stackedThreadToast({
609 type: "warning",
610 title: "Start a Codex thread first",
611 description: "Send a message before you submit feedback.",
612 }),
613 );
614 return;
615 }
616 feedbackUploadsInFlightRef.current.add(routeThreadKey);
617 await submitCodexFeedback({
618 submission: {
619 id: newMessageId(),
620 command: trimmed,
621 createdAt: new Date().toISOString(),
622 },
623 clearDraft: () => {
624 promptRef.current = "";
625 clearComposerDraftContent(composerDraftTarget);
626 composerRef.current?.resetCursorState();
627 },
628 onUpdate: (submission) => {
629 setFeedbackSubmissionsByThreadKey((current) => {
630 const existing = current[routeThreadKey] ?? [];
631 const found = existing.some((entry) => entry.id === submission.id);
632 return {
633 ...current,
634 [routeThreadKey]: found
635 ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
636 : [...existing, submission],
637 };
638 });
639 },
640 upload: () =>
641 uploadThreadFeedback({
642 environmentId: activeThread.environmentId,
643 input: { threadId: activeThread.id, ...feedbackCommand },
644 }),
645 }).finally(() => {
646 feedbackUploadsInFlightRef.current.delete(routeThreadKey);
647 });
648
649 return;
650 }
651 if (
652 !directAnnotation &&
653 sendInteractionModeEnabled &&
654 showPlanFollowUpPrompt &&
655 activeProposedPlan &&
656 composerImages.length === 0 &&
657 composerFiles.length === 0
658 ) {
659 const followUp = resolvePlanFollowUpSubmission({
660 draftText: promptForSend,
661 planMarkdown: activeProposedPlan.planMarkdown,
662 });
663 const outgoingFollowUpText = formatOutgoingPrompt({
664 provider: ctxSelectedProvider,
665 model: ctxSelectedModel,
666 models: ctxSelectedProviderModels,
667 effort: ctxSelectedPromptEffort,
668 text: followUp.text.trim(),
669 });
670 if (composerRef.current?.validateProviderInput(outgoingFollowUpText) === false) {
671 return;
672 }
673 const followUpPromptSnapshot = promptRef.current;
674 const followUpTerminalContexts = [...sendableComposerTerminalContexts];
675 const followUpReviewComments = [...composerReviewComments];
676 const followUpPreviewAnnotations = [...composerPreviewAnnotations];
677 const followUpThreadContexts = [...composerThreadContexts];
678 promptRef.current = "";
679 clearComposerDraftContent(composerDraftTarget);
680 composerRef.current?.resetCursorState();
681 const followUpSent = await submitPlanFollowUp({
682 text: followUp.text,
683 context: buildMessageContext({
684 terminalContexts: sendableComposerTerminalContexts,
685 reviewComments: composerReviewComments,
686 previewAnnotations: composerPreviewAnnotations,
687 threadContexts: composerThreadContexts,
688 }),
689 interactionMode: followUp.interactionMode,
690 });
691 if (!followUpSent) {
692 promptRef.current = followUpPromptSnapshot;
693 composerTerminalContextsRef.current = [...followUpTerminalContexts];
694 restorePlanFollowUpComposer({
695 snapshot: {
696 prompt: followUpPromptSnapshot,
697 terminalContexts: followUpTerminalContexts,
698 reviewComments: followUpReviewComments,
699 previewAnnotations: followUpPreviewAnnotations,
700 threadContexts: followUpThreadContexts,
701 },
702 writePrompt: (prompt) => setComposerDraftPrompt(composerDraftTarget, prompt),
703 writeTerminalContexts: (contexts) =>
704 setComposerDraftTerminalContexts(composerDraftTarget, [...contexts]),
705 writeReviewComments: (comments) =>
706 setComposerDraftReviewComments(composerDraftTarget, [...comments]),
707 writePreviewAnnotations: (annotations) =>
708 setComposerDraftPreviewAnnotations(composerDraftTarget, [...annotations]),
709 writeThreadContexts: (records) =>
710 setComposerDraftThreadContexts(composerDraftTarget, [...records]),
711 resetCursor: (options) => composerRef.current?.resetCursorState(options),
712 });
713 } else if (
714 submissionIntent === "background" &&
715 currentRouteThreadKeyRef.current === routeThreadKey
716 ) {
717 handleNewThreadInActiveProject();
718 }
719 return;
720 }
721 const standaloneSlashCommand =
722 sendInteractionModeEnabled &&
723 composerImages.length === 0 &&
724 composerFiles.length === 0 &&
725 sendableComposerTerminalContexts.length === 0 &&
726 composerPreviewAnnotations.length === 0 &&
727 composerReviewComments.length === 0 &&
728 composerThreadContexts.length === 0
729 ? parseStandaloneComposerSlashCommand(trimmed)
730 : null;
731 if (standaloneSlashCommand && multipleModelSelections === null) {
732 handleInteractionModeChange(standaloneSlashCommand);
733 promptRef.current = "";
734 clearComposerDraftContent(composerDraftTarget);
735 composerRef.current?.resetCursorState();
736 return;
737 }
738 if (!hasSendableContent) {
739 if (expiredTerminalContextCount > 0) {
740 const toastCopy = buildExpiredTerminalContextToastCopy(
741 expiredTerminalContextCount,
742 "empty",
743 );
744 toastManager.add(
745 stackedThreadToast({
746 type: "warning",
747 title: toastCopy.title,
748 description: toastCopy.description,
749 }),
750 );
751 }
752 return;
753 }
754 if (!activeProject) {
755 toastManager.add(
756 stackedThreadToast({
757 type: "warning",
758 title: "Choose a project first",
759 description: "This draft no longer points to an available project.",
760 }),
761 );
762 return;
763 }
764 const threadIdForSend = activeThread.id;
765 const sendSnapshot = snapshotComposerSend({
766 prompt: promptForSend,
767 images: composerImages,
768 files: composerFiles,
769 terminalContexts: composerTerminalContexts,
770 sendableTerminalContexts: sendableComposerTerminalContexts,
771 previewAnnotations: composerPreviewAnnotations,
772 reviewComments: composerReviewComments,
773 threadContexts: composerThreadContexts,
774 });
775 const {
776 files: composerFilesSnapshot,
777 attachments: composerAttachmentsSnapshot,
778 terminalContexts: composerTerminalContextsSnapshot,
779 previewAnnotations: composerPreviewAnnotationsSnapshot,
780 reviewComments: composerReviewCommentsSnapshot,
781 threadContexts: composerThreadContextsSnapshot,
782 messageText: messageTextForSend,
783 } = sendSnapshot;
784 const {
785 missingWorktreeBaseBranch,
786 baseBranchForWorktree,
787 compactBeforeSend,
788 turnDispatchMode,
789 shouldQueueBehindActiveRun,
790 } = planComposerTurn({
791 messageText: messageTextForSend,
792 sendQueuesBehindSetup,
793 isServerThread,
794 activeMessageCount,
795 sendEnvMode,
796 worktreePath: activeThread.worktreePath,
797 activeThreadBranch,
798 resumeCompactionTokens,
799 keepFullHistory,
800 phase,
801 dispatchMode,
802 });
803 if (missingWorktreeBaseBranch) {
804 setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
805 return;
806 }
807 // Records bind attachments by the id each side knows: the local id for the optimistic
808 // row, the upload id (or local id on the data-URL path) on the wire; the server
809 // rebinds them to the persisted id.
810 const buildOutgoingMessageContext = (attachmentIds: ReadonlyArray<string>) =>
811 buildMessageContext({
812 terminalContexts: composerTerminalContextsSnapshot,
813 reviewComments: composerReviewCommentsSnapshot,
814 previewAnnotations: composerPreviewAnnotationsSnapshot,
815 threadContexts: composerThreadContextsSnapshot,
816 attachments: composerAttachmentsSnapshot.map((attachment, index) => ({
817 attachment,
818 attachmentId: attachmentIds[index] ?? attachment.id,
819 })),
820 });
821 const outgoingMessageContext = buildOutgoingMessageContext(
822 composerAttachmentsSnapshot.map((attachment) => attachment.id),
823 );
824 const messageIdForSend = newMessageId();
825 const messageCreatedAt = new Date().toISOString();
826 const outgoingMessageText = formatOutgoingPrompt({
827 provider: ctxSelectedProvider,
828 model: ctxSelectedModel,
829 models: ctxSelectedProviderModels,
830 effort: ctxSelectedPromptEffort,
831 text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
832 });
833 if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) {
834 return;
835 }
836
837 const readLiveAttachmentCapabilities = () => {
838 const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
839 const liveSupportsAttachmentUploads =
840 config?.environment.capabilities.attachmentUploads === true;
841 return {
842 supportsAttachmentUploads: liveSupportsAttachmentUploads,
843 fileBlockReason: fileAttachmentCapabilityBlockReason({
844 files: composerFilesSnapshot,
845 attachmentUploadsCapabilityKnown: config !== null,
846 supportsAttachmentUploads: liveSupportsAttachmentUploads,
847 maxFileAttachmentBytes:
848 config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
849 }),
850 };
851 };
852
853 const multipleTargets: MultipleModelTarget[] = [];
854 for (const resolved of resolveMultipleModelTargets({
855 selections: multipleModelSelections ?? [],
856 providerInstanceEntries,
857 messageText: messageTextForSend,
858 planModeEnabled,
859 interactionMode: sendInteractionMode,
860 })) {
861 if ("error" in resolved) {
862 setThreadError(threadIdForSend, resolved.error);
863 return;
864 }
865 if (composerRef.current?.validateProviderInput(resolved.text) === false) return;
866 multipleTargets.push(resolved);
867 }
868
869 sendInFlightRef.current = true;
870 const sendGeneration = ++composerSendGenerationRef.current;
871 const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities();
872 if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) {
873 sendInFlightRef.current = false;
874 setThreadError(threadIdForSend, attachmentCapabilitiesBeforeUpload.fileBlockReason);
875 return;
876 }
877 const turnUsesAttachmentUploads =
878 composerFilesSnapshot.length > 0
879 ? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads
880 : readEnvironmentPresentation(environmentId)?.serverConfig?.environment.capabilities
881 .attachmentUploads === true;
882 if (turnUsesAttachmentUploads && composerAttachmentsSnapshot.length > 0) {
883 for (const attachment of composerAttachmentsSnapshot) {
884 const upload =
885 readAttachmentUpload(attachment.id)?.status === "failed"
886 ? retryAttachmentUpload
887 : startAttachmentUpload;
888 upload({
889 environmentId,
890 image: attachment,
891 draftTarget: composerDraftTarget,
892 });
893 }
894 await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id));
895 const attachmentCapabilitiesAfterUpload = readLiveAttachmentCapabilities();
896 if (attachmentCapabilitiesAfterUpload.fileBlockReason !== null) {
897 sendInFlightRef.current = false;
898 setThreadError(threadIdForSend, attachmentCapabilitiesAfterUpload.fileBlockReason);
899 return;
900 }
901 if (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null) {
902 sendInFlightRef.current = false;
903 setThreadError(threadIdForSend, "Retry or remove failed uploads before sending.");
904 return;
905 }
906 }
907
908 if (
909 multipleModelSelections === null &&
910 shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) &&
911 activeThreadKey
912 ) {
913 let resolveDockStarted: (() => void) | undefined;
914 const dockStarted = new Promise<void>((resolve) => {
915 resolveDockStarted = resolve;
916 });
917 const dockTransition = runMobileComposerTransition(
918 () => {
919 flushSync(() => {
920 captureDraftHeroComposerRect();
921 setDockedDraftHeroThreadKey(activeThreadKey);
922 });
923 resolveDockStarted?.();
924 },
925 {
926 active: panelAnimationsActive,
927 durationMs: panelAnimationDurationMs,
928 },
929 );
930 void dockTransition.catch(() => resolveDockStarted?.());
931 await dockStarted;
932 }
933
934 const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();
935 if (
936 !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
937 attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null
938 ) {
939 sendInFlightRef.current = false;
940 setThreadError(
941 threadIdForSend,
942 attachmentCapabilitiesBeforeDispatch.fileBlockReason ??
943 "This connection cannot change threads.",
944 );
945 setDockedDraftHeroThreadKey((currentThreadKey) =>
946 currentThreadKey === activeThreadKey ? null : currentThreadKey,
947 );
948 return;
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 return !promptUnchanged || !attachmentsUnchanged;
985 };
986 const draftBeforeDecline = useComposerDraftStore
987 .getState()
988 .getComposerDraft(composerDraftTarget);
989 const changedBeforeDecline = draftChangedSinceSend();
990 const pendingIdsBeforeDecline = pendingApprovalsRef.current.map(
991 (approval) => approval.requestId,
992 );
993 const approvalResponding = approvalsToDecline.some((approval) =>
994 respondingRequestIdsRef.current.includes(approval.requestId),
995 );
996 if (approvalFeedbackTarget !== undefined) {
997 if (composerAttachmentsSnapshot.length > 0 || outgoingMessageContext !== undefined) {
998 setThreadError(
999 threadIdForSend,
1000 "Send approval feedback without attachments or added context.",
1001 );
1002 sendInFlightRef.current = false;
1003 return;
1004 }
1005 if (
1006 changedBeforeDecline ||
1007 approvalResponding ||
1008 currentRouteThreadKeyRef.current !== routeThreadKey
1009 ) {
1010 sendInFlightRef.current = false;
1011 return;
1012 }
1013 const sent = await sendApprovalFeedback(
1014 approvalFeedbackTarget,
1015 messageTextForSend,
1016 onRespondToApprovalStable,
1017 ).catch(() => false);
1018 sendInFlightRef.current = false;
1019 if (
1020 sent &&
1021 !draftChangedSinceSend() &&
1022 currentRouteThreadKeyRef.current === routeThreadKey &&
1023 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
1024 draftBeforeDecline
1025 ) {
1026 promptRef.current = "";
1027 clearComposerDraftContent(composerDraftTarget);
1028 composerRef.current?.resetCursorState();
1029 }
1030 return;
1031 }
1032 const declined =
1033 !changedBeforeDecline &&
1034 !approvalResponding &&
1035 (await declinePendingApprovals(approvalsToDecline, onRespondToApprovalStable).catch(
1036 () => false,
1037 ));
1038 const draftChanged =
1039 changedBeforeDecline ||
1040 draftChangedSinceSend() ||
1041 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) !==
1042 draftBeforeDecline;
1043 // An approval that arrived during the decline would block the redirect; keep the draft so
1044 // the next send declines it too.
1045 const approvalArrived = pendingApprovalsRef.current.some(
1046 (approval) => !pendingIdsBeforeDecline.includes(approval.requestId),
1047 );
1048 if (
1049 !declined ||
1050 draftChanged ||
1051 approvalArrived ||
1052 currentRouteThreadKeyRef.current !== routeThreadKey
1053 ) {
1054 sendInFlightRef.current = false;
1055 setDockedDraftHeroThreadKey((currentThreadKey) =>
1056 currentThreadKey === activeThreadKey ? null : currentThreadKey,
1057 );
1058 const notice = approvalRedirectNotice({
1059 draftChanged,
1060 declined,
1061 approvalResponding,
1062 approvalArrived,
1063 });
1064 if (notice !== null) {
1065 toastManager.add({
1066 type: "info",
1067 title: notice,
1068 description: "Send again when it's ready.",
1069 });
1070 }
1071 return;
1072 }
1073 }
1074 if (sendQueuesBehindSetup) {
1075 setSetupQueueSendThreadKey(activeThreadKey);
1076 } else {
1077 beginLocalDispatch({
1078 preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree),
1079 submissionIntent:
1080 submissionIntent === "background" && !isLocalDraftThread
1081 ? "foreground"
1082 : submissionIntent,
1083 });
1084 beginWorktreeSetup(
1085 multipleModelSelections === null && baseBranchForWorktree
1086 ? { environmentId: activeThread.environmentId, threadId: threadIdForSend }
1087 : null,
1088 );
1089 }
1090
1091 const turnAttachmentsPromise = prepareTurnAttachments({
1092 environmentId,
1093 attachments: composerAttachmentsSnapshot,
1094 usesAttachmentUploads: turnUsesAttachmentUploads,
1095 });
1096 if (multipleModelSelections !== null) {
1097 await sendToMultipleModels({
1098 threadId: threadIdForSend,
1099 project: activeProject,
1100 branch: activeThreadBranch!,
1101 selections: multipleModelSelections,
1102 targets: multipleTargets,
1103 sendSnapshot,
1104 createdAt: messageCreatedAt,
1105 attachmentsPromise: turnAttachmentsPromise,
1106 usesAttachmentUploads: turnUsesAttachmentUploads,
1107 readFileBlockReason: () => readLiveAttachmentCapabilities().fileBlockReason,
1108 buildOutgoingMessageContext,
1109 isCurrentSend: () => composerSendGenerationRef.current === sendGeneration,
1110 });
1111 return;
1112 }
1113 const optimisticAttachments = optimisticMessageAttachments(composerAttachmentsSnapshot);
1114 if (!shouldQueueBehindActiveRun) {
1115 anchorNewTurn(
1116 scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
1117 messageIdForSend,
1118 );
1119 }
1120 const optimisticMessage: ChatMessage = {
1121 id: messageIdForSend,
1122 role: "user",
1123 text: outgoingMessageText,
1124 ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
1125 ...(outgoingMessageContext !== undefined ? { context: outgoingMessageContext } : {}),
1126 runId: null,
1127 createdAt: messageCreatedAt,
1128 updatedAt: messageCreatedAt,
1129 streaming: false,
1130 ...(shouldQueueBehindActiveRun
1131 ? { inputIntent: "queued_turn" as const }
1132 : phase === "running" && dispatchMode === "steer"
1133 ? { inputIntent: "steer" as const }
1134 : {}),
1135 };
1136 // After leaving the thread during an upload, its previews were already released and the
1137 // message is never shown, so tracking them would keep them alive past the thread.
1138 if (currentRouteThreadKeyRef.current === routeThreadKey) {
1139 optimisticBlobPreviews.track(optimisticMessage);
1140 } else {
1141 optimisticBlobPreviews.release(optimisticMessage);
1142 }
1143 setOptimisticUserMessages((existing) => [...existing, optimisticMessage]);
1144 setThreadError(threadIdForSend, null);
1145 if (expiredTerminalContextCount > 0) {
1146 const toastCopy = buildExpiredTerminalContextToastCopy(
1147 expiredTerminalContextCount,
1148 "omitted",
1149 );
1150 toastManager.add(
1151 stackedThreadToast({
1152 type: "warning",
1153 title: toastCopy.title,
1154 description: toastCopy.description,
1155 }),
1156 );
1157 }
1158 const sentDraftThreadRef = isLocalDraftThread
1159 ? scopeThreadRef(environmentId, threadIdForSend)
1160 : null;
1161 // Keep new-thread flows from reusing this draft while attachments and worktree setup settle.
1162 if (sentDraftThreadRef) markPromotedDraftThreadByRef(sentDraftThreadRef);
1163 promptRef.current = "";
1164 clearComposerDraftContent(composerDraftTarget);
1165 composerRef.current?.resetCursorState();
1166
1167 const title = deriveThreadTitleSeed({
1168 text: messageTextForSend,
1169 attachments: composerAttachmentsSnapshot,
1170 fallbackLabels: sendTitleFallbackLabels(sendSnapshot),
1171 });
1172 const threadCreateModelSelection = createModelSelection(
1173 ctxSelectedModelSelection.instanceId,
1174 ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL,
1175 ctxSelectedModelSelection.options,
1176 );
1177
1178 let failure: AtomCommandResult<unknown, unknown> | null = null;
1179
1180 if (failure === null && isServerThread) {
1181 const settingsResult = await persistThreadSettingsForNextTurn({
1182 threadId: threadIdForSend,
1183 createdAt: messageCreatedAt,
1184 ...(localCheckoutBranchMismatch
1185 ? { branch: localCheckoutBranchMismatch.currentBranch }
1186 : {}),
1187 runtimeMode,
1188 interactionMode: sendInteractionMode,
1189 });
1190 if (settingsResult._tag === "Failure") {
1191 failure = settingsResult;
1192 }
1193 }
1194
1195 const turnAttachmentsResult = await settlePromise(async () => {
1196 const turnAttachments = await turnAttachmentsPromise;
1197 const liveFileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
1198 if (liveFileBlockReason !== null) {
1199 throw new Error(liveFileBlockReason);
1200 }
1201 return turnAttachments;
1202 });
1203 if (failure === null && turnAttachmentsResult._tag === "Failure") {
1204 failure = turnAttachmentsResult;
1205 }
1206
1207 if (failure === null && compactBeforeSend) {
1208 const compactResult = await startThreadTurn({
1209 environmentId,
1210 input: {
1211 threadId: threadIdForSend,
1212 message: {
1213 messageId: newMessageId(),
1214 role: "user",
1215 text: "/compact",
1216 attachments: [],
1217 idleCompaction: "onReturn",
1218 },
1219 modelSelection: ctxSelectedModelSelection,
1220 runtimeMode,
1221 interactionMode: sendInteractionMode,
1222 },
1223 });
1224 if (compactResult._tag === "Failure") {
1225 failure = compactResult;
1226 }
1227 }
1228
1229 let backgroundDraftOpened = false;
1230 let turnStartSucceeded = false;
1231 if (failure === null && turnAttachmentsResult._tag === "Success") {
1232 const bootstrap =
1233 isLocalDraftThread || baseBranchForWorktree
1234 ? {
1235 ...(isLocalDraftThread
1236 ? {
1237 createThread: {
1238 projectId: activeProject.id,
1239 title,
1240 modelSelection: threadCreateModelSelection,
1241 runtimeMode,
1242 interactionMode: sendInteractionMode,
1243 branch: activeThreadBranch,
1244 worktreePath: activeThread.worktreePath,
1245 createdAt: activeThread.createdAt,
1246 },
1247 }
1248 : {}),
1249 ...(baseBranchForWorktree
1250 ? {
1251 prepareWorktree: {
1252 projectCwd: activeProject.workspaceRoot,
1253 baseBranch: baseBranchForWorktree,
1254 ...(startFromOrigin ? { startFromOrigin: true } : {}),
1255 },
1256 runSetupScript: true,
1257 }
1258 : {}),
1259 }
1260 : undefined;
1261 const backgroundThreadRef =
1262 submissionIntent === "background" && isLocalDraftThread
1263 ? scopeThreadRef(environmentId, threadIdForSend)
1264 : null;
1265 if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef);
1266 const startPromise = startThreadTurn({
1267 environmentId,
1268 input: {
1269 threadId: threadIdForSend,
1270 message: {
1271 messageId: messageIdForSend,
1272 role: "user",
1273 attachments: turnAttachmentsResult.value,
1274 ...withMessageContext({
1275 text: outgoingMessageText,
1276 context: buildOutgoingMessageContext(
1277 boundAttachmentIds(turnAttachmentsResult.value, composerAttachmentsSnapshot),
1278 ),
1279 // Read at dispatch time: the upload and persistence awaits above can
1280 // span a server reconnect that changes it.
1281 supportsInlineMessageContext:
1282 appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
1283 .capabilities.inlineMessageContext === true,
1284 }),
1285 },
1286 modelSelection: ctxSelectedModelSelection,
1287 titleSeed: title,
1288 runtimeMode,
1289 interactionMode: sendInteractionMode,
1290 dispatchMode: turnDispatchMode,
1291 ...(bootstrap ? { bootstrap } : {}),
1292 createdAt: messageCreatedAt,
1293 },
1294 });
1295 if (backgroundThreadRef) {
1296 try {
1297 backgroundDraftOpened = Boolean(
1298 await handleNewThread(
1299 scopeProjectRef(activeProject.environmentId, activeProject.id),
1300 resolveBackgroundDraftWorkspaceOptions({
1301 envMode: sendEnvMode,
1302 branch: activeThreadBranch,
1303 startFromOrigin,
1304 }),
1305 ),
1306 );
1307 } catch (error) {
1308 clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
1309 toastManager.add(
1310 stackedThreadToast({
1311 type: "warning",
1312 title: "Could not open a fresh composer",
1313 description: error instanceof Error ? error.message : undefined,
1314 }),
1315 );
1316 }
1317 }
1318 const startResult = await startPromise;
1319 if (startResult._tag === "Failure") {
1320 failure = startResult;
1321 } else {
1322 turnStartSucceeded = true;
1323 setKeepFullHistory(routeThreadKey, false);
1324 clearUsageLimitsFor(routeThreadKey);
1325 if (turnUsesAttachmentUploads) {
1326 releaseDraftAttachments(composerAttachmentsSnapshot);
1327 }
1328 acknowledgeActiveThreadWoke();
1329 // A draft still on screen finalizes once its thread route takes over.
1330 if (sentDraftThreadRef) {
1331 if (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey) {
1332 finalizePromotedDraftThreadByRef(sentDraftThreadRef);
1333 } else {
1334 clearBackgroundDraftSubmissionByRef(sentDraftThreadRef);
1335 }
1336 }
1337 if (backgroundThreadRef) {
1338 if (backgroundDraftOpened) {
1339 toastManager.add(
1340 stackedThreadToast({
1341 type: "success",
1342 title: "Started in background",
1343 timeout: 5_000,
1344 actionProps: {
1345 children: "Open",
1346 onClick: () => {
1347 void navigate({
1348 to: "/$environmentId/$threadId",
1349 params: buildThreadRouteParams(backgroundThreadRef),
1350 });
1351 },
1352 },
1353 }),
1354 );
1355 }
1356 } else if (
1357 submissionIntent === "background" &&
1358 currentRouteThreadKeyRef.current === routeThreadKey
1359 ) {
1360 handleNewThreadInActiveProject();
1361 }
1362 }
1363 }
1364
1365 if (failure !== null) {
1366 if (isLocalDraftThread && draftId && draftThread) {
1367 restoreFailedDraftThread(
1368 draftId,
1369 draftThread,
1370 wasBootstrapThreadDeleted(squashAtomCommandFailure(failure))
1371 ? newThreadId()
1372 : threadIdForSend,
1373 );
1374 clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend));
1375 }
1376 if (
1377 !composerDraftHasUserContent(
1378 useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
1379 )
1380 ) {
1381 setOptimisticUserMessages((existing) => {
1382 const next = existing.filter((message) => message.id !== messageIdForSend);
1383 return next.length === existing.length ? existing : next;
1384 });
1385 // The restored draft clones its images, so the sent copies are no longer used.
1386 optimisticBlobPreviews.release(optimisticMessage);
1387 const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot);
1388 if (currentRouteThreadKeyRef.current === routeThreadKey) {
1389 promptRef.current = messageTextForSend;
1390 composerImagesRef.current = retryComposerImages;
1391 composerFilesRef.current = composerFilesSnapshot;
1392 composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
1393 composerRef.current?.resetCursorState({
1394 cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
1395 prompt: messageTextForSend,
1396 detectTrigger: true,
1397 });
1398 }
1399 }
1400 if (!isAtomCommandInterrupted(failure)) {
1401 const error = squashAtomCommandFailure(failure);
1402 setThreadError(
1403 threadIdForSend,
1404 error instanceof Error ? error.message : "Failed to send message.",
1405 );
1406 if (
1407 draftId &&
1408 (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey)
1409 ) {
1410 toastManager.add(
1411 stackedThreadToast({
1412 type: "error",
1413 title:
1414 submissionIntent === "background"
1415 ? "Background task failed"
1416 : "Could not start thread",
1417 description: error instanceof Error ? error.message : "Failed to send message.",
1418 actionProps: {
1419 children: "Open draft",
1420 onClick: () => {
1421 void navigate({ to: "/draft/$draftId", params: { draftId } });
1422 },
1423 },
1424 }),
1425 );
1426 }
1427 }
1428 }
1429 sendInFlightRef.current = false;
1430 setSetupQueueSendThreadKey((current) => (current === activeThreadKey ? null : current));
1431 if (!turnStartSucceeded) {
1432 setDockedDraftHeroThreadKey((currentThreadKey) =>
1433 currentThreadKey === activeThreadKey ? null : currentThreadKey,
1434 );
1435 if (!sendQueuesBehindSetup) resetLocalDispatch();
1436 }
1437 };
1438
1439 return { onSend };
1440}