@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

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