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

useComposerSend.ts

1,432 lines54.0 KB

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