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