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

useComposerSend.ts

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