The best way to control Claude Code, Codex and more from any computer or phone
refactor(web): ChatView's send paths live in useComposerSend (#23062)
Co-authored-by: Claude Opus 5.5 <noreply@anthropic.com>
Julius Marminge committed
Oct 21, 2026 at 13:40 UTC
f136d5a75515c7eee9d2ce0c50a20ca140fec32c
2 files changed
+2007
-1649
apps/web/src/components/ChatView.tsx
+91
-1649
@@ -1,16 +1,10 @@
1
+import { useComposerSend } from "./chat/useComposerSend";
2
import { formatFilePathForClipboard } from "@t3tools/client-runtime/media-actions";
3
import { resolvePathLinkTarget } from "@t3tools/shared/fileLinks";
4
import { ThreadFind, ThreadFindCanvas, type ThreadFindControls } from "./chat/ThreadFindProvider";
5
import { THREAD_FIND_BAR_RESERVED_HEIGHT } from "./chat/ThreadFindBar";
6
import { usageLimitRecoveryBannerItem } from "./chat/UsageLimitRecoveryBanner";
6
-import {
7
- isThreadWokeUnseen,
8
- mergeDirectPreviewAnnotation,
9
- resolveBackgroundDraftWorkspaceOptions,
10
- resolveDraftHeroState,
11
- shouldDockDraftHeroForSubmission,
12
-} from "./ChatView.logic";
13
-import { restorePlanFollowUpComposer } from "./ChatView.logic";
7
+import { isThreadWokeUnseen, resolveDraftHeroState } from "./ChatView.logic";
8
import { useQueuedRunEdit } from "./chat/useQueuedRunEdit";
9
import {
10
isPaintOnlyThreadTimeline,
@@ -36,7 +30,6 @@ import {
30
latestRootProviderFailure,
31
} from "@t3tools/shared/orchestrationV2ThreadError";
32
import type { UsageLimitSourceSnapshots } from "@t3tools/contracts";
39
-import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits";
33
import { feedbackBannerItem } from "./chat/ComposerFeedback";
34
import { useUsageLimitsPanel } from "./chat/useUsageLimitsPanel";
35
import { useWorktreeSetup } from "./chat/useWorktreeSetup";
@@ -55,7 +48,6 @@ import {
48
AuthTerminalOperateScope,
49
type AssistantCitation,
50
type ChatFileAttachment,
58
- DEFAULT_MODEL,
51
isProviderNativeSubagentThread,
52
type EnvironmentId,
53
type MessageId,
@@ -73,12 +65,9 @@ import {
65
resolveIdleCompaction,
66
RuntimeMode,
67
} from "@t3tools/contracts";
76
-import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
77
-import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
68
import { readPastedComposerContext } from "./composerInlineTokenPaste";
69
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
70
import { effectiveSnoozed, threadWokeAt } from "@t3tools/client-runtime/state/thread-settled";
81
-import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests";
71
import { presentThreadShell } from "@t3tools/client-runtime/state/shell";
72
import { useAcknowledgeThreadWoke, useThreadActions } from "../hooks/useThreadActions";
73
import {
@@ -99,9 +88,7 @@ import { resolvePendingHandoff } from "@t3tools/client-runtime/handoff";
88
import { HandoffRow } from "./chat/V2LifecycleRow";
89
import {
90
codexFeedbackMessage,
102
- parseCodexFeedbackCommand,
91
shouldShowLoadEarlierControl,
104
- submitCodexFeedback,
92
type CodexFeedbackSubmission,
93
} from "@t3tools/client-runtime/state/threads";
94
import { resolveThreadLastVisitedAt } from "./Sidebar.logic";
@@ -111,11 +98,7 @@ import {
98
scopeProjectRef,
99
scopeThreadRef,
100
} from "@t3tools/client-runtime/environment";
114
-import {
115
- createModelSelection,
116
- formatModelSlugName,
117
- resolveSelectableModel,
118
-} from "@t3tools/shared/model";
101
+import { formatModelSlugName, resolveSelectableModel } from "@t3tools/shared/model";
102
import {
103
projectScriptCwd,
104
projectScriptTerminalInput,
@@ -128,12 +111,10 @@ import {
111
} from "@t3tools/shared/orchestrationV2ThreadError";
112
import { resolveProjectSettings } from "@t3tools/shared/projectSettings";
113
import { sourceControlRepositorySelector } from "@t3tools/shared/sourceControl";
131
-import { truncate } from "@t3tools/shared/String";
114
import { resolveThreadReferenceCopyTarget } from "@t3tools/shared/threadReference";
115
import { resolveTerminalSessionLabel } from "@t3tools/shared/terminalLabels";
116
import { useAtomValue } from "@effect/atom-react";
117
import { type SetStateAction, useEffect, useLayoutEffect, useRef, useState } from "react";
136
-import { flushSync } from "react-dom";
118
import { useLocation, useNavigate, useRouter } from "@tanstack/react-router";
119
import { assistantCitationFromLocation } from "../lib/assistantCitationNavigation";
120
import { isMacPlatform } from "../lib/utils";
@@ -142,7 +123,6 @@ import { useShallow } from "zustand/react/shallow";
123
import {
124
isAtomCommandInterrupted,
125
mapAtomCommandResult,
145
- settlePromise,
126
squashAtomCommandFailure,
127
type AtomCommandResult,
128
} from "@t3tools/client-runtime/state/runtime";
@@ -151,12 +131,7 @@ import { isElectron } from "../env";
131
import { readLocalApi } from "../localApi";
132
import { useDiffPanelStore } from "../diffPanelStore";
133
import { useActiveThreadRef } from "../hooks/useActiveThreadRef";
154
-import {
155
- type ComposerSubmissionIntent,
156
- collapseExpandedComposerCursor,
157
- composerRequiresModifier,
158
- parseStandaloneComposerSlashCommand,
159
-} from "../composer-logic";
134
+import { composerRequiresModifier } from "../composer-logic";
135
import {
136
derivePhase,
137
selectHandoffImageResources,
@@ -172,11 +147,6 @@ import {
147
import { type LegendListRef } from "@legendapp/list/react";
148
import { useUiStateStore } from "../uiStateStore";
149
import { useWorkspaceMutationRefresh } from "../hooks/useWorkspaceMutationRefresh";
175
-import {
176
- buildPlanImplementationThreadTitle,
177
- buildPlanImplementationPrompt,
178
- resolvePlanFollowUpSubmission,
179
-} from "../proposedPlan";
150
import { DEFAULT_INTERACTION_MODE, MAX_TERMINALS_PER_GROUP, type ChatMessage } from "../types";
151
import { useTheme } from "../hooks/useTheme";
152
import { writeTextToClipboard } from "../hooks/useCopyToClipboard";
@@ -272,11 +242,6 @@ import {
242
useSidebarPendingFileDropStore,
243
} from "../sidebarPendingFileDropStore";
244
import {
275
- beginBackgroundDraftSubmissionByRef,
276
- clearBackgroundDraftSubmissionByRef,
277
- finalizePromotedDraftThreadByRef,
278
- markPromotedDraftThreadByRef,
279
- restoreFailedDraftThread,
245
composerDraftHasUserContent,
246
type ComposerFileAttachment,
247
type ComposerImageAttachment,
@@ -285,20 +250,12 @@ import {
250
DraftId,
251
} from "../composerDraftStore";
252
import { type TerminalContextDraft, type TerminalContextSelection } from "../lib/terminalContext";
288
-import {
289
- collectInlineContextIds,
290
- ensureInlineContextReferences,
291
-} from "../lib/composerContextReferences";
292
-import {
293
- buildMessageContext,
294
- previewAnnotationContextReference,
295
-} from "../lib/composerContextRecords";
253
+import { collectInlineContextIds } from "../lib/composerContextReferences";
254
import { selectThreadTerminalUiState, useTerminalUiStateStore } from "../terminalUiStateStore";
255
import { useKnownTerminalSessions, useThreadRunningTerminalIds } from "../state/terminalSessions";
256
import { useEnvironmentQuery } from "../state/query";
257
import { useEnvironmentScope } from "~/state/session";
258
import {
301
- environmentServerConfigsAtom,
259
primaryServerAvailableEditorsAtom,
260
primaryServerKeybindingsAtom,
261
serverEnvironment,
@@ -406,16 +363,12 @@ import {
363
import {
364
MOBILE_COMPOSER_VIEW_TRANSITION_NAME,
365
MOBILE_DRAFT_HEADLINE_VIEW_TRANSITION_NAME,
409
- runMobileComposerTransition,
366
} from "./chat/draftHeroTransition";
411
-import type { ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
367
import {
368
branchMismatchKey,
414
- buildExpiredTerminalContextToastCopy,
369
buildLocalDraftThread,
370
collectUserMessageBlobPreviewUrls,
371
deriveCommittedServerUserMessageIds,
418
- deriveComposerSendState,
372
dismissBranchMismatchForSession,
373
isBranchMismatchDismissedForSession,
374
shouldShowBranchMismatchBanner,
@@ -425,7 +378,6 @@ import {
378
LAST_INVOKED_SCRIPT_BY_PROJECT_KEY,
379
LastInvokedScriptByProjectSchema,
380
deriveLockedProvider,
428
- readFileAsDataUrl,
381
resolveFileAttachmentUrl,
382
resolveComposerInteractionMode,
383
resolveComposerProviderSelection,
@@ -435,23 +387,13 @@ import {
387
revokeUserMessagePreviewUrls,
388
startNewThreadForProject,
389
codexArtifactTemplatePromptToAppend,
438
- waitForStartedServerThread,
390
shouldRefocusComposerOnWindowFocus,
391
} from "./ChatView.logic";
392
import { useLocalStorage } from "~/hooks/useLocalStorage";
393
import { useComposerHandleContext } from "../composerHandleContext";
443
-import {
444
- awaitAttachmentUploads,
445
- getUploadedAttachments,
446
- readAttachmentUpload,
447
- releaseDraftAttachments,
448
- retryAttachmentUpload,
449
- startAttachmentUpload,
450
-} from "../lib/attachmentUploadQueue";
394
import { previewEnvironment } from "../state/preview";
395
import { clampFileAttachmentUploadBytes } from "@t3tools/client-runtime/state/attachments";
396
import { appAtomRegistry } from "../rpc/atomRegistry";
454
-import { fileAttachmentCapabilityBlockReason } from "./chat/composerAttachmentFiles";
397
import { assetEnvironment } from "../state/assets";
398
import { readEnvironmentScope, readPreparedConnection } from "../state/session";
399
import { useAtomCommand } from "../state/use-atom-command";
@@ -459,10 +401,6 @@ import { useOrchestrationCommand } from "../state/use-orchestration-command";
401
import { useAtomQueryRunner } from "../state/use-atom-query-runner";
402
import { Button } from "./ui/button";
403
import { useAssetUrls } from "../assets/assetUrls";
462
-import {
463
- ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
464
- threadContextsOutsideEnvironment,
465
-} from "@t3tools/shared/composerContextReferences";
404
import { observeResize } from "~/lib/observeResize";
405
import { ThreadVisitWatermark } from "./chat/ThreadVisitWatermark";
406
import { ChatTerminalDrawers } from "./chat/ChatTerminalDrawers";
@@ -481,24 +419,9 @@ import {
419
} from "./chat/useSystemComposerBanners";
420
import { useDraftHeroLayoutTransition } from "./chat/useDraftHeroLayoutTransition";
421
import { useLocalDispatchState } from "./chat/useLocalDispatchState";
422
+import { draftFanoutSelectionsAtom, draftSendState, rewindToMessage } from "./chat/chatViewSend";
423
import {
485
- draftFanoutSelectionsAtom,
486
- draftSendState,
487
- type MultipleModelTarget,
488
- resolveMultipleModelTargets,
489
- restoreComposerDraft,
490
- rewindToMessage,
491
- startFanoutThread,
492
-} from "./chat/chatViewSend";
493
-import {
494
- boundAttachmentIds,
424
chatActionErrorMessage,
496
- formatOutgoingPrompt,
497
- optimisticMessageAttachments,
498
- planComposerTurn,
499
- sendTitleFallbackLabels,
500
- snapshotComposerSend,
501
- withMessageContext,
425
isCompactCommandMessage,
426
type LocalThreadErrorEntry,
427
makeModelDisabledReason,
@@ -546,7 +469,6 @@ interface TerminalLaunchContext {
469
worktreePath: string | null;
470
}
471
549
-const ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE = 3;
472
const EMPTY_HELD_TURN_DIFF_SUMMARIES: readonly never[] = [];
473
const noopHeldTurnDiff = (_turnId: RunId, _filePath?: string) => {};
474
const noopHeldRevert = (_targetTurnCount: number) => {};
@@ -578,8 +500,6 @@ export default function ChatView(props: ChatViewProps) {
500
currentRouteThreadKeyRef.current = null;
501
};
502
}, [routeThreadKey]);
581
- const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });
582
- const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });
503
const updateThreadMetadata = useOrchestrationCommand(threadEnvironment.updateMetadata, {
504
reportFailure: false,
505
});
@@ -594,12 +514,6 @@ export default function ChatView(props: ChatViewProps) {
514
const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
515
reportFailure: false,
516
});
597
- const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
598
- reportFailure: false,
599
- });
600
- const uploadThreadFeedback = useOrchestrationCommand(threadEnvironment.uploadFeedback, {
601
- reportFailure: false,
602
- });
517
const createAttachmentAssetUrl = useAtomQueryRunner(assetEnvironment.createUrl, {
518
reportFailure: false,
519
refresh: true,
@@ -800,20 +714,11 @@ export default function ChatView(props: ChatViewProps) {
714
return draft ? composerDraftHasUserContent({ ...draft, prompt: "" }) : false;
715
});
716
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
803
- const setComposerDraftTerminalContexts = useComposerDraftStore(
804
- (store) => store.setTerminalContexts,
805
- );
806
- const setComposerDraftPreviewAnnotations = useComposerDraftStore(
807
- (store) => store.setPreviewAnnotations,
808
- );
809
- const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments);
810
- const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
717
const setComposerDraftModelSelection = useComposerDraftStore((store) => store.setModelSelection);
718
const setComposerDraftRuntimeMode = useComposerDraftStore((store) => store.setRuntimeMode);
719
const setComposerDraftInteractionMode = useComposerDraftStore(
720
(store) => store.setInteractionMode,
721
);
816
- const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
722
const setDraftThreadContext = useComposerDraftStore((store) => store.setDraftThreadContext);
723
const getDraftSessionByLogicalProjectKey = useComposerDraftStore(
724
(store) => store.getDraftSessionByLogicalProjectKey,
@@ -932,13 +837,7 @@ export default function ChatView(props: ChatViewProps) {
837
const attachmentPreviewHandoffByMessageIdRef = useRef<Record<string, string[]>>({});
838
const attachmentPreviewPromotionInFlightByMessageIdRef = useRef<Record<string, true>>({});
839
const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
935
- const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainMultipleSubmissionsRef } =
936
- draftSendState(routeThreadKey);
937
- const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
938
- () => new Set(),
939
- );
940
- const isResuming = resumingThreadKeys.has(routeThreadKey);
941
- const composerSendGenerationRef = useRef(0);
840
+ const { sendInFlight: sendInFlightRef } = draftSendState(routeThreadKey);
841
const multipleModelSelections = useAtomValue(fanoutSelectionsAtom);
842
const setMultipleModelSelections = (
843
selections: SetStateAction<ReadonlyArray<ModelSelection> | null>,
@@ -948,8 +847,6 @@ export default function ChatView(props: ChatViewProps) {
847
);
848
};
849
const setMultipleModelSelectionsStable = useStableCallback(setMultipleModelSelections);
951
- const readMultipleModelSelections = () => appAtomRegistry.get(fanoutSelectionsAtom);
952
- const environmentUnavailableSendToastSlotRef = useRef(0);
850
const feedbackUploadsInFlightRef = useRef(new Set<string>());
851
const terminalUiOpenByThreadRef = useRef<Record<string, boolean>>({});
852
@@ -1746,13 +1643,6 @@ export default function ChatView(props: ChatViewProps) {
1643
composerRef,
1644
setThreadError,
1645
});
1749
- // A send awaits uploads before it declines, so it reads the approvals pending by then.
1750
- const pendingApprovalsRef = useRef(pendingApprovals);
1751
- const respondingRequestIdsRef = useRef(respondingRequestIds);
1752
- useLayoutEffect(() => {
1753
- pendingApprovalsRef.current = pendingApprovals;
1754
- respondingRequestIdsRef.current = respondingRequestIds;
1755
- }, [pendingApprovals, respondingRequestIds]);
1646
const activeProposedPlan = (() => {
1647
if (!latestRunSettled) {
1648
return null;
@@ -4552,1538 +4442,90 @@ export default function ChatView(props: ChatViewProps) {
4442
void sendStandaloneCommand("/compact", "Failed to compact context.");
4443
};
4444
4555
- const onResume = async () => {
4556
- if (
4557
- !activeThread ||
4558
- (resumableRunId === null && !hasHeldQueuedRuns) ||
4559
- isSendBusy ||
4560
- isResuming ||
4561
- isConnecting ||
4562
- isRevertingCheckpoint ||
4563
- threadDetailLoading ||
4564
- activeEnvironmentUnavailable ||
4565
- sendInFlightRef.current
4566
- ) {
4567
- return;
4568
- }
4569
- const threadId = activeThread.id;
4570
- sendInFlightRef.current = true;
4571
- setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
4572
- setThreadError(threadId, null);
4573
- // Commands settle into a result, so this always runs.
4574
- const resume = async () => {
4575
- if (resumableRunId === null) {
4576
- return resumeThreadQueue({ environmentId, input: { threadId } });
4577
- }
4578
- const createdAt = new Date().toISOString();
4579
- const settingsResult = await persistThreadSettingsForNextTurn({
4580
- threadId,
4581
- createdAt,
4582
- ...(localCheckoutBranchMismatch
4583
- ? { branch: localCheckoutBranchMismatch.currentBranch }
4584
- : {}),
4585
- runtimeMode,
4586
- interactionMode,
4587
- });
4588
- if (settingsResult._tag === "Failure") return settingsResult;
4589
- const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
4590
- const turnResult = await startThreadTurn({
4591
- environmentId,
4592
- input: {
4593
- threadId,
4594
- manualContinuationOfRunId: resumableRunId,
4595
- ...(modelSelection ? { modelSelection } : {}),
4596
- message: {
4597
- messageId: newMessageId(),
4598
- role: "user",
4599
- text: "Continue where you left off.",
4600
- attachments: [],
4601
- },
4602
- runtimeMode,
4603
- interactionMode,
4604
- dispatchMode: "start",
4605
- },
4606
- });
4607
- if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
4608
- clearUsageLimitsFor(routeThreadKey);
4609
- return resumeThreadQueue({ environmentId, input: { threadId } });
4610
- };
4611
- const result = await resume();
4612
- if (result._tag === "Failure") {
4613
- if (!isAtomCommandInterrupted(result)) {
4614
- const error = squashAtomCommandFailure(result);
4615
- setThreadError(
4616
- threadId,
4617
- error instanceof Error ? error.message : "Could not resume thread.",
4618
- );
4619
- }
4620
- } else {
4621
- clearUsageLimitsFor(routeThreadKey);
4622
- if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
4623
- }
4624
- sendInFlightRef.current = false;
4625
- setResumingThreadKeys((current) => {
4626
- const next = new Set(current);
4627
- next.delete(routeThreadKey);
4628
- return next;
4629
- });
4630
- };
4631
-
4632
- const onSend = async (
4633
- e?: { preventDefault: () => void },
4634
- dispatchMode: ComposerDispatchMode = "auto",
4635
- submissionIntent: ComposerSubmissionIntent = "foreground",
4636
- directAnnotation?: {
4637
- annotation: PreviewAnnotationPayload;
4638
- image: ComposerImageAttachment | null;
4639
- },
4640
- ) => {
4641
- e?.preventDefault();
4642
- // What the user pressed send on; uploads below can take a while, and a redirect must not
4643
- // decline approvals for a draft that changed meanwhile.
4644
- const promptAtSend = promptRef.current;
4645
- if (
4646
- usageLimitsOffered &&
4647
- usageLimitsKey !== null &&
4648
- !directAnnotation &&
4649
- !composerHasNonPromptContent &&
4650
- isUsageLimitsCommand(promptRef.current)
4651
- ) {
4652
- if (openUsageLimits()) {
4653
- promptRef.current = "";
4654
- setComposerDraftPrompt(composerDraftTarget, "");
4655
- composerRef.current?.resetCursorState();
4656
- }
4657
- return;
4658
- }
4659
-
4660
- const notifyDirectAnnotationAttached = () => {
4661
- if (!directAnnotation) return;
4662
- toastManager.add(
4663
- stackedThreadToast({
4664
- type: "info",
4665
- title: "Annotation attached to draft",
4666
- description: "Sending is unavailable right now. Finish the current action, then send.",
4667
- }),
4668
- );
4669
- };
4670
- if (
4671
- !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
4672
- !activeThread ||
4673
- (isSendBusy && !sendQueuesBehindSetup) ||
4674
- isConnecting ||
4675
- isRevertingCheckpoint ||
4676
- !clientSettingsHydrated ||
4677
- threadDetailLoading ||
4678
- readPendingEnvironmentChange() !== null ||
4679
- sendInFlightRef.current ||
4680
- feedbackUploadsInFlightRef.current.has(routeThreadKey)
4681
- ) {
4682
- notifyDirectAnnotationAttached();
4683
- return;
4684
- }
4685
- if (needsLoadBalancing) {
4686
- toastManager.add({
4687
- type: "warning",
4688
- title: loadBalancing.pending
4689
- ? "Checking machine resources"
4690
- : "Choose a machine to continue",
4691
- description: loadBalancing.pending
4692
- ? "Resource checks are still running. You can choose a machine in the composer."
4693
- : referencedThreadContexts.length > 0 &&
4694
- !logicalProjectEnvironments.some((candidate) =>
4695
- referencedThreadContexts.every(
4696
- (record) => record.environmentId === candidate.environmentId,
4697
- ),
4698
- )
4699
- ? "No machine can read every attached thread. Choose a machine in the composer or remove the threads."
4700
- : "No eligible machine has available resources. Choose a machine in the composer to override.",
4701
- });
4702
- return;
4703
- }
4704
- if (activeEnvironmentUnavailable) {
4705
- const toastSlot = environmentUnavailableSendToastSlotRef.current;
4706
- environmentUnavailableSendToastSlotRef.current =
4707
- (toastSlot + 1) % ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE;
4708
- toastManager.add({
4709
- ...stackedThreadToast({
4710
- type: "warning",
4711
- title: "Not connected: message not sent",
4712
- description: "Reconnecting to the environment. Try again once it is connected.",
4713
- }),
4714
- id: `chat-send-environment-unavailable:${toastSlot}`,
4715
- });
4716
- return;
4717
- }
4718
- const sendCtx = composerRef.current?.getSendContext();
4719
- if (activePendingProgress && sendCtx?.answeringPendingUserInput !== false) {
4720
- if (directAnnotation) {
4721
- notifyDirectAnnotationAttached();
4722
- return;
4723
- }
4724
- onAdvanceActivePendingUserInput();
4725
- return;
4726
- }
4727
- if (!sendCtx?.providerAvailable) {
4728
- notifyDirectAnnotationAttached();
4729
- return;
4730
- }
4731
- const multipleModelSelections = sendCtx.multipleModelSelections;
4732
- if (
4733
- multipleModelSelections !== null &&
4734
- serverConfig?.environment.capabilities.requiredWorktreeBootstrap !== true
4735
- ) {
4736
- setThreadError(activeThread.id, "Update this server before starting multiple models.");
4737
- return;
4738
- }
4739
- if (
4740
- multipleModelSelections !== null &&
4741
- (!isLocalDraftThread ||
4742
- !isGitRepo ||
4743
- !activeThreadBranch ||
4744
- multipleModelSelections.length === 0)
4745
- ) {
4746
- toastManager.add(
4747
- stackedThreadToast({
4748
- type: "warning",
4749
- title: "Choose models and a base branch",
4750
- description:
4751
- "Multiple models need a new thread in a Git project. Each gets its own worktree.",
4752
- }),
4753
- );
4754
- return;
4755
- }
4756
- const {
4757
- images: sendContextImages,
4758
- files: composerFiles,
4759
- terminalContexts: composerTerminalContexts,
4760
- previewAnnotations: sendContextPreviewAnnotations,
4761
- reviewComments: composerReviewComments,
4762
- threadContexts: composerThreadContexts,
4763
- selectedProvider: ctxSelectedProvider,
4764
- selectedModel: ctxSelectedModel,
4765
- selectedProviderModels: ctxSelectedProviderModels,
4766
- selectedPromptEffort: ctxSelectedPromptEffort,
4767
- selectedModelSelection: ctxSelectedModelSelection,
4768
- interactionMode: sendInteractionMode,
4769
- interactionModeEnabled: sendInteractionModeEnabled,
4770
- } = sendCtx;
4771
- const { images: composerImages, previewAnnotations: composerPreviewAnnotations } =
4772
- mergeDirectPreviewAnnotation({
4773
- images: sendContextImages,
4774
- fileCount: composerFiles.length,
4775
- previewAnnotations: sendContextPreviewAnnotations,
4776
- direct: directAnnotation,
4777
- });
4778
- // A direct "send annotation" writes the draft and sends in the same tick; the reference
4779
- // must be in the text now, not after the next render.
4780
- const promptForSend = directAnnotation
4781
- ? ensureInlineContextReferences(promptRef.current, [
4782
- previewAnnotationContextReference(directAnnotation.annotation),
4783
- ])
4784
- : promptRef.current;
4785
- const strandedThread = threadContextsOutsideEnvironment({
4786
- text: promptForSend,
4787
- records: composerThreadContexts,
4788
- environmentId,
4789
- })[0];
4790
- if (strandedThread) {
4791
- const owner = environmentById.get(strandedThread.environmentId)?.label ?? "its machine";
4792
- toastManager.add(
4793
- stackedThreadToast({
4794
- type: "warning",
4795
- title: "Attached thread is on another machine",
4796
- description: `This machine's agent can't read "${strandedThread.title}". Remove it, or switch back to ${owner} to send.`,
4797
- }),
4798
- );
4799
- return;
4800
- }
4801
- if (queuedRunEdit.isEditing) {
4802
- // Edit mode repurposes the composer: sending saves the queued message
4803
- // in place instead of dispatching a new turn.
4804
- await queuedRunEdit.saveEdit(
4805
- {
4806
- prompt: promptForSend,
4807
- images: composerImages,
4808
- files: composerFiles,
4809
- terminalContexts: composerTerminalContexts,
4810
- reviewComments: composerReviewComments,
4811
- previewAnnotations: composerPreviewAnnotations,
4812
- threadContexts: composerThreadContexts,
4813
- },
4814
- setThreadError,
4815
- );
4816
- return;
4817
- }
4818
- const {
4819
- trimmedPrompt: trimmed,
4820
- sendableTerminalContexts: sendableComposerTerminalContexts,
4821
- expiredTerminalContextCount,
4822
- hasSendableContent,
4823
- } = deriveComposerSendState({
4824
- prompt: promptForSend,
4825
- imageCount: composerImages.length + composerFiles.length,
4826
- terminalContexts: composerTerminalContexts,
4827
- elementContextCount:
4828
- composerPreviewAnnotations.length +
4829
- composerReviewComments.length +
4830
- composerThreadContexts.length,
4831
- });
4832
- const feedbackCommand =
4833
- ctxSelectedProvider === "codex" &&
4834
- composerImages.length === 0 &&
4835
- composerFiles.length === 0 &&
4836
- sendableComposerTerminalContexts.length === 0 &&
4837
- composerPreviewAnnotations.length === 0 &&
4838
- composerReviewComments.length === 0 &&
4839
- composerThreadContexts.length === 0
4840
- ? parseCodexFeedbackCommand(trimmed)
4841
- : null;
4842
- if (feedbackCommand && multipleModelSelections === null) {
4843
- if (!isServerThread || activeThread.activeProviderThreadId === null) {
4844
- toastManager.add(
4845
- stackedThreadToast({
4846
- type: "warning",
4847
- title: "Start a Codex thread first",
4848
- description: "Send a message before you submit feedback.",
4849
- }),
4850
- );
4851
- return;
4852
- }
4853
- feedbackUploadsInFlightRef.current.add(routeThreadKey);
4854
- await submitCodexFeedback({
4855
- submission: {
4856
- id: newMessageId(),
4857
- command: trimmed,
4858
- createdAt: new Date().toISOString(),
4859
- },
4860
- clearDraft: () => {
4861
- promptRef.current = "";
4862
- clearComposerDraftContent(composerDraftTarget);
4863
- composerRef.current?.resetCursorState();
4864
- },
4865
- onUpdate: (submission) => {
4866
- setFeedbackSubmissionsByThreadKey((current) => {
4867
- const existing = current[routeThreadKey] ?? [];
4868
- const found = existing.some((entry) => entry.id === submission.id);
4869
- return {
4870
- ...current,
4871
- [routeThreadKey]: found
4872
- ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
4873
- : [...existing, submission],
4874
- };
4875
- });
4876
- },
4877
- upload: () =>
4878
- uploadThreadFeedback({
4879
- environmentId: activeThread.environmentId,
4880
- input: { threadId: activeThread.id, ...feedbackCommand },
4881
- }),
4882
- }).finally(() => {
4883
- feedbackUploadsInFlightRef.current.delete(routeThreadKey);
4884
- });
4885
-
4886
- return;
4887
- }
4888
- if (
4889
- !directAnnotation &&
4890
- sendInteractionModeEnabled &&
4891
- showPlanFollowUpPrompt &&
4892
- activeProposedPlan &&
4893
- composerImages.length === 0 &&
4894
- composerFiles.length === 0
4895
- ) {
4896
- const followUp = resolvePlanFollowUpSubmission({
4897
- draftText: promptForSend,
4898
- planMarkdown: activeProposedPlan.planMarkdown,
4899
- });
4900
- const outgoingFollowUpText = formatOutgoingPrompt({
4901
- provider: ctxSelectedProvider,
4902
- model: ctxSelectedModel,
4903
- models: ctxSelectedProviderModels,
4904
- effort: ctxSelectedPromptEffort,
4905
- text: followUp.text.trim(),
4906
- });
4907
- if (composerRef.current?.validateProviderInput(outgoingFollowUpText) === false) {
4908
- return;
4909
- }
4910
- const followUpPromptSnapshot = promptRef.current;
4911
- const followUpTerminalContexts = [...sendableComposerTerminalContexts];
4912
- const followUpReviewComments = [...composerReviewComments];
4913
- const followUpPreviewAnnotations = [...composerPreviewAnnotations];
4914
- const followUpThreadContexts = [...composerThreadContexts];
4915
- promptRef.current = "";
4916
- clearComposerDraftContent(composerDraftTarget);
4917
- composerRef.current?.resetCursorState();
4918
- const followUpSent = await onSubmitPlanFollowUp({
4919
- text: followUp.text,
4920
- context: buildMessageContext({
4921
- terminalContexts: sendableComposerTerminalContexts,
4922
- reviewComments: composerReviewComments,
4923
- previewAnnotations: composerPreviewAnnotations,
4924
- threadContexts: composerThreadContexts,
4925
- }),
4926
- interactionMode: followUp.interactionMode,
4927
- });
4928
- if (!followUpSent) {
4929
- promptRef.current = followUpPromptSnapshot;
4930
- composerTerminalContextsRef.current = [...followUpTerminalContexts];
4931
- restorePlanFollowUpComposer({
4932
- snapshot: {
4933
- prompt: followUpPromptSnapshot,
4934
- terminalContexts: followUpTerminalContexts,
4935
- reviewComments: followUpReviewComments,
4936
- previewAnnotations: followUpPreviewAnnotations,
4937
- threadContexts: followUpThreadContexts,
4938
- },
4939
- writePrompt: (prompt) => setComposerDraftPrompt(composerDraftTarget, prompt),
4940
- writeTerminalContexts: (contexts) =>
4941
- setComposerDraftTerminalContexts(composerDraftTarget, [...contexts]),
4942
- writeReviewComments: (comments) =>
4943
- setComposerDraftReviewComments(composerDraftTarget, [...comments]),
4944
- writePreviewAnnotations: (annotations) =>
4945
- setComposerDraftPreviewAnnotations(composerDraftTarget, [...annotations]),
4946
- writeThreadContexts: (records) =>
4947
- setComposerDraftThreadContexts(composerDraftTarget, [...records]),
4948
- resetCursor: (options) => composerRef.current?.resetCursorState(options),
4949
- });
4950
- } else if (
4951
- submissionIntent === "background" &&
4952
- currentRouteThreadKeyRef.current === routeThreadKey
4953
- ) {
4954
- handleNewThreadInActiveProject();
4955
- }
4956
- return;
4957
- }
4958
- const standaloneSlashCommand =
4959
- sendInteractionModeEnabled &&
4960
- composerImages.length === 0 &&
4961
- composerFiles.length === 0 &&
4962
- sendableComposerTerminalContexts.length === 0 &&
4963
- composerPreviewAnnotations.length === 0 &&
4964
- composerReviewComments.length === 0 &&
4965
- composerThreadContexts.length === 0
4966
- ? parseStandaloneComposerSlashCommand(trimmed)
4967
- : null;
4968
- if (standaloneSlashCommand && multipleModelSelections === null) {
4969
- handleInteractionModeChange(standaloneSlashCommand);
4970
- promptRef.current = "";
4971
- clearComposerDraftContent(composerDraftTarget);
4972
- composerRef.current?.resetCursorState();
4973
- return;
4974
- }
4975
- if (!hasSendableContent) {
4976
- if (expiredTerminalContextCount > 0) {
4977
- const toastCopy = buildExpiredTerminalContextToastCopy(
4978
- expiredTerminalContextCount,
4979
- "empty",
4980
- );
4981
- toastManager.add(
4982
- stackedThreadToast({
4983
- type: "warning",
4984
- title: toastCopy.title,
4985
- description: toastCopy.description,
4986
- }),
4987
- );
4988
- }
4989
- return;
4990
- }
4991
- if (!activeProject) {
4992
- toastManager.add(
4993
- stackedThreadToast({
4994
- type: "warning",
4995
- title: "Choose a project first",
4996
- description: "This draft no longer points to an available project.",
4997
- }),
4998
- );
4999
- return;
5000
- }
5001
- const threadIdForSend = activeThread.id;
5002
- const sendSnapshot = snapshotComposerSend({
5003
- prompt: promptForSend,
5004
- images: composerImages,
5005
- files: composerFiles,
5006
- terminalContexts: composerTerminalContexts,
5007
- sendableTerminalContexts: sendableComposerTerminalContexts,
5008
- previewAnnotations: composerPreviewAnnotations,
5009
- reviewComments: composerReviewComments,
5010
- threadContexts: composerThreadContexts,
5011
- });
5012
- const {
5013
- files: composerFilesSnapshot,
5014
- attachments: composerAttachmentsSnapshot,
5015
- terminalContexts: composerTerminalContextsSnapshot,
5016
- previewAnnotations: composerPreviewAnnotationsSnapshot,
5017
- reviewComments: composerReviewCommentsSnapshot,
5018
- threadContexts: composerThreadContextsSnapshot,
5019
- messageText: messageTextForSend,
5020
- } = sendSnapshot;
5021
- const {
5022
- missingWorktreeBaseBranch,
5023
- baseBranchForWorktree,
5024
- compactBeforeSend,
5025
- turnDispatchMode,
5026
- shouldQueueBehindActiveRun,
5027
- } = planComposerTurn({
5028
- messageText: messageTextForSend,
5029
- sendQueuesBehindSetup,
5030
- isServerThread,
5031
- activeMessageCount,
5032
- sendEnvMode,
5033
- worktreePath: activeThread.worktreePath,
5034
- activeThreadBranch,
5035
- resumeCompactionTokens,
5036
- keepFullHistory,
5037
- phase,
5038
- dispatchMode,
5039
- });
5040
- if (missingWorktreeBaseBranch) {
5041
- setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
5042
- return;
5043
- }
5044
- // Records bind attachments by the id each side knows: the local id for the optimistic
5045
- // row, the upload id (or local id on the data-URL path) on the wire; the server
5046
- // rebinds them to the persisted id.
5047
- const buildOutgoingMessageContext = (attachmentIds: ReadonlyArray<string>) =>
5048
- buildMessageContext({
5049
- terminalContexts: composerTerminalContextsSnapshot,
5050
- reviewComments: composerReviewCommentsSnapshot,
5051
- previewAnnotations: composerPreviewAnnotationsSnapshot,
5052
- threadContexts: composerThreadContextsSnapshot,
5053
- attachments: composerAttachmentsSnapshot.map((attachment, index) => ({
5054
- attachment,
5055
- attachmentId: attachmentIds[index] ?? attachment.id,
5056
- })),
5057
- });
5058
- const outgoingMessageContext = buildOutgoingMessageContext(
5059
- composerAttachmentsSnapshot.map((attachment) => attachment.id),
5060
- );
5061
- const messageIdForSend = newMessageId();
5062
- const messageCreatedAt = new Date().toISOString();
5063
- const outgoingMessageText = formatOutgoingPrompt({
5064
- provider: ctxSelectedProvider,
5065
- model: ctxSelectedModel,
5066
- models: ctxSelectedProviderModels,
5067
- effort: ctxSelectedPromptEffort,
5068
- text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
5069
- });
5070
- if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) {
5071
- return;
5072
- }
5073
-
5074
- const readLiveAttachmentCapabilities = () => {
5075
- const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
5076
- const liveSupportsAttachmentUploads =
5077
- config?.environment.capabilities.attachmentUploads === true;
5078
- return {
5079
- supportsAttachmentUploads: liveSupportsAttachmentUploads,
5080
- fileBlockReason: fileAttachmentCapabilityBlockReason({
5081
- files: composerFilesSnapshot,
5082
- attachmentUploadsCapabilityKnown: config !== null,
5083
- supportsAttachmentUploads: liveSupportsAttachmentUploads,
5084
- maxFileAttachmentBytes:
5085
- config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
5086
- }),
5087
- };
5088
- };
5089
-
5090
- const multipleTargets: MultipleModelTarget[] = [];
5091
- for (const resolved of resolveMultipleModelTargets({
5092
- selections: multipleModelSelections ?? [],
5093
- providerInstanceEntries,
5094
- messageText: messageTextForSend,
5095
- planModeEnabled: settings.planModeEnabled,
5096
- interactionMode: sendInteractionMode,
5097
- })) {
5098
- if ("error" in resolved) {
5099
- setThreadError(threadIdForSend, resolved.error);
5100
- return;
5101
- }
5102
- if (composerRef.current?.validateProviderInput(resolved.text) === false) return;
5103
- multipleTargets.push(resolved);
5104
- }
5105
-
5106
- sendInFlightRef.current = true;
5107
- const sendGeneration = ++composerSendGenerationRef.current;
5108
- const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities();
5109
- if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) {
5110
- sendInFlightRef.current = false;
5111
- setThreadError(threadIdForSend, attachmentCapabilitiesBeforeUpload.fileBlockReason);
5112
- return;
5113
- }
5114
- const turnUsesAttachmentUploads =
5115
- composerFilesSnapshot.length > 0
5116
- ? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads
5117
- : supportsAttachmentUploads;
5118
- if (turnUsesAttachmentUploads && composerAttachmentsSnapshot.length > 0) {
5119
- for (const attachment of composerAttachmentsSnapshot) {
5120
- const upload =
5121
- readAttachmentUpload(attachment.id)?.status === "failed"
5122
- ? retryAttachmentUpload
5123
- : startAttachmentUpload;
5124
- upload({
5125
- environmentId,
5126
- image: attachment,
5127
- draftTarget: composerDraftTarget,
5128
- });
5129
- }
5130
- await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id));
5131
- const attachmentCapabilitiesAfterUpload = readLiveAttachmentCapabilities();
5132
- if (attachmentCapabilitiesAfterUpload.fileBlockReason !== null) {
5133
- sendInFlightRef.current = false;
5134
- setThreadError(threadIdForSend, attachmentCapabilitiesAfterUpload.fileBlockReason);
5135
- return;
5136
- }
5137
- if (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null) {
5138
- sendInFlightRef.current = false;
5139
- setThreadError(threadIdForSend, "Retry or remove failed uploads before sending.");
5140
- return;
5141
- }
5142
- }
5143
-
5144
- if (
5145
- multipleModelSelections === null &&
5146
- shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) &&
5147
- activeThreadKey
5148
- ) {
5149
- let resolveDockStarted: (() => void) | undefined;
5150
- const dockStarted = new Promise<void>((resolve) => {
5151
- resolveDockStarted = resolve;
5152
- });
5153
- const dockTransition = runMobileComposerTransition(
5154
- () => {
5155
- flushSync(() => {
5156
- captureDraftHeroComposerRect();
5157
- setDockedDraftHeroThreadKey(activeThreadKey);
5158
- });
5159
- resolveDockStarted?.();
5160
- },
5161
- {
5162
- active: panelAnimationsActive,
5163
- durationMs: panelAnimationDurationMs,
5164
- },
5165
- );
5166
- void dockTransition.catch(() => resolveDockStarted?.());
5167
- await dockStarted;
5168
- }
5169
-
5170
- const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();
5171
- if (
5172
- !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
5173
- attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null
5174
- ) {
5175
- sendInFlightRef.current = false;
5176
- setThreadError(
5177
- threadIdForSend,
5178
- attachmentCapabilitiesBeforeDispatch.fileBlockReason ??
5179
- "This connection cannot change threads.",
5180
- );
5181
- setDockedDraftHeroThreadKey((currentThreadKey) =>
5182
- currentThreadKey === activeThreadKey ? null : currentThreadKey,
5183
- );
5184
- return;
5185
- }
5186
- // A message sent while approvals are pending redirects the agent. They are declined only
5187
- // here, after everything above has accepted the send, so local commands and rejected
5188
- // drafts leave them alone. After navigating away during an upload, the shown approvals
5189
- // are another thread's, so this send leaves them alone too.
5190
- const approvalsToDecline =
5191
- currentRouteThreadKeyRef.current === routeThreadKey
5192
- ? pendingApprovalsRef.current.filter((approval) =>
5193
- sendCtx?.shownPendingApprovalIds.includes(approval.requestId),
5194
- )
5195
- : [];
5196
- if (approvalsToDecline.length > 0) {
5197
- // A draft edited since send, or a paste still landing in it, is no longer the message
5198
- // the user sent.
5199
- const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id);
5200
- // A direct annotation send writes its image and reference into the draft as it sends,
5201
- // so the live draft may still lack them; anything else differing is a real edit.
5202
- const annotationImageId = directAnnotation?.image?.id;
5203
- const attachmentIdsBeforeAnnotation = attachmentIdsAtSend.filter(
5204
- (id) => id !== annotationImageId,
5205
- );
5206
- const sameIds = (left: ReadonlyArray<string>, right: ReadonlyArray<string>) =>
5207
- left.length === right.length && left.every((id, index) => id === right[index]);
5208
- const draftChangedSinceSend = () => {
5209
- if (composerRef.current?.hasPendingAttachments() === true) return true;
5210
- const sendContext = composerRef.current?.getSendContext();
5211
- const attachmentIds = sendContext
5212
- ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id)
5213
- : attachmentIdsAtSend;
5214
- const promptUnchanged =
5215
- promptRef.current === promptAtSend || promptRef.current === promptForSend;
5216
- const attachmentsUnchanged =
5217
- sameIds(attachmentIds, attachmentIdsAtSend) ||
5218
- (annotationImageId !== undefined &&
5219
- sameIds(attachmentIds, attachmentIdsBeforeAnnotation));
5220
- return !promptUnchanged || !attachmentsUnchanged;
5221
- };
5222
- const draftBeforeDecline = useComposerDraftStore
5223
- .getState()
5224
- .getComposerDraft(composerDraftTarget);
5225
- const changedBeforeDecline = draftChangedSinceSend();
5226
- const pendingIdsBeforeDecline = pendingApprovalsRef.current.map(
5227
- (approval) => approval.requestId,
5228
- );
5229
- const approvalResponding = approvalsToDecline.some((approval) =>
5230
- respondingRequestIdsRef.current.includes(approval.requestId),
5231
- );
5232
- const declined =
5233
- !changedBeforeDecline &&
5234
- !approvalResponding &&
5235
- (await declinePendingApprovals(approvalsToDecline, onRespondToApprovalStable).catch(
5236
- () => false,
5237
- ));
5238
- const draftChanged =
5239
- changedBeforeDecline ||
5240
- draftChangedSinceSend() ||
5241
- useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) !==
5242
- draftBeforeDecline;
5243
- // An approval that arrived during the decline would block the redirect; keep the draft so
5244
- // the next send declines it too.
5245
- const approvalArrived = pendingApprovalsRef.current.some(
5246
- (approval) => !pendingIdsBeforeDecline.includes(approval.requestId),
5247
- );
5248
- if (
5249
- !declined ||
5250
- draftChanged ||
5251
- approvalArrived ||
5252
- currentRouteThreadKeyRef.current !== routeThreadKey
5253
- ) {
5254
- sendInFlightRef.current = false;
5255
- setDockedDraftHeroThreadKey((currentThreadKey) =>
5256
- currentThreadKey === activeThreadKey ? null : currentThreadKey,
5257
- );
5258
- if (draftChanged || approvalResponding || (declined && approvalArrived)) {
5259
- toastManager.add({
5260
- type: "info",
5261
- title: draftChanged
5262
- ? declined
5263
- ? "Approval declined. Your message changed, so it wasn't sent."
5264
- : "Your message changed, so it wasn't sent."
5265
- : approvalResponding
5266
- ? "An approval is already being answered, so your message wasn't sent."
5267
- : "Another approval arrived, so your message wasn't sent.",
5268
- description: "Send again when it's ready.",
5269
- });
5270
- }
5271
- return;
5272
- }
5273
- }
5274
- if (sendQueuesBehindSetup) {
5275
- setSetupQueueSendThreadKey(activeThreadKey);
5276
- } else {
5277
- beginLocalDispatch({
5278
- preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree),
5279
- submissionIntent:
5280
- submissionIntent === "background" && !isLocalDraftThread
5281
- ? "foreground"
5282
- : submissionIntent,
5283
- });
5284
- beginWorktreeSetup(
5285
- multipleModelSelections === null && baseBranchForWorktree
5286
- ? { environmentId: activeThread.environmentId, threadId: threadIdForSend }
5287
- : null,
5288
- );
5289
- }
5290
-
5291
- const turnAttachmentsPromise = Promise.all(
5292
- composerAttachmentsSnapshot.map(async (attachment) => {
5293
- if (turnUsesAttachmentUploads) {
5294
- const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
5295
- if (!uploaded) {
5296
- throw new Error(`Attachment '${attachment.name}' did not finish uploading.`);
5297
- }
5298
- return uploaded;
5299
- }
5300
- if (attachment.type !== "image") {
5301
- throw new Error("This server does not support file attachments.");
5302
- }
5303
- return {
5304
- type: "image" as const,
5305
- id: attachment.id,
5306
- name: attachment.name,
5307
- mimeType: attachment.mimeType,
5308
- sizeBytes: attachment.sizeBytes,
5309
- dataUrl: await readFileAsDataUrl(attachment.file),
5310
- ...(attachment.source ? { source: attachment.source } : {}),
5311
- };
5312
- }),
5313
- );
5314
- if (multipleModelSelections !== null) {
5315
- const failedSelections: ModelSelection[] = [];
5316
- let clearedDraft = false;
5317
- let releasedComposer = false;
5318
- let canRestoreDraft = () => false;
5319
- let startedCount = 0;
5320
- // Anything thrown here (an attachment the server can no longer take)
5321
- // fails every selection; the draft restore below still runs.
5322
- const sendResult = await settlePromise(async () => {
5323
- const attachments = await turnAttachmentsPromise;
5324
- const fileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
5325
- if (fileBlockReason !== null) throw new Error(fileBlockReason);
5326
- const context = buildOutgoingMessageContext(
5327
- boundAttachmentIds(attachments, composerAttachmentsSnapshot),
5328
- );
5329
- const title = deriveThreadTitleSeed({
5330
- text: messageTextForSend,
5331
- attachments: composerAttachmentsSnapshot,
5332
- });
5333
- promptRef.current = "";
5334
- clearComposerDraftContent(composerDraftTarget);
5335
- composerRef.current?.resetCursorState();
5336
- clearedDraft = true;
5337
- const clearedDraftSnapshot = useComposerDraftStore
5338
- .getState()
5339
- .getComposerDraft(composerDraftTarget);
5340
- const submittedSelections = readMultipleModelSelections();
5341
- canRestoreDraft = () =>
5342
- currentRouteThreadKeyRef.current === routeThreadKey &&
5343
- composerSendGenerationRef.current === sendGeneration &&
5344
- useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
5345
- clearedDraftSnapshot &&
5346
- readMultipleModelSelections() === submittedSelections;
5347
- setThreadError(threadIdForSend, null);
5348
- const starts = Promise.all(
5349
- multipleTargets.map(async (target) => {
5350
- const started = await startFanoutThread({
5351
- retryKey: JSON.stringify([
5352
- routeThreadKey,
5353
- target.selection.instanceId,
5354
- target.selection.model,
5355
- ]),
5356
- model: target.selection.model,
5357
- uncertainSubmissions: uncertainMultipleSubmissionsRef.current,
5358
- start: (targetThreadId) => {
5359
- const supportsInlineMessageContext =
5360
- appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
5361
- .capabilities.inlineMessageContext === true;
5362
- return startThreadTurn({
5363
- environmentId,
5364
- input: {
5365
- threadId: targetThreadId,
5366
- message: {
5367
- messageId: newMessageId(),
5368
- role: "user",
5369
- attachments,
5370
- ...withMessageContext({
5371
- text: target.text,
5372
- context,
5373
- supportsInlineMessageContext,
5374
- }),
5375
- },
5376
- modelSelection: target.selection,
5377
- titleSeed: title,
5378
- runtimeMode,
5379
- interactionMode: target.interactionMode,
5380
- bootstrap: {
5381
- createThread: {
5382
- projectId: activeProject.id,
5383
- title,
5384
- modelSelection: target.selection,
5385
- runtimeMode,
5386
- interactionMode: target.interactionMode,
5387
- branch: activeThreadBranch,
5388
- worktreePath: null,
5389
- createdAt: messageCreatedAt,
5390
- },
5391
- prepareWorktree: {
5392
- projectCwd: activeProject.workspaceRoot,
5393
- baseBranch: activeThreadBranch!,
5394
- requireWorktree: true,
5395
- ...(startFromOrigin ? { startFromOrigin: true } : {}),
5396
- },
5397
- runSetupScript: true,
5398
- },
5399
- createdAt: messageCreatedAt,
5400
- },
5401
- });
5402
- },
5403
- openThread: (threadId) =>
5404
- void navigate({
5405
- to: "/$environmentId/$threadId",
5406
- params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
5407
- }),
5408
- });
5409
- if (started) startedCount += 1;
5410
- else failedSelections.push(target.selection);
5411
- }),
5412
- );
5413
- sendInFlightRef.current = false;
5414
- resetLocalDispatch();
5415
- releasedComposer = true;
5416
- await starts;
5417
- if (startedCount > 0) {
5418
- toastManager.add(
5419
- stackedThreadToast({
5420
- type: "success",
5421
- title: `Started ${startedCount} ${startedCount === 1 ? "thread" : "threads"} in background`,
5422
- }),
5423
- );
5424
- }
5425
- if (failedSelections.length === 0 && turnUsesAttachmentUploads) {
5426
- releaseDraftAttachments(composerAttachmentsSnapshot);
5427
- }
5428
- });
5429
- if (sendResult._tag === "Failure") {
5430
- const error = squashAtomCommandFailure(sendResult);
5431
- failedSelections.push(...multipleModelSelections);
5432
- setThreadError(
5433
- threadIdForSend,
5434
- error instanceof Error ? error.message : "Failed to send messages.",
5435
- );
5436
- }
5437
- const restoreFailedDraft = () => {
5438
- setMultipleModelSelections(failedSelections);
5439
- if (clearedDraft) {
5440
- restoreComposerDraft(composerDraftTarget, sendSnapshot);
5441
- if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) {
5442
- promptRef.current = messageTextForSend;
5443
- composerRef.current.resetCursorState({
5444
- cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
5445
- prompt: messageTextForSend,
5446
- detectTrigger: true,
5447
- });
5448
- }
5449
- }
5450
- };
5451
- if (failedSelections.length > 0) {
5452
- if (canRestoreDraft() && composerRef.current) {
5453
- restoreFailedDraft();
5454
- } else if (clearedDraft) {
5455
- const recoveryToastId = toastManager.add(
5456
- stackedThreadToast({
5457
- type: "error",
5458
- title: "A background prompt could not be sent",
5459
- description:
5460
- "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.",
5461
- timeout: 0,
5462
- actionProps: {
5463
- children: "Restore prompt",
5464
- onClick: () => {
5465
- if (
5466
- !draftId ||
5467
- !useComposerDraftStore.getState().getDraftSession(draftId) ||
5468
- sendInFlightRef.current ||
5469
- composerDraftHasUserContent(
5470
- useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
5471
- )
5472
- ) {
5473
- toastManager.update(recoveryToastId, {
5474
- description:
5475
- "Return to the original draft and send or clear its current prompt before restoring.",
5476
- });
5477
- return;
5478
- }
5479
- restoreFailedDraft();
5480
- void navigate({ to: "/draft/$draftId", params: { draftId } });
5481
- toastManager.close(recoveryToastId);
5482
- },
5483
- },
5484
- }),
5485
- );
5486
- }
5487
- }
5488
- if (!releasedComposer) {
5489
- sendInFlightRef.current = false;
5490
- resetLocalDispatch();
5491
- }
5492
- return;
5493
- }
5494
- const optimisticAttachments = optimisticMessageAttachments(composerAttachmentsSnapshot);
5495
- if (!shouldQueueBehindActiveRun) {
5496
- anchorNewTurn(
5497
- scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
5498
- messageIdForSend,
5499
- );
5500
- }
5501
- setOptimisticUserMessages((existing) => [
5502
- ...existing,
5503
- {
5504
- id: messageIdForSend,
5505
- role: "user",
5506
- text: outgoingMessageText,
5507
- ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
5508
- ...(outgoingMessageContext !== undefined ? { context: outgoingMessageContext } : {}),
5509
- runId: null,
5510
- createdAt: messageCreatedAt,
5511
- updatedAt: messageCreatedAt,
5512
- streaming: false,
5513
- ...(shouldQueueBehindActiveRun
5514
- ? { inputIntent: "queued_turn" as const }
5515
- : phase === "running" && dispatchMode === "steer"
5516
- ? { inputIntent: "steer" as const }
5517
- : {}),
5518
- },
5519
- ]);
5520
- setThreadError(threadIdForSend, null);
5521
- if (expiredTerminalContextCount > 0) {
5522
- const toastCopy = buildExpiredTerminalContextToastCopy(
5523
- expiredTerminalContextCount,
5524
- "omitted",
5525
- );
5526
- toastManager.add(
5527
- stackedThreadToast({
5528
- type: "warning",
5529
- title: toastCopy.title,
5530
- description: toastCopy.description,
5531
- }),
5532
- );
5533
- }
5534
- const sentDraftThreadRef = isLocalDraftThread
5535
- ? scopeThreadRef(environmentId, threadIdForSend)
5536
- : null;
5537
- // Keep new-thread flows from reusing this draft while attachments and worktree setup settle.
5538
- if (sentDraftThreadRef) markPromotedDraftThreadByRef(sentDraftThreadRef);
5539
- promptRef.current = "";
5540
- clearComposerDraftContent(composerDraftTarget);
5541
- composerRef.current?.resetCursorState();
5542
-
5543
- const title = deriveThreadTitleSeed({
5544
- text: messageTextForSend,
5545
- attachments: composerAttachmentsSnapshot,
5546
- fallbackLabels: sendTitleFallbackLabels(sendSnapshot),
5547
- });
5548
- const threadCreateModelSelection = createModelSelection(
5549
- ctxSelectedModelSelection.instanceId,
5550
- ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL,
5551
- ctxSelectedModelSelection.options,
5552
- );
5553
-
5554
- let failure: AtomCommandResult<unknown, unknown> | null = null;
5555
-
5556
- if (failure === null && isServerThread) {
5557
- const settingsResult = await persistThreadSettingsForNextTurn({
5558
- threadId: threadIdForSend,
5559
- createdAt: messageCreatedAt,
5560
- ...(localCheckoutBranchMismatch
5561
- ? { branch: localCheckoutBranchMismatch.currentBranch }
5562
- : {}),
5563
- runtimeMode,
5564
- interactionMode: sendInteractionMode,
5565
- });
5566
- if (settingsResult._tag === "Failure") {
5567
- failure = settingsResult;
5568
- }
5569
- }
5570
-
5571
- const turnAttachmentsResult = await settlePromise(async () => {
5572
- const turnAttachments = await turnAttachmentsPromise;
5573
- const liveFileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
5574
- if (liveFileBlockReason !== null) {
5575
- throw new Error(liveFileBlockReason);
5576
- }
5577
- return turnAttachments;
5578
- });
5579
- if (failure === null && turnAttachmentsResult._tag === "Failure") {
5580
- failure = turnAttachmentsResult;
5581
- }
5582
-
5583
- if (failure === null && compactBeforeSend) {
5584
- const compactResult = await startThreadTurn({
5585
- environmentId,
5586
- input: {
5587
- threadId: threadIdForSend,
5588
- message: { messageId: newMessageId(), role: "user", text: "/compact", attachments: [] },
5589
- modelSelection: ctxSelectedModelSelection,
5590
- runtimeMode,
5591
- interactionMode: sendInteractionMode,
5592
- },
5593
- });
5594
- if (compactResult._tag === "Failure") {
5595
- failure = compactResult;
5596
- }
5597
- }
5598
-
5599
- let backgroundDraftOpened = false;
5600
- let turnStartSucceeded = false;
5601
- if (failure === null && turnAttachmentsResult._tag === "Success") {
5602
- const bootstrap =
5603
- isLocalDraftThread || baseBranchForWorktree
5604
- ? {
5605
- ...(isLocalDraftThread
5606
- ? {
5607
- createThread: {
5608
- projectId: activeProject.id,
5609
- title,
5610
- modelSelection: threadCreateModelSelection,
5611
- runtimeMode,
5612
- interactionMode: sendInteractionMode,
5613
- branch: activeThreadBranch,
5614
- worktreePath: activeThread.worktreePath,
5615
- createdAt: activeThread.createdAt,
5616
- },
5617
- }
5618
- : {}),
5619
- ...(baseBranchForWorktree
5620
- ? {
5621
- prepareWorktree: {
5622
- projectCwd: activeProject.workspaceRoot,
5623
- baseBranch: baseBranchForWorktree,
5624
- ...(startFromOrigin ? { startFromOrigin: true } : {}),
5625
- },
5626
- runSetupScript: true,
5627
- }
5628
- : {}),
5629
- }
5630
- : undefined;
5631
- const backgroundThreadRef =
5632
- submissionIntent === "background" && isLocalDraftThread
5633
- ? scopeThreadRef(environmentId, threadIdForSend)
5634
- : null;
5635
- if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef);
5636
- const startPromise = startThreadTurn({
5637
- environmentId,
5638
- input: {
5639
- threadId: threadIdForSend,
5640
- message: {
5641
- messageId: messageIdForSend,
5642
- role: "user",
5643
- attachments: turnAttachmentsResult.value,
5644
- ...withMessageContext({
5645
- text: outgoingMessageText,
5646
- context: buildOutgoingMessageContext(
5647
- boundAttachmentIds(turnAttachmentsResult.value, composerAttachmentsSnapshot),
5648
- ),
5649
- // Read at dispatch time: the upload and persistence awaits above can
5650
- // span a server reconnect that changes it.
5651
- supportsInlineMessageContext:
5652
- appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
5653
- .capabilities.inlineMessageContext === true,
5654
- }),
5655
- },
5656
- modelSelection: ctxSelectedModelSelection,
5657
- titleSeed: title,
5658
- runtimeMode,
5659
- interactionMode: sendInteractionMode,
5660
- dispatchMode: turnDispatchMode,
5661
- ...(bootstrap ? { bootstrap } : {}),
5662
- createdAt: messageCreatedAt,
5663
- },
5664
- });
5665
- if (backgroundThreadRef) {
5666
- try {
5667
- backgroundDraftOpened = Boolean(
5668
- await handleNewThread(
5669
- scopeProjectRef(activeProject.environmentId, activeProject.id),
5670
- resolveBackgroundDraftWorkspaceOptions({
5671
- envMode: sendEnvMode,
5672
- branch: activeThreadBranch,
5673
- startFromOrigin,
5674
- }),
5675
- ),
5676
- );
5677
- } catch (error) {
5678
- clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
5679
- toastManager.add(
5680
- stackedThreadToast({
5681
- type: "warning",
5682
- title: "Could not open a fresh composer",
5683
- description: error instanceof Error ? error.message : undefined,
5684
- }),
5685
- );
5686
- }
5687
- }
5688
- const startResult = await startPromise;
5689
- if (startResult._tag === "Failure") {
5690
- failure = startResult;
5691
- } else {
5692
- turnStartSucceeded = true;
5693
- setKeepFullHistory(routeThreadKey, false);
5694
- clearUsageLimitsFor(routeThreadKey);
5695
- if (turnUsesAttachmentUploads) {
5696
- releaseDraftAttachments(composerAttachmentsSnapshot);
5697
- }
5698
- acknowledgeActiveThreadWoke();
5699
- // A draft still on screen finalizes once its thread route takes over.
5700
- if (sentDraftThreadRef) {
5701
- if (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey) {
5702
- finalizePromotedDraftThreadByRef(sentDraftThreadRef);
5703
- } else {
5704
- clearBackgroundDraftSubmissionByRef(sentDraftThreadRef);
5705
- }
5706
- }
5707
- if (backgroundThreadRef) {
5708
- if (backgroundDraftOpened) {
5709
- toastManager.add(
5710
- stackedThreadToast({
5711
- type: "success",
5712
- title: "Started in background",
5713
- timeout: 5_000,
5714
- actionProps: {
5715
- children: "Open",
5716
- onClick: () => {
5717
- void navigate({
5718
- to: "/$environmentId/$threadId",
5719
- params: buildThreadRouteParams(backgroundThreadRef),
5720
- });
5721
- },
5722
- },
5723
- }),
5724
- );
5725
- }
5726
- } else if (
5727
- submissionIntent === "background" &&
5728
- currentRouteThreadKeyRef.current === routeThreadKey
5729
- ) {
5730
- handleNewThreadInActiveProject();
5731
- }
5732
- }
5733
- }
5734
-
5735
- if (failure !== null) {
5736
- if (isLocalDraftThread && draftId && draftThread) {
5737
- restoreFailedDraftThread(
5738
- draftId,
5739
- draftThread,
5740
- wasBootstrapThreadDeleted(squashAtomCommandFailure(failure))
5741
- ? newThreadId()
5742
- : threadIdForSend,
5743
- );
5744
- clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend));
5745
- }
5746
- if (
5747
- !composerDraftHasUserContent(
5748
- useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
5749
- )
5750
- ) {
5751
- setOptimisticUserMessages((existing) => {
5752
- const removed = existing.filter((message) => message.id === messageIdForSend);
5753
- for (const message of removed) {
5754
- revokeUserMessagePreviewUrls(message);
5755
- }
5756
- const next = existing.filter((message) => message.id !== messageIdForSend);
5757
- return next.length === existing.length ? existing : next;
5758
- });
5759
- const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot);
5760
- if (currentRouteThreadKeyRef.current === routeThreadKey) {
5761
- promptRef.current = messageTextForSend;
5762
- composerImagesRef.current = retryComposerImages;
5763
- composerFilesRef.current = composerFilesSnapshot;
5764
- composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
5765
- composerRef.current?.resetCursorState({
5766
- cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
5767
- prompt: messageTextForSend,
5768
- detectTrigger: true,
5769
- });
5770
- }
5771
- }
5772
- if (!isAtomCommandInterrupted(failure)) {
5773
- const error = squashAtomCommandFailure(failure);
5774
- setThreadError(
5775
- threadIdForSend,
5776
- error instanceof Error ? error.message : "Failed to send message.",
5777
- );
5778
- if (
5779
- draftId &&
5780
- (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey)
5781
- ) {
5782
- toastManager.add(
5783
- stackedThreadToast({
5784
- type: "error",
5785
- title:
5786
- submissionIntent === "background"
5787
- ? "Background task failed"
5788
- : "Could not start thread",
5789
- description: error instanceof Error ? error.message : "Failed to send message.",
5790
- actionProps: {
5791
- children: "Open draft",
5792
- onClick: () => {
5793
- void navigate({ to: "/draft/$draftId", params: { draftId } });
5794
- },
5795
- },
5796
- }),
5797
- );
5798
- }
5799
- }
5800
- }
5801
- sendInFlightRef.current = false;
5802
- setSetupQueueSendThreadKey((current) => (current === activeThreadKey ? null : current));
5803
- if (!turnStartSucceeded) {
5804
- setDockedDraftHeroThreadKey((currentThreadKey) =>
5805
- currentThreadKey === activeThreadKey ? null : currentThreadKey,
5806
- );
5807
- if (!sendQueuesBehindSetup) resetLocalDispatch();
5808
- }
5809
- };
5810
-
5811
- async function onSubmitPlanFollowUp({
5812
- text,
5813
- context,
5814
- interactionMode: nextInteractionMode,
5815
- }: {
5816
- text: string;
5817
- context?: ReturnType<typeof buildMessageContext>;
5818
- interactionMode: "default" | "plan";
5819
- }) {
5820
- if (
5821
- !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
5822
- !activeThread ||
5823
- !isServerThread ||
5824
- isSendBusy ||
5825
- isConnecting ||
5826
- sendInFlightRef.current
5827
- ) {
5828
- return false;
5829
- }
5830
-
5831
- const trimmed = text.trim();
5832
- if (!trimmed) {
5833
- return false;
5834
- }
5835
-
5836
- const sendCtx = composerRef.current?.getSendContext();
5837
- if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
5838
- return false;
5839
- }
5840
- const {
5841
- selectedProvider: ctxSelectedProvider,
5842
- selectedModel: ctxSelectedModel,
5843
- selectedProviderModels: ctxSelectedProviderModels,
5844
- selectedPromptEffort: ctxSelectedPromptEffort,
5845
- selectedModelSelection: ctxSelectedModelSelection,
5846
- } = sendCtx;
5847
-
5848
- const threadIdForSend = activeThread.id;
5849
- const messageIdForSend = newMessageId();
5850
- const messageCreatedAt = new Date().toISOString();
5851
- const outgoingMessageText = formatOutgoingPrompt({
5852
- provider: ctxSelectedProvider,
5853
- model: ctxSelectedModel,
5854
- models: ctxSelectedProviderModels,
5855
- effort: ctxSelectedPromptEffort,
5856
- text: trimmed,
5857
- });
5858
-
5859
- sendInFlightRef.current = true;
5860
- beginLocalDispatch({ preparingWorktree: false });
5861
- setThreadError(threadIdForSend, null);
5862
-
5863
- anchorNewTurn(
5864
- scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
5865
- messageIdForSend,
5866
- );
5867
-
5868
- setOptimisticUserMessages((existing) => [
5869
- ...existing,
5870
- {
5871
- id: messageIdForSend,
5872
- role: "user",
5873
- text: outgoingMessageText,
5874
- ...(context ? { context } : {}),
5875
- runId: null,
5876
- createdAt: messageCreatedAt,
5877
- updatedAt: messageCreatedAt,
5878
- streaming: false,
5879
- },
5880
- ]);
5881
-
5882
- const settingsResult = await persistThreadSettingsForNextTurn({
5883
- threadId: threadIdForSend,
5884
- createdAt: messageCreatedAt,
5885
- ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
5886
- runtimeMode,
5887
- interactionMode: nextInteractionMode,
5888
- });
5889
- let failure: AtomCommandResult<unknown, unknown> | null =
5890
- settingsResult._tag === "Failure" ? settingsResult : null;
5891
-
5892
- if (failure === null) {
5893
- setComposerDraftInteractionMode(
5894
- scopeThreadRef(activeThread.environmentId, threadIdForSend),
5895
- nextInteractionMode,
5896
- );
5897
-
5898
- const startResult = await startThreadTurn({
5899
- environmentId,
5900
- input: {
5901
- threadId: threadIdForSend,
5902
- message: {
5903
- messageId: messageIdForSend,
5904
- role: "user",
5905
- text: outgoingMessageText,
5906
- ...(context ? { context } : {}),
5907
- attachments: [],
5908
- },
5909
- modelSelection: ctxSelectedModelSelection,
5910
- titleSeed: activeThread.title,
5911
- runtimeMode,
5912
- interactionMode: nextInteractionMode,
5913
- ...(nextInteractionMode === "default" && activeProposedPlan
5914
- ? {
5915
- sourceProposedPlan: {
5916
- threadId: activeThread.id,
5917
- planId: activeProposedPlan.id,
5918
- },
5919
- }
5920
- : {}),
5921
- createdAt: messageCreatedAt,
5922
- },
5923
- });
5924
- failure = startResult._tag === "Failure" ? startResult : null;
5925
- }
5926
-
5927
- if (failure === null) {
5928
- sendInFlightRef.current = false;
5929
- resetLocalDispatch();
5930
- return true;
5931
- }
5932
-
5933
- setOptimisticUserMessages((existing) =>
5934
- existing.filter((message) => message.id !== messageIdForSend),
5935
- );
5936
- if (!isAtomCommandInterrupted(failure)) {
5937
- const error = squashAtomCommandFailure(failure);
5938
- setThreadError(
5939
- threadIdForSend,
5940
- error instanceof Error ? error.message : "Failed to send plan follow-up.",
5941
- );
5942
- }
5943
- sendInFlightRef.current = false;
5944
- resetLocalDispatch();
5945
- return false;
5946
- }
5947
-
5948
- const onImplementPlanInNewThread = async () => {
5949
- if (
5950
- !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
5951
- !activeThread ||
5952
- !activeProject ||
5953
- !activeProposedPlan ||
5954
- !isServerThread ||
5955
- isSendBusy ||
5956
- isConnecting ||
5957
- activeEnvironmentUnavailable ||
5958
- sendInFlightRef.current
5959
- ) {
5960
- return;
5961
- }
5962
-
5963
- const sendCtx = composerRef.current?.getSendContext();
5964
- if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
5965
- return;
5966
- }
5967
- const {
5968
- selectedProvider: ctxSelectedProvider,
5969
- selectedModel: ctxSelectedModel,
5970
- selectedProviderModels: ctxSelectedProviderModels,
5971
- selectedPromptEffort: ctxSelectedPromptEffort,
5972
- selectedModelSelection: ctxSelectedModelSelection,
5973
- } = sendCtx;
5974
-
5975
- const createdAt = new Date().toISOString();
5976
- const nextThreadId = newThreadId();
5977
- const planMarkdown = activeProposedPlan.planMarkdown;
5978
- const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
5979
- const outgoingImplementationPrompt = formatOutgoingPrompt({
5980
- provider: ctxSelectedProvider,
5981
- model: ctxSelectedModel,
5982
- models: ctxSelectedProviderModels,
5983
- effort: ctxSelectedPromptEffort,
5984
- text: implementationPrompt,
5985
- });
5986
- const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown));
5987
- const nextThreadModelSelection: ModelSelection = ctxSelectedModelSelection;
5988
-
5989
- sendInFlightRef.current = true;
5990
- beginLocalDispatch({ preparingWorktree: false });
5991
- const finish = () => {
5992
- sendInFlightRef.current = false;
5993
- resetLocalDispatch();
5994
- };
5995
-
5996
- const createResult = await createThread({
5997
- environmentId,
5998
- input: {
5999
- threadId: nextThreadId,
6000
- projectId: activeProject.id,
6001
- title: nextThreadTitle,
6002
- modelSelection: nextThreadModelSelection,
6003
- runtimeMode: defaultRuntimeMode,
6004
- interactionMode: "default",
6005
- branch: activeThreadBranch,
6006
- worktreePath: activeThread.worktreePath,
6007
- createdAt,
6008
- },
6009
- });
6010
- let failure: AtomCommandResult<unknown, unknown> | null =
6011
- createResult._tag === "Failure" ? createResult : null;
6012
-
6013
- if (failure === null) {
6014
- const startResult = await startThreadTurn({
6015
- environmentId,
6016
- input: {
6017
- threadId: nextThreadId,
6018
- message: {
6019
- messageId: newMessageId(),
6020
- role: "user",
6021
- text: outgoingImplementationPrompt,
6022
- attachments: [],
6023
- },
6024
- modelSelection: ctxSelectedModelSelection,
6025
- titleSeed: nextThreadTitle,
6026
- runtimeMode: defaultRuntimeMode,
6027
- interactionMode: "default",
6028
- sourceProposedPlan: {
6029
- threadId: activeThread.id,
6030
- planId: activeProposedPlan.id,
6031
- },
6032
- createdAt,
6033
- },
6034
- });
6035
- failure = startResult._tag === "Failure" ? startResult : null;
6036
- }
6037
-
6038
- if (failure === null) {
6039
- const startedResult = await settlePromise(() =>
6040
- waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)),
6041
- );
6042
- failure = startedResult._tag === "Failure" ? startedResult : null;
6043
- }
6044
-
6045
- if (failure === null) {
6046
- const navigateResult = await settlePromise(() =>
6047
- navigate({
6048
- to: "/$environmentId/$threadId",
6049
- params: {
6050
- environmentId: activeThread.environmentId,
6051
- threadId: nextThreadId,
6052
- },
6053
- }),
6054
- );
6055
- failure = navigateResult._tag === "Failure" ? navigateResult : null;
6056
- }
6057
-
6058
- if (failure !== null) {
6059
- const cleanupResult = await deleteThread({
6060
- environmentId,
6061
- input: {
6062
- threadId: nextThreadId,
6063
- },
6064
- });
6065
- if (cleanupResult._tag === "Failure" && !isAtomCommandInterrupted(cleanupResult)) {
6066
- console.warn(
6067
- "Failed to clean up implementation thread after start failure.",
6068
- squashAtomCommandFailure(cleanupResult),
6069
- );
6070
- }
6071
- if (!isAtomCommandInterrupted(failure)) {
6072
- const error = squashAtomCommandFailure(failure);
6073
- toastManager.add(
6074
- stackedThreadToast({
6075
- type: "error",
6076
- title: "Could not start implementation thread",
6077
- description:
6078
- error instanceof Error
6079
- ? error.message
6080
- : "An error occurred while creating the new thread.",
6081
- }),
6082
- );
6083
- }
6084
- }
6085
- finish();
6086
- };
4445
+ const { onSend, onResume, onImplementPlanInNewThread, isResuming } = useComposerSend({
4446
+ environmentId,
4447
+ routeThreadKey,
4448
+ currentRouteThreadKeyRef,
4449
+ draftId,
4450
+ draftThread,
4451
+ activeThread,
4452
+ activeThreadKey,
4453
+ activeThreadBranch,
4454
+ activeProject,
4455
+ activeProjectDefaultModelSelection,
4456
+ activeProposedPlan,
4457
+ activeMessageCount,
4458
+ isServerThread,
4459
+ isLocalDraftThread,
4460
+ isGitRepo,
4461
+ hasHeldQueuedRuns,
4462
+ resumableRunId,
4463
+ phase,
4464
+ runtimeMode,
4465
+ defaultRuntimeMode,
4466
+ interactionMode,
4467
+ sendEnvMode,
4468
+ startFromOrigin,
4469
+ localCheckoutBranchMismatch,
4470
+ settings,
4471
+ clientSettingsHydrated,
4472
+ serverConfig,
4473
+ environmentById,
4474
+ logicalProjectEnvironments,
4475
+ providerInstanceEntries,
4476
+ supportsAttachmentUploads,
4477
+ referencedThreadContexts,
4478
+ composerHasNonPromptContent,
4479
+ composerRef,
4480
+ composerDraftTarget,
4481
+ promptRef,
4482
+ composerImagesRef,
4483
+ composerFilesRef,
4484
+ composerTerminalContextsRef,
4485
+ feedbackUploadsInFlightRef,
4486
+ queuedRunEdit,
4487
+ isConnecting,
4488
+ isRevertingCheckpoint,
4489
+ threadDetailLoading,
4490
+ activeEnvironmentUnavailable,
4491
+ isSendBusy,
4492
+ sendQueuesBehindSetup,
4493
+ isDraftHeroState,
4494
+ panelAnimationsActive,
4495
+ panelAnimationDurationMs,
4496
+ keepFullHistory,
4497
+ resumeCompactionTokens,
4498
+ showPlanFollowUpPrompt,
4499
+ usageLimitsKey,
4500
+ usageLimitsOffered,
4501
+ openUsageLimits,
4502
+ clearUsageLimitsFor,
4503
+ needsLoadBalancing,
4504
+ loadBalancing,
4505
+ readPendingEnvironmentChange,
4506
+ pendingApprovals,
4507
+ respondingRequestIds,
4508
+ activePendingProgress,
4509
+ onAdvanceActivePendingUserInput,
4510
+ onRespondToApproval: onRespondToApprovalStable,
4511
+ beginLocalDispatch,
4512
+ resetLocalDispatch,
4513
+ beginWorktreeSetup,
4514
+ captureDraftHeroComposerRect,
4515
+ setDockedDraftHeroThreadKey,
4516
+ setSetupQueueSendThreadKey,
4517
+ setOptimisticUserMessages,
4518
+ setFeedbackSubmissionsByThreadKey,
4519
+ setMultipleModelSelections,
4520
+ setThreadError,
4521
+ setKeepFullHistory,
4522
+ scrollToEnd,
4523
+ anchorNewTurn,
4524
+ acknowledgeActiveThreadWoke,
4525
+ handleInteractionModeChange,
4526
+ handleNewThreadInActiveProject,
4527
+ persistThreadSettingsForNextTurn,
4528
+ });
4529
const onImplementPlanInNewThreadStable = useStableCallback(onImplementPlanInNewThread);
4530
4531
// Keyed on the fields it reads: the thread and runtime objects change with
apps/web/src/components/chat/useComposerSend.ts
new
+1916
@@ -0,0 +1,1916 @@
1
+import {
2
+ mergeDirectPreviewAnnotation,
3
+ resolveBackgroundDraftWorkspaceOptions,
4
+ shouldDockDraftHeroForSubmission,
5
+ restorePlanFollowUpComposer,
6
+ buildExpiredTerminalContextToastCopy,
7
+ deriveComposerSendState,
8
+ readFileAsDataUrl,
9
+ revokeUserMessagePreviewUrls,
10
+ waitForStartedServerThread,
11
+ boundAttachmentIds,
12
+ formatOutgoingPrompt,
13
+ optimisticMessageAttachments,
14
+ planComposerTurn,
15
+ sendTitleFallbackLabels,
16
+ snapshotComposerSend,
17
+ withMessageContext,
18
+ makeThreadErrorSetter,
19
+} from "../ChatView.logic";
20
+import { isUsageLimitsCommand } from "@t3tools/shared/usageLimits";
21
+import {
22
+ AuthOrchestrationOperateScope,
23
+ DEFAULT_MODEL,
24
+ type EnvironmentId,
25
+ type ModelSelection,
26
+ type PreviewAnnotationPayload,
27
+ type ThreadId,
28
+ type RunId,
29
+ ProviderInteractionMode,
30
+ RuntimeMode,
31
+} from "@t3tools/contracts";
32
+import { deriveThreadTitleSeed } from "@t3tools/client-runtime/operations";
33
+import { wasBootstrapThreadDeleted } from "@t3tools/client-runtime/errors";
34
+import { declinePendingApprovals } from "@t3tools/client-runtime/state/thread-requests";
35
+import {
36
+ parseCodexFeedbackCommand,
37
+ submitCodexFeedback,
38
+ type CodexFeedbackSubmission,
39
+} from "@t3tools/client-runtime/state/threads";
40
+import {
41
+ scopedThreadKey,
42
+ scopeProjectRef,
43
+ scopeThreadRef,
44
+} from "@t3tools/client-runtime/environment";
45
+import { createModelSelection } from "@t3tools/shared/model";
46
+import { truncate } from "@t3tools/shared/String";
47
+import { type SetStateAction, useLayoutEffect, useRef, useState } from "react";
48
+import { flushSync } from "react-dom";
49
+import { useNavigate } from "@tanstack/react-router";
50
+import {
51
+ isAtomCommandInterrupted,
52
+ settlePromise,
53
+ squashAtomCommandFailure,
54
+ type AtomCommandResult,
55
+} from "@t3tools/client-runtime/state/runtime";
56
+import {
57
+ type ComposerSubmissionIntent,
58
+ collapseExpandedComposerCursor,
59
+ parseStandaloneComposerSlashCommand,
60
+} from "../../composer-logic";
61
+import {
62
+ buildPlanImplementationThreadTitle,
63
+ buildPlanImplementationPrompt,
64
+ resolvePlanFollowUpSubmission,
65
+} from "../../proposedPlan";
66
+import { type ChatMessage } from "../../types";
67
+import { stackedThreadToast, toastManager } from "../ui/toast";
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
+ composerDraftHasUserContent,
78
+ type ComposerFileAttachment,
79
+ type ComposerImageAttachment,
80
+ type DraftThreadEnvMode,
81
+ useComposerDraftStore,
82
+ DraftId,
83
+} from "../../composerDraftStore";
84
+import { type TerminalContextDraft } from "../../lib/terminalContext";
85
+import { ensureInlineContextReferences } from "../../lib/composerContextReferences";
86
+import {
87
+ buildMessageContext,
88
+ previewAnnotationContextReference,
89
+} from "../../lib/composerContextRecords";
90
+import { environmentServerConfigsAtom } from "../../state/server";
91
+import { threadEnvironment } from "../../state/threads";
92
+import { runMobileComposerTransition } from "./draftHeroTransition";
93
+import { type ComposerDispatchMode } from "@t3tools/client-runtime/state/composer-dispatch";
94
+import {
95
+ awaitAttachmentUploads,
96
+ getUploadedAttachments,
97
+ readAttachmentUpload,
98
+ releaseDraftAttachments,
99
+ retryAttachmentUpload,
100
+ startAttachmentUpload,
101
+} from "../../lib/attachmentUploadQueue";
102
+import { appAtomRegistry } from "../../rpc/atomRegistry";
103
+import { fileAttachmentCapabilityBlockReason } from "./composerAttachmentFiles";
104
+import { readEnvironmentScope } from "../../state/session";
105
+import { useOrchestrationCommand } from "../../state/use-orchestration-command";
106
+import {
107
+ ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
108
+ threadContextsOutsideEnvironment,
109
+} from "@t3tools/shared/composerContextReferences";
110
+import {
111
+ draftFanoutSelectionsAtom,
112
+ draftSendState,
113
+ type MultipleModelTarget,
114
+ resolveMultipleModelTargets,
115
+ restoreComposerDraft,
116
+ startFanoutThread,
117
+} from "./chatViewSend";
118
+import type { EnvironmentServerConfig } from "@t3tools/client-runtime/connection";
119
+import type {
120
+ EnvironmentProject,
121
+ EnvironmentThreadShell,
122
+} from "@t3tools/client-runtime/state/shell";
123
+import type { ThreadContextRecord, UnifiedSettings } from "@t3tools/contracts";
124
+import type { Dispatch } from "react";
125
+import type { ComposerThreadTarget } from "../../composerDraftStore";
126
+import type { ProviderInstanceEntry } from "../../providerInstances";
127
+import type { SessionPhase } from "../../types";
128
+import type { DraftSessionState } from "../../composerDraftStore";
129
+import type { ComposerHandleRef } from "../../composerHandleContext";
130
+import type { useLogicalProjectEnvironments } from "../../hooks/useLogicalProjectEnvironments";
131
+import type { LatestProposedPlanState } from "../../session-logic";
132
+import type { EnvironmentPresentation } from "../../state/environments";
133
+import type { useDraftEnvironmentRouting } from "./useDraftEnvironmentRouting";
134
+import type { useLocalDispatchState } from "./useLocalDispatchState";
135
+import type { usePendingThreadRequests } from "./usePendingThreadRequests";
136
+import type { useQueuedRunEdit } from "./useQueuedRunEdit";
137
+import type { useTimelineFollow } from "./useTimelineFollow";
138
+import type { useUsageLimitsPanel } from "./useUsageLimitsPanel";
139
+import type { useWorktreeSetup } from "./useWorktreeSetup";
140
+
141
+const ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE = 3;
142
+
143
+type PendingThreadRequests = ReturnType<typeof usePendingThreadRequests>;
144
+type LocalDispatchState = ReturnType<typeof useLocalDispatchState>;
145
+type DraftEnvironmentRouting = ReturnType<typeof useDraftEnvironmentRouting>;
146
+type UsageLimitsPanel = ReturnType<typeof useUsageLimitsPanel>;
147
+type TimelineFollow = ReturnType<typeof useTimelineFollow>;
148
+
149
+interface ComposerSendInput {
150
+ readonly environmentId: EnvironmentId;
151
+ readonly routeThreadKey: string;
152
+ readonly currentRouteThreadKeyRef: { readonly current: string | null };
153
+ readonly draftId: DraftId | null;
154
+ readonly draftThread: DraftSessionState | null;
155
+ readonly activeThread: EnvironmentThreadShell | undefined;
156
+ readonly activeThreadKey: string | null;
157
+ readonly activeThreadBranch: string | null;
158
+ readonly activeProject: EnvironmentProject | null;
159
+ readonly activeProjectDefaultModelSelection: ModelSelection | null;
160
+ readonly activeProposedPlan: LatestProposedPlanState | null;
161
+ readonly activeMessageCount: number;
162
+ readonly isServerThread: boolean;
163
+ readonly isLocalDraftThread: boolean;
164
+ readonly isGitRepo: boolean;
165
+ readonly hasHeldQueuedRuns: boolean;
166
+ readonly resumableRunId: RunId | null;
167
+ readonly phase: SessionPhase;
168
+ readonly runtimeMode: RuntimeMode;
169
+ readonly defaultRuntimeMode: RuntimeMode;
170
+ readonly interactionMode: ProviderInteractionMode;
171
+ readonly sendEnvMode: DraftThreadEnvMode;
172
+ readonly startFromOrigin: boolean;
173
+ readonly localCheckoutBranchMismatch: {
174
+ readonly threadBranch: string;
175
+ readonly currentBranch: string;
176
+ } | null;
177
+ readonly settings: UnifiedSettings;
178
+ readonly clientSettingsHydrated: boolean;
179
+ readonly serverConfig: EnvironmentServerConfig | null;
180
+ readonly environmentById: ReadonlyMap<EnvironmentId, EnvironmentPresentation>;
181
+ readonly logicalProjectEnvironments: ReturnType<typeof useLogicalProjectEnvironments>;
182
+ readonly providerInstanceEntries: ReadonlyArray<ProviderInstanceEntry>;
183
+ readonly supportsAttachmentUploads: boolean;
184
+ readonly referencedThreadContexts: ReadonlyArray<ThreadContextRecord>;
185
+ readonly composerHasNonPromptContent: boolean;
186
+ readonly composerRef: ComposerHandleRef;
187
+ readonly composerDraftTarget: ComposerThreadTarget;
188
+ readonly promptRef: { current: string };
189
+ readonly composerImagesRef: { current: ComposerImageAttachment[] };
190
+ readonly composerFilesRef: { current: ComposerFileAttachment[] };
191
+ readonly composerTerminalContextsRef: { current: TerminalContextDraft[] };
192
+ readonly feedbackUploadsInFlightRef: { readonly current: Set<string> };
193
+ readonly queuedRunEdit: ReturnType<typeof useQueuedRunEdit>;
194
+ readonly isConnecting: boolean;
195
+ readonly isRevertingCheckpoint: boolean;
196
+ readonly threadDetailLoading: boolean;
197
+ readonly activeEnvironmentUnavailable: boolean;
198
+ readonly isSendBusy: boolean;
199
+ readonly sendQueuesBehindSetup: boolean;
200
+ readonly isDraftHeroState: boolean;
201
+ readonly panelAnimationsActive: boolean;
202
+ readonly panelAnimationDurationMs: number;
203
+ readonly keepFullHistory: boolean;
204
+ readonly resumeCompactionTokens: number | null;
205
+ readonly showPlanFollowUpPrompt: boolean;
206
+ readonly usageLimitsKey: string | null;
207
+ readonly usageLimitsOffered: boolean;
208
+ readonly openUsageLimits: UsageLimitsPanel["open"];
209
+ readonly clearUsageLimitsFor: UsageLimitsPanel["clearFor"];
210
+ readonly needsLoadBalancing: boolean;
211
+ readonly loadBalancing: DraftEnvironmentRouting["loadBalancing"];
212
+ readonly readPendingEnvironmentChange: DraftEnvironmentRouting["readPendingEnvironmentChange"];
213
+ readonly pendingApprovals: PendingThreadRequests["pendingApprovals"];
214
+ readonly respondingRequestIds: PendingThreadRequests["respondingRequestIds"];
215
+ readonly activePendingProgress: PendingThreadRequests["activePendingProgress"];
216
+ readonly onAdvanceActivePendingUserInput: PendingThreadRequests["onAdvanceActivePendingUserInput"];
217
+ readonly onRespondToApproval: PendingThreadRequests["onRespondToApproval"];
218
+ readonly beginLocalDispatch: LocalDispatchState["beginLocalDispatch"];
219
+ readonly resetLocalDispatch: LocalDispatchState["resetLocalDispatch"];
220
+ readonly beginWorktreeSetup: ReturnType<typeof useWorktreeSetup>["begin"];
221
+ readonly captureDraftHeroComposerRect: () => void;
222
+ readonly setDockedDraftHeroThreadKey: Dispatch<SetStateAction<string | null>>;
223
+ readonly setSetupQueueSendThreadKey: Dispatch<SetStateAction<string | null>>;
224
+ readonly setOptimisticUserMessages: Dispatch<SetStateAction<ChatMessage[]>>;
225
+ readonly setFeedbackSubmissionsByThreadKey: Dispatch<
226
+ SetStateAction<Record<string, ReadonlyArray<CodexFeedbackSubmission>>>
227
+ >;
228
+ readonly setMultipleModelSelections: (
229
+ selections: SetStateAction<ReadonlyArray<ModelSelection> | null>,
230
+ ) => void;
231
+ readonly setThreadError: ReturnType<typeof makeThreadErrorSetter>;
232
+ readonly setKeepFullHistory: (threadKey: string, keep: boolean) => void;
233
+ readonly scrollToEnd: TimelineFollow["scrollToEnd"];
234
+ readonly anchorNewTurn: TimelineFollow["anchorNewTurn"];
235
+ readonly acknowledgeActiveThreadWoke: () => void;
236
+ readonly handleInteractionModeChange: (mode: ProviderInteractionMode) => void;
237
+ readonly handleNewThreadInActiveProject: () => void;
238
+ readonly persistThreadSettingsForNextTurn: (input: {
239
+ threadId: ThreadId;
240
+ createdAt: string;
241
+ branch?: string;
242
+ runtimeMode: RuntimeMode;
243
+ interactionMode: ProviderInteractionMode;
244
+ }) => Promise<AtomCommandResult<void, unknown>>;
245
+}
246
+
247
+/**
248
+ * Everything the composer's send button can start: a turn on this thread or a new one,
249
+ * a multiple-model start, a queued or steering message, a plan follow-up or implementation
250
+ * thread, a feedback upload, and resuming an interrupted run. Each path restores the draft
251
+ * when it fails.
252
+ */
253
+export function useComposerSend(input: ComposerSendInput) {
254
+ const {
255
+ environmentId,
256
+ routeThreadKey,
257
+ currentRouteThreadKeyRef,
258
+ draftId,
259
+ draftThread,
260
+ activeThread,
261
+ activeThreadKey,
262
+ activeThreadBranch,
263
+ activeProject,
264
+ activeProjectDefaultModelSelection,
265
+ activeProposedPlan,
266
+ activeMessageCount,
267
+ isServerThread,
268
+ isLocalDraftThread,
269
+ isGitRepo,
270
+ hasHeldQueuedRuns,
271
+ resumableRunId,
272
+ phase,
273
+ runtimeMode,
274
+ defaultRuntimeMode,
275
+ interactionMode,
276
+ sendEnvMode,
277
+ startFromOrigin,
278
+ localCheckoutBranchMismatch,
279
+ settings,
280
+ clientSettingsHydrated,
281
+ serverConfig,
282
+ environmentById,
283
+ logicalProjectEnvironments,
284
+ providerInstanceEntries,
285
+ supportsAttachmentUploads,
286
+ referencedThreadContexts,
287
+ composerHasNonPromptContent,
288
+ composerRef,
289
+ composerDraftTarget,
290
+ promptRef,
291
+ composerImagesRef,
292
+ composerFilesRef,
293
+ composerTerminalContextsRef,
294
+ feedbackUploadsInFlightRef,
295
+ queuedRunEdit,
296
+ isConnecting,
297
+ isRevertingCheckpoint,
298
+ threadDetailLoading,
299
+ activeEnvironmentUnavailable,
300
+ isSendBusy,
301
+ sendQueuesBehindSetup,
302
+ isDraftHeroState,
303
+ panelAnimationsActive,
304
+ panelAnimationDurationMs,
305
+ keepFullHistory,
306
+ resumeCompactionTokens,
307
+ showPlanFollowUpPrompt,
308
+ usageLimitsKey,
309
+ usageLimitsOffered,
310
+ openUsageLimits,
311
+ clearUsageLimitsFor,
312
+ needsLoadBalancing,
313
+ loadBalancing,
314
+ readPendingEnvironmentChange,
315
+ pendingApprovals,
316
+ respondingRequestIds,
317
+ activePendingProgress,
318
+ onAdvanceActivePendingUserInput,
319
+ onRespondToApproval: onRespondToApprovalStable,
320
+ beginLocalDispatch,
321
+ resetLocalDispatch,
322
+ beginWorktreeSetup,
323
+ captureDraftHeroComposerRect,
324
+ setDockedDraftHeroThreadKey,
325
+ setSetupQueueSendThreadKey,
326
+ setOptimisticUserMessages,
327
+ setFeedbackSubmissionsByThreadKey,
328
+ setMultipleModelSelections,
329
+ setThreadError,
330
+ setKeepFullHistory,
331
+ scrollToEnd,
332
+ anchorNewTurn,
333
+ acknowledgeActiveThreadWoke,
334
+ handleInteractionModeChange,
335
+ handleNewThreadInActiveProject,
336
+ persistThreadSettingsForNextTurn,
337
+ } = input;
338
+ const handleNewThread = useNewThreadHandler();
339
+ const navigate = useNavigate();
340
+ const createThread = useOrchestrationCommand(threadEnvironment.create, { reportFailure: false });
341
+ const deleteThread = useOrchestrationCommand(threadEnvironment.delete, { reportFailure: false });
342
+ const startThreadTurn = useOrchestrationCommand(threadEnvironment.startTurn, {
343
+ reportFailure: false,
344
+ });
345
+ const resumeThreadQueue = useOrchestrationCommand(threadEnvironment.resumeThreadQueue, {
346
+ reportFailure: false,
347
+ });
348
+ const uploadThreadFeedback = useOrchestrationCommand(threadEnvironment.uploadFeedback, {
349
+ reportFailure: false,
350
+ });
351
+ const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
352
+ const setComposerDraftTerminalContexts = useComposerDraftStore(
353
+ (store) => store.setTerminalContexts,
354
+ );
355
+ const setComposerDraftPreviewAnnotations = useComposerDraftStore(
356
+ (store) => store.setPreviewAnnotations,
357
+ );
358
+ const setComposerDraftReviewComments = useComposerDraftStore((store) => store.setReviewComments);
359
+ const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
360
+ const setComposerDraftInteractionMode = useComposerDraftStore(
361
+ (store) => store.setInteractionMode,
362
+ );
363
+ const clearComposerDraftContent = useComposerDraftStore((store) => store.clearComposerContent);
364
+ const fanoutSelectionsAtom = draftFanoutSelectionsAtom(routeThreadKey);
365
+ const readMultipleModelSelections = () => appAtomRegistry.get(fanoutSelectionsAtom);
366
+ const { sendInFlight: sendInFlightRef, uncertainSubmissions: uncertainMultipleSubmissionsRef } =
367
+ draftSendState(routeThreadKey);
368
+ const [resumingThreadKeys, setResumingThreadKeys] = useState<ReadonlySet<string>>(
369
+ () => new Set(),
370
+ );
371
+ const isResuming = resumingThreadKeys.has(routeThreadKey);
372
+ const composerSendGenerationRef = useRef(0);
373
+ const environmentUnavailableSendToastSlotRef = useRef(0);
374
+ // A send awaits uploads before it declines, so it reads the approvals pending by then.
375
+ const pendingApprovalsRef = useRef(pendingApprovals);
376
+ const respondingRequestIdsRef = useRef(respondingRequestIds);
377
+ useLayoutEffect(() => {
378
+ pendingApprovalsRef.current = pendingApprovals;
379
+ respondingRequestIdsRef.current = respondingRequestIds;
380
+ }, [pendingApprovals, respondingRequestIds]);
381
+
382
+ const onResume = async () => {
383
+ if (
384
+ !activeThread ||
385
+ (resumableRunId === null && !hasHeldQueuedRuns) ||
386
+ isSendBusy ||
387
+ isResuming ||
388
+ isConnecting ||
389
+ isRevertingCheckpoint ||
390
+ threadDetailLoading ||
391
+ activeEnvironmentUnavailable ||
392
+ sendInFlightRef.current
393
+ ) {
394
+ return;
395
+ }
396
+ const threadId = activeThread.id;
397
+ sendInFlightRef.current = true;
398
+ setResumingThreadKeys((current) => new Set(current).add(routeThreadKey));
399
+ setThreadError(threadId, null);
400
+ // Commands settle into a result, so this always runs.
401
+ const resume = async () => {
402
+ if (resumableRunId === null) {
403
+ return resumeThreadQueue({ environmentId, input: { threadId } });
404
+ }
405
+ const createdAt = new Date().toISOString();
406
+ const settingsResult = await persistThreadSettingsForNextTurn({
407
+ threadId,
408
+ createdAt,
409
+ ...(localCheckoutBranchMismatch
410
+ ? { branch: localCheckoutBranchMismatch.currentBranch }
411
+ : {}),
412
+ runtimeMode,
413
+ interactionMode,
414
+ });
415
+ if (settingsResult._tag === "Failure") return settingsResult;
416
+ const modelSelection = composerRef.current?.getSendContext().selectedModelSelection;
417
+ const turnResult = await startThreadTurn({
418
+ environmentId,
419
+ input: {
420
+ threadId,
421
+ manualContinuationOfRunId: resumableRunId,
422
+ ...(modelSelection ? { modelSelection } : {}),
423
+ message: {
424
+ messageId: newMessageId(),
425
+ role: "user",
426
+ text: "Continue where you left off.",
427
+ attachments: [],
428
+ },
429
+ runtimeMode,
430
+ interactionMode,
431
+ dispatchMode: "start",
432
+ },
433
+ });
434
+ if (turnResult._tag === "Failure" || !hasHeldQueuedRuns) return turnResult;
435
+ clearUsageLimitsFor(routeThreadKey);
436
+ return resumeThreadQueue({ environmentId, input: { threadId } });
437
+ };
438
+ const result = await resume();
439
+ if (result._tag === "Failure") {
440
+ if (!isAtomCommandInterrupted(result)) {
441
+ const error = squashAtomCommandFailure(result);
442
+ setThreadError(
443
+ threadId,
444
+ error instanceof Error ? error.message : "Could not resume thread.",
445
+ );
446
+ }
447
+ } else {
448
+ clearUsageLimitsFor(routeThreadKey);
449
+ if (currentRouteThreadKeyRef.current === routeThreadKey) scrollToEnd();
450
+ }
451
+ sendInFlightRef.current = false;
452
+ setResumingThreadKeys((current) => {
453
+ const next = new Set(current);
454
+ next.delete(routeThreadKey);
455
+ return next;
456
+ });
457
+ };
458
+
459
+ const onSend = async (
460
+ e?: { preventDefault: () => void },
461
+ dispatchMode: ComposerDispatchMode = "auto",
462
+ submissionIntent: ComposerSubmissionIntent = "foreground",
463
+ directAnnotation?: {
464
+ annotation: PreviewAnnotationPayload;
465
+ image: ComposerImageAttachment | null;
466
+ },
467
+ ) => {
468
+ e?.preventDefault();
469
+ // What the user pressed send on; uploads below can take a while, and a redirect must not
470
+ // decline approvals for a draft that changed meanwhile.
471
+ const promptAtSend = promptRef.current;
472
+ if (
473
+ usageLimitsOffered &&
474
+ usageLimitsKey !== null &&
475
+ !directAnnotation &&
476
+ !composerHasNonPromptContent &&
477
+ isUsageLimitsCommand(promptRef.current)
478
+ ) {
479
+ if (openUsageLimits()) {
480
+ promptRef.current = "";
481
+ setComposerDraftPrompt(composerDraftTarget, "");
482
+ composerRef.current?.resetCursorState();
483
+ }
484
+ return;
485
+ }
486
+
487
+ const notifyDirectAnnotationAttached = () => {
488
+ if (!directAnnotation) return;
489
+ toastManager.add(
490
+ stackedThreadToast({
491
+ type: "info",
492
+ title: "Annotation attached to draft",
493
+ description: "Sending is unavailable right now. Finish the current action, then send.",
494
+ }),
495
+ );
496
+ };
497
+ if (
498
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
499
+ !activeThread ||
500
+ (isSendBusy && !sendQueuesBehindSetup) ||
501
+ isConnecting ||
502
+ isRevertingCheckpoint ||
503
+ !clientSettingsHydrated ||
504
+ threadDetailLoading ||
505
+ readPendingEnvironmentChange() !== null ||
506
+ sendInFlightRef.current ||
507
+ feedbackUploadsInFlightRef.current.has(routeThreadKey)
508
+ ) {
509
+ notifyDirectAnnotationAttached();
510
+ return;
511
+ }
512
+ if (needsLoadBalancing) {
513
+ toastManager.add({
514
+ type: "warning",
515
+ title: loadBalancing.pending
516
+ ? "Checking machine resources"
517
+ : "Choose a machine to continue",
518
+ description: loadBalancing.pending
519
+ ? "Resource checks are still running. You can choose a machine in the composer."
520
+ : referencedThreadContexts.length > 0 &&
521
+ !logicalProjectEnvironments.some((candidate) =>
522
+ referencedThreadContexts.every(
523
+ (record) => record.environmentId === candidate.environmentId,
524
+ ),
525
+ )
526
+ ? "No machine can read every attached thread. Choose a machine in the composer or remove the threads."
527
+ : "No eligible machine has available resources. Choose a machine in the composer to override.",
528
+ });
529
+ return;
530
+ }
531
+ if (activeEnvironmentUnavailable) {
532
+ const toastSlot = environmentUnavailableSendToastSlotRef.current;
533
+ environmentUnavailableSendToastSlotRef.current =
534
+ (toastSlot + 1) % ENVIRONMENT_UNAVAILABLE_SEND_TOAST_TRAIL_SIZE;
535
+ toastManager.add({
536
+ ...stackedThreadToast({
537
+ type: "warning",
538
+ title: "Not connected: message not sent",
539
+ description: "Reconnecting to the environment. Try again once it is connected.",
540
+ }),
541
+ id: `chat-send-environment-unavailable:${toastSlot}`,
542
+ });
543
+ return;
544
+ }
545
+ const sendCtx = composerRef.current?.getSendContext();
546
+ if (activePendingProgress && sendCtx?.answeringPendingUserInput !== false) {
547
+ if (directAnnotation) {
548
+ notifyDirectAnnotationAttached();
549
+ return;
550
+ }
551
+ onAdvanceActivePendingUserInput();
552
+ return;
553
+ }
554
+ if (!sendCtx?.providerAvailable) {
555
+ notifyDirectAnnotationAttached();
556
+ return;
557
+ }
558
+ const multipleModelSelections = sendCtx.multipleModelSelections;
559
+ if (
560
+ multipleModelSelections !== null &&
561
+ serverConfig?.environment.capabilities.requiredWorktreeBootstrap !== true
562
+ ) {
563
+ setThreadError(activeThread.id, "Update this server before starting multiple models.");
564
+ return;
565
+ }
566
+ if (
567
+ multipleModelSelections !== null &&
568
+ (!isLocalDraftThread ||
569
+ !isGitRepo ||
570
+ !activeThreadBranch ||
571
+ multipleModelSelections.length === 0)
572
+ ) {
573
+ toastManager.add(
574
+ stackedThreadToast({
575
+ type: "warning",
576
+ title: "Choose models and a base branch",
577
+ description:
578
+ "Multiple models need a new thread in a Git project. Each gets its own worktree.",
579
+ }),
580
+ );
581
+ return;
582
+ }
583
+ const {
584
+ images: sendContextImages,
585
+ files: composerFiles,
586
+ terminalContexts: composerTerminalContexts,
587
+ previewAnnotations: sendContextPreviewAnnotations,
588
+ reviewComments: composerReviewComments,
589
+ threadContexts: composerThreadContexts,
590
+ selectedProvider: ctxSelectedProvider,
591
+ selectedModel: ctxSelectedModel,
592
+ selectedProviderModels: ctxSelectedProviderModels,
593
+ selectedPromptEffort: ctxSelectedPromptEffort,
594
+ selectedModelSelection: ctxSelectedModelSelection,
595
+ interactionMode: sendInteractionMode,
596
+ interactionModeEnabled: sendInteractionModeEnabled,
597
+ } = sendCtx;
598
+ const { images: composerImages, previewAnnotations: composerPreviewAnnotations } =
599
+ mergeDirectPreviewAnnotation({
600
+ images: sendContextImages,
601
+ fileCount: composerFiles.length,
602
+ previewAnnotations: sendContextPreviewAnnotations,
603
+ direct: directAnnotation,
604
+ });
605
+ // A direct "send annotation" writes the draft and sends in the same tick; the reference
606
+ // must be in the text now, not after the next render.
607
+ const promptForSend = directAnnotation
608
+ ? ensureInlineContextReferences(promptRef.current, [
609
+ previewAnnotationContextReference(directAnnotation.annotation),
610
+ ])
611
+ : promptRef.current;
612
+ const strandedThread = threadContextsOutsideEnvironment({
613
+ text: promptForSend,
614
+ records: composerThreadContexts,
615
+ environmentId,
616
+ })[0];
617
+ if (strandedThread) {
618
+ const owner = environmentById.get(strandedThread.environmentId)?.label ?? "its machine";
619
+ toastManager.add(
620
+ stackedThreadToast({
621
+ type: "warning",
622
+ title: "Attached thread is on another machine",
623
+ description: `This machine's agent can't read "${strandedThread.title}". Remove it, or switch back to ${owner} to send.`,
624
+ }),
625
+ );
626
+ return;
627
+ }
628
+ if (queuedRunEdit.isEditing) {
629
+ // Edit mode repurposes the composer: sending saves the queued message
630
+ // in place instead of dispatching a new turn.
631
+ await queuedRunEdit.saveEdit(
632
+ {
633
+ prompt: promptForSend,
634
+ images: composerImages,
635
+ files: composerFiles,
636
+ terminalContexts: composerTerminalContexts,
637
+ reviewComments: composerReviewComments,
638
+ previewAnnotations: composerPreviewAnnotations,
639
+ threadContexts: composerThreadContexts,
640
+ },
641
+ setThreadError,
642
+ );
643
+ return;
644
+ }
645
+ const {
646
+ trimmedPrompt: trimmed,
647
+ sendableTerminalContexts: sendableComposerTerminalContexts,
648
+ expiredTerminalContextCount,
649
+ hasSendableContent,
650
+ } = deriveComposerSendState({
651
+ prompt: promptForSend,
652
+ imageCount: composerImages.length + composerFiles.length,
653
+ terminalContexts: composerTerminalContexts,
654
+ elementContextCount:
655
+ composerPreviewAnnotations.length +
656
+ composerReviewComments.length +
657
+ composerThreadContexts.length,
658
+ });
659
+ const feedbackCommand =
660
+ ctxSelectedProvider === "codex" &&
661
+ composerImages.length === 0 &&
662
+ composerFiles.length === 0 &&
663
+ sendableComposerTerminalContexts.length === 0 &&
664
+ composerPreviewAnnotations.length === 0 &&
665
+ composerReviewComments.length === 0 &&
666
+ composerThreadContexts.length === 0
667
+ ? parseCodexFeedbackCommand(trimmed)
668
+ : null;
669
+ if (feedbackCommand && multipleModelSelections === null) {
670
+ if (!isServerThread || activeThread.activeProviderThreadId === null) {
671
+ toastManager.add(
672
+ stackedThreadToast({
673
+ type: "warning",
674
+ title: "Start a Codex thread first",
675
+ description: "Send a message before you submit feedback.",
676
+ }),
677
+ );
678
+ return;
679
+ }
680
+ feedbackUploadsInFlightRef.current.add(routeThreadKey);
681
+ await submitCodexFeedback({
682
+ submission: {
683
+ id: newMessageId(),
684
+ command: trimmed,
685
+ createdAt: new Date().toISOString(),
686
+ },
687
+ clearDraft: () => {
688
+ promptRef.current = "";
689
+ clearComposerDraftContent(composerDraftTarget);
690
+ composerRef.current?.resetCursorState();
691
+ },
692
+ onUpdate: (submission) => {
693
+ setFeedbackSubmissionsByThreadKey((current) => {
694
+ const existing = current[routeThreadKey] ?? [];
695
+ const found = existing.some((entry) => entry.id === submission.id);
696
+ return {
697
+ ...current,
698
+ [routeThreadKey]: found
699
+ ? existing.map((entry) => (entry.id === submission.id ? submission : entry))
700
+ : [...existing, submission],
701
+ };
702
+ });
703
+ },
704
+ upload: () =>
705
+ uploadThreadFeedback({
706
+ environmentId: activeThread.environmentId,
707
+ input: { threadId: activeThread.id, ...feedbackCommand },
708
+ }),
709
+ }).finally(() => {
710
+ feedbackUploadsInFlightRef.current.delete(routeThreadKey);
711
+ });
712
+
713
+ return;
714
+ }
715
+ if (
716
+ !directAnnotation &&
717
+ sendInteractionModeEnabled &&
718
+ showPlanFollowUpPrompt &&
719
+ activeProposedPlan &&
720
+ composerImages.length === 0 &&
721
+ composerFiles.length === 0
722
+ ) {
723
+ const followUp = resolvePlanFollowUpSubmission({
724
+ draftText: promptForSend,
725
+ planMarkdown: activeProposedPlan.planMarkdown,
726
+ });
727
+ const outgoingFollowUpText = formatOutgoingPrompt({
728
+ provider: ctxSelectedProvider,
729
+ model: ctxSelectedModel,
730
+ models: ctxSelectedProviderModels,
731
+ effort: ctxSelectedPromptEffort,
732
+ text: followUp.text.trim(),
733
+ });
734
+ if (composerRef.current?.validateProviderInput(outgoingFollowUpText) === false) {
735
+ return;
736
+ }
737
+ const followUpPromptSnapshot = promptRef.current;
738
+ const followUpTerminalContexts = [...sendableComposerTerminalContexts];
739
+ const followUpReviewComments = [...composerReviewComments];
740
+ const followUpPreviewAnnotations = [...composerPreviewAnnotations];
741
+ const followUpThreadContexts = [...composerThreadContexts];
742
+ promptRef.current = "";
743
+ clearComposerDraftContent(composerDraftTarget);
744
+ composerRef.current?.resetCursorState();
745
+ const followUpSent = await onSubmitPlanFollowUp({
746
+ text: followUp.text,
747
+ context: buildMessageContext({
748
+ terminalContexts: sendableComposerTerminalContexts,
749
+ reviewComments: composerReviewComments,
750
+ previewAnnotations: composerPreviewAnnotations,
751
+ threadContexts: composerThreadContexts,
752
+ }),
753
+ interactionMode: followUp.interactionMode,
754
+ });
755
+ if (!followUpSent) {
756
+ promptRef.current = followUpPromptSnapshot;
757
+ composerTerminalContextsRef.current = [...followUpTerminalContexts];
758
+ restorePlanFollowUpComposer({
759
+ snapshot: {
760
+ prompt: followUpPromptSnapshot,
761
+ terminalContexts: followUpTerminalContexts,
762
+ reviewComments: followUpReviewComments,
763
+ previewAnnotations: followUpPreviewAnnotations,
764
+ threadContexts: followUpThreadContexts,
765
+ },
766
+ writePrompt: (prompt) => setComposerDraftPrompt(composerDraftTarget, prompt),
767
+ writeTerminalContexts: (contexts) =>
768
+ setComposerDraftTerminalContexts(composerDraftTarget, [...contexts]),
769
+ writeReviewComments: (comments) =>
770
+ setComposerDraftReviewComments(composerDraftTarget, [...comments]),
771
+ writePreviewAnnotations: (annotations) =>
772
+ setComposerDraftPreviewAnnotations(composerDraftTarget, [...annotations]),
773
+ writeThreadContexts: (records) =>
774
+ setComposerDraftThreadContexts(composerDraftTarget, [...records]),
775
+ resetCursor: (options) => composerRef.current?.resetCursorState(options),
776
+ });
777
+ } else if (
778
+ submissionIntent === "background" &&
779
+ currentRouteThreadKeyRef.current === routeThreadKey
780
+ ) {
781
+ handleNewThreadInActiveProject();
782
+ }
783
+ return;
784
+ }
785
+ const standaloneSlashCommand =
786
+ sendInteractionModeEnabled &&
787
+ composerImages.length === 0 &&
788
+ composerFiles.length === 0 &&
789
+ sendableComposerTerminalContexts.length === 0 &&
790
+ composerPreviewAnnotations.length === 0 &&
791
+ composerReviewComments.length === 0 &&
792
+ composerThreadContexts.length === 0
793
+ ? parseStandaloneComposerSlashCommand(trimmed)
794
+ : null;
795
+ if (standaloneSlashCommand && multipleModelSelections === null) {
796
+ handleInteractionModeChange(standaloneSlashCommand);
797
+ promptRef.current = "";
798
+ clearComposerDraftContent(composerDraftTarget);
799
+ composerRef.current?.resetCursorState();
800
+ return;
801
+ }
802
+ if (!hasSendableContent) {
803
+ if (expiredTerminalContextCount > 0) {
804
+ const toastCopy = buildExpiredTerminalContextToastCopy(
805
+ expiredTerminalContextCount,
806
+ "empty",
807
+ );
808
+ toastManager.add(
809
+ stackedThreadToast({
810
+ type: "warning",
811
+ title: toastCopy.title,
812
+ description: toastCopy.description,
813
+ }),
814
+ );
815
+ }
816
+ return;
817
+ }
818
+ if (!activeProject) {
819
+ toastManager.add(
820
+ stackedThreadToast({
821
+ type: "warning",
822
+ title: "Choose a project first",
823
+ description: "This draft no longer points to an available project.",
824
+ }),
825
+ );
826
+ return;
827
+ }
828
+ const threadIdForSend = activeThread.id;
829
+ const sendSnapshot = snapshotComposerSend({
830
+ prompt: promptForSend,
831
+ images: composerImages,
832
+ files: composerFiles,
833
+ terminalContexts: composerTerminalContexts,
834
+ sendableTerminalContexts: sendableComposerTerminalContexts,
835
+ previewAnnotations: composerPreviewAnnotations,
836
+ reviewComments: composerReviewComments,
837
+ threadContexts: composerThreadContexts,
838
+ });
839
+ const {
840
+ files: composerFilesSnapshot,
841
+ attachments: composerAttachmentsSnapshot,
842
+ terminalContexts: composerTerminalContextsSnapshot,
843
+ previewAnnotations: composerPreviewAnnotationsSnapshot,
844
+ reviewComments: composerReviewCommentsSnapshot,
845
+ threadContexts: composerThreadContextsSnapshot,
846
+ messageText: messageTextForSend,
847
+ } = sendSnapshot;
848
+ const {
849
+ missingWorktreeBaseBranch,
850
+ baseBranchForWorktree,
851
+ compactBeforeSend,
852
+ turnDispatchMode,
853
+ shouldQueueBehindActiveRun,
854
+ } = planComposerTurn({
855
+ messageText: messageTextForSend,
856
+ sendQueuesBehindSetup,
857
+ isServerThread,
858
+ activeMessageCount,
859
+ sendEnvMode,
860
+ worktreePath: activeThread.worktreePath,
861
+ activeThreadBranch,
862
+ resumeCompactionTokens,
863
+ keepFullHistory,
864
+ phase,
865
+ dispatchMode,
866
+ });
867
+ if (missingWorktreeBaseBranch) {
868
+ setThreadError(threadIdForSend, "Select a base branch before sending in New worktree mode.");
869
+ return;
870
+ }
871
+ // Records bind attachments by the id each side knows: the local id for the optimistic
872
+ // row, the upload id (or local id on the data-URL path) on the wire; the server
873
+ // rebinds them to the persisted id.
874
+ const buildOutgoingMessageContext = (attachmentIds: ReadonlyArray<string>) =>
875
+ buildMessageContext({
876
+ terminalContexts: composerTerminalContextsSnapshot,
877
+ reviewComments: composerReviewCommentsSnapshot,
878
+ previewAnnotations: composerPreviewAnnotationsSnapshot,
879
+ threadContexts: composerThreadContextsSnapshot,
880
+ attachments: composerAttachmentsSnapshot.map((attachment, index) => ({
881
+ attachment,
882
+ attachmentId: attachmentIds[index] ?? attachment.id,
883
+ })),
884
+ });
885
+ const outgoingMessageContext = buildOutgoingMessageContext(
886
+ composerAttachmentsSnapshot.map((attachment) => attachment.id),
887
+ );
888
+ const messageIdForSend = newMessageId();
889
+ const messageCreatedAt = new Date().toISOString();
890
+ const outgoingMessageText = formatOutgoingPrompt({
891
+ provider: ctxSelectedProvider,
892
+ model: ctxSelectedModel,
893
+ models: ctxSelectedProviderModels,
894
+ effort: ctxSelectedPromptEffort,
895
+ text: messageTextForSend || ATTACHMENT_ONLY_BOOTSTRAP_PROMPT,
896
+ });
897
+ if (composerRef.current?.validateProviderInput(outgoingMessageText) === false) {
898
+ return;
899
+ }
900
+
901
+ const readLiveAttachmentCapabilities = () => {
902
+ const config = appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId) ?? null;
903
+ const liveSupportsAttachmentUploads =
904
+ config?.environment.capabilities.attachmentUploads === true;
905
+ return {
906
+ supportsAttachmentUploads: liveSupportsAttachmentUploads,
907
+ fileBlockReason: fileAttachmentCapabilityBlockReason({
908
+ files: composerFilesSnapshot,
909
+ attachmentUploadsCapabilityKnown: config !== null,
910
+ supportsAttachmentUploads: liveSupportsAttachmentUploads,
911
+ maxFileAttachmentBytes:
912
+ config?.environment.capabilities.fileAttachments?.maxUploadBytes ?? null,
913
+ }),
914
+ };
915
+ };
916
+
917
+ const multipleTargets: MultipleModelTarget[] = [];
918
+ for (const resolved of resolveMultipleModelTargets({
919
+ selections: multipleModelSelections ?? [],
920
+ providerInstanceEntries,
921
+ messageText: messageTextForSend,
922
+ planModeEnabled: settings.planModeEnabled,
923
+ interactionMode: sendInteractionMode,
924
+ })) {
925
+ if ("error" in resolved) {
926
+ setThreadError(threadIdForSend, resolved.error);
927
+ return;
928
+ }
929
+ if (composerRef.current?.validateProviderInput(resolved.text) === false) return;
930
+ multipleTargets.push(resolved);
931
+ }
932
+
933
+ sendInFlightRef.current = true;
934
+ const sendGeneration = ++composerSendGenerationRef.current;
935
+ const attachmentCapabilitiesBeforeUpload = readLiveAttachmentCapabilities();
936
+ if (attachmentCapabilitiesBeforeUpload.fileBlockReason !== null) {
937
+ sendInFlightRef.current = false;
938
+ setThreadError(threadIdForSend, attachmentCapabilitiesBeforeUpload.fileBlockReason);
939
+ return;
940
+ }
941
+ const turnUsesAttachmentUploads =
942
+ composerFilesSnapshot.length > 0
943
+ ? attachmentCapabilitiesBeforeUpload.supportsAttachmentUploads
944
+ : supportsAttachmentUploads;
945
+ if (turnUsesAttachmentUploads && composerAttachmentsSnapshot.length > 0) {
946
+ for (const attachment of composerAttachmentsSnapshot) {
947
+ const upload =
948
+ readAttachmentUpload(attachment.id)?.status === "failed"
949
+ ? retryAttachmentUpload
950
+ : startAttachmentUpload;
951
+ upload({
952
+ environmentId,
953
+ image: attachment,
954
+ draftTarget: composerDraftTarget,
955
+ });
956
+ }
957
+ await awaitAttachmentUploads(composerAttachmentsSnapshot.map((attachment) => attachment.id));
958
+ const attachmentCapabilitiesAfterUpload = readLiveAttachmentCapabilities();
959
+ if (attachmentCapabilitiesAfterUpload.fileBlockReason !== null) {
960
+ sendInFlightRef.current = false;
961
+ setThreadError(threadIdForSend, attachmentCapabilitiesAfterUpload.fileBlockReason);
962
+ return;
963
+ }
964
+ if (getUploadedAttachments({ environmentId, images: composerAttachmentsSnapshot }) === null) {
965
+ sendInFlightRef.current = false;
966
+ setThreadError(threadIdForSend, "Retry or remove failed uploads before sending.");
967
+ return;
968
+ }
969
+ }
970
+
971
+ if (
972
+ multipleModelSelections === null &&
973
+ shouldDockDraftHeroForSubmission({ isDraftHeroState, activeThreadKey, submissionIntent }) &&
974
+ activeThreadKey
975
+ ) {
976
+ let resolveDockStarted: (() => void) | undefined;
977
+ const dockStarted = new Promise<void>((resolve) => {
978
+ resolveDockStarted = resolve;
979
+ });
980
+ const dockTransition = runMobileComposerTransition(
981
+ () => {
982
+ flushSync(() => {
983
+ captureDraftHeroComposerRect();
984
+ setDockedDraftHeroThreadKey(activeThreadKey);
985
+ });
986
+ resolveDockStarted?.();
987
+ },
988
+ {
989
+ active: panelAnimationsActive,
990
+ durationMs: panelAnimationDurationMs,
991
+ },
992
+ );
993
+ void dockTransition.catch(() => resolveDockStarted?.());
994
+ await dockStarted;
995
+ }
996
+
997
+ const attachmentCapabilitiesBeforeDispatch = readLiveAttachmentCapabilities();
998
+ if (
999
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
1000
+ attachmentCapabilitiesBeforeDispatch.fileBlockReason !== null
1001
+ ) {
1002
+ sendInFlightRef.current = false;
1003
+ setThreadError(
1004
+ threadIdForSend,
1005
+ attachmentCapabilitiesBeforeDispatch.fileBlockReason ??
1006
+ "This connection cannot change threads.",
1007
+ );
1008
+ setDockedDraftHeroThreadKey((currentThreadKey) =>
1009
+ currentThreadKey === activeThreadKey ? null : currentThreadKey,
1010
+ );
1011
+ return;
1012
+ }
1013
+ // A message sent while approvals are pending redirects the agent. They are declined only
1014
+ // here, after everything above has accepted the send, so local commands and rejected
1015
+ // drafts leave them alone. After navigating away during an upload, the shown approvals
1016
+ // are another thread's, so this send leaves them alone too.
1017
+ const approvalsToDecline =
1018
+ currentRouteThreadKeyRef.current === routeThreadKey
1019
+ ? pendingApprovalsRef.current.filter((approval) =>
1020
+ sendCtx?.shownPendingApprovalIds.includes(approval.requestId),
1021
+ )
1022
+ : [];
1023
+ if (approvalsToDecline.length > 0) {
1024
+ // A draft edited since send, or a paste still landing in it, is no longer the message
1025
+ // the user sent.
1026
+ const attachmentIdsAtSend = composerAttachmentsSnapshot.map((attachment) => attachment.id);
1027
+ // A direct annotation send writes its image and reference into the draft as it sends,
1028
+ // so the live draft may still lack them; anything else differing is a real edit.
1029
+ const annotationImageId = directAnnotation?.image?.id;
1030
+ const attachmentIdsBeforeAnnotation = attachmentIdsAtSend.filter(
1031
+ (id) => id !== annotationImageId,
1032
+ );
1033
+ const sameIds = (left: ReadonlyArray<string>, right: ReadonlyArray<string>) =>
1034
+ left.length === right.length && left.every((id, index) => id === right[index]);
1035
+ const draftChangedSinceSend = () => {
1036
+ if (composerRef.current?.hasPendingAttachments() === true) return true;
1037
+ const sendContext = composerRef.current?.getSendContext();
1038
+ const attachmentIds = sendContext
1039
+ ? [...sendContext.images, ...sendContext.files].map((attachment) => attachment.id)
1040
+ : attachmentIdsAtSend;
1041
+ const promptUnchanged =
1042
+ promptRef.current === promptAtSend || promptRef.current === promptForSend;
1043
+ const attachmentsUnchanged =
1044
+ sameIds(attachmentIds, attachmentIdsAtSend) ||
1045
+ (annotationImageId !== undefined &&
1046
+ sameIds(attachmentIds, attachmentIdsBeforeAnnotation));
1047
+ return !promptUnchanged || !attachmentsUnchanged;
1048
+ };
1049
+ const draftBeforeDecline = useComposerDraftStore
1050
+ .getState()
1051
+ .getComposerDraft(composerDraftTarget);
1052
+ const changedBeforeDecline = draftChangedSinceSend();
1053
+ const pendingIdsBeforeDecline = pendingApprovalsRef.current.map(
1054
+ (approval) => approval.requestId,
1055
+ );
1056
+ const approvalResponding = approvalsToDecline.some((approval) =>
1057
+ respondingRequestIdsRef.current.includes(approval.requestId),
1058
+ );
1059
+ const declined =
1060
+ !changedBeforeDecline &&
1061
+ !approvalResponding &&
1062
+ (await declinePendingApprovals(approvalsToDecline, onRespondToApprovalStable).catch(
1063
+ () => false,
1064
+ ));
1065
+ const draftChanged =
1066
+ changedBeforeDecline ||
1067
+ draftChangedSinceSend() ||
1068
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) !==
1069
+ draftBeforeDecline;
1070
+ // An approval that arrived during the decline would block the redirect; keep the draft so
1071
+ // the next send declines it too.
1072
+ const approvalArrived = pendingApprovalsRef.current.some(
1073
+ (approval) => !pendingIdsBeforeDecline.includes(approval.requestId),
1074
+ );
1075
+ if (
1076
+ !declined ||
1077
+ draftChanged ||
1078
+ approvalArrived ||
1079
+ currentRouteThreadKeyRef.current !== routeThreadKey
1080
+ ) {
1081
+ sendInFlightRef.current = false;
1082
+ setDockedDraftHeroThreadKey((currentThreadKey) =>
1083
+ currentThreadKey === activeThreadKey ? null : currentThreadKey,
1084
+ );
1085
+ if (draftChanged || approvalResponding || (declined && approvalArrived)) {
1086
+ toastManager.add({
1087
+ type: "info",
1088
+ title: draftChanged
1089
+ ? declined
1090
+ ? "Approval declined. Your message changed, so it wasn't sent."
1091
+ : "Your message changed, so it wasn't sent."
1092
+ : approvalResponding
1093
+ ? "An approval is already being answered, so your message wasn't sent."
1094
+ : "Another approval arrived, so your message wasn't sent.",
1095
+ description: "Send again when it's ready.",
1096
+ });
1097
+ }
1098
+ return;
1099
+ }
1100
+ }
1101
+ if (sendQueuesBehindSetup) {
1102
+ setSetupQueueSendThreadKey(activeThreadKey);
1103
+ } else {
1104
+ beginLocalDispatch({
1105
+ preparingWorktree: multipleModelSelections !== null || Boolean(baseBranchForWorktree),
1106
+ submissionIntent:
1107
+ submissionIntent === "background" && !isLocalDraftThread
1108
+ ? "foreground"
1109
+ : submissionIntent,
1110
+ });
1111
+ beginWorktreeSetup(
1112
+ multipleModelSelections === null && baseBranchForWorktree
1113
+ ? { environmentId: activeThread.environmentId, threadId: threadIdForSend }
1114
+ : null,
1115
+ );
1116
+ }
1117
+
1118
+ const turnAttachmentsPromise = Promise.all(
1119
+ composerAttachmentsSnapshot.map(async (attachment) => {
1120
+ if (turnUsesAttachmentUploads) {
1121
+ const uploaded = getUploadedAttachments({ environmentId, images: [attachment] })?.[0];
1122
+ if (!uploaded) {
1123
+ throw new Error(`Attachment '${attachment.name}' did not finish uploading.`);
1124
+ }
1125
+ return uploaded;
1126
+ }
1127
+ if (attachment.type !== "image") {
1128
+ throw new Error("This server does not support file attachments.");
1129
+ }
1130
+ return {
1131
+ type: "image" as const,
1132
+ id: attachment.id,
1133
+ name: attachment.name,
1134
+ mimeType: attachment.mimeType,
1135
+ sizeBytes: attachment.sizeBytes,
1136
+ dataUrl: await readFileAsDataUrl(attachment.file),
1137
+ ...(attachment.source ? { source: attachment.source } : {}),
1138
+ };
1139
+ }),
1140
+ );
1141
+ if (multipleModelSelections !== null) {
1142
+ const failedSelections: ModelSelection[] = [];
1143
+ let clearedDraft = false;
1144
+ let releasedComposer = false;
1145
+ let canRestoreDraft = () => false;
1146
+ let startedCount = 0;
1147
+ // Anything thrown here (an attachment the server can no longer take)
1148
+ // fails every selection; the draft restore below still runs.
1149
+ const sendResult = await settlePromise(async () => {
1150
+ const attachments = await turnAttachmentsPromise;
1151
+ const fileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
1152
+ if (fileBlockReason !== null) throw new Error(fileBlockReason);
1153
+ const context = buildOutgoingMessageContext(
1154
+ boundAttachmentIds(attachments, composerAttachmentsSnapshot),
1155
+ );
1156
+ const title = deriveThreadTitleSeed({
1157
+ text: messageTextForSend,
1158
+ attachments: composerAttachmentsSnapshot,
1159
+ });
1160
+ promptRef.current = "";
1161
+ clearComposerDraftContent(composerDraftTarget);
1162
+ composerRef.current?.resetCursorState();
1163
+ clearedDraft = true;
1164
+ const clearedDraftSnapshot = useComposerDraftStore
1165
+ .getState()
1166
+ .getComposerDraft(composerDraftTarget);
1167
+ const submittedSelections = readMultipleModelSelections();
1168
+ canRestoreDraft = () =>
1169
+ currentRouteThreadKeyRef.current === routeThreadKey &&
1170
+ composerSendGenerationRef.current === sendGeneration &&
1171
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget) ===
1172
+ clearedDraftSnapshot &&
1173
+ readMultipleModelSelections() === submittedSelections;
1174
+ setThreadError(threadIdForSend, null);
1175
+ const starts = Promise.all(
1176
+ multipleTargets.map(async (target) => {
1177
+ const started = await startFanoutThread({
1178
+ retryKey: JSON.stringify([
1179
+ routeThreadKey,
1180
+ target.selection.instanceId,
1181
+ target.selection.model,
1182
+ ]),
1183
+ model: target.selection.model,
1184
+ uncertainSubmissions: uncertainMultipleSubmissionsRef.current,
1185
+ start: (targetThreadId) => {
1186
+ const supportsInlineMessageContext =
1187
+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
1188
+ .capabilities.inlineMessageContext === true;
1189
+ return startThreadTurn({
1190
+ environmentId,
1191
+ input: {
1192
+ threadId: targetThreadId,
1193
+ message: {
1194
+ messageId: newMessageId(),
1195
+ role: "user",
1196
+ attachments,
1197
+ ...withMessageContext({
1198
+ text: target.text,
1199
+ context,
1200
+ supportsInlineMessageContext,
1201
+ }),
1202
+ },
1203
+ modelSelection: target.selection,
1204
+ titleSeed: title,
1205
+ runtimeMode,
1206
+ interactionMode: target.interactionMode,
1207
+ bootstrap: {
1208
+ createThread: {
1209
+ projectId: activeProject.id,
1210
+ title,
1211
+ modelSelection: target.selection,
1212
+ runtimeMode,
1213
+ interactionMode: target.interactionMode,
1214
+ branch: activeThreadBranch,
1215
+ worktreePath: null,
1216
+ createdAt: messageCreatedAt,
1217
+ },
1218
+ prepareWorktree: {
1219
+ projectCwd: activeProject.workspaceRoot,
1220
+ baseBranch: activeThreadBranch!,
1221
+ requireWorktree: true,
1222
+ ...(startFromOrigin ? { startFromOrigin: true } : {}),
1223
+ },
1224
+ runSetupScript: true,
1225
+ },
1226
+ createdAt: messageCreatedAt,
1227
+ },
1228
+ });
1229
+ },
1230
+ openThread: (threadId) =>
1231
+ void navigate({
1232
+ to: "/$environmentId/$threadId",
1233
+ params: buildThreadRouteParams(scopeThreadRef(environmentId, threadId)),
1234
+ }),
1235
+ });
1236
+ if (started) startedCount += 1;
1237
+ else failedSelections.push(target.selection);
1238
+ }),
1239
+ );
1240
+ sendInFlightRef.current = false;
1241
+ resetLocalDispatch();
1242
+ releasedComposer = true;
1243
+ await starts;
1244
+ if (startedCount > 0) {
1245
+ toastManager.add(
1246
+ stackedThreadToast({
1247
+ type: "success",
1248
+ title: `Started ${startedCount} ${startedCount === 1 ? "thread" : "threads"} in background`,
1249
+ }),
1250
+ );
1251
+ }
1252
+ if (failedSelections.length === 0 && turnUsesAttachmentUploads) {
1253
+ releaseDraftAttachments(composerAttachmentsSnapshot);
1254
+ }
1255
+ });
1256
+ if (sendResult._tag === "Failure") {
1257
+ const error = squashAtomCommandFailure(sendResult);
1258
+ failedSelections.push(...multipleModelSelections);
1259
+ setThreadError(
1260
+ threadIdForSend,
1261
+ error instanceof Error ? error.message : "Failed to send messages.",
1262
+ );
1263
+ }
1264
+ const restoreFailedDraft = () => {
1265
+ setMultipleModelSelections(failedSelections);
1266
+ if (clearedDraft) {
1267
+ restoreComposerDraft(composerDraftTarget, sendSnapshot);
1268
+ if (composerRef.current && currentRouteThreadKeyRef.current === routeThreadKey) {
1269
+ promptRef.current = messageTextForSend;
1270
+ composerRef.current.resetCursorState({
1271
+ cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
1272
+ prompt: messageTextForSend,
1273
+ detectTrigger: true,
1274
+ });
1275
+ }
1276
+ }
1277
+ };
1278
+ if (failedSelections.length > 0) {
1279
+ if (canRestoreDraft() && composerRef.current) {
1280
+ restoreFailedDraft();
1281
+ } else if (clearedDraft) {
1282
+ const recoveryToastId = toastManager.add(
1283
+ stackedThreadToast({
1284
+ type: "error",
1285
+ title: "A background prompt could not be sent",
1286
+ description:
1287
+ "Your newer draft is unchanged. Restore the failed prompt when this composer is empty.",
1288
+ timeout: 0,
1289
+ actionProps: {
1290
+ children: "Restore prompt",
1291
+ onClick: () => {
1292
+ if (
1293
+ !draftId ||
1294
+ !useComposerDraftStore.getState().getDraftSession(draftId) ||
1295
+ sendInFlightRef.current ||
1296
+ composerDraftHasUserContent(
1297
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
1298
+ )
1299
+ ) {
1300
+ toastManager.update(recoveryToastId, {
1301
+ description:
1302
+ "Return to the original draft and send or clear its current prompt before restoring.",
1303
+ });
1304
+ return;
1305
+ }
1306
+ restoreFailedDraft();
1307
+ void navigate({ to: "/draft/$draftId", params: { draftId } });
1308
+ toastManager.close(recoveryToastId);
1309
+ },
1310
+ },
1311
+ }),
1312
+ );
1313
+ }
1314
+ }
1315
+ if (!releasedComposer) {
1316
+ sendInFlightRef.current = false;
1317
+ resetLocalDispatch();
1318
+ }
1319
+ return;
1320
+ }
1321
+ const optimisticAttachments = optimisticMessageAttachments(composerAttachmentsSnapshot);
1322
+ if (!shouldQueueBehindActiveRun) {
1323
+ anchorNewTurn(
1324
+ scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
1325
+ messageIdForSend,
1326
+ );
1327
+ }
1328
+ setOptimisticUserMessages((existing) => [
1329
+ ...existing,
1330
+ {
1331
+ id: messageIdForSend,
1332
+ role: "user",
1333
+ text: outgoingMessageText,
1334
+ ...(optimisticAttachments.length > 0 ? { attachments: optimisticAttachments } : {}),
1335
+ ...(outgoingMessageContext !== undefined ? { context: outgoingMessageContext } : {}),
1336
+ runId: null,
1337
+ createdAt: messageCreatedAt,
1338
+ updatedAt: messageCreatedAt,
1339
+ streaming: false,
1340
+ ...(shouldQueueBehindActiveRun
1341
+ ? { inputIntent: "queued_turn" as const }
1342
+ : phase === "running" && dispatchMode === "steer"
1343
+ ? { inputIntent: "steer" as const }
1344
+ : {}),
1345
+ },
1346
+ ]);
1347
+ setThreadError(threadIdForSend, null);
1348
+ if (expiredTerminalContextCount > 0) {
1349
+ const toastCopy = buildExpiredTerminalContextToastCopy(
1350
+ expiredTerminalContextCount,
1351
+ "omitted",
1352
+ );
1353
+ toastManager.add(
1354
+ stackedThreadToast({
1355
+ type: "warning",
1356
+ title: toastCopy.title,
1357
+ description: toastCopy.description,
1358
+ }),
1359
+ );
1360
+ }
1361
+ const sentDraftThreadRef = isLocalDraftThread
1362
+ ? scopeThreadRef(environmentId, threadIdForSend)
1363
+ : null;
1364
+ // Keep new-thread flows from reusing this draft while attachments and worktree setup settle.
1365
+ if (sentDraftThreadRef) markPromotedDraftThreadByRef(sentDraftThreadRef);
1366
+ promptRef.current = "";
1367
+ clearComposerDraftContent(composerDraftTarget);
1368
+ composerRef.current?.resetCursorState();
1369
+
1370
+ const title = deriveThreadTitleSeed({
1371
+ text: messageTextForSend,
1372
+ attachments: composerAttachmentsSnapshot,
1373
+ fallbackLabels: sendTitleFallbackLabels(sendSnapshot),
1374
+ });
1375
+ const threadCreateModelSelection = createModelSelection(
1376
+ ctxSelectedModelSelection.instanceId,
1377
+ ctxSelectedModel || activeProjectDefaultModelSelection?.model || DEFAULT_MODEL,
1378
+ ctxSelectedModelSelection.options,
1379
+ );
1380
+
1381
+ let failure: AtomCommandResult<unknown, unknown> | null = null;
1382
+
1383
+ if (failure === null && isServerThread) {
1384
+ const settingsResult = await persistThreadSettingsForNextTurn({
1385
+ threadId: threadIdForSend,
1386
+ createdAt: messageCreatedAt,
1387
+ ...(localCheckoutBranchMismatch
1388
+ ? { branch: localCheckoutBranchMismatch.currentBranch }
1389
+ : {}),
1390
+ runtimeMode,
1391
+ interactionMode: sendInteractionMode,
1392
+ });
1393
+ if (settingsResult._tag === "Failure") {
1394
+ failure = settingsResult;
1395
+ }
1396
+ }
1397
+
1398
+ const turnAttachmentsResult = await settlePromise(async () => {
1399
+ const turnAttachments = await turnAttachmentsPromise;
1400
+ const liveFileBlockReason = readLiveAttachmentCapabilities().fileBlockReason;
1401
+ if (liveFileBlockReason !== null) {
1402
+ throw new Error(liveFileBlockReason);
1403
+ }
1404
+ return turnAttachments;
1405
+ });
1406
+ if (failure === null && turnAttachmentsResult._tag === "Failure") {
1407
+ failure = turnAttachmentsResult;
1408
+ }
1409
+
1410
+ if (failure === null && compactBeforeSend) {
1411
+ const compactResult = await startThreadTurn({
1412
+ environmentId,
1413
+ input: {
1414
+ threadId: threadIdForSend,
1415
+ message: { messageId: newMessageId(), role: "user", text: "/compact", attachments: [] },
1416
+ modelSelection: ctxSelectedModelSelection,
1417
+ runtimeMode,
1418
+ interactionMode: sendInteractionMode,
1419
+ },
1420
+ });
1421
+ if (compactResult._tag === "Failure") {
1422
+ failure = compactResult;
1423
+ }
1424
+ }
1425
+
1426
+ let backgroundDraftOpened = false;
1427
+ let turnStartSucceeded = false;
1428
+ if (failure === null && turnAttachmentsResult._tag === "Success") {
1429
+ const bootstrap =
1430
+ isLocalDraftThread || baseBranchForWorktree
1431
+ ? {
1432
+ ...(isLocalDraftThread
1433
+ ? {
1434
+ createThread: {
1435
+ projectId: activeProject.id,
1436
+ title,
1437
+ modelSelection: threadCreateModelSelection,
1438
+ runtimeMode,
1439
+ interactionMode: sendInteractionMode,
1440
+ branch: activeThreadBranch,
1441
+ worktreePath: activeThread.worktreePath,
1442
+ createdAt: activeThread.createdAt,
1443
+ },
1444
+ }
1445
+ : {}),
1446
+ ...(baseBranchForWorktree
1447
+ ? {
1448
+ prepareWorktree: {
1449
+ projectCwd: activeProject.workspaceRoot,
1450
+ baseBranch: baseBranchForWorktree,
1451
+ ...(startFromOrigin ? { startFromOrigin: true } : {}),
1452
+ },
1453
+ runSetupScript: true,
1454
+ }
1455
+ : {}),
1456
+ }
1457
+ : undefined;
1458
+ const backgroundThreadRef =
1459
+ submissionIntent === "background" && isLocalDraftThread
1460
+ ? scopeThreadRef(environmentId, threadIdForSend)
1461
+ : null;
1462
+ if (backgroundThreadRef) beginBackgroundDraftSubmissionByRef(backgroundThreadRef);
1463
+ const startPromise = startThreadTurn({
1464
+ environmentId,
1465
+ input: {
1466
+ threadId: threadIdForSend,
1467
+ message: {
1468
+ messageId: messageIdForSend,
1469
+ role: "user",
1470
+ attachments: turnAttachmentsResult.value,
1471
+ ...withMessageContext({
1472
+ text: outgoingMessageText,
1473
+ context: buildOutgoingMessageContext(
1474
+ boundAttachmentIds(turnAttachmentsResult.value, composerAttachmentsSnapshot),
1475
+ ),
1476
+ // Read at dispatch time: the upload and persistence awaits above can
1477
+ // span a server reconnect that changes it.
1478
+ supportsInlineMessageContext:
1479
+ appAtomRegistry.get(environmentServerConfigsAtom).get(environmentId)?.environment
1480
+ .capabilities.inlineMessageContext === true,
1481
+ }),
1482
+ },
1483
+ modelSelection: ctxSelectedModelSelection,
1484
+ titleSeed: title,
1485
+ runtimeMode,
1486
+ interactionMode: sendInteractionMode,
1487
+ dispatchMode: turnDispatchMode,
1488
+ ...(bootstrap ? { bootstrap } : {}),
1489
+ createdAt: messageCreatedAt,
1490
+ },
1491
+ });
1492
+ if (backgroundThreadRef) {
1493
+ try {
1494
+ backgroundDraftOpened = Boolean(
1495
+ await handleNewThread(
1496
+ scopeProjectRef(activeProject.environmentId, activeProject.id),
1497
+ resolveBackgroundDraftWorkspaceOptions({
1498
+ envMode: sendEnvMode,
1499
+ branch: activeThreadBranch,
1500
+ startFromOrigin,
1501
+ }),
1502
+ ),
1503
+ );
1504
+ } catch (error) {
1505
+ clearBackgroundDraftSubmissionByRef(backgroundThreadRef);
1506
+ toastManager.add(
1507
+ stackedThreadToast({
1508
+ type: "warning",
1509
+ title: "Could not open a fresh composer",
1510
+ description: error instanceof Error ? error.message : undefined,
1511
+ }),
1512
+ );
1513
+ }
1514
+ }
1515
+ const startResult = await startPromise;
1516
+ if (startResult._tag === "Failure") {
1517
+ failure = startResult;
1518
+ } else {
1519
+ turnStartSucceeded = true;
1520
+ setKeepFullHistory(routeThreadKey, false);
1521
+ clearUsageLimitsFor(routeThreadKey);
1522
+ if (turnUsesAttachmentUploads) {
1523
+ releaseDraftAttachments(composerAttachmentsSnapshot);
1524
+ }
1525
+ acknowledgeActiveThreadWoke();
1526
+ // A draft still on screen finalizes once its thread route takes over.
1527
+ if (sentDraftThreadRef) {
1528
+ if (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey) {
1529
+ finalizePromotedDraftThreadByRef(sentDraftThreadRef);
1530
+ } else {
1531
+ clearBackgroundDraftSubmissionByRef(sentDraftThreadRef);
1532
+ }
1533
+ }
1534
+ if (backgroundThreadRef) {
1535
+ if (backgroundDraftOpened) {
1536
+ toastManager.add(
1537
+ stackedThreadToast({
1538
+ type: "success",
1539
+ title: "Started in background",
1540
+ timeout: 5_000,
1541
+ actionProps: {
1542
+ children: "Open",
1543
+ onClick: () => {
1544
+ void navigate({
1545
+ to: "/$environmentId/$threadId",
1546
+ params: buildThreadRouteParams(backgroundThreadRef),
1547
+ });
1548
+ },
1549
+ },
1550
+ }),
1551
+ );
1552
+ }
1553
+ } else if (
1554
+ submissionIntent === "background" &&
1555
+ currentRouteThreadKeyRef.current === routeThreadKey
1556
+ ) {
1557
+ handleNewThreadInActiveProject();
1558
+ }
1559
+ }
1560
+ }
1561
+
1562
+ if (failure !== null) {
1563
+ if (isLocalDraftThread && draftId && draftThread) {
1564
+ restoreFailedDraftThread(
1565
+ draftId,
1566
+ draftThread,
1567
+ wasBootstrapThreadDeleted(squashAtomCommandFailure(failure))
1568
+ ? newThreadId()
1569
+ : threadIdForSend,
1570
+ );
1571
+ clearBackgroundDraftSubmissionByRef(scopeThreadRef(environmentId, threadIdForSend));
1572
+ }
1573
+ if (
1574
+ !composerDraftHasUserContent(
1575
+ useComposerDraftStore.getState().getComposerDraft(composerDraftTarget),
1576
+ )
1577
+ ) {
1578
+ setOptimisticUserMessages((existing) => {
1579
+ const removed = existing.filter((message) => message.id === messageIdForSend);
1580
+ for (const message of removed) {
1581
+ revokeUserMessagePreviewUrls(message);
1582
+ }
1583
+ const next = existing.filter((message) => message.id !== messageIdForSend);
1584
+ return next.length === existing.length ? existing : next;
1585
+ });
1586
+ const retryComposerImages = restoreComposerDraft(composerDraftTarget, sendSnapshot);
1587
+ if (currentRouteThreadKeyRef.current === routeThreadKey) {
1588
+ promptRef.current = messageTextForSend;
1589
+ composerImagesRef.current = retryComposerImages;
1590
+ composerFilesRef.current = composerFilesSnapshot;
1591
+ composerTerminalContextsRef.current = composerTerminalContextsSnapshot;
1592
+ composerRef.current?.resetCursorState({
1593
+ cursor: collapseExpandedComposerCursor(messageTextForSend, messageTextForSend.length),
1594
+ prompt: messageTextForSend,
1595
+ detectTrigger: true,
1596
+ });
1597
+ }
1598
+ }
1599
+ if (!isAtomCommandInterrupted(failure)) {
1600
+ const error = squashAtomCommandFailure(failure);
1601
+ setThreadError(
1602
+ threadIdForSend,
1603
+ error instanceof Error ? error.message : "Failed to send message.",
1604
+ );
1605
+ if (
1606
+ draftId &&
1607
+ (backgroundDraftOpened || currentRouteThreadKeyRef.current !== routeThreadKey)
1608
+ ) {
1609
+ toastManager.add(
1610
+ stackedThreadToast({
1611
+ type: "error",
1612
+ title:
1613
+ submissionIntent === "background"
1614
+ ? "Background task failed"
1615
+ : "Could not start thread",
1616
+ description: error instanceof Error ? error.message : "Failed to send message.",
1617
+ actionProps: {
1618
+ children: "Open draft",
1619
+ onClick: () => {
1620
+ void navigate({ to: "/draft/$draftId", params: { draftId } });
1621
+ },
1622
+ },
1623
+ }),
1624
+ );
1625
+ }
1626
+ }
1627
+ }
1628
+ sendInFlightRef.current = false;
1629
+ setSetupQueueSendThreadKey((current) => (current === activeThreadKey ? null : current));
1630
+ if (!turnStartSucceeded) {
1631
+ setDockedDraftHeroThreadKey((currentThreadKey) =>
1632
+ currentThreadKey === activeThreadKey ? null : currentThreadKey,
1633
+ );
1634
+ if (!sendQueuesBehindSetup) resetLocalDispatch();
1635
+ }
1636
+ };
1637
+
1638
+ async function onSubmitPlanFollowUp({
1639
+ text,
1640
+ context,
1641
+ interactionMode: nextInteractionMode,
1642
+ }: {
1643
+ text: string;
1644
+ context?: ReturnType<typeof buildMessageContext>;
1645
+ interactionMode: "default" | "plan";
1646
+ }) {
1647
+ if (
1648
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
1649
+ !activeThread ||
1650
+ !isServerThread ||
1651
+ isSendBusy ||
1652
+ isConnecting ||
1653
+ sendInFlightRef.current
1654
+ ) {
1655
+ return false;
1656
+ }
1657
+
1658
+ const trimmed = text.trim();
1659
+ if (!trimmed) {
1660
+ return false;
1661
+ }
1662
+
1663
+ const sendCtx = composerRef.current?.getSendContext();
1664
+ if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
1665
+ return false;
1666
+ }
1667
+ const {
1668
+ selectedProvider: ctxSelectedProvider,
1669
+ selectedModel: ctxSelectedModel,
1670
+ selectedProviderModels: ctxSelectedProviderModels,
1671
+ selectedPromptEffort: ctxSelectedPromptEffort,
1672
+ selectedModelSelection: ctxSelectedModelSelection,
1673
+ } = sendCtx;
1674
+
1675
+ const threadIdForSend = activeThread.id;
1676
+ const messageIdForSend = newMessageId();
1677
+ const messageCreatedAt = new Date().toISOString();
1678
+ const outgoingMessageText = formatOutgoingPrompt({
1679
+ provider: ctxSelectedProvider,
1680
+ model: ctxSelectedModel,
1681
+ models: ctxSelectedProviderModels,
1682
+ effort: ctxSelectedPromptEffort,
1683
+ text: trimmed,
1684
+ });
1685
+
1686
+ sendInFlightRef.current = true;
1687
+ beginLocalDispatch({ preparingWorktree: false });
1688
+ setThreadError(threadIdForSend, null);
1689
+
1690
+ anchorNewTurn(
1691
+ scopedThreadKey(scopeThreadRef(activeThread.environmentId, threadIdForSend)),
1692
+ messageIdForSend,
1693
+ );
1694
+
1695
+ setOptimisticUserMessages((existing) => [
1696
+ ...existing,
1697
+ {
1698
+ id: messageIdForSend,
1699
+ role: "user",
1700
+ text: outgoingMessageText,
1701
+ ...(context ? { context } : {}),
1702
+ runId: null,
1703
+ createdAt: messageCreatedAt,
1704
+ updatedAt: messageCreatedAt,
1705
+ streaming: false,
1706
+ },
1707
+ ]);
1708
+
1709
+ const settingsResult = await persistThreadSettingsForNextTurn({
1710
+ threadId: threadIdForSend,
1711
+ createdAt: messageCreatedAt,
1712
+ ...(localCheckoutBranchMismatch ? { branch: localCheckoutBranchMismatch.currentBranch } : {}),
1713
+ runtimeMode,
1714
+ interactionMode: nextInteractionMode,
1715
+ });
1716
+ let failure: AtomCommandResult<unknown, unknown> | null =
1717
+ settingsResult._tag === "Failure" ? settingsResult : null;
1718
+
1719
+ if (failure === null) {
1720
+ setComposerDraftInteractionMode(
1721
+ scopeThreadRef(activeThread.environmentId, threadIdForSend),
1722
+ nextInteractionMode,
1723
+ );
1724
+
1725
+ const startResult = await startThreadTurn({
1726
+ environmentId,
1727
+ input: {
1728
+ threadId: threadIdForSend,
1729
+ message: {
1730
+ messageId: messageIdForSend,
1731
+ role: "user",
1732
+ text: outgoingMessageText,
1733
+ ...(context ? { context } : {}),
1734
+ attachments: [],
1735
+ },
1736
+ modelSelection: ctxSelectedModelSelection,
1737
+ titleSeed: activeThread.title,
1738
+ runtimeMode,
1739
+ interactionMode: nextInteractionMode,
1740
+ ...(nextInteractionMode === "default" && activeProposedPlan
1741
+ ? {
1742
+ sourceProposedPlan: {
1743
+ threadId: activeThread.id,
1744
+ planId: activeProposedPlan.id,
1745
+ },
1746
+ }
1747
+ : {}),
1748
+ createdAt: messageCreatedAt,
1749
+ },
1750
+ });
1751
+ failure = startResult._tag === "Failure" ? startResult : null;
1752
+ }
1753
+
1754
+ if (failure === null) {
1755
+ sendInFlightRef.current = false;
1756
+ resetLocalDispatch();
1757
+ return true;
1758
+ }
1759
+
1760
+ setOptimisticUserMessages((existing) =>
1761
+ existing.filter((message) => message.id !== messageIdForSend),
1762
+ );
1763
+ if (!isAtomCommandInterrupted(failure)) {
1764
+ const error = squashAtomCommandFailure(failure);
1765
+ setThreadError(
1766
+ threadIdForSend,
1767
+ error instanceof Error ? error.message : "Failed to send plan follow-up.",
1768
+ );
1769
+ }
1770
+ sendInFlightRef.current = false;
1771
+ resetLocalDispatch();
1772
+ return false;
1773
+ }
1774
+
1775
+ const onImplementPlanInNewThread = async () => {
1776
+ if (
1777
+ !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) ||
1778
+ !activeThread ||
1779
+ !activeProject ||
1780
+ !activeProposedPlan ||
1781
+ !isServerThread ||
1782
+ isSendBusy ||
1783
+ isConnecting ||
1784
+ activeEnvironmentUnavailable ||
1785
+ sendInFlightRef.current
1786
+ ) {
1787
+ return;
1788
+ }
1789
+
1790
+ const sendCtx = composerRef.current?.getSendContext();
1791
+ if (!sendCtx?.providerAvailable || !sendCtx.interactionModeEnabled) {
1792
+ return;
1793
+ }
1794
+ const {
1795
+ selectedProvider: ctxSelectedProvider,
1796
+ selectedModel: ctxSelectedModel,
1797
+ selectedProviderModels: ctxSelectedProviderModels,
1798
+ selectedPromptEffort: ctxSelectedPromptEffort,
1799
+ selectedModelSelection: ctxSelectedModelSelection,
1800
+ } = sendCtx;
1801
+
1802
+ const createdAt = new Date().toISOString();
1803
+ const nextThreadId = newThreadId();
1804
+ const planMarkdown = activeProposedPlan.planMarkdown;
1805
+ const implementationPrompt = buildPlanImplementationPrompt(planMarkdown);
1806
+ const outgoingImplementationPrompt = formatOutgoingPrompt({
1807
+ provider: ctxSelectedProvider,
1808
+ model: ctxSelectedModel,
1809
+ models: ctxSelectedProviderModels,
1810
+ effort: ctxSelectedPromptEffort,
1811
+ text: implementationPrompt,
1812
+ });
1813
+ const nextThreadTitle = truncate(buildPlanImplementationThreadTitle(planMarkdown));
1814
+ const nextThreadModelSelection: ModelSelection = ctxSelectedModelSelection;
1815
+
1816
+ sendInFlightRef.current = true;
1817
+ beginLocalDispatch({ preparingWorktree: false });
1818
+ const finish = () => {
1819
+ sendInFlightRef.current = false;
1820
+ resetLocalDispatch();
1821
+ };
1822
+
1823
+ const createResult = await createThread({
1824
+ environmentId,
1825
+ input: {
1826
+ threadId: nextThreadId,
1827
+ projectId: activeProject.id,
1828
+ title: nextThreadTitle,
1829
+ modelSelection: nextThreadModelSelection,
1830
+ runtimeMode: defaultRuntimeMode,
1831
+ interactionMode: "default",
1832
+ branch: activeThreadBranch,
1833
+ worktreePath: activeThread.worktreePath,
1834
+ createdAt,
1835
+ },
1836
+ });
1837
+ let failure: AtomCommandResult<unknown, unknown> | null =
1838
+ createResult._tag === "Failure" ? createResult : null;
1839
+
1840
+ if (failure === null) {
1841
+ const startResult = await startThreadTurn({
1842
+ environmentId,
1843
+ input: {
1844
+ threadId: nextThreadId,
1845
+ message: {
1846
+ messageId: newMessageId(),
1847
+ role: "user",
1848
+ text: outgoingImplementationPrompt,
1849
+ attachments: [],
1850
+ },
1851
+ modelSelection: ctxSelectedModelSelection,
1852
+ titleSeed: nextThreadTitle,
1853
+ runtimeMode: defaultRuntimeMode,
1854
+ interactionMode: "default",
1855
+ sourceProposedPlan: {
1856
+ threadId: activeThread.id,
1857
+ planId: activeProposedPlan.id,
1858
+ },
1859
+ createdAt,
1860
+ },
1861
+ });
1862
+ failure = startResult._tag === "Failure" ? startResult : null;
1863
+ }
1864
+
1865
+ if (failure === null) {
1866
+ const startedResult = await settlePromise(() =>
1867
+ waitForStartedServerThread(scopeThreadRef(activeThread.environmentId, nextThreadId)),
1868
+ );
1869
+ failure = startedResult._tag === "Failure" ? startedResult : null;
1870
+ }
1871
+
1872
+ if (failure === null) {
1873
+ const navigateResult = await settlePromise(() =>
1874
+ navigate({
1875
+ to: "/$environmentId/$threadId",
1876
+ params: {
1877
+ environmentId: activeThread.environmentId,
1878
+ threadId: nextThreadId,
1879
+ },
1880
+ }),
1881
+ );
1882
+ failure = navigateResult._tag === "Failure" ? navigateResult : null;
1883
+ }
1884
+
1885
+ if (failure !== null) {
1886
+ const cleanupResult = await deleteThread({
1887
+ environmentId,
1888
+ input: {
1889
+ threadId: nextThreadId,
1890
+ },
1891
+ });
1892
+ if (cleanupResult._tag === "Failure" && !isAtomCommandInterrupted(cleanupResult)) {
1893
+ console.warn(
1894
+ "Failed to clean up implementation thread after start failure.",
1895
+ squashAtomCommandFailure(cleanupResult),
1896
+ );
1897
+ }
1898
+ if (!isAtomCommandInterrupted(failure)) {
1899
+ const error = squashAtomCommandFailure(failure);
1900
+ toastManager.add(
1901
+ stackedThreadToast({
1902
+ type: "error",
1903
+ title: "Could not start implementation thread",
1904
+ description:
1905
+ error instanceof Error
1906
+ ? error.message
1907
+ : "An error occurred while creating the new thread.",
1908
+ }),
1909
+ );
1910
+ }
1911
+ }
1912
+ finish();
1913
+ };
1914
+
1915
+ return { onSend, onResume, onImplementPlanInNewThread, isResuming };
1916
+}