import { VoiceInputSetup } from "./VoiceInputSetup";
import { useComposerTypingGuard } from "./useComposerTypingGuard";
import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences";
import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText";
import { BackgroundThreadContext } from "./backgroundThread";
import {
resolveCompatibleRuntimeMode,
runtimeModeConfig,
resolveRuntimeModeOptions,
} from "./runtimeModeConfig";
import { isLocalEnvironmentDisabled } from "../../localEnvironment";
import { usePrimaryEnvironmentId } from "../../state/environments";
import { useRightPanelStore } from "~/rightPanelStore";
import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste";
import {
questionAttachmentDraftId,
trackOpenQuestionAttachmentDraft,
useQuestionAttachmentPreparation,
} from "../../questionAttachments";
import type {
KeybindingCommand,
AssistantCitation,
ChatAttachment as ContractChatAttachment,
ChatFileAttachment,
EnvironmentId,
ModelSelection,
ProjectId,
PreviewAnnotationPayload,
ThreadContextRecord,
EnvironmentContextRecord,
ProviderInteractionMode,
ResolvedKeybindingsConfig,
RuntimeMode,
RuntimeRequestId,
ScopedThreadRef,
ServerProvider,
ThreadId,
} from "@t3tools/contracts";
import {
EnvironmentRequestInvalidError,
AuthOrchestrationOperateScope,
clampManagedRuntimeMode,
managedRuntimeModeDenial,
ProviderDriverKind,
ProviderInstanceId,
PROVIDER_SEND_TURN_MAX_ATTACHMENTS,
} from "@t3tools/contracts";
import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection";
import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime";
import * as Schema from "effect/Schema";
import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste";
import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger";
import { folderDropTarget, resolveDroppedFolderPath } from "./folderDrop";
import { splitTransferredFiles } from "./workspaceFileDrop";
import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model";
import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits";
import {
memo,
use,
useEffect,
useEffectEvent,
useId,
useImperativeHandle,
useLayoutEffect,
useRef,
useState,
} from "react";
import { flushSync } from "react-dom";
import {
clampCollapsedComposerCursor,
type ComposerTrigger,
type ComposerSubmissionIntent,
collapseExpandedComposerCursor,
composerRequiresModifier,
composerSubmissionIntentForKey,
composerStateAtPromptEnd,
detectComposerTrigger,
expandCollapsedComposerCursor,
formatAssistantCitationForComposer,
isPathSuggestionCurrent,
extendReplacementRangeForTrailingSpace,
replaceTextRange,
} from "../../composer-logic";
import { DEFAULT_COMPOSER_PLACEHOLDER } from "../../composerPlaceholder";
import {
deriveComposerSendState,
getAntigravitySendBlockReason,
resolveComposerInteractionMode,
threadShellHasStarted,
} from "../ChatView.logic";
import {
dataTransferHasComposerMention,
makeComposerMentionDragHandlers,
} from "./composerMentionDrag";
import { serializeComposerImages } from "./composerImagePersistence";
import {
isInsideCollapsedComposerControls,
isInsideRestingComposerControlScope,
markOpenToEffort,
markOpenToPermissions,
} from "./composerEventScope";
import {
type ComposerFileAttachment,
type ComposerImageAttachment,
type DraftId,
composerFileNeedsReattach,
composerDraftHasUserContent,
composerTargetKey,
useComposerDraftStore,
useComposerThreadDraft,
} from "../../composerDraftStore";
import { ComposerStashBadge } from "./ComposerStashBadge";
import { ComposerStashMenu } from "./ComposerStashMenu";
import { useComposerTriggerState } from "./useComposerTriggerState";
import { useComposerMenuItems } from "./useComposerMenuItems";
import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt";
import {
reconcileAttachmentContextReferences,
useRetainedContextPayloads,
} from "./composerContextUndo";
import type { ThreadSyncPhase } from "../../threadSync";
import { ComposerBanner } from "./ComposerBanner";
import { ComposerSurface } from "./ComposerSurface";
import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack";
import {
attachmentsToReleaseOnUploadCapabilityLoss,
composerOtherFilesForPresentation,
fileAttachmentCapabilityBlockReason,
fileAttachmentStagingLimit,
isPreviewableComposerVideo,
shouldHandleComposerAttachmentPaste,
} from "./composerAttachmentFiles";
import {
releaseAttachmentUpload,
releaseDraftAttachment,
startAttachmentUpload,
useAttachmentUploadStore,
} from "../../lib/attachmentUploadQueue";
import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState";
import { useDictationShortcut } from "../../speech/useDictationShortcut";
import { useDictationSubmissionShortcut } from "../../speech/useDictationSubmissionShortcut";
import { useEnvironmentSpeechInput } from "../../speech/useEnvironmentSpeechInput";
import { ComposerSpeechButton, ComposerSpeechRecordingPill } from "./ComposerSpeechButton";
import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection";
import { shortcutLabelForCommand } from "../../keybindings";
import {
type TerminalContextDraft,
type TerminalContextSelection,
} from "../../lib/terminalContext";
import {
threadContextRecord,
toKindScopedComposerContextId,
} from "@t3tools/shared/composerContextReferences";
import {
shouldUseCompactComposerPrimaryActions,
shouldUseCompactComposerFooter,
} from "../composerFooterLayout";
import {
type ComposerCitationCommentRequest,
type ComposerPromptEditorHandle,
ComposerPromptEditorTiptap as ComposerPromptEditor,
} from "../ComposerPromptEditorTiptap";
import {
ComposerContextActionsContext,
composerContextRecordsFromDraft,
} from "../composerContextPresentation";
import { useOpenPrLink } from "~/lib/openPullRequestLink";
import {
collectInlineContextIds,
type ComposerContextReference,
ensureInlineContextReferences,
formatInlineContextReference,
insertInlineContextReference,
inlineContextReferenceReplacement,
} from "~/lib/composerContextReferences";
import {
attachmentContextRecord,
uploadedAttachmentContextRecord,
previewAnnotationContextId,
previewAnnotationContextRecord,
reviewCommentContextId,
reviewCommentContextReference,
reviewCommentContextRecord,
terminalContextReference,
terminalContextRecord,
threadContextReference,
environmentContextRecord,
environmentContextReference,
} from "~/lib/composerContextRecords";
import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments";
import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag";
import { readThreadShell } from "~/state/entities";
import { useLinkedEnvironments } from "~/state/peerLinks";
import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard";
import type { ComposerContextRecord, ThreadPullRequestLink } from "@t3tools/contracts";
import { threadContextAttachment } from "~/lib/threadContextAttachment";
import {
type ComposerCommandItem,
ComposerCommandMenu,
composerSuggestionOptionId,
} from "./ComposerCommandMenu";
import {
ComposerAttachButton,
ComposerAttachmentFileList,
ComposerAttachmentMediaRow,
ComposerFilePreviewDialog,
ComposerQueuedAttachmentRow,
ComposerRestingImagePreviews,
} from "./ComposerAttachmentStrip";
import { ComposerPrimaryActions } from "./ComposerPrimaryActions";
import { ComposerFooterPrimaryActions } from "./ComposerFooterControls";
import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel";
import { ComposerPlanFollowUpBanner } from "./ComposerPlanFollowUpBanner";
import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight";
import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic";
import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState";
import { readPromptUltrathink } from "./TraitsPicker";
import {
providerSupportsManualCompaction,
resolveContextWindowModelDisplayName,
shouldReserveContextWindowMeter,
} from "./ContextWindowMeter.logic";
import {
buildAttachmentVideoPreview,
buildExpandedImagePreview,
type ExpandedImagePreview,
} from "./ExpandedImagePreview";
import { cn, isMacPlatform, randomUUID } from "~/lib/utils";
import {
getComposerPromptLengthValidationMessage,
getComposerSubmissionValidationMessage,
submitComposerDraft,
} from "./composerSubmission";
import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation";
import { pendingDraftWork } from "./pendingDraftWork";
import { importComposerThreadAttachment } from "./composerThreadImport";
import { observeResize } from "~/lib/observeResize";
const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError);
import { toastManager } from "../ui/toast";
import { BuildingIcon, PlayIcon } from "lucide-react";
import { Button } from "../ui/button";
import { useManagedPolicy } from "../../state/managedPolicy";
import { proposedPlanTitle } from "@t3tools/shared/proposedPlanText";
import { hasProviderSetup } from "./ProviderStatusBanner";
import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection";
import type { UnifiedSettings } from "@t3tools/contracts/settings";
import { isVideoAttachment, type SessionPhase, type Thread, type ThreadShell } from "../../types";
import { type ComposerPromptHistoryPosition } from "./composerPromptHistory";
import type { PendingUserInputDraftAnswer } from "@t3tools/client-runtime/state/pending-user-input";
import type {
LatestProposedPlanState,
PendingApproval,
PendingUserInput,
TimelineEntry,
} from "../../session-logic";
import {
resolveComposerDispatchMode,
type ComposerDispatchMode,
} from "@t3tools/client-runtime/state/composer-dispatch";
import { deriveLatestContextWindowSnapshot } from "@t3tools/client-runtime/state/context-window";
import {
resolveProviderSkillsForCwd,
resolveProviderSlashCommandsForCwd,
} from "@t3tools/client-runtime/providerSkills";
import { useMediaQuery } from "../../hooks/useMediaQuery";
import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen";
import { useStableCallback } from "../../hooks/useStableCallback";
import { usePanelAnimationSettings } from "../../panelAnimations";
import { readEnvironmentScope, readPreparedConnection } from "../../state/session";
import type { ReviewCommentContext } from "../../reviewCommentContext";
import { useComposerRestingTransition } from "./useComposerRestingTransition";
import { ComposerCommandMenuLayer } from "./ComposerCommandMenuLayer";
import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLayout";
import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh";
import { useComposerProviderModel } from "./useComposerProviderModel";
import { useComposerImageGroups } from "./useComposerImageGroups";
import { useComposerStash } from "./useComposerStash";
import { useComposerContextImport } from "./useComposerContextImport";
import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake";
import {
countPreparingComposerImages,
usePreparingComposerImages,
} from "./preparingComposerImages";
import { ComposerControlsBar } from "./ComposerControlsBar";
import { composerCommandKeyHandler } from "./composerCommandKey";
function consumePasteAsTextShortcut(deadline: { current: number }): boolean {
const armed = Date.now() <= deadline.current;
deadline.current = 0;
return armed;
}
export interface ChatComposerHandle {
focusAtEnd: () => void;
focusAt: (cursor: number) => void;
addDroppedFiles: (files: File[]) => void;
addDroppedFolders: (folders: File[]) => void;
hasPendingAttachments: () => boolean;
insertTextAtEnd: (
text: string,
options?: { ensureLeadingBoundary?: boolean; clipboardData?: DataTransfer },
) => boolean;
pasteTextAtEnd: (text: string, options?: { bypassAutoAttachment?: boolean }) => boolean;
citeAssistantText: (
citation: AssistantCitation,
sourceAnchor: AssistantCitationSourceAnchor,
) => boolean;
openModelPicker: () => void;
stepReasoningEffort: (direction: 1 | -1) => void;
toggleModelPicker: () => void;
openControl: (command: KeybindingCommand) => void;
isModelPickerOpen: () => boolean;
isCaretAtStart: () => boolean;
compactContext: () => void;
readSnapshot: () => {
value: string;
cursor: number;
expandedCursor: number;
contextIds: string[];
};
resetCursorState: (options?: {
cursor?: number;
prompt?: string;
detectTrigger?: boolean;
}) => void;
addTerminalContext: (selection: TerminalContextSelection) => void;
getSendContext: () => {
answeringPendingUserInput: boolean;
prompt: string;
images: ComposerImageAttachment[];
files: ComposerFileAttachment[];
terminalContexts: TerminalContextDraft[];
previewAnnotations: PreviewAnnotationPayload[];
reviewComments: ReviewCommentContext[];
threadContexts: ThreadContextRecord[];
environmentContexts: EnvironmentContextRecord[];
selectedPromptEffort: string | null;
selectedModelSelection: ModelSelection;
multipleModelSelections: ReadonlyArray<ModelSelection> | null;
providerAvailable: boolean;
selectedProvider: ProviderDriverKind;
selectedModel: string;
selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]>;
interactionMode: ProviderInteractionMode;
interactionModeEnabled: boolean;
shownPendingApprovalIds: ReadonlyArray<RuntimeRequestId>;
};
validateProviderInput: (providerInput: string) => boolean;
setMultipleModelSelections: (selections: ReadonlyArray<ModelSelection>) => void;
}
export interface ChatComposerProps {
composerDraftTarget: ScopedThreadRef | DraftId;
environmentId: EnvironmentId;
canOperateThread: boolean;
attachmentUploadsCapabilityKnown: boolean;
supportsAttachmentUploads: boolean;
supportsQuestionAttachments: boolean;
maxFileAttachmentBytes: number | null;
routeKind: "server" | "draft";
routeThreadRef: ScopedThreadRef;
draftId: DraftId | null;
multipleModelSelections: ReadonlyArray<ModelSelection> | null;
supportsMultipleModels: boolean;
onMultipleModelSelectionsChange: React.Dispatch<
React.SetStateAction<ReadonlyArray<ModelSelection> | null>
>;
activeThreadId: ThreadId | null;
activeThread: Thread | undefined;
activeThreadShell: ThreadShell | null;
promptHistoryEntries: ReadonlyArray<TimelineEntry>;
forceExpandedOnMobile: boolean;
projectSelectionRequired: boolean;
phase: SessionPhase;
canInterrupt: boolean;
isSendBusy: boolean;
canResume: boolean;
isRevertingCheckpoint?: boolean;
sendDisabledReason: string | null;
isPreparingWorktree: boolean;
isCompacting: boolean;
bannerItems: readonly ComposerBannerStackItem[];
resumeCompactionTokens: number | null;
keepFullHistory: boolean;
onToggleKeepFullHistory: () => void;
onUsageLimitsCommand?: (() => void) | undefined;
sideChatAvailable?: boolean;
sideChatDisabledReason?: string | null;
/** Arms a fresh session for the next message; absent where `/clear` is unavailable. */
onFreshSession?: (() => void) | undefined;
environmentUnavailable: {
readonly label: string;
readonly connection: EnvironmentConnectionPresentation;
} | null;
activePendingApproval: PendingApproval | null;
pendingApprovals: PendingApproval[];
onHeldRequestIdsChange: (requestIds: ReadonlySet<string>) => void;
pendingUserInputs: PendingUserInput[];
activePendingProgress: {
questionIndex: number;
isLastQuestion: boolean;
canAdvance: boolean;
customAnswer: string;
activeQuestion: {
id: string;
initialAnswer?: string | undefined;
multiSelect?: boolean | undefined;
allowCustomAnswer?: boolean | undefined;
} | null;
} | null;
activePendingResolvedAnswers: Record<string, unknown> | null;
activePendingIsResponding: boolean;
activePendingDraftAnswers: Record<string, PendingUserInputDraftAnswer>;
activePendingQuestionIndex: number;
respondingRequestIds: RuntimeRequestId[];
showPlanFollowUpPrompt: boolean;
activeProposedPlan: LatestProposedPlanState | null;
threadSyncPhase: ThreadSyncPhase | null;
runtimeMode: RuntimeMode;
defaultRuntimeMode?: RuntimeMode;
interactionMode: ProviderInteractionMode;
lockedProvider: ProviderDriverKind | null;
providerStatuses: ServerProvider[];
providerCatalogKnown: boolean;
activeProjectDefaultModelSelection: ModelSelection | null | undefined;
activeThreadModelSelection: ModelSelection | null | undefined;
reportedModelSelection?: ModelSelection | null;
activeProjectId: ProjectId | null;
projectName?: string | undefined;
contextWindowEntries: Parameters<typeof deriveLatestContextWindowSnapshot>[0];
contextWindowLiveUsage: Parameters<typeof deriveLatestContextWindowSnapshot>[1];
contextWindowProviderThread: Parameters<typeof deriveLatestContextWindowSnapshot>[2];
compactThreadUnavailable: boolean;
compactDisabled: boolean;
compactDisabledReason: string | null;
resolvedTheme: "light" | "dark";
settings: UnifiedSettings;
keybindings: ResolvedKeybindingsConfig;
terminalOpen: boolean;
gitCwd: string | null;
pullRequestProjectId: ProjectId | null;
pullRequestRepository: string | null;
threadPullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined;
onComposerOverlayHeightChange: (height: number) => void;
/** The new-thread strip names the permissions, so the controls row hides its chip. */
permissionsShownInStrip: boolean;
promptRef: React.RefObject<string>;
composerImagesRef: React.RefObject<ComposerImageAttachment[]>;
composerFilesRef: React.RefObject<ComposerFileAttachment[]>;
composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>;
composerRef: React.RefObject<ChatComposerHandle | null>;
onPageScrollKeyDown: (key: "PageUp" | "PageDown") => void;
onPageScrollKeyUp: (key: string) => void;
onPageScrollRelease: () => void;
editingQueuedAttachments: ReadonlyArray<{
readonly attachment: ContractChatAttachment;
readonly url: string | null;
}> | null;
onRemoveEditingQueuedAttachment: (attachmentId: string) => void;
onCompactContext: () => void;
onSend: (
e?: { preventDefault: () => void },
dispatchMode?: ComposerDispatchMode,
submissionIntent?: ComposerSubmissionIntent,
) => void;
onResume: () => void;
onInterrupt: () => void;
onImplementPlanInNewThread: () => void;
onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void;
onAdvanceActivePendingUserInput: () => void;
onDismissActivePendingUserInput: (requestId: RuntimeRequestId) => void;
onPreviousActivePendingUserInputQuestion: () => void;
onChangeActivePendingUserInputCustomAnswer: (
questionId: string,
value: string,
nextCursor: number,
expandedCursor: number,
cursorAdjacentToMention: boolean,
) => void;
onProviderModelSelect: (
instanceId: ProviderInstanceId,
model: string,
options?: { focusComposer?: boolean },
) => void;
onOpenProviderSetup: (instanceId: ProviderInstanceId) => void;
getModelDisabledReason: (instanceId: ProviderInstanceId, model: string) => string | null;
toggleInteractionMode: () => void;
handleRuntimeModeChange: (mode: RuntimeMode) => void;
handleInteractionModeChange: (mode: ProviderInteractionMode) => void;
focusComposer: () => void;
scheduleComposerFocus: () => void;
setThreadError: (threadId: ThreadId | null, error: string | null) => void;
onExpandImage: (preview: ExpandedImagePreview) => void;
onFileOpen: (attachment: ChatFileAttachment) => void;
}
const NO_PROVIDER_SKILLS: ServerProvider["skills"] = [];
const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = [];
export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) {
const {
composerDraftTarget,
environmentId,
canOperateThread,
attachmentUploadsCapabilityKnown,
supportsAttachmentUploads,
supportsQuestionAttachments,
maxFileAttachmentBytes,
routeKind,
routeThreadRef,
draftId,
multipleModelSelections,
supportsMultipleModels,
onMultipleModelSelectionsChange: setMultipleModelSelections,
activeThreadId,
activeThread,
promptHistoryEntries,
forceExpandedOnMobile,
projectSelectionRequired,
phase,
canInterrupt,
isSendBusy,
canResume,
isRevertingCheckpoint = false,
sendDisabledReason: externalSendDisabledReason,
isPreparingWorktree,
isCompacting,
environmentUnavailable,
activePendingApproval: incomingPendingApproval,
pendingApprovals,
onHeldRequestIdsChange,
pendingUserInputs: incomingPendingUserInputs,
activePendingProgress: incomingPendingProgress,
activePendingResolvedAnswers,
activePendingIsResponding: incomingPendingIsResponding,
activePendingDraftAnswers,
activePendingQuestionIndex,
respondingRequestIds,
showPlanFollowUpPrompt,
activeProposedPlan,
runtimeMode,
interactionMode: requestedInteractionMode,
lockedProvider,
providerStatuses,
providerCatalogKnown,
activeProjectDefaultModelSelection,
activeThreadModelSelection,
reportedModelSelection,
activeProjectId,
projectName,
contextWindowEntries,
contextWindowLiveUsage,
contextWindowProviderThread,
compactThreadUnavailable,
compactDisabled,
compactDisabledReason,
resolvedTheme,
settings,
keybindings,
terminalOpen,
gitCwd,
pullRequestProjectId,
pullRequestRepository,
threadPullRequests,
onComposerOverlayHeightChange,
promptRef,
composerRef,
composerImagesRef,
composerFilesRef,
composerTerminalContextsRef,
onPageScrollKeyDown,
onPageScrollKeyUp,
onPageScrollRelease,
onCompactContext,
onSend,
onResume,
onInterrupt,
onImplementPlanInNewThread,
onSelectActivePendingUserInputOption,
onAdvanceActivePendingUserInput,
onDismissActivePendingUserInput,
onPreviousActivePendingUserInputQuestion,
onChangeActivePendingUserInputCustomAnswer,
onProviderModelSelect,
onOpenProviderSetup,
getModelDisabledReason,
toggleInteractionMode,
handleRuntimeModeChange,
handleInteractionModeChange,
focusComposer,
scheduleComposerFocus,
setThreadError,
onExpandImage,
onFileOpen,
editingQueuedAttachments,
onRemoveEditingQueuedAttachment,
} = props;
const activeContextWindow = deriveLatestContextWindowSnapshot(
contextWindowEntries,
contextWindowLiveUsage,
contextWindowProviderThread,
);
const primaryEnvironmentId = usePrimaryEnvironmentId();
const composerDraftTargetKey = composerTargetKey(composerDraftTarget);
const {
heldRequestIds,
onDraftChange: onTypingGuardDraftChange,
onFocus: onTypingGuardFocus,
onBlur: onTypingGuardBlur,
onSend: onTypingGuardSend,
} = useComposerTypingGuard(composerDraftTargetKey, [
...pendingApprovals.map((request) => request.requestId),
...incomingPendingUserInputs.map((request) => request.requestId),
]);
// A layout effect so the timeline never paints a held approval as answerable.
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes held requests to the timeline without lifting per-keystroke typing state
useLayoutEffect(() => {
onHeldRequestIdsChange(heldRequestIds);
}, [heldRequestIds, onHeldRequestIdsChange]);
const activePendingApproval =
incomingPendingApproval && !heldRequestIds.has(incomingPendingApproval.requestId)
? incomingPendingApproval
: null;
const holdingUserInput = incomingPendingUserInputs[0]
? heldRequestIds.has(incomingPendingUserInputs[0].requestId)
: false;
const pendingUserInputs = holdingUserInput ? [] : incomingPendingUserInputs;
const activePendingProgress = holdingUserInput ? null : incomingPendingProgress;
const activePendingIsResponding = !holdingUserInput && incomingPendingIsResponding;
const isLiteralPendingAnswer = activePendingProgress?.activeQuestion?.initialAnswer !== undefined;
const isEditingQueuedMessage = editingQueuedAttachments !== null;
const composerDraft = useComposerThreadDraft(composerDraftTarget);
const composerDraftTargetKeyRef = useRef("");
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed draft target key to a ref read by async handlers
useLayoutEffect(() => {
composerDraftTargetKeyRef.current = composerDraftTargetKey;
});
const questionAttachmentTarget =
pendingUserInputs[0] && activePendingProgress?.activeQuestion
? questionAttachmentDraftId(
environmentId,
activeThreadId!,
pendingUserInputs[0].requestId,
activePendingProgress.activeQuestion.id,
)
: null;
const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget;
const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget);
const questionTakesSnapShots =
supportsQuestionAttachments &&
activePendingProgress?.activeQuestion?.allowCustomAnswer !== false &&
!activePendingIsResponding;
const questionRequest = pendingUserInputs[0];
// Publish eligibility before async captures can observe a question the UI has already closed.
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers the open question's attachment draft in the module tracker before async captures read it
useLayoutEffect(() => {
if (!questionAttachmentTarget || !questionRequest || !questionTakesSnapShots) return;
return trackOpenQuestionAttachmentDraft(routeThreadRef, {
draftId: questionAttachmentTarget,
requestKeys: questionRequest.questions.map((question) =>
questionAttachmentDraftId(
environmentId,
activeThreadId!,
questionRequest.requestId,
question.id,
),
),
});
}, [
activeThreadId,
environmentId,
questionAttachmentTarget,
questionRequest,
questionTakesSnapShots,
routeThreadRef,
]);
const attachmentTargetKey = composerTargetKey(attachmentDraftTarget);
// Reject async imports after a draft switch.
const attachmentTargetKeyRef = useRef(attachmentTargetKey);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed attachment target key to a ref so async imports reject after a draft switch
useLayoutEffect(() => {
attachmentTargetKeyRef.current = attachmentTargetKey;
});
const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts);
const prompt = composerDraft.prompt;
const composerImages = attachmentDraft.images;
const composerFiles = attachmentDraft.files;
const inlineFileIdSet = (() => {
if (questionAttachmentTarget) return new Set<string>();
const contextIds = new Set(collectInlineContextIds(prompt));
return new Set(
composerFiles
.filter((file) => contextIds.has(toKindScopedComposerContextId("file", file.id)))
.map((file) => file.id),
);
})();
const composerVideos = composerFiles.filter((file) =>
isPreviewableComposerVideo(file, environmentId),
);
const composerOtherFiles = composerOtherFilesForPresentation(
composerFiles,
environmentId,
inlineFileIdSet,
);
const composerTerminalContexts = composerDraft.terminalContexts;
const composerPreviewAnnotations = composerDraft.previewAnnotations;
const composerReviewComments = composerDraft.reviewComments;
const composerThreadContexts = attachmentDraft.threadContexts;
const composerEnvironmentContexts = composerDraft.environmentContexts;
const {
pendingSnapShotAnimations,
pendingSnapShotIds,
uncommittedSnapShotIds,
standaloneComposerImages,
} = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations);
const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey);
const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds;
const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId);
const openPrLink = useOpenPrLink(routeThreadRef);
const [previewFileId, setPreviewFileId] = useState<string | null>(null);
const previewFile = composerFiles.find((file) => file.id === previewFileId);
const composerContextActions = {
environmentId,
cwd: gitCwd ?? undefined,
projectId: activeProjectId ?? undefined,
expandImage: (imageId: string) => {
const preview = buildExpandedImagePreview(composerImages, imageId);
if (preview) onExpandImage(preview);
},
openFile: setPreviewFileId,
openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path),
expandVideo: (fileId: string) => {
const file = composerFiles.find((candidate) => candidate.id === fileId);
if (!file || !isVideoAttachment(file)) return;
const localPreview = buildExpandedImagePreview([file], file.id);
if (localPreview) {
onExpandImage(localPreview);
return;
}
if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) {
return;
}
const persistedPreview = buildAttachmentVideoPreview(environmentId, {
type: "file",
id: file.uploadedAttachmentId,
name: file.name,
mimeType: file.mimeType,
sizeBytes: file.sizeBytes,
});
if (persistedPreview) onExpandImage(persistedPreview);
},
openPullRequest: (event: React.MouseEvent<HTMLElement>, url: string) => {
openPrLink(event, url);
},
};
const composerContextRecords = composerContextRecordsFromDraft({
terminalContexts: composerTerminalContexts,
reviewComments: composerReviewComments,
previewAnnotations: composerPreviewAnnotations,
threadContexts: composerThreadContexts,
environmentContexts: composerEnvironmentContexts,
images: composerImages,
files: composerFiles,
uploadsByImageId,
});
const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length;
const fileStagingLimit = fileAttachmentStagingLimit({
attachmentUploadsCapabilityKnown,
supportsAttachmentUploads,
maxFileAttachmentBytes,
});
const fileCapabilityBlockReason = fileAttachmentCapabilityBlockReason({
files: composerFiles,
attachmentUploadsCapabilityKnown,
supportsAttachmentUploads,
maxFileAttachmentBytes,
});
const attachmentBlockReason =
(questionAttachmentTarget &&
!supportsQuestionAttachments &&
(composerImages.length > 0 || composerFiles.length > 0)
? "Update this server to send files with question answers"
: null) ??
fileCapabilityBlockReason ??
(supportsAttachmentUploads
? needsReattachFileCount > 0
? needsReattachFileCount === 1
? "Attach the interrupted file again or remove it"
: "Attach the interrupted files again or remove them"
: attachmentUploadBlockReason({
imageIds: [...composerImages, ...composerFiles].map((attachment) => attachment.id),
uploadsByImageId,
environmentId,
})
: null);
const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt);
const addComposerDraftImages = useComposerDraftStore((store) => store.addImages);
const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage);
const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles);
const removeComposerDraftFile = useComposerDraftStore((store) => store.removeFile);
const insertComposerDraftTerminalContext = useComposerDraftStore(
(store) => store.insertTerminalContext,
);
const setComposerDraftTerminalContexts = useComposerDraftStore(
(store) => store.setTerminalContexts,
);
const removeComposerDraftPreviewAnnotation = useComposerDraftStore(
(store) => store.removePreviewAnnotation,
);
const removeComposerDraftReviewComment = useComposerDraftStore(
(store) => store.removeReviewComment,
);
const clearComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.clearPersistedAttachments,
);
const syncComposerDraftPersistedAttachments = useComposerDraftStore(
(store) => store.syncPersistedAttachments,
);
const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts or releases server attachment uploads as upload capability, limits and draft attachments change
useEffect(() => {
if (!attachmentUploadsCapabilityKnown) {
return;
}
if (!supportsAttachmentUploads) {
// Reconnect or version skew can hide upload support; retain hydrated uploads.
for (const attachment of attachmentsToReleaseOnUploadCapabilityLoss([
...composerImages,
...composerFiles,
])) {
releaseAttachmentUpload(attachment.id);
}
return;
}
if (!canOperateThread) return;
const invalidFiles =
maxFileAttachmentBytes === null
? composerFiles
: composerFiles.filter((file) => file.sizeBytes > maxFileAttachmentBytes);
for (const attachment of attachmentsToReleaseOnUploadCapabilityLoss(invalidFiles)) {
releaseAttachmentUpload(attachment.id);
}
const uploadableFiles =
maxFileAttachmentBytes === null
? []
: composerFiles.filter((file) => file.sizeBytes <= maxFileAttachmentBytes);
const uploadableAttachments = [...composerImages, ...uploadableFiles];
for (const attachment of uploadableAttachments) {
if (attachment.type === "file" && composerFileNeedsReattach(attachment)) {
continue;
}
startAttachmentUpload({
environmentId,
image: attachment,
draftTarget: attachmentDraftTarget,
});
}
}, [
attachmentUploadsCapabilityKnown,
attachmentDraftTarget,
canOperateThread,
composerFiles,
composerImages,
environmentId,
maxFileAttachmentBytes,
supportsAttachmentUploads,
]);
const {
providerInstanceEntries,
selectedProviderEntry,
lockedContinuationGroupKey,
unavailableProviderInstanceId,
selectedInstanceId,
selectedProvider,
selectedProviderModels,
composerModelOptions,
selectedModel,
composerProviderState,
} = useComposerProviderModel({
providerStatuses,
settings,
activeProjectId,
threadRef: composerDraftTarget,
threadModelSelection: activeThreadModelSelection,
projectModelSelection: activeProjectDefaultModelSelection,
promptInjectionState: getComposerPromptInjectionState(prompt),
candidateInstanceIds: [
composerDraft.activeProvider ?? null,
activeThread?.runtime?.providerInstanceId,
activeThreadModelSelection?.instanceId,
activeProjectDefaultModelSelection?.instanceId,
],
lockedProvider,
lockedInstanceId:
activeThread?.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId,
});
const noProviderAvailable =
selectedProviderEntry === undefined && multipleModelSelections === null;
const providerCatalogPending = noProviderAvailable && !providerCatalogKnown;
const showProviderUnavailable = noProviderAvailable && !providerCatalogPending;
const providerSetupInstanceId = noProviderAvailable
? (unavailableProviderInstanceId ??
(lockedProvider === null
? providerInstanceEntries.find((entry) => hasProviderSetup(entry.snapshot))?.instanceId
: undefined))
: undefined;
const resolvedCompactDisabledReason =
compactDisabledReason ?? (noProviderAvailable ? "Compacting is unavailable right now" : null);
const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } =
resolveCompatibleRuntimeMode(
runtimeMode,
selectedProviderEntry?.snapshot.supportedRuntimeModes,
);
// Modes above an administrator's ceiling stay listed, disabled with the reason.
const managedPolicy = useManagedPolicy(environmentId);
const compatibleRuntimeModeOptions = resolveRuntimeModeOptions(
compatibleRuntimeModes,
managedPolicy,
);
// A thread or draft already above the ceiling would be refused; offer the broadest mode left.
const runtimeModeCeilingDenial = managedRuntimeModeDenial(managedPolicy, compatibleRuntimeMode);
const runtimeModeCeilingFallback =
runtimeModeCeilingDenial === undefined
? undefined
: clampManagedRuntimeMode(managedPolicy, compatibleRuntimeMode, compatibleRuntimeModes);
const providerSendBlockReason = getAntigravitySendBlockReason(
selectedProviderEntry?.snapshot,
selectedModel,
);
const sendDisabledReason =
externalSendDisabledReason ??
(multipleModelSelections?.length === 0 ? "Select at least one model." : null) ??
(activePendingProgress
? attachmentBlockReason
: (attachmentBlockReason ??
runtimeModeCeilingDenial ??
(multipleModelSelections === null ? providerSendBlockReason : null)));
const isSendDisabled = sendDisabledReason !== null;
const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null;
const compactCommandAvailable = providerSupportsManualCompaction(selectedProviderEntry);
const selectedProviderSkills = selectedProviderStatus
? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd)
: NO_PROVIDER_SKILLS;
const selectedProviderSlashCommands = selectedProviderStatus
? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd)
: NO_PROVIDER_SLASH_COMMANDS;
const { refresh: refreshWorkspaceSnapshotOnTyping, scanning: workspaceSkillsScanning } =
useProviderWorkspaceSnapshotRefresh({
environmentId,
gitCwd,
instanceId: selectedProviderEntry?.instanceId,
});
const selectedPromptEffort = composerProviderState.promptEffort;
const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch;
const { enabled: planModeUiEnabled, interactionMode } = resolveComposerInteractionMode({
planModeEnabled: settings.planModeEnabled,
provider: selectedProviderStatus,
interactionMode: requestedInteractionMode,
});
const selectedModelSelection: ModelSelection = createModelSelection(
selectedInstanceId,
selectedModel,
selectedModelOptionsForDispatch,
);
const selectedModelForPicker = selectedModel;
const modelOptionsByInstance = new Map<ProviderInstanceId, ReadonlyArray<AppModelOption>>();
for (const entry of providerInstanceEntries) {
modelOptionsByInstance.set(
entry.instanceId,
getAppModelOptionsForInstance(
settings,
entry,
entry.instanceId === selectedInstanceId ? selectedModelForPicker : null,
),
);
}
const selectedModelForPickerWithCustomFallback = (() => {
const currentOptions = modelOptionsByInstance.get(selectedInstanceId) ?? [];
return currentOptions.some((option) => option.slug === selectedModelForPicker)
? selectedModelForPicker
: (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker);
})();
const activeThreadModelDisplayName = resolveContextWindowModelDisplayName(
activeThreadModelSelection,
modelOptionsByInstance,
);
const reserveContextWindowMeter = shouldReserveContextWindowMeter({
meterEnabled: settings.contextWindowMeterEnabled,
detailLoading: props.threadSyncPhase === "loading",
threadStarted: threadShellHasStarted(props.activeThreadShell),
providerReportsContextWindow: selectedProviderStatus
? selectedProviderStatus.reportsContextWindow === true
: null,
});
const [composerCursor, setComposerCursor] = useState(() => {
const value = isLiteralPendingAnswer ? (activePendingProgress?.customAnswer ?? prompt) : prompt;
return collapseExpandedComposerCursor(value, value.length, isLiteralPendingAnswer);
});
const {
trigger: composerTrigger,
setTrigger: setComposerTrigger,
resolveTrigger: resolveComposerTrigger,
dismissTrigger: dismissComposerTrigger,
resetTrigger: resetComposerTrigger,
} = useComposerTriggerState(() =>
isLiteralPendingAnswer ? null : detectComposerTrigger(prompt, prompt.length),
);
const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null);
const composerSuggestionId = useId();
const composerSuggestionListId = `${composerSuggestionId}-${encodeURIComponent(draftId ?? activeThreadId ?? "new")}-suggestions`;
const promptHistoryPositionRef = useRef<{
targetKey: string;
position: ComposerPromptHistoryPosition;
} | null>(null);
const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState<string | null>(
null,
);
const [isDragOverComposer, setIsDragOverComposer] = useState(false);
const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false);
const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false);
const isMobileViewport = useMediaQuery("max-sm");
const isSoftwareKeyboardOpen = useSoftwareKeyboardOpen();
const [isComposerFocused, setIsComposerFocused] = useState(false);
const [composerSubmissionError, setComposerSubmissionError] = useState<string | null>(null);
const [providerInputSubmissionError, setProviderInputSubmissionError] = useState<string | null>(
null,
);
const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null);
const [hasWrappedPrompt, observeWrappedPrompt] = useComposerMultilinePrompt();
const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt;
// A pending question stays expanded: its card moves into the banner dock,
// so collapsing would leave the surface empty and squashed beneath it.
const isComposerCollapsedMobile =
isMobileViewport &&
!forceExpandedOnMobile &&
!isComposerFocused &&
!hasMultilinePrompt &&
pendingUserInputs.length === 0;
const composerEditorRef = useRef<ComposerPromptEditorHandle>(null);
const pasteAsTextShortcutUntilRef = useRef(0);
const composerFormRef = useRef<HTMLFormElement>(null);
const composerSurfaceRef = useRef<HTMLDivElement>(null);
const providerInputRejectedRef = useRef(false);
const composerSelectLockRef = useRef(false);
const composerMenuOpenRef = useRef(false);
const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]);
const activeComposerMenuItemRef = useRef<ComposerCommandItem | null>(null);
const composerBlurFrameRef = useRef<number | null>(null);
const mobileComposerExpandFrameRef = useRef<number | null>(null);
const mobileComposerExpandReleaseFrameRef = useRef<number | null>(null);
const mobileComposerExpandInFlightRef = useRef(false);
const pendingThreadImportsRef = useRef<Map<string, number>>(new Map());
const isRevertingCheckpointRef = useRef(isRevertingCheckpoint);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed checkpoint revert flag to a ref read by async handlers
useLayoutEffect(() => {
isRevertingCheckpointRef.current = isRevertingCheckpoint;
});
const backgroundThread = use(BackgroundThreadContext);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- subscribes to keydown, window blur and the desktop paste-as-text event to arm plain-text paste
useEffect(() => {
// A background composer listens on its own form, so it never hears the main composer's keys.
const target: EventTarget | null = backgroundThread ? composerFormRef.current : window;
if (target === null) return;
const armPasteAsTextShortcut = () => {
// Electron's menu action can precede paste; browsers deliver keydown first.
pasteAsTextShortcutUntilRef.current = Date.now() + 1_000;
};
const onKeyDown = (event: Event) => {
if (
event instanceof KeyboardEvent &&
event.target instanceof Node &&
composerFormRef.current?.contains(event.target) &&
isPasteAsTextShortcut(event, isMacPlatform(navigator.platform))
) {
armPasteAsTextShortcut();
}
};
const onBlur = () => {
pasteAsTextShortcutUntilRef.current = 0;
};
const onDesktopPasteAsText = () => {
const activeElement = document.activeElement;
const blocksPasteToFocus =
activeElement instanceof Element &&
activeElement.closest(
'input, textarea, select, button, a[href], summary, [contenteditable="true"], [contenteditable="plaintext-only"], [role="textbox"], [role="button"], [role="menuitem"], [role="option"]',
) !== null;
// A background composer takes no paste-to-focus, so it arms only for its own focus.
if (
(activeElement instanceof Node && composerFormRef.current?.contains(activeElement)) ||
(!blocksPasteToFocus && !backgroundThread)
) {
armPasteAsTextShortcut();
}
};
target.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
target.addEventListener("keydown", onKeyDown, true);
// An arm lasts a second, so a background composer can skip the window blur reset.
if (!backgroundThread) window.addEventListener("blur", onBlur);
return () => {
target.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText);
target.removeEventListener("keydown", onKeyDown, true);
window.removeEventListener("blur", onBlur);
};
}, [backgroundThread]);
const composerSendState = deriveComposerSendState({
prompt,
imageCount: composerImages.length + composerFiles.length,
existingAttachmentCount: editingQueuedAttachments?.length ?? 0,
terminalContexts: composerTerminalContexts,
elementContextCount: composerPreviewAnnotations.length + composerReviewComments.length,
});
const composerTriggerKind = composerTrigger?.kind ?? null;
const compactSlashCommandAvailable =
composerTrigger?.kind === "slash-command" &&
prompt.slice(0, composerTrigger.rangeStart).trim() === "" &&
!compactThreadUnavailable &&
prompt.slice(composerTrigger.rangeEnd).trim() === "" &&
composerImages.length + composerFiles.length === 0 &&
composerDraft.persistedAttachments.length === 0 &&
composerTerminalContexts.length === 0 &&
composerPreviewAnnotations.length === 0 &&
composerReviewComments.length === 0;
const linkedEnvironments = useLinkedEnvironments(environmentId);
const {
items: composerMenuItems,
isLoading: isComposerMenuLoading,
emptyState: composerMenuEmptyState,
} = useComposerMenuItems({
composerTrigger,
environmentId,
linkedEnvironments,
gitCwd,
activeThreadId,
pullRequestProjectId,
pullRequestRepository,
threadPullRequests,
planModeUiEnabled,
sideChatAvailable: props.sideChatAvailable === true,
sideChatDisabledReason: props.sideChatDisabledReason ?? null,
freshSessionAvailable: props.onFreshSession !== undefined,
compactSlashCommandAvailable,
selectedProvider,
selectedProviderSkills,
selectedProviderSlashCommands,
showSkillsInSlashMenu: settings.showSkillsInSlashMenu,
workspaceSkillsScanning,
questionAttachmentTarget,
});
const composerMenuOpen = Boolean(composerTrigger);
const composerMenuSearchKey = composerTrigger
? `${composerSuggestionListId}:${composerTrigger.kind}:${composerTrigger.query.trim().toLowerCase()}`
: null;
const activeComposerMenuItemId = resolveComposerMenuActiveItemId({
items: composerMenuItems,
highlightedItemId: composerHighlightedItemId,
currentSearchKey: composerMenuSearchKey,
highlightedSearchKey: composerHighlightedSearchKey,
});
const activeComposerMenuItem =
composerMenuItems.find((item) => item.id === activeComposerMenuItemId) ?? null;
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed composer menu state to refs read by editor key handlers
useLayoutEffect(() => {
composerMenuOpenRef.current = composerMenuOpen;
composerMenuItemsRef.current = composerMenuItems;
activeComposerMenuItemRef.current = activeComposerMenuItem;
});
const isComposerApprovalState = activePendingApproval !== null;
// A send declines the approvals shown here to redirect the agent, so it steers the waiting
// turn instead of queueing behind it. Approvals the typing guard holds stay unseen and pending.
const followUpBehavior = pendingApprovals.some(
(approval) => !heldRequestIds.has(approval.requestId),
)
? "steer"
: settings.followUpBehavior;
const composerSuggestionsVisible = composerMenuOpen;
const composerSuggestionListVisible = composerSuggestionsVisible && composerMenuItems.length > 0;
const activePendingUserInput = pendingUserInputs[0] ?? null;
const isChoiceOnlyPendingQuestion =
activePendingProgress?.activeQuestion?.allowCustomAnswer === false;
const showComposerTopDrawer =
pendingUserInputs.length > 0 ||
(!isComposerCollapsedMobile && showPlanFollowUpPrompt && activeProposedPlan !== null);
const showCollapsedMobilePromptRow = isComposerCollapsedMobile;
const showComposerAttachAction =
fileStagingLimit !== null &&
(!activePendingProgress ||
(supportsQuestionAttachments &&
activePendingProgress.activeQuestion?.allowCustomAnswer !== false));
const composerFooterHasWideActions = showPlanFollowUpPrompt || activePendingProgress !== null;
const editPromptFromTraits = (edit: (prompt: string) => string) => {
const currentPrompt = getComposerDraft(composerDraftTarget)?.prompt ?? "";
const nextPrompt = edit(currentPrompt);
if (nextPrompt === currentPrompt) return;
if (nextPrompt === promptRef.current) {
scheduleComposerFocus();
return;
}
promptRef.current = nextPrompt;
setComposerDraftPrompt(composerDraftTarget, nextPrompt);
const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length);
setComposerCursor(nextCursor);
setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length));
scheduleComposerFocus();
};
const editPromptFromTraitsStable = useStableCallback(editPromptFromTraits);
const promptUltrathink = readPromptUltrathink(prompt);
const [inlineRestingControlsHost, setInlineRestingControlsHost] = useState<HTMLDivElement | null>(
null,
);
const {
controlsRef: restingComposerControlsRef,
attachControls: attachRestingComposerControls,
hiddenBlockCount: restingControlsHiddenBlockCount,
iconOnlyBlockCount: restingControlsIconOnlyBlockCount,
controlsVisible: restingControlsVisible,
} = useRestingComposerControlsLayout(inlineRestingControlsHost);
const {
attachControls: attachExpandedComposerControls,
hiddenBlockCount: expandedControlsHiddenBlockCount,
iconOnlyBlockCount: expandedControlsIconOnlyBlockCount,
} = useRestingComposerControlsLayout(null, true);
const pendingPrimaryAction = activePendingProgress
? {
questionIndex: activePendingProgress.questionIndex,
isLastQuestion: activePendingProgress.isLastQuestion,
canAdvance:
activePendingProgress.canAdvance &&
!attachmentBlockReason &&
!(questionPreparations[attachmentTargetKey] ?? 0),
isResponding: activePendingIsResponding,
isComplete: Boolean(activePendingResolvedAnswers),
}
: null;
const showResumeAction =
canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage;
const collapsedComposerPrimaryActionDisabled =
phase === "running" ||
isSendBusy ||
isSendDisabled ||
noProviderAvailable ||
projectSelectionRequired ||
environmentUnavailable !== null ||
(!composerSendState.hasSendableContent && !showResumeAction);
const collapsedComposerPrimaryActionLabel = showResumeAction
? "Resume thread"
: props.resumeCompactionTokens !== null && !props.keepFullHistory
? "Open composer to compact and send"
: "Send message";
const showMobilePendingAnswerActions =
isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null;
const setPrompt = (nextPrompt: string) => {
setComposerDraftPrompt(composerDraftTarget, nextPrompt);
};
const addComposerImage = (image: ComposerImageAttachment) =>
addComposerDraftImages(attachmentDraftTarget, [image]);
const addComposerImagesToDraft = (images: ComposerImageAttachment[]) =>
addComposerDraftImages(attachmentDraftTarget, images);
const addComposerFilesToDraft = (files: ComposerFileAttachment[]) =>
addComposerDraftFiles(attachmentDraftTarget, files, {
appendReference: questionAttachmentTarget === null,
});
const removeComposerImageFromDraft = (imageId: string) => {
if (questionAttachmentTarget && activePendingIsResponding) return;
releaseAttachmentUpload(imageId);
removeComposerDraftImage(attachmentDraftTarget, imageId);
};
const removeComposerFileFromDraft = (fileId: string) => {
if (questionAttachmentTarget && activePendingIsResponding) return;
// Hydrated uploads use persisted attachment ids, not queue keys.
const file = composerFilesRef.current.find((candidate) => candidate.id === fileId);
if (file) {
releaseDraftAttachment(file);
} else {
releaseAttachmentUpload(fileId);
}
removeComposerDraftFile(attachmentDraftTarget, fileId);
};
const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment);
const addComposerDraftPreviewAnnotation = useComposerDraftStore(
(store) => store.addPreviewAnnotation,
);
const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts);
const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts);
const addComposerDraftEnvironmentContexts = useComposerDraftStore(
(store) => store.addEnvironmentContexts,
);
const setComposerDraftEnvironmentContexts = useComposerDraftStore(
(store) => store.setEnvironmentContexts,
);
const buildContextClipboardFragment = (contextIds: ReadonlyArray<string>): string | null => {
const wanted = new Set(contextIds);
const copiedFiles = new Map<string, File>();
for (const annotation of composerPreviewAnnotations) {
if (
wanted.has(previewAnnotationContextId(annotation.id)) &&
composerImages.some((image) => image.id === annotation.id)
) {
wanted.add(toKindScopedComposerContextId("image", annotation.id));
}
}
const records: ComposerContextRecord[] = [
...composerTerminalContexts
.filter((c) => wanted.has(terminalContextReference(c).contextId))
.map(terminalContextRecord),
...composerThreadContexts.filter((record) => wanted.has(record.contextId)),
...composerEnvironmentContexts.filter((record) => wanted.has(record.contextId)),
...composerReviewComments
.filter((c) => wanted.has(reviewCommentContextId(c.id)))
.map(reviewCommentContextRecord),
...composerPreviewAnnotations
.filter((a) => wanted.has(previewAnnotationContextId(a.id)))
.map((annotation) =>
previewAnnotationContextRecord(annotation, {
screenshotContextId: composerImages.some((image) => image.id === annotation.id)
? annotation.id
: undefined,
}),
),
...[...composerImages, ...composerFiles]
.filter((attachment) =>
wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)),
)
.flatMap((attachment) => {
const record =
uploadedAttachmentContextRecord(attachment, uploadsByImageId[attachment.id]) ??
(attachment.file
? attachmentContextRecord({ attachment, attachmentId: attachment.id })
: null);
if (!record) return [];
if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file);
return [record];
}),
];
if (records.length === 0) return null;
const fragment = encodeComposerContextFragment({
version: 1,
source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) },
records,
});
if (fragment) rememberCopiedComposerAttachments(environmentId, copiedFiles);
return fragment;
};
const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment);
const {
loadThreadTranscript,
countReservedAttachments,
countReservedAttachmentsStable,
importContextRecords,
importContextFragment,
importContextFragmentStable,
} = useComposerContextImport({
environmentId,
linkedEnvironments,
activeThread,
activeThreadId,
composerDraftTarget,
attachmentDraftTarget,
attachmentTargetKey,
attachmentTargetKeyRef,
questionAttachmentTarget,
pendingUserInputs,
composerContextRecords,
composerImages,
composerFilesRef,
promptRef,
pendingThreadImportsRef,
addComposerFilesToDraft,
});
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers
useEffect(() => {
if (isLiteralPendingAnswer) return;
promptRef.current = prompt;
}, [isLiteralPendingAnswer, prompt, promptRef]);
const [cursorClampedFor, setCursorClampedFor] = useState({ prompt, isLiteralPendingAnswer });
if (
cursorClampedFor.prompt !== prompt ||
cursorClampedFor.isLiteralPendingAnswer !== isLiteralPendingAnswer
) {
setCursorClampedFor({ prompt, isLiteralPendingAnswer });
if (!isLiteralPendingAnswer) {
setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing));
}
}
if (composerSubmissionError !== null) {
const nextError = getComposerPromptLengthValidationMessage(prompt);
if (nextError !== composerSubmissionError) {
setComposerSubmissionError(nextError);
}
}
const providerInputInputs = [
composerPreviewAnnotations,
composerReviewComments,
composerTerminalContexts,
prompt,
selectedModel,
selectedPromptEffort,
selectedProvider,
] as const;
const [providerInputValidatedFor, setProviderInputValidatedFor] = useState(providerInputInputs);
if (providerInputInputs.some((value, index) => value !== providerInputValidatedFor[index])) {
setProviderInputValidatedFor(providerInputInputs);
setProviderInputSubmissionError(null);
}
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared images ref in step with committed draft images for async handlers
useEffect(() => {
composerImagesRef.current = composerImages;
}, [composerImages, composerImagesRef]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared files ref in step with committed draft files for async handlers
useEffect(() => {
composerFilesRef.current = composerFiles;
}, [composerFiles, composerFilesRef]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared terminal contexts ref in step with committed draft contexts for async handlers
useEffect(() => {
composerTerminalContextsRef.current = composerTerminalContexts;
}, [composerTerminalContexts, composerTerminalContextsRef]);
const resolvedHighlightedItemId = composerMenuOpen ? activeComposerMenuItemId : null;
const resolvedHighlightedSearchKey = composerMenuOpen ? composerMenuSearchKey : null;
if (composerHighlightedItemId !== resolvedHighlightedItemId) {
setComposerHighlightedItemId(resolvedHighlightedItemId);
}
if (composerHighlightedSearchKey !== resolvedHighlightedSearchKey) {
setComposerHighlightedSearchKey(resolvedHighlightedSearchKey);
}
const lastSyncedPendingInputRef = useRef<{
requestId: string | null;
questionId: string | null;
} | null>(null);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- moves the prompt ref and caret to the end when the pending question or its answer changes externally
useEffect(() => {
const nextCustomAnswer = activePendingProgress?.customAnswer;
if (typeof nextCustomAnswer !== "string") {
if (lastSyncedPendingInputRef.current !== null) {
promptRef.current = prompt;
const { cursor, trigger } = composerStateAtPromptEnd(prompt);
setComposerCursor(cursor);
resetComposerTrigger(trigger);
}
lastSyncedPendingInputRef.current = null;
return;
}
const nextRequestId = activePendingUserInput?.requestId ?? null;
const nextQuestionId = activePendingProgress?.activeQuestion?.id ?? null;
const questionChanged =
lastSyncedPendingInputRef.current?.requestId !== nextRequestId ||
lastSyncedPendingInputRef.current?.questionId !== nextQuestionId;
const textChangedExternally = promptRef.current !== nextCustomAnswer;
lastSyncedPendingInputRef.current = {
requestId: nextRequestId,
questionId: nextQuestionId,
};
if (!questionChanged && !textChangedExternally) {
return;
}
promptRef.current = nextCustomAnswer;
const { cursor, trigger } = composerStateAtPromptEnd(nextCustomAnswer, isLiteralPendingAnswer);
setComposerCursor(cursor);
resetComposerTrigger(trigger);
setComposerHighlightedItemId(null);
}, [
activePendingProgress?.customAnswer,
activePendingProgress?.activeQuestion?.id,
isLiteralPendingAnswer,
activePendingUserInput?.requestId,
prompt,
promptRef,
resetComposerTrigger,
]);
const composerSessionKey = `${draftId ?? ""}:${activeThreadId ?? ""}:${isLiteralPendingAnswer}`;
const [shownComposerSessionKey, setShownComposerSessionKey] = useState(composerSessionKey);
if (shownComposerSessionKey !== composerSessionKey) {
setShownComposerSessionKey(composerSessionKey);
setComposerHighlightedItemId(null);
setComposerHighlightedSearchKey(null);
setComposerSubmissionError(null);
setProviderInputSubmissionError(null);
const pendingAnswer = activePendingProgress?.customAnswer;
const { cursor, trigger } = composerStateAtPromptEnd(
typeof pendingAnswer === "string" ? pendingAnswer : prompt,
isLiteralPendingAnswer,
);
setComposerCursor(cursor);
resetComposerTrigger(trigger);
setIsDragOverComposer(false);
}
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes composer form resizes to switch the footer and primary actions between compact layouts
useLayoutEffect(() => {
const composerForm = composerFormRef.current;
if (!composerForm) return;
const measurePrimaryActionsCompact = () => {
const composerFormWidth = composerForm.clientWidth;
const options = { hasWideActions: composerFooterHasWideActions };
return (
shouldUseCompactComposerFooter(composerFormWidth, options) &&
shouldUseCompactComposerPrimaryActions(composerFormWidth, options)
);
};
setIsComposerPrimaryActionsCompact(measurePrimaryActionsCompact());
return observeResize(composerForm, () => {
setIsComposerPrimaryActionsCompact(measurePrimaryActionsCompact());
});
}, [composerFooterHasWideActions]);
// oxlint-disable-next-line t3code/no-unreasoned-state-sync -- reads draft images as data URLs and persists them to the draft store, dropping stale results on cleanup
useEffect(() => {
let cancelled = false;
void (async () => {
if (composerImages.length === 0) {
clearComposerDraftPersistedAttachments(attachmentDraftTarget);
return;
}
const getPersistedAttachmentsForThread = () =>
getComposerDraft(attachmentDraftTarget)?.persistedAttachments ?? [];
try {
const currentPersistedAttachments = getPersistedAttachmentsForThread();
const serialized = await serializeComposerImages(
composerImages,
currentPersistedAttachments,
);
if (cancelled) return;
syncComposerDraftPersistedAttachments(attachmentDraftTarget, serialized);
} catch {
const currentImageIds = new Set(composerImages.map((image) => image.id));
const fallbackPersistedAttachments = getPersistedAttachmentsForThread();
const fallbackPersistedIds: Array<string> = [];
for (const attachment of fallbackPersistedAttachments) {
if (currentImageIds.has(attachment.id)) {
fallbackPersistedIds.push(attachment.id);
}
}
const fallbackPersistedIdSet = new Set(fallbackPersistedIds);
const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) =>
fallbackPersistedIdSet.has(attachment.id),
);
if (cancelled) return;
syncComposerDraftPersistedAttachments(attachmentDraftTarget, fallbackAttachments);
}
})();
return () => {
cancelled = true;
};
}, [
attachmentDraftTarget,
clearComposerDraftPersistedAttachments,
composerImages,
getComposerDraft,
syncComposerDraftPersistedAttachments,
]);