Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

useComposerSend.ts

1,492 lines56.9 KB

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