The best way to control Claude Code, Codex and more from any computer or phone
Mirrored from https://github.com/Camo67/t3code.git
Synced Nov 21, 04:45 UTC
| 1 | import { copySnapshot } from "./copySnapshot"; |
| 2 | import { VoiceInputSetup } from "./VoiceInputSetup"; |
| 3 | import { useComposerTypingGuard } from "./useComposerTypingGuard"; |
| 4 | import { insertAttachmentReferencesForDraft } from "./composerAttachmentReferences"; |
| 5 | import type { ComposerAttachmentInsertion } from "../composerAttachmentInsertion"; |
| 6 | import { DESKTOP_PASTE_AS_TEXT_EVENT } from "../../lib/desktopPasteAsText"; |
| 7 | import { BackgroundThreadContext, HiddenThreadContext } from "./backgroundThread"; |
| 8 | import { |
| 9 | resolveCompatibleRuntimeMode, |
| 10 | runtimeModeConfig, |
| 11 | resolveRuntimeModeOptions, |
| 12 | runtimeModeDenial, |
| 13 | } from "./runtimeModeConfig"; |
| 14 | import { isLocalEnvironmentDisabled } from "../../localEnvironment"; |
| 15 | import { usePrimaryEnvironmentId } from "../../state/environments"; |
| 16 | import { useRightPanelStore } from "~/rightPanelStore"; |
| 17 | import { importPastedComposerText, readPastedComposerContext } from "../composerInlineTokenPaste"; |
| 18 | import { |
| 19 | questionAttachmentDraftId, |
| 20 | trackOpenQuestionAttachmentDraft, |
| 21 | useQuestionAttachmentPreparation, |
| 22 | } from "../../questionAttachments"; |
| 23 | import type { |
| 24 | KeybindingCommand, |
| 25 | AssistantCitation, |
| 26 | ResponseContextRecord, |
| 27 | ChatAttachment as ContractChatAttachment, |
| 28 | ChatFileAttachment, |
| 29 | EnvironmentId, |
| 30 | ModelSelection, |
| 31 | ProjectId, |
| 32 | PreviewAnnotationPayload, |
| 33 | ThreadContextRecord, |
| 34 | EnvironmentContextRecord, |
| 35 | ResolvedKeybindingsConfig, |
| 36 | RuntimeMode, |
| 37 | RuntimeRequestId, |
| 38 | ScopedThreadRef, |
| 39 | ServerProvider, |
| 40 | ThreadId, |
| 41 | } from "@t3tools/contracts"; |
| 42 | import { |
| 43 | EnvironmentRequestInvalidError, |
| 44 | AuthOrchestrationOperateScope, |
| 45 | clampManagedRuntimeMode, |
| 46 | ProviderDriverKind, |
| 47 | ProviderInstanceId, |
| 48 | PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 49 | PRIMARY_LOCAL_ENVIRONMENT_ID, |
| 50 | } from "@t3tools/contracts"; |
| 51 | import type { EnvironmentConnectionPresentation } from "@t3tools/client-runtime/connection"; |
| 52 | import { settlePromise, squashAtomCommandFailure } from "@t3tools/client-runtime/state/runtime"; |
| 53 | import * as Schema from "effect/Schema"; |
| 54 | import { formatComposerModelMention } from "@t3tools/client-runtime/composer-model-mentions"; |
| 55 | import { isPasteAsTextShortcut } from "@t3tools/client-runtime/text-paste"; |
| 56 | import { scopedThreadKey, scopeThreadRef } from "@t3tools/client-runtime/environment"; |
| 57 | import { serializeComposerFileLink } from "@t3tools/shared/composerTrigger"; |
| 58 | import { type FolderDropTarget, folderDropTarget, resolveDroppedFolderPath } from "./folderDrop"; |
| 59 | import { splitTransferredFiles } from "./workspaceFileDrop"; |
| 60 | import { createModelSelection, normalizeModelSlug } from "@t3tools/shared/model"; |
| 61 | import { USAGE_LIMITS_COMMAND } from "@t3tools/shared/usageLimits"; |
| 62 | import { |
| 63 | memo, |
| 64 | use, |
| 65 | useEffect, |
| 66 | useEffectEvent, |
| 67 | useId, |
| 68 | useImperativeHandle, |
| 69 | useLayoutEffect, |
| 70 | useRef, |
| 71 | useState, |
| 72 | } from "react"; |
| 73 | import { msg, T, useGT, useMessages, Var } from "gt-react"; |
| 74 | import { flushSync } from "react-dom"; |
| 75 | import { |
| 76 | clampCollapsedComposerCursor, |
| 77 | type ComposerTrigger, |
| 78 | type ComposerSubmissionIntent, |
| 79 | collapseExpandedComposerCursor, |
| 80 | composerRequiresModifier, |
| 81 | composerSubmissionIntentForKey, |
| 82 | composerStateAtPromptEnd, |
| 83 | detectComposerTrigger, |
| 84 | expandCollapsedComposerCursor, |
| 85 | formatAssistantCitationForComposer, |
| 86 | isPathSuggestionCurrent, |
| 87 | extendReplacementRangeForTrailingSpace, |
| 88 | replaceTextRange, |
| 89 | } from "../../composer-logic"; |
| 90 | import { DEFAULT_COMPOSER_PLACEHOLDER } from "../../composerPlaceholder"; |
| 91 | import { deriveComposerSendState, getAntigravitySendBlockReason } from "../ChatView.logic"; |
| 92 | import { threadHasStarted } from "../../lib/chatThreadActions"; |
| 93 | import { |
| 94 | dataTransferHasComposerMention, |
| 95 | makeComposerMentionDragHandlers, |
| 96 | } from "./composerMentionDrag"; |
| 97 | import { serializeComposerImages } from "./composerImagePersistence"; |
| 98 | import { |
| 99 | isInsideCollapsedComposerControls, |
| 100 | isInsideRestingComposerControlScope, |
| 101 | markOpenToEffort, |
| 102 | markOpenToPermissions, |
| 103 | } from "./composerEventScope"; |
| 104 | import { |
| 105 | type ComposerFileAttachment, |
| 106 | type ComposerImageAttachment, |
| 107 | type DraftId, |
| 108 | composerFileNeedsReattach, |
| 109 | composerDraftHasUserContent, |
| 110 | composerTargetKey, |
| 111 | readComposerDraftPrompt, |
| 112 | resolveLiveComposerDraftTarget, |
| 113 | useComposerDraftStore, |
| 114 | useComposerThreadDraft, |
| 115 | } from "../../composerDraftStore"; |
| 116 | import { buildDraftThreadRouteParams, buildThreadRouteParams } from "../../threadRoutes"; |
| 117 | import { ComposerStashBadge } from "./ComposerStashBadge"; |
| 118 | import { ComposerStashMenu } from "./ComposerStashMenu"; |
| 119 | import { useComposerTriggerState } from "./useComposerTriggerState"; |
| 120 | import { useComposerMenuItems } from "./useComposerMenuItems"; |
| 121 | import { useComposerMultilinePrompt } from "./useComposerMultilinePrompt"; |
| 122 | import { |
| 123 | reconcileAttachmentContextReferences, |
| 124 | useRetainedContextPayloads, |
| 125 | } from "./composerContextUndo"; |
| 126 | import { ComposerBanner } from "./ComposerBanner"; |
| 127 | import { ComposerSurface } from "./ComposerSurface"; |
| 128 | import { CollapsedComposerPromptPreview } from "./CollapsedComposerPromptPreview"; |
| 129 | import { ComposerBannerStack, type ComposerBannerStackItem } from "./ComposerBannerStack"; |
| 130 | import { |
| 131 | attachmentsToReleaseOnUploadCapabilityLoss, |
| 132 | composerOtherFilesForPresentation, |
| 133 | fileAttachmentCapabilityBlockReason, |
| 134 | fileAttachmentStagingLimit, |
| 135 | isPreviewableComposerVideo, |
| 136 | shouldHandleComposerAttachmentPaste, |
| 137 | } from "./composerAttachmentFiles"; |
| 138 | import { |
| 139 | releaseAttachmentUpload, |
| 140 | releaseDraftAttachment, |
| 141 | startAttachmentUpload, |
| 142 | useAttachmentUploadStore, |
| 143 | } from "../../lib/attachmentUploadQueue"; |
| 144 | import { attachmentUploadBlockReason } from "../../lib/attachmentUploadState"; |
| 145 | import { useDictationShortcut } from "../../speech/useDictationShortcut"; |
| 146 | import { useDictationSubmissionShortcut } from "../../speech/useDictationSubmissionShortcut"; |
| 147 | import { useEnvironmentSpeechInput } from "../../speech/useEnvironmentSpeechInput"; |
| 148 | import { ComposerSpeechButton, ComposerSpeechRecordingPill } from "./ComposerSpeechButton"; |
| 149 | import type { AssistantCitationSourceAnchor } from "~/lib/assistantTextSelection"; |
| 150 | import { shortcutLabelForCommand, type ShortcutMatchContext } from "../../keybindings"; |
| 151 | import { |
| 152 | type TerminalContextDraft, |
| 153 | type TerminalContextSelection, |
| 154 | } from "../../lib/terminalContext"; |
| 155 | import { |
| 156 | formatComposerContextReference, |
| 157 | threadContextRecord, |
| 158 | toKindScopedComposerContextId, |
| 159 | } from "@t3tools/shared/composerContextReferences"; |
| 160 | import { |
| 161 | shouldUseCompactComposerPrimaryActions, |
| 162 | shouldUseCompactComposerFooter, |
| 163 | } from "../composerFooterLayout"; |
| 164 | import { |
| 165 | type ComposerCitationCommentRequest, |
| 166 | type ComposerPromptEditorHandle, |
| 167 | ComposerPromptEditorTiptap as ComposerPromptEditor, |
| 168 | } from "../ComposerPromptEditorTiptap"; |
| 169 | import { |
| 170 | ComposerContextActionsContext, |
| 171 | composerContextRecordsFromDraft, |
| 172 | } from "../composerContextPresentation"; |
| 173 | import { useOpenPrLink } from "~/lib/openPullRequestLink"; |
| 174 | import { |
| 175 | collectInlineContextIds, |
| 176 | type ComposerContextReference, |
| 177 | ensureInlineContextReferences, |
| 178 | formatInlineContextReference, |
| 179 | insertInlineContextReference, |
| 180 | inlineContextReferenceReplacement, |
| 181 | } from "~/lib/composerContextReferences"; |
| 182 | import { |
| 183 | attachmentContextRecord, |
| 184 | uploadedAttachmentContextRecord, |
| 185 | previewAnnotationContextId, |
| 186 | previewAnnotationContextRecord, |
| 187 | reviewCommentContextId, |
| 188 | reviewCommentContextReference, |
| 189 | reviewCommentContextRecord, |
| 190 | terminalContextReference, |
| 191 | terminalContextRecord, |
| 192 | threadContextReference, |
| 193 | environmentContextRecord, |
| 194 | environmentContextReference, |
| 195 | } from "~/lib/composerContextRecords"; |
| 196 | import { rememberCopiedComposerAttachments } from "~/lib/copiedComposerAttachments"; |
| 197 | import { useThreadContextDrop, threadContextDropTargetProps } from "./threadContextDrag"; |
| 198 | import { droppedThreadContextRecord } from "./threadContextDrop.logic"; |
| 199 | import { readThreadShell } from "~/state/entities"; |
| 200 | import { useLinkedEnvironments } from "~/state/peerLinks"; |
| 201 | import { encodeComposerContextFragment } from "@t3tools/shared/composerContextClipboard"; |
| 202 | import type { |
| 203 | ComposerContextRecord, |
| 204 | OrchestrationV2Run, |
| 205 | ThreadPullRequestLink, |
| 206 | } from "@t3tools/contracts"; |
| 207 | import { threadContextAttachment } from "~/lib/threadContextAttachment"; |
| 208 | import { |
| 209 | type ComposerCommandItem, |
| 210 | ComposerCommandMenu, |
| 211 | composerSuggestionOptionId, |
| 212 | } from "./ComposerCommandMenu"; |
| 213 | import { |
| 214 | ComposerAttachButton, |
| 215 | ComposerAttachmentFileList, |
| 216 | ComposerAttachmentMediaRow, |
| 217 | ComposerFilePreviewDialog, |
| 218 | ComposerQueuedAttachmentRow, |
| 219 | ComposerRestingImagePreviews, |
| 220 | } from "./ComposerAttachmentStrip"; |
| 221 | import { CollapsedComposerStopAction, ComposerPrimaryActions } from "./ComposerPrimaryActions"; |
| 222 | import { ComposerFooterPrimaryActions } from "./ComposerFooterControls"; |
| 223 | import { ComposerPendingUserInputPanel } from "./ComposerPendingUserInputPanel"; |
| 224 | import { resolveComposerMenuActiveItemId } from "./composerMenuHighlight"; |
| 225 | import { buildPullRequestReferenceContext } from "../pullRequest/pullRequestDetail.logic"; |
| 226 | import { getComposerPromptInjectionState, getComposerReasoningStep } from "./composerProviderState"; |
| 227 | import { readPromptUltrathink } from "./TraitsPicker"; |
| 228 | import { useApplyThreadModelPick } from "./useApplyThreadModelPick"; |
| 229 | import { |
| 230 | buildAttachmentVideoPreview, |
| 231 | buildExpandedImagePreview, |
| 232 | type ExpandedImagePreview, |
| 233 | } from "./ExpandedImagePreview"; |
| 234 | import { cn, isMacPlatform, randomUUID } from "~/lib/utils"; |
| 235 | import { |
| 236 | getComposerPromptLengthValidationMessage, |
| 237 | getComposerSubmissionValidationMessage, |
| 238 | isComposerSubmissionBlocked, |
| 239 | submitComposerDraft, |
| 240 | } from "./composerSubmission"; |
| 241 | import { ComposerPromptLengthValidation } from "./ComposerPromptLengthValidation"; |
| 242 | import { pendingDraftWork } from "./pendingDraftWork"; |
| 243 | import { importComposerThreadAttachment } from "./composerThreadImport"; |
| 244 | import { observeResize } from "~/lib/observeResize"; |
| 245 | |
| 246 | const isEnvironmentRequestInvalidError = Schema.is(EnvironmentRequestInvalidError); |
| 247 | import { toastManager } from "../ui/toast"; |
| 248 | import { m as resolveMessage } from "../../i18n/messages"; |
| 249 | import { BuildingIcon, PlayIcon, ReplyIcon } from "lucide-react"; |
| 250 | import { useNavigate } from "@tanstack/react-router"; |
| 251 | import { assistantCitationLabel } from "@t3tools/shared/assistantCitations"; |
| 252 | import { assistantCitationNavigation } from "../../lib/assistantCitationNavigation"; |
| 253 | import { Button } from "../ui/button"; |
| 254 | import { useManagedPolicy } from "../../state/managedPolicy"; |
| 255 | import { hasProviderSetup } from "./ProviderStatusBanner"; |
| 256 | import { type AppModelOption, getAppModelOptionsForInstance } from "../../modelSelection"; |
| 257 | import type { UnifiedSettings } from "@t3tools/contracts/settings"; |
| 258 | import { isVideoAttachment, type SessionPhase, type Thread } from "../../types"; |
| 259 | import { type ComposerPromptHistoryPosition } from "./composerPromptHistory"; |
| 260 | import { usePendingUserInputDraft } from "./usePendingThreadRequests"; |
| 261 | import type { PendingApproval, PendingUserInput, TimelineEntry } from "../../session-logic"; |
| 262 | import { |
| 263 | composerRunsDraftLocally, |
| 264 | resolveComposerDispatchMode, |
| 265 | type ComposerDispatchMode, |
| 266 | } from "@t3tools/client-runtime/state/composer-dispatch"; |
| 267 | import { |
| 268 | resolveProviderSkillsForCwd, |
| 269 | resolveProviderSlashCommandsForCwd, |
| 270 | } from "@t3tools/client-runtime/providerSkills"; |
| 271 | import { useMediaQuery } from "../../hooks/useMediaQuery"; |
| 272 | import { Kbd } from "../ui/kbd"; |
| 273 | import { useSoftwareKeyboardOpen } from "../../hooks/useSoftwareKeyboardOpen"; |
| 274 | import { useStableCallback } from "../../hooks/useStableCallback"; |
| 275 | import { usePanelAnimationSettings } from "../../panelAnimations"; |
| 276 | import { readEnvironmentScope, readPreparedConnection } from "../../state/session"; |
| 277 | import type { ReviewCommentContext } from "../../reviewCommentContext"; |
| 278 | import { useComposerRestingTransition } from "./useComposerRestingTransition"; |
| 279 | import { ComposerCommandMenuLayer } from "./ComposerCommandMenuLayer"; |
| 280 | import { useRestingComposerControlsLayout } from "./useRestingComposerControlsLayout"; |
| 281 | import { useProviderWorkspaceSnapshotRefresh } from "./useProviderWorkspaceSnapshotRefresh"; |
| 282 | import { useComposerProviderModel } from "./useComposerProviderModel"; |
| 283 | import { useComposerImageGroups } from "./useComposerImageGroups"; |
| 284 | import { useComposerStash } from "./useComposerStash"; |
| 285 | import { useComposerContextImport } from "./useComposerContextImport"; |
| 286 | import { useComposerAttachmentIntake } from "./useComposerAttachmentIntake"; |
| 287 | import { |
| 288 | countPreparingComposerImages, |
| 289 | usePreparingComposerImages, |
| 290 | useSubmitAfterPreparingImages, |
| 291 | } from "./preparingComposerImages"; |
| 292 | import { ComposerControlsBar } from "./ComposerControlsBar"; |
| 293 | import { composerCommandKeyHandler } from "./composerCommandKey"; |
| 294 | import { usePromptSuggestion } from "./usePromptSuggestion"; |
| 295 | import { useFreshSessionArmed } from "./freshSessionArms"; |
| 296 | |
| 297 | function consumePasteAsTextShortcut(deadline: { current: number }): boolean { |
| 298 | const armed = Date.now() <= deadline.current; |
| 299 | deadline.current = 0; |
| 300 | return armed; |
| 301 | } |
| 302 | |
| 303 | export interface ChatComposerHandle { |
| 304 | focusAtEnd: () => void; |
| 305 | focusAt: (cursor: number) => void; |
| 306 | addDroppedFiles: (files: File[]) => void; |
| 307 | addDroppedFolders: (folders: File[]) => void; |
| 308 | hasPendingAttachments: () => boolean; |
| 309 | insertTextAtEnd: ( |
| 310 | text: string, |
| 311 | options?: { ensureLeadingBoundary?: boolean; clipboardData?: DataTransfer }, |
| 312 | ) => boolean; |
| 313 | pasteTextAtEnd: (text: string, options?: { bypassAutoAttachment?: boolean }) => boolean; |
| 314 | citeAssistantText: ( |
| 315 | citation: AssistantCitation, |
| 316 | sourceAnchor: AssistantCitationSourceAnchor, |
| 317 | ) => boolean; |
| 318 | replyToResponse: (response: ResponseContextRecord) => boolean; |
| 319 | openModelPicker: () => void; |
| 320 | stepReasoningEffort: (direction: 1 | -1) => void; |
| 321 | toggleModelPicker: () => void; |
| 322 | openControl: (command: KeybindingCommand) => void; |
| 323 | isModelPickerOpen: () => boolean; |
| 324 | isCaretAtStart: () => boolean; |
| 325 | compactContext: () => void; |
| 326 | readSnapshot: () => { |
| 327 | value: string; |
| 328 | cursor: number; |
| 329 | expandedCursor: number; |
| 330 | contextIds: string[]; |
| 331 | }; |
| 332 | resetCursorState: (options?: { |
| 333 | cursor?: number; |
| 334 | prompt?: string; |
| 335 | detectTrigger?: boolean; |
| 336 | }) => void; |
| 337 | addTerminalContext: (selection: TerminalContextSelection) => void; |
| 338 | getSendContext: () => { |
| 339 | answeringPendingUserInput: boolean; |
| 340 | prompt: string; |
| 341 | images: ComposerImageAttachment[]; |
| 342 | files: ComposerFileAttachment[]; |
| 343 | terminalContexts: TerminalContextDraft[]; |
| 344 | previewAnnotations: PreviewAnnotationPayload[]; |
| 345 | reviewComments: ReviewCommentContext[]; |
| 346 | threadContexts: ThreadContextRecord[]; |
| 347 | environmentContexts: EnvironmentContextRecord[]; |
| 348 | selectedPromptEffort: string | null; |
| 349 | selectedModelSelection: ModelSelection; |
| 350 | multipleModelSelections: ReadonlyArray<ModelSelection> | null; |
| 351 | providerAvailable: boolean; |
| 352 | selectedProvider: ProviderDriverKind; |
| 353 | selectedModel: string; |
| 354 | selectedProviderModels: ReadonlyArray<ServerProvider["models"][number]>; |
| 355 | shownPendingApprovalIds: ReadonlyArray<RuntimeRequestId>; |
| 356 | }; |
| 357 | validateProviderInput: (providerInput: string) => boolean; |
| 358 | setMultipleModelSelections: (selections: ReadonlyArray<ModelSelection>) => void; |
| 359 | } |
| 360 | |
| 361 | export interface ChatComposerProps { |
| 362 | composerDraftTarget: ScopedThreadRef | DraftId; |
| 363 | environmentId: EnvironmentId; |
| 364 | canOperateThread: boolean; |
| 365 | attachmentUploadsCapabilityKnown: boolean; |
| 366 | supportsAttachmentUploads: boolean; |
| 367 | supportsQuestionAttachments: boolean; |
| 368 | maxFileAttachmentBytes: number | null; |
| 369 | routeKind: "server" | "draft"; |
| 370 | routeThreadRef: ScopedThreadRef; |
| 371 | draftId: DraftId | null; |
| 372 | multipleModelSelections: ReadonlyArray<ModelSelection> | null; |
| 373 | supportsMultipleModels: boolean; |
| 374 | onMultipleModelSelectionsChange: React.Dispatch< |
| 375 | React.SetStateAction<ReadonlyArray<ModelSelection> | null> |
| 376 | >; |
| 377 | |
| 378 | activeThreadId: ThreadId | null; |
| 379 | activeThread: Thread | undefined; |
| 380 | activeThreadRuns: ReadonlyArray<OrchestrationV2Run>; |
| 381 | promptHistoryEntries: ReadonlyArray<TimelineEntry>; |
| 382 | forceExpandedOnMobile: boolean; |
| 383 | projectSelectionRequired: boolean; |
| 384 | |
| 385 | phase: SessionPhase; |
| 386 | canInterrupt: boolean; |
| 387 | isSendBusy: boolean; |
| 388 | canResume: boolean; |
| 389 | isRevertingCheckpoint?: boolean; |
| 390 | sendDisabledReason: string | null; |
| 391 | isPreparingWorktree: boolean; |
| 392 | canSteer: boolean; |
| 393 | bannerItems: readonly ComposerBannerStackItem[]; |
| 394 | resumeCompactionTokens: number | null; |
| 395 | keepFullHistory: boolean; |
| 396 | onToggleKeepFullHistory: () => void; |
| 397 | onUsageLimitsCommand?: (() => void) | undefined; |
| 398 | sideChatAvailable?: boolean; |
| 399 | sideChatDisabledReason?: string | null; |
| 400 | /** Arms a fresh session for the next message; absent where `/clear` is unavailable. */ |
| 401 | onFreshSession?: (() => void) | undefined; |
| 402 | environmentUnavailable: { |
| 403 | readonly label: string; |
| 404 | readonly connection: EnvironmentConnectionPresentation; |
| 405 | } | null; |
| 406 | |
| 407 | activePendingApproval: PendingApproval | null; |
| 408 | pendingApprovals: PendingApproval[]; |
| 409 | onHeldRequestIdsChange: (requestIds: ReadonlySet<string>) => void; |
| 410 | pendingUserInputs: PendingUserInput[]; |
| 411 | activePendingIsResponding: boolean; |
| 412 | respondingRequestIds: RuntimeRequestId[]; |
| 413 | |
| 414 | runtimeMode: RuntimeMode; |
| 415 | defaultRuntimeMode?: RuntimeMode; |
| 416 | |
| 417 | lockedProvider: ProviderDriverKind | null; |
| 418 | providerStatuses: ServerProvider[]; |
| 419 | providerCatalogKnown: boolean; |
| 420 | activeProjectDefaultModelSelection: ModelSelection | null | undefined; |
| 421 | activeThreadModelSelection: ModelSelection | null | undefined; |
| 422 | reportedModelSelection?: ModelSelection | null; |
| 423 | activeProjectId: ProjectId | null; |
| 424 | projectName?: string | undefined; |
| 425 | |
| 426 | compactThreadUnavailable: boolean; |
| 427 | compactDisabled: boolean; |
| 428 | |
| 429 | resolvedTheme: "light" | "dark"; |
| 430 | settings: UnifiedSettings; |
| 431 | keybindings: ResolvedKeybindingsConfig; |
| 432 | getShortcutContext: (eventTarget: EventTarget | null) => ShortcutMatchContext; |
| 433 | terminalOpen: boolean; |
| 434 | gitCwd: string | null; |
| 435 | pullRequestProjectId: ProjectId | null; |
| 436 | pullRequestRepository: string | null; |
| 437 | threadPullRequests: ReadonlyArray<ThreadPullRequestLink> | undefined; |
| 438 | onComposerOverlayHeightChange: (height: number) => void; |
| 439 | /** The new-thread strip names the permissions, so the controls row hides its chip. */ |
| 440 | permissionsShownInStrip: boolean; |
| 441 | |
| 442 | promptRef: React.RefObject<string>; |
| 443 | composerImagesRef: React.RefObject<ComposerImageAttachment[]>; |
| 444 | composerFilesRef: React.RefObject<ComposerFileAttachment[]>; |
| 445 | composerTerminalContextsRef: React.RefObject<TerminalContextDraft[]>; |
| 446 | composerRef: React.RefObject<ChatComposerHandle | null>; |
| 447 | onPageScrollKeyDown: (key: "PageUp" | "PageDown") => void; |
| 448 | onPageScrollKeyUp: (key: string) => void; |
| 449 | onPageScrollRelease: () => void; |
| 450 | |
| 451 | editingQueuedAttachments: ReadonlyArray<{ |
| 452 | readonly attachment: ContractChatAttachment; |
| 453 | readonly url: string | null; |
| 454 | }> | null; |
| 455 | onRemoveEditingQueuedAttachment: (attachmentId: string) => void; |
| 456 | |
| 457 | onCompactContext: () => void; |
| 458 | onSend: ( |
| 459 | e?: { preventDefault: () => void }, |
| 460 | dispatchMode?: ComposerDispatchMode, |
| 461 | submissionIntent?: ComposerSubmissionIntent, |
| 462 | ) => void; |
| 463 | onResume: () => void; |
| 464 | onInterrupt: () => void; |
| 465 | onSelectActivePendingUserInputOption: (questionId: string, optionValue: string) => void; |
| 466 | onAdvanceActivePendingUserInput: () => void; |
| 467 | onDismissActivePendingUserInput: (requestId: RuntimeRequestId) => void; |
| 468 | onPreviousActivePendingUserInputQuestion: () => void; |
| 469 | onChangeActivePendingUserInputCustomAnswer: ( |
| 470 | questionId: string, |
| 471 | value: string, |
| 472 | nextCursor: number, |
| 473 | expandedCursor: number, |
| 474 | cursorAdjacentToMention: boolean, |
| 475 | ) => void; |
| 476 | |
| 477 | onProviderModelSelect: ( |
| 478 | instanceId: ProviderInstanceId, |
| 479 | model: string, |
| 480 | options?: { focusComposer?: boolean }, |
| 481 | ) => void; |
| 482 | onOpenProviderSetup: (instanceId: ProviderInstanceId) => void; |
| 483 | getModelDisabledReason: (instanceId: ProviderInstanceId, model: string) => string | null; |
| 484 | handleRuntimeModeChange: (mode: RuntimeMode) => void; |
| 485 | |
| 486 | focusComposer: () => void; |
| 487 | scheduleComposerFocus: () => void; |
| 488 | setThreadError: (threadId: ThreadId | null, error: string | null) => void; |
| 489 | onExpandImage: (preview: ExpandedImagePreview) => void; |
| 490 | onFileOpen: (attachment: ChatFileAttachment) => void; |
| 491 | } |
| 492 | |
| 493 | const NO_PROVIDER_SKILLS: ServerProvider["skills"] = []; |
| 494 | const NO_PROVIDER_SLASH_COMMANDS: ServerProvider["slashCommands"] = []; |
| 495 | |
| 496 | export const ChatComposer = memo(function ChatComposer(props: ChatComposerProps) { |
| 497 | const gt = useGT(); |
| 498 | const m = useMessages(); |
| 499 | const { |
| 500 | composerDraftTarget, |
| 501 | environmentId, |
| 502 | canOperateThread, |
| 503 | attachmentUploadsCapabilityKnown, |
| 504 | supportsAttachmentUploads, |
| 505 | supportsQuestionAttachments, |
| 506 | maxFileAttachmentBytes, |
| 507 | routeKind, |
| 508 | routeThreadRef, |
| 509 | draftId, |
| 510 | multipleModelSelections, |
| 511 | supportsMultipleModels, |
| 512 | onMultipleModelSelectionsChange: setMultipleModelSelections, |
| 513 | activeThreadId, |
| 514 | activeThread, |
| 515 | activeThreadRuns, |
| 516 | promptHistoryEntries, |
| 517 | forceExpandedOnMobile, |
| 518 | projectSelectionRequired, |
| 519 | phase, |
| 520 | canInterrupt, |
| 521 | isSendBusy, |
| 522 | canResume, |
| 523 | isRevertingCheckpoint = false, |
| 524 | sendDisabledReason: externalSendDisabledReason, |
| 525 | isPreparingWorktree, |
| 526 | canSteer, |
| 527 | environmentUnavailable, |
| 528 | activePendingApproval: incomingPendingApproval, |
| 529 | pendingApprovals, |
| 530 | onHeldRequestIdsChange, |
| 531 | pendingUserInputs: incomingPendingUserInputs, |
| 532 | activePendingIsResponding: incomingPendingIsResponding, |
| 533 | respondingRequestIds, |
| 534 | runtimeMode, |
| 535 | lockedProvider, |
| 536 | providerStatuses, |
| 537 | providerCatalogKnown, |
| 538 | activeProjectDefaultModelSelection, |
| 539 | activeThreadModelSelection, |
| 540 | reportedModelSelection, |
| 541 | activeProjectId, |
| 542 | projectName, |
| 543 | compactThreadUnavailable, |
| 544 | compactDisabled, |
| 545 | resolvedTheme, |
| 546 | settings, |
| 547 | keybindings, |
| 548 | getShortcutContext, |
| 549 | terminalOpen, |
| 550 | gitCwd, |
| 551 | pullRequestProjectId, |
| 552 | pullRequestRepository, |
| 553 | threadPullRequests, |
| 554 | onComposerOverlayHeightChange, |
| 555 | promptRef, |
| 556 | composerRef, |
| 557 | composerImagesRef, |
| 558 | composerFilesRef, |
| 559 | composerTerminalContextsRef, |
| 560 | onPageScrollKeyDown, |
| 561 | onPageScrollKeyUp, |
| 562 | onPageScrollRelease, |
| 563 | onCompactContext, |
| 564 | onSend, |
| 565 | onResume, |
| 566 | onInterrupt, |
| 567 | onSelectActivePendingUserInputOption, |
| 568 | onAdvanceActivePendingUserInput, |
| 569 | onDismissActivePendingUserInput, |
| 570 | onPreviousActivePendingUserInputQuestion, |
| 571 | onChangeActivePendingUserInputCustomAnswer, |
| 572 | onProviderModelSelect, |
| 573 | onOpenProviderSetup, |
| 574 | getModelDisabledReason, |
| 575 | handleRuntimeModeChange, |
| 576 | focusComposer, |
| 577 | scheduleComposerFocus, |
| 578 | setThreadError, |
| 579 | onExpandImage, |
| 580 | onFileOpen, |
| 581 | editingQueuedAttachments, |
| 582 | onRemoveEditingQueuedAttachment, |
| 583 | } = props; |
| 584 | const { |
| 585 | activePendingProgress: incomingPendingProgress, |
| 586 | activePendingResolvedAnswers, |
| 587 | activePendingDraftAnswers, |
| 588 | activePendingQuestionIndex, |
| 589 | } = usePendingUserInputDraft({ |
| 590 | environmentId, |
| 591 | activeThreadId, |
| 592 | activePendingUserInput: incomingPendingUserInputs[0] ?? null, |
| 593 | supportsQuestionAttachments, |
| 594 | }); |
| 595 | const primaryEnvironmentId = usePrimaryEnvironmentId(); |
| 596 | const composerDraftTargetKey = composerTargetKey(composerDraftTarget); |
| 597 | const { |
| 598 | heldRequestIds, |
| 599 | onDraftChange: onTypingGuardDraftChange, |
| 600 | onFocus: onTypingGuardFocus, |
| 601 | onBlur: onTypingGuardBlur, |
| 602 | onSend: onTypingGuardSend, |
| 603 | } = useComposerTypingGuard(composerDraftTargetKey, [ |
| 604 | ...pendingApprovals.map((request) => request.requestId), |
| 605 | ...incomingPendingUserInputs.map((request) => request.requestId), |
| 606 | ]); |
| 607 | // A layout effect so the timeline never paints a held approval as answerable. |
| 608 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes held requests to the timeline without lifting per-keystroke typing state |
| 609 | useLayoutEffect(() => { |
| 610 | onHeldRequestIdsChange(heldRequestIds); |
| 611 | }, [heldRequestIds, onHeldRequestIdsChange]); |
| 612 | const activePendingApproval = |
| 613 | incomingPendingApproval && !heldRequestIds.has(incomingPendingApproval.requestId) |
| 614 | ? incomingPendingApproval |
| 615 | : null; |
| 616 | const holdingUserInput = incomingPendingUserInputs[0] |
| 617 | ? heldRequestIds.has(incomingPendingUserInputs[0].requestId) |
| 618 | : false; |
| 619 | const pendingUserInputs = holdingUserInput ? [] : incomingPendingUserInputs; |
| 620 | const activePendingProgress = holdingUserInput ? null : incomingPendingProgress; |
| 621 | const activePendingIsResponding = !holdingUserInput && incomingPendingIsResponding; |
| 622 | const isLiteralPendingAnswer = activePendingProgress?.activeQuestion?.initialAnswer !== undefined; |
| 623 | const isEditingQueuedMessage = editingQueuedAttachments !== null; |
| 624 | const applyThreadModelPick = useApplyThreadModelPick(); |
| 625 | const composerDraft = useComposerThreadDraft(composerDraftTarget); |
| 626 | const composerDraftTargetKeyRef = useRef(""); |
| 627 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed draft target key to a ref read by async handlers |
| 628 | useLayoutEffect(() => { |
| 629 | composerDraftTargetKeyRef.current = composerDraftTargetKey; |
| 630 | }); |
| 631 | const questionAttachmentTarget = |
| 632 | pendingUserInputs[0] && activePendingProgress?.activeQuestion |
| 633 | ? questionAttachmentDraftId( |
| 634 | environmentId, |
| 635 | activeThreadId!, |
| 636 | pendingUserInputs[0].requestId, |
| 637 | activePendingProgress.activeQuestion.id, |
| 638 | ) |
| 639 | : null; |
| 640 | const attachmentDraftTarget = questionAttachmentTarget ?? composerDraftTarget; |
| 641 | const attachmentDraft = useComposerThreadDraft(attachmentDraftTarget); |
| 642 | const questionTakesSnapShots = |
| 643 | supportsQuestionAttachments && |
| 644 | activePendingProgress?.activeQuestion?.allowCustomAnswer !== false && |
| 645 | !activePendingIsResponding; |
| 646 | const questionRequest = pendingUserInputs[0]; |
| 647 | // Publish eligibility before async captures can observe a question the UI has already closed. |
| 648 | // 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 |
| 649 | useLayoutEffect(() => { |
| 650 | if (!questionAttachmentTarget || !questionRequest || !questionTakesSnapShots) return; |
| 651 | return trackOpenQuestionAttachmentDraft(routeThreadRef, { |
| 652 | draftId: questionAttachmentTarget, |
| 653 | requestKeys: questionRequest.questions.map((question) => |
| 654 | questionAttachmentDraftId( |
| 655 | environmentId, |
| 656 | activeThreadId!, |
| 657 | questionRequest.requestId, |
| 658 | question.id, |
| 659 | ), |
| 660 | ), |
| 661 | }); |
| 662 | }, [ |
| 663 | activeThreadId, |
| 664 | environmentId, |
| 665 | questionAttachmentTarget, |
| 666 | questionRequest, |
| 667 | questionTakesSnapShots, |
| 668 | routeThreadRef, |
| 669 | ]); |
| 670 | const attachmentTargetKey = composerTargetKey(attachmentDraftTarget); |
| 671 | // Reject async imports after a draft switch. |
| 672 | const attachmentTargetKeyRef = useRef(attachmentTargetKey); |
| 673 | // 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 |
| 674 | useLayoutEffect(() => { |
| 675 | attachmentTargetKeyRef.current = attachmentTargetKey; |
| 676 | }); |
| 677 | const composerMountedRef = useRef(true); |
| 678 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- tracks unmount so an awaited folder conversion cannot write into ChatView's reused promptRef |
| 679 | useLayoutEffect(() => { |
| 680 | composerMountedRef.current = true; |
| 681 | return () => { |
| 682 | composerMountedRef.current = false; |
| 683 | }; |
| 684 | }, []); |
| 685 | const questionPreparations = useQuestionAttachmentPreparation((state) => state.counts); |
| 686 | const prompt = composerDraft.prompt; |
| 687 | const composerImages = attachmentDraft.images; |
| 688 | const composerFiles = attachmentDraft.files; |
| 689 | const inlineFileIdSet = (() => { |
| 690 | if (questionAttachmentTarget) return new Set<string>(); |
| 691 | const contextIds = new Set(collectInlineContextIds(prompt)); |
| 692 | return new Set( |
| 693 | composerFiles |
| 694 | .filter((file) => contextIds.has(toKindScopedComposerContextId("file", file.id))) |
| 695 | .map((file) => file.id), |
| 696 | ); |
| 697 | })(); |
| 698 | const composerVideos = composerFiles.filter((file) => |
| 699 | isPreviewableComposerVideo(file, environmentId), |
| 700 | ); |
| 701 | const composerOtherFiles = composerOtherFilesForPresentation( |
| 702 | composerFiles, |
| 703 | environmentId, |
| 704 | inlineFileIdSet, |
| 705 | ); |
| 706 | const composerTerminalContexts = composerDraft.terminalContexts; |
| 707 | const composerPreviewAnnotations = composerDraft.previewAnnotations; |
| 708 | const composerReviewComments = composerDraft.reviewComments; |
| 709 | const composerThreadContexts = attachmentDraft.threadContexts; |
| 710 | const composerEnvironmentContexts = composerDraft.environmentContexts; |
| 711 | const { |
| 712 | pendingSnapShotAnimations, |
| 713 | pendingSnapShotIds, |
| 714 | uncommittedSnapShotIds, |
| 715 | standaloneComposerImages, |
| 716 | } = useComposerImageGroups(attachmentDraftTarget, composerImages, composerPreviewAnnotations); |
| 717 | const preparingComposerImages = usePreparingComposerImages(attachmentTargetKey).filter( |
| 718 | (image) => !image.hidden, |
| 719 | ); |
| 720 | const nonPersistedComposerImageIds = attachmentDraft.nonPersistedImageIds; |
| 721 | const uploadsByImageId = useAttachmentUploadStore((state) => state.uploadsByImageId); |
| 722 | const openPrLink = useOpenPrLink(routeThreadRef); |
| 723 | const [previewFileId, setPreviewFileId] = useState<string | null>(null); |
| 724 | const previewFile = composerFiles.find((file) => file.id === previewFileId); |
| 725 | const composerContextActions = { |
| 726 | environmentId, |
| 727 | cwd: gitCwd ?? undefined, |
| 728 | projectId: activeProjectId ?? undefined, |
| 729 | expandImage: (imageId: string) => { |
| 730 | const preview = buildExpandedImagePreview( |
| 731 | composerImages, |
| 732 | imageId, |
| 733 | copyComposerSnapshotStable, |
| 734 | ); |
| 735 | if (preview) onExpandImage(preview); |
| 736 | }, |
| 737 | openFile: setPreviewFileId, |
| 738 | openMention: (path: string) => useRightPanelStore.getState().openFile(routeThreadRef, path), |
| 739 | expandVideo: (fileId: string) => { |
| 740 | const file = composerFiles.find((candidate) => candidate.id === fileId); |
| 741 | if (!file || !isVideoAttachment(file)) return; |
| 742 | const localPreview = buildExpandedImagePreview([file], file.id); |
| 743 | if (localPreview) { |
| 744 | onExpandImage(localPreview); |
| 745 | return; |
| 746 | } |
| 747 | if (file.uploadedAttachmentId === undefined || file.uploadEnvironmentId !== environmentId) { |
| 748 | return; |
| 749 | } |
| 750 | const persistedPreview = buildAttachmentVideoPreview(environmentId, { |
| 751 | type: "file", |
| 752 | id: file.uploadedAttachmentId, |
| 753 | name: file.name, |
| 754 | mimeType: file.mimeType, |
| 755 | sizeBytes: file.sizeBytes, |
| 756 | }); |
| 757 | if (persistedPreview) onExpandImage(persistedPreview); |
| 758 | }, |
| 759 | openPullRequest: (event: React.MouseEvent<HTMLElement>, url: string) => { |
| 760 | openPrLink(event, url); |
| 761 | }, |
| 762 | }; |
| 763 | const composerContextRecords = composerContextRecordsFromDraft({ |
| 764 | terminalContexts: composerTerminalContexts, |
| 765 | reviewComments: composerReviewComments, |
| 766 | previewAnnotations: composerPreviewAnnotations, |
| 767 | threadContexts: composerThreadContexts, |
| 768 | environmentContexts: composerEnvironmentContexts, |
| 769 | images: composerImages, |
| 770 | files: composerFiles, |
| 771 | uploadsByImageId, |
| 772 | }); |
| 773 | const needsReattachFileCount = composerFiles.filter(composerFileNeedsReattach).length; |
| 774 | const fileStagingLimit = fileAttachmentStagingLimit({ |
| 775 | attachmentUploadsCapabilityKnown, |
| 776 | supportsAttachmentUploads, |
| 777 | maxFileAttachmentBytes, |
| 778 | }); |
| 779 | const fileCapabilityBlockReason = fileAttachmentCapabilityBlockReason( |
| 780 | { |
| 781 | files: composerFiles, |
| 782 | attachmentUploadsCapabilityKnown, |
| 783 | supportsAttachmentUploads, |
| 784 | maxFileAttachmentBytes, |
| 785 | }, |
| 786 | m, |
| 787 | ); |
| 788 | const attachmentBlockReason = |
| 789 | (questionAttachmentTarget && |
| 790 | !supportsQuestionAttachments && |
| 791 | (composerImages.length > 0 || composerFiles.length > 0) |
| 792 | ? gt("Update this server to send files with question answers") |
| 793 | : null) ?? |
| 794 | fileCapabilityBlockReason ?? |
| 795 | (supportsAttachmentUploads |
| 796 | ? needsReattachFileCount > 0 |
| 797 | ? needsReattachFileCount === 1 |
| 798 | ? gt("Attach the interrupted file again or remove it") |
| 799 | : gt("Attach the interrupted files again or remove them") |
| 800 | : // A plain send waits for its uploads. Answers and approval redirects need them first. |
| 801 | questionAttachmentTarget || |
| 802 | pendingApprovals.some((approval) => !heldRequestIds.has(approval.requestId)) |
| 803 | ? attachmentUploadBlockReason( |
| 804 | { |
| 805 | imageIds: [...composerImages, ...composerFiles].map((attachment) => attachment.id), |
| 806 | uploadsByImageId, |
| 807 | environmentId, |
| 808 | }, |
| 809 | m, |
| 810 | ) |
| 811 | : null |
| 812 | : null); |
| 813 | const setComposerDraftPrompt = useComposerDraftStore((store) => store.setPrompt); |
| 814 | const addComposerDraftImages = useComposerDraftStore((store) => store.addImages); |
| 815 | const removeComposerDraftImage = useComposerDraftStore((store) => store.removeImage); |
| 816 | const addComposerDraftFiles = useComposerDraftStore((store) => store.addFiles); |
| 817 | const removeComposerDraftFile = useComposerDraftStore((store) => store.removeFile); |
| 818 | const insertComposerDraftTerminalContext = useComposerDraftStore( |
| 819 | (store) => store.insertTerminalContext, |
| 820 | ); |
| 821 | const setComposerDraftTerminalContexts = useComposerDraftStore( |
| 822 | (store) => store.setTerminalContexts, |
| 823 | ); |
| 824 | const removeComposerDraftPreviewAnnotation = useComposerDraftStore( |
| 825 | (store) => store.removePreviewAnnotation, |
| 826 | ); |
| 827 | const removeComposerDraftReviewComment = useComposerDraftStore( |
| 828 | (store) => store.removeReviewComment, |
| 829 | ); |
| 830 | const clearComposerDraftPersistedAttachments = useComposerDraftStore( |
| 831 | (store) => store.clearPersistedAttachments, |
| 832 | ); |
| 833 | const syncComposerDraftPersistedAttachments = useComposerDraftStore( |
| 834 | (store) => store.syncPersistedAttachments, |
| 835 | ); |
| 836 | const getComposerDraft = useComposerDraftStore((store) => store.getComposerDraft); |
| 837 | const setComposerDraftReplyTo = useComposerDraftStore((store) => store.setReplyTo); |
| 838 | const navigate = useNavigate(); |
| 839 | |
| 840 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- starts or releases server attachment uploads as upload capability, limits and draft attachments change |
| 841 | useEffect(() => { |
| 842 | if (!attachmentUploadsCapabilityKnown) { |
| 843 | return; |
| 844 | } |
| 845 | if (!supportsAttachmentUploads) { |
| 846 | // Reconnect or version skew can hide upload support; retain hydrated uploads. |
| 847 | for (const attachment of attachmentsToReleaseOnUploadCapabilityLoss([ |
| 848 | ...composerImages, |
| 849 | ...composerFiles, |
| 850 | ])) { |
| 851 | releaseAttachmentUpload(attachment.id); |
| 852 | } |
| 853 | return; |
| 854 | } |
| 855 | if (!canOperateThread) return; |
| 856 | const invalidFiles = |
| 857 | maxFileAttachmentBytes === null |
| 858 | ? composerFiles |
| 859 | : composerFiles.filter((file) => file.sizeBytes > maxFileAttachmentBytes); |
| 860 | for (const attachment of attachmentsToReleaseOnUploadCapabilityLoss(invalidFiles)) { |
| 861 | releaseAttachmentUpload(attachment.id); |
| 862 | } |
| 863 | const uploadableFiles = |
| 864 | maxFileAttachmentBytes === null |
| 865 | ? [] |
| 866 | : composerFiles.filter((file) => file.sizeBytes <= maxFileAttachmentBytes); |
| 867 | const uploadableAttachments = [...composerImages, ...uploadableFiles]; |
| 868 | for (const attachment of uploadableAttachments) { |
| 869 | if (attachment.type === "file" && composerFileNeedsReattach(attachment)) { |
| 870 | continue; |
| 871 | } |
| 872 | startAttachmentUpload({ |
| 873 | environmentId, |
| 874 | image: attachment, |
| 875 | draftTarget: attachmentDraftTarget, |
| 876 | }); |
| 877 | } |
| 878 | }, [ |
| 879 | attachmentUploadsCapabilityKnown, |
| 880 | attachmentDraftTarget, |
| 881 | canOperateThread, |
| 882 | composerFiles, |
| 883 | composerImages, |
| 884 | environmentId, |
| 885 | maxFileAttachmentBytes, |
| 886 | supportsAttachmentUploads, |
| 887 | ]); |
| 888 | |
| 889 | const { |
| 890 | providerInstanceEntries, |
| 891 | selectedProviderEntry, |
| 892 | lockedContinuationGroupKey, |
| 893 | unavailableProviderInstanceId, |
| 894 | selectedInstanceId, |
| 895 | selectedProvider, |
| 896 | selectedProviderModels, |
| 897 | composerModelOptions, |
| 898 | selectedModel, |
| 899 | composerProviderState, |
| 900 | } = useComposerProviderModel({ |
| 901 | providerStatuses, |
| 902 | settings, |
| 903 | activeProjectId, |
| 904 | threadRef: composerDraftTarget, |
| 905 | threadModelSelection: activeThreadModelSelection, |
| 906 | projectModelSelection: activeProjectDefaultModelSelection, |
| 907 | promptInjectionState: getComposerPromptInjectionState(prompt), |
| 908 | threadStarted: threadHasStarted(activeThread), |
| 909 | candidateInstanceIds: [ |
| 910 | activeThread?.runtime?.providerInstanceId, |
| 911 | activeThreadModelSelection?.instanceId, |
| 912 | activeProjectDefaultModelSelection?.instanceId, |
| 913 | ], |
| 914 | lockedProvider, |
| 915 | lockedInstanceId: |
| 916 | activeThread?.runtime?.providerInstanceId ?? activeThreadModelSelection?.instanceId, |
| 917 | }); |
| 918 | const noProviderAvailable = |
| 919 | selectedProviderEntry === undefined && multipleModelSelections === null; |
| 920 | const providerCatalogPending = noProviderAvailable && !providerCatalogKnown; |
| 921 | const showProviderUnavailable = noProviderAvailable && !providerCatalogPending; |
| 922 | const providerSetupInstanceId = noProviderAvailable |
| 923 | ? (unavailableProviderInstanceId ?? |
| 924 | (lockedProvider === null |
| 925 | ? providerInstanceEntries.find((entry) => hasProviderSetup(entry.snapshot))?.instanceId |
| 926 | : undefined)) |
| 927 | : undefined; |
| 928 | // Called before the derivation below: a hook between it and its uses stops React Compiler |
| 929 | // from caching the mode options, and the footer then re-renders on every keystroke. |
| 930 | const managedPolicy = useManagedPolicy(environmentId); |
| 931 | const { modes: compatibleRuntimeModes, mode: compatibleRuntimeMode } = |
| 932 | resolveCompatibleRuntimeMode( |
| 933 | runtimeMode, |
| 934 | selectedProviderEntry?.snapshot.supportedRuntimeModes, |
| 935 | ); |
| 936 | // Modes above an administrator's ceiling stay listed, disabled with the reason. |
| 937 | const compatibleRuntimeModeOptions = resolveRuntimeModeOptions( |
| 938 | compatibleRuntimeModes, |
| 939 | managedPolicy, |
| 940 | m, |
| 941 | ); |
| 942 | // A thread or draft already above the ceiling would be refused; offer the broadest mode left. |
| 943 | const runtimeModeCeilingDenial = runtimeModeDenial(managedPolicy, compatibleRuntimeMode, m); |
| 944 | const runtimeModeCeilingFallback = |
| 945 | runtimeModeCeilingDenial === undefined |
| 946 | ? undefined |
| 947 | : clampManagedRuntimeMode(managedPolicy, compatibleRuntimeMode, compatibleRuntimeModes); |
| 948 | |
| 949 | const providerSendBlockReason = getAntigravitySendBlockReason( |
| 950 | selectedProviderEntry?.snapshot, |
| 951 | selectedModel, |
| 952 | m, |
| 953 | ); |
| 954 | const sendDisabledReason = |
| 955 | externalSendDisabledReason ?? |
| 956 | (multipleModelSelections?.length === 0 ? gt("Select at least one model.") : null) ?? |
| 957 | (activePendingProgress |
| 958 | ? attachmentBlockReason |
| 959 | : (attachmentBlockReason ?? |
| 960 | runtimeModeCeilingDenial ?? |
| 961 | (multipleModelSelections === null ? providerSendBlockReason : null))); |
| 962 | const isSendDisabled = sendDisabledReason !== null; |
| 963 | const selectedProviderStatus = selectedProviderEntry?.snapshot ?? null; |
| 964 | const selectedProviderSkills = selectedProviderStatus |
| 965 | ? resolveProviderSkillsForCwd(selectedProviderStatus, gitCwd) |
| 966 | : NO_PROVIDER_SKILLS; |
| 967 | const selectedProviderSlashCommands = selectedProviderStatus |
| 968 | ? resolveProviderSlashCommandsForCwd(selectedProviderStatus, gitCwd) |
| 969 | : NO_PROVIDER_SLASH_COMMANDS; |
| 970 | const { refresh: refreshWorkspaceSnapshotOnTyping, scanning: workspaceSkillsScanning } = |
| 971 | useProviderWorkspaceSnapshotRefresh({ |
| 972 | environmentId, |
| 973 | gitCwd, |
| 974 | instanceId: selectedProviderEntry?.instanceId, |
| 975 | }); |
| 976 | |
| 977 | const selectedPromptEffort = composerProviderState.promptEffort; |
| 978 | const selectedModelOptionsForDispatch = composerProviderState.modelOptionsForDispatch; |
| 979 | const selectedModelSelection: ModelSelection = createModelSelection( |
| 980 | selectedInstanceId, |
| 981 | selectedModel, |
| 982 | selectedModelOptionsForDispatch, |
| 983 | ); |
| 984 | const selectedModelForPicker = selectedModel; |
| 985 | const modelOptionsByInstance = new Map<ProviderInstanceId, ReadonlyArray<AppModelOption>>(); |
| 986 | for (const entry of providerInstanceEntries) { |
| 987 | modelOptionsByInstance.set( |
| 988 | entry.instanceId, |
| 989 | getAppModelOptionsForInstance( |
| 990 | settings, |
| 991 | entry, |
| 992 | entry.instanceId === selectedInstanceId ? selectedModelForPicker : null, |
| 993 | ), |
| 994 | ); |
| 995 | } |
| 996 | |
| 997 | const selectedModelForPickerWithCustomFallback = (() => { |
| 998 | const currentOptions = modelOptionsByInstance.get(selectedInstanceId) ?? []; |
| 999 | return currentOptions.some((option) => option.slug === selectedModelForPicker) |
| 1000 | ? selectedModelForPicker |
| 1001 | : (normalizeModelSlug(selectedModelForPicker, selectedProvider) ?? selectedModelForPicker); |
| 1002 | })(); |
| 1003 | |
| 1004 | const [composerCursor, setComposerCursor] = useState(() => { |
| 1005 | const value = isLiteralPendingAnswer ? (activePendingProgress?.customAnswer ?? prompt) : prompt; |
| 1006 | return collapseExpandedComposerCursor(value, value.length, isLiteralPendingAnswer); |
| 1007 | }); |
| 1008 | const { |
| 1009 | trigger: composerTrigger, |
| 1010 | setTrigger: setComposerTrigger, |
| 1011 | followCaret: followComposerCaret, |
| 1012 | resolveTrigger: resolveComposerTrigger, |
| 1013 | dismissTrigger: dismissComposerTrigger, |
| 1014 | resetTrigger: resetComposerTrigger, |
| 1015 | } = useComposerTriggerState(() => |
| 1016 | isLiteralPendingAnswer ? null : detectComposerTrigger(prompt, prompt.length), |
| 1017 | ); |
| 1018 | const [composerHighlightedItemId, setComposerHighlightedItemId] = useState<string | null>(null); |
| 1019 | const composerSuggestionId = useId(); |
| 1020 | const composerSuggestionListId = `${composerSuggestionId}-${encodeURIComponent(draftId ?? activeThreadId ?? "new")}-suggestions`; |
| 1021 | const promptHistoryPositionRef = useRef<{ |
| 1022 | targetKey: string; |
| 1023 | position: ComposerPromptHistoryPosition; |
| 1024 | } | null>(null); |
| 1025 | const [composerHighlightedSearchKey, setComposerHighlightedSearchKey] = useState<string | null>( |
| 1026 | null, |
| 1027 | ); |
| 1028 | const [isDragOverComposer, setIsDragOverComposer] = useState(false); |
| 1029 | const [isComposerFooterCompact, setIsComposerFooterCompact] = useState(false); |
| 1030 | const [isComposerPrimaryActionsCompact, setIsComposerPrimaryActionsCompact] = useState(false); |
| 1031 | const [isComposerModelPickerOpen, setIsComposerModelPickerOpen] = useState(false); |
| 1032 | const isMobileViewport = useMediaQuery("max-sm"); |
| 1033 | const isSoftwareKeyboardOpen = useSoftwareKeyboardOpen(); |
| 1034 | const [isComposerFocused, setIsComposerFocused] = useState(false); |
| 1035 | const [composerSubmissionError, setComposerSubmissionError] = useState<string | null>(null); |
| 1036 | const [providerInputSubmissionError, setProviderInputSubmissionError] = useState<string | null>( |
| 1037 | null, |
| 1038 | ); |
| 1039 | const [composerMenuAnchor, setComposerMenuAnchor] = useState<HTMLDivElement | null>(null); |
| 1040 | const [hasWrappedPrompt, observeWrappedPrompt] = useComposerMultilinePrompt(); |
| 1041 | const hasMultilinePrompt = prompt.includes("\n") || hasWrappedPrompt; |
| 1042 | // A pending question stays expanded: its card moves into the banner dock, |
| 1043 | // so collapsing would leave the surface empty and squashed beneath it. |
| 1044 | const isComposerCollapsedMobile = |
| 1045 | isMobileViewport && |
| 1046 | !forceExpandedOnMobile && |
| 1047 | !isComposerFocused && |
| 1048 | !hasMultilinePrompt && |
| 1049 | pendingUserInputs.length === 0; |
| 1050 | |
| 1051 | const composerEditorRef = useRef<ComposerPromptEditorHandle>(null); |
| 1052 | const pasteAsTextShortcutUntilRef = useRef(0); |
| 1053 | const composerFormRef = useRef<HTMLFormElement>(null); |
| 1054 | const composerSurfaceRef = useRef<HTMLDivElement>(null); |
| 1055 | const providerInputRejectedRef = useRef(false); |
| 1056 | const composerSelectLockRef = useRef(false); |
| 1057 | const composerMenuItemsRef = useRef<ComposerCommandItem[]>([]); |
| 1058 | const activeComposerMenuItemRef = useRef<ComposerCommandItem | null>(null); |
| 1059 | const composerBlurFrameRef = useRef<number | null>(null); |
| 1060 | const mobileComposerExpandFrameRef = useRef<number | null>(null); |
| 1061 | const mobileComposerExpandReleaseFrameRef = useRef<number | null>(null); |
| 1062 | const mobileComposerExpandInFlightRef = useRef(false); |
| 1063 | const pendingThreadImportsRef = useRef<Map<string, number>>(new Map()); |
| 1064 | const isRevertingCheckpointRef = useRef(isRevertingCheckpoint); |
| 1065 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed checkpoint revert flag to a ref read by async handlers |
| 1066 | useLayoutEffect(() => { |
| 1067 | isRevertingCheckpointRef.current = isRevertingCheckpoint; |
| 1068 | }); |
| 1069 | |
| 1070 | const backgroundThread = use(BackgroundThreadContext); |
| 1071 | const hiddenThread = use(HiddenThreadContext); |
| 1072 | // 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 |
| 1073 | useEffect(() => { |
| 1074 | // A background composer listens on its own form, so it never hears the main composer's keys. |
| 1075 | const target: EventTarget | null = backgroundThread ? composerFormRef.current : window; |
| 1076 | if (target === null) return; |
| 1077 | const armPasteAsTextShortcut = () => { |
| 1078 | // Electron's menu action can precede paste; browsers deliver keydown first. |
| 1079 | pasteAsTextShortcutUntilRef.current = Date.now() + 1_000; |
| 1080 | }; |
| 1081 | const onKeyDown = (event: Event) => { |
| 1082 | if ( |
| 1083 | event instanceof KeyboardEvent && |
| 1084 | event.target instanceof Node && |
| 1085 | composerFormRef.current?.contains(event.target) && |
| 1086 | isPasteAsTextShortcut(event, isMacPlatform(navigator.platform)) |
| 1087 | ) { |
| 1088 | armPasteAsTextShortcut(); |
| 1089 | } |
| 1090 | }; |
| 1091 | const onBlur = () => { |
| 1092 | pasteAsTextShortcutUntilRef.current = 0; |
| 1093 | }; |
| 1094 | const onDesktopPasteAsText = () => { |
| 1095 | const activeElement = document.activeElement; |
| 1096 | const blocksPasteToFocus = |
| 1097 | activeElement instanceof Element && |
| 1098 | activeElement.closest( |
| 1099 | 'input, textarea, select, button, a[href], summary, [contenteditable="true"], [contenteditable="plaintext-only"], [role="textbox"], [role="button"], [role="menuitem"], [role="option"]', |
| 1100 | ) !== null; |
| 1101 | // A background composer takes no paste-to-focus, so it arms only for its own focus. |
| 1102 | if ( |
| 1103 | (activeElement instanceof Node && composerFormRef.current?.contains(activeElement)) || |
| 1104 | (!blocksPasteToFocus && !backgroundThread) |
| 1105 | ) { |
| 1106 | armPasteAsTextShortcut(); |
| 1107 | } |
| 1108 | }; |
| 1109 | target.addEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText); |
| 1110 | target.addEventListener("keydown", onKeyDown, true); |
| 1111 | // An arm lasts a second, so a background composer can skip the window blur reset. |
| 1112 | if (!backgroundThread) window.addEventListener("blur", onBlur); |
| 1113 | return () => { |
| 1114 | target.removeEventListener(DESKTOP_PASTE_AS_TEXT_EVENT, onDesktopPasteAsText); |
| 1115 | target.removeEventListener("keydown", onKeyDown, true); |
| 1116 | window.removeEventListener("blur", onBlur); |
| 1117 | }; |
| 1118 | }, [backgroundThread]); |
| 1119 | |
| 1120 | const composerSendState = deriveComposerSendState({ |
| 1121 | prompt, |
| 1122 | imageCount: composerImages.length + composerFiles.length, |
| 1123 | existingAttachmentCount: editingQueuedAttachments?.length ?? 0, |
| 1124 | terminalContexts: composerTerminalContexts, |
| 1125 | elementContextCount: |
| 1126 | composerPreviewAnnotations.length + |
| 1127 | composerReviewComments.length + |
| 1128 | composerThreadContexts.length + |
| 1129 | composerEnvironmentContexts.length, |
| 1130 | }); |
| 1131 | const composerTriggerKind = composerTrigger?.kind ?? null; |
| 1132 | const compactSlashCommandAvailable = |
| 1133 | composerTrigger?.kind === "slash-command" && |
| 1134 | prompt.slice(0, composerTrigger.rangeStart).trim() === "" && |
| 1135 | !compactThreadUnavailable && |
| 1136 | prompt.slice(composerTrigger.rangeEnd).trim() === "" && |
| 1137 | composerImages.length + composerFiles.length === 0 && |
| 1138 | composerDraft.persistedAttachments.length === 0 && |
| 1139 | composerTerminalContexts.length === 0 && |
| 1140 | composerPreviewAnnotations.length === 0 && |
| 1141 | composerReviewComments.length === 0; |
| 1142 | const linkedEnvironments = useLinkedEnvironments(environmentId); |
| 1143 | const { |
| 1144 | items: composerMenuItems, |
| 1145 | isLoading: isComposerMenuLoading, |
| 1146 | emptyState: composerMenuEmptyState, |
| 1147 | } = useComposerMenuItems({ |
| 1148 | composerTrigger, |
| 1149 | environmentId, |
| 1150 | linkedEnvironments, |
| 1151 | gitCwd, |
| 1152 | activeThreadId, |
| 1153 | pullRequestProjectId, |
| 1154 | pullRequestRepository, |
| 1155 | threadPullRequests, |
| 1156 | sideChatAvailable: props.sideChatAvailable === true, |
| 1157 | sideChatDisabledReason: props.sideChatDisabledReason ?? null, |
| 1158 | freshSessionAvailable: props.onFreshSession !== undefined, |
| 1159 | compactSlashCommandAvailable, |
| 1160 | selectedProvider, |
| 1161 | selectedProviderSkills, |
| 1162 | selectedProviderSlashCommands, |
| 1163 | showSkillsInSlashMenu: settings.showSkillsInSlashMenu, |
| 1164 | workspaceSkillsScanning, |
| 1165 | questionAttachmentTarget, |
| 1166 | modelMentions: { instanceEntries: providerInstanceEntries, modelOptionsByInstance }, |
| 1167 | }); |
| 1168 | |
| 1169 | const composerMenuOpen = Boolean(composerTrigger); |
| 1170 | const composerMenuSearchKey = composerTrigger |
| 1171 | ? `${composerSuggestionListId}:${composerTrigger.kind}:${composerTrigger.query.trim().toLowerCase()}` |
| 1172 | : null; |
| 1173 | const activeComposerMenuItemId = resolveComposerMenuActiveItemId({ |
| 1174 | items: composerMenuItems, |
| 1175 | highlightedItemId: composerHighlightedItemId, |
| 1176 | currentSearchKey: composerMenuSearchKey, |
| 1177 | highlightedSearchKey: composerHighlightedSearchKey, |
| 1178 | }); |
| 1179 | const activeComposerMenuItem = |
| 1180 | composerMenuItems.find((item) => item.id === activeComposerMenuItemId) ?? null; |
| 1181 | |
| 1182 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes committed composer menu state to refs read by editor key handlers |
| 1183 | useLayoutEffect(() => { |
| 1184 | composerMenuItemsRef.current = composerMenuItems; |
| 1185 | activeComposerMenuItemRef.current = activeComposerMenuItem; |
| 1186 | }); |
| 1187 | |
| 1188 | const isComposerApprovalState = activePendingApproval !== null; |
| 1189 | // A send declines the approvals shown here to redirect the agent, so it steers the waiting |
| 1190 | // turn instead of queueing behind it. Approvals the typing guard holds stay unseen and pending. |
| 1191 | const followUpBehavior = pendingApprovals.some( |
| 1192 | (approval) => !heldRequestIds.has(approval.requestId), |
| 1193 | ) |
| 1194 | ? "steer" |
| 1195 | : settings.followUpBehavior; |
| 1196 | const composerSuggestionsVisible = composerMenuOpen; |
| 1197 | const composerSuggestionListVisible = composerSuggestionsVisible && composerMenuItems.length > 0; |
| 1198 | const activePendingUserInput = pendingUserInputs[0] ?? null; |
| 1199 | const isChoiceOnlyPendingQuestion = |
| 1200 | activePendingProgress?.activeQuestion?.allowCustomAnswer === false; |
| 1201 | const showComposerTopDrawer = pendingUserInputs.length > 0; |
| 1202 | const showCollapsedMobilePromptRow = isComposerCollapsedMobile; |
| 1203 | const showComposerAttachAction = |
| 1204 | fileStagingLimit !== null && |
| 1205 | (!activePendingProgress || |
| 1206 | (supportsQuestionAttachments && |
| 1207 | activePendingProgress.activeQuestion?.allowCustomAnswer !== false)); |
| 1208 | const composerFooterHasWideActions = activePendingProgress !== null; |
| 1209 | |
| 1210 | const editPromptFromTraits = (edit: (prompt: string) => string) => { |
| 1211 | const currentPrompt = getComposerDraft(composerDraftTarget)?.prompt ?? ""; |
| 1212 | const nextPrompt = edit(currentPrompt); |
| 1213 | if (nextPrompt === currentPrompt) return; |
| 1214 | if (nextPrompt === promptRef.current) { |
| 1215 | scheduleComposerFocus(); |
| 1216 | return; |
| 1217 | } |
| 1218 | promptRef.current = nextPrompt; |
| 1219 | setComposerDraftPrompt(composerDraftTarget, nextPrompt); |
| 1220 | const nextCursor = collapseExpandedComposerCursor(nextPrompt, nextPrompt.length); |
| 1221 | setComposerCursor(nextCursor); |
| 1222 | setComposerTrigger(detectComposerTrigger(nextPrompt, nextPrompt.length)); |
| 1223 | scheduleComposerFocus(); |
| 1224 | }; |
| 1225 | const editPromptFromTraitsStable = useStableCallback(editPromptFromTraits); |
| 1226 | const promptUltrathink = readPromptUltrathink(prompt); |
| 1227 | |
| 1228 | const [inlineRestingControlsHost, setInlineRestingControlsHost] = useState<HTMLDivElement | null>( |
| 1229 | null, |
| 1230 | ); |
| 1231 | const { |
| 1232 | controlsRef: restingComposerControlsRef, |
| 1233 | attachControls: attachRestingComposerControls, |
| 1234 | hiddenBlockCount: restingControlsHiddenBlockCount, |
| 1235 | iconOnlyBlockCount: restingControlsIconOnlyBlockCount, |
| 1236 | controlsVisible: restingControlsVisible, |
| 1237 | } = useRestingComposerControlsLayout(inlineRestingControlsHost); |
| 1238 | const { |
| 1239 | attachControls: attachExpandedComposerControls, |
| 1240 | hiddenBlockCount: expandedControlsHiddenBlockCount, |
| 1241 | iconOnlyBlockCount: expandedControlsIconOnlyBlockCount, |
| 1242 | } = useRestingComposerControlsLayout(null, true); |
| 1243 | const pendingPrimaryAction = activePendingProgress |
| 1244 | ? { |
| 1245 | questionIndex: activePendingProgress.questionIndex, |
| 1246 | isLastQuestion: activePendingProgress.isLastQuestion, |
| 1247 | canAdvance: |
| 1248 | activePendingProgress.canAdvance && |
| 1249 | !attachmentBlockReason && |
| 1250 | !(questionPreparations[attachmentTargetKey] ?? 0), |
| 1251 | isResponding: activePendingIsResponding, |
| 1252 | isComplete: Boolean(activePendingResolvedAnswers), |
| 1253 | } |
| 1254 | : null; |
| 1255 | const showResumeAction = |
| 1256 | canResume && !composerDraftHasUserContent(composerDraft) && !isEditingQueuedMessage; |
| 1257 | const collapsedComposerPrimaryActionDisabled = |
| 1258 | phase === "running" || |
| 1259 | isSendBusy || |
| 1260 | isSendDisabled || |
| 1261 | noProviderAvailable || |
| 1262 | projectSelectionRequired || |
| 1263 | environmentUnavailable !== null || |
| 1264 | (!composerSendState.hasSendableContent && !showResumeAction); |
| 1265 | const collapsedComposerPrimaryActionLabel = showResumeAction |
| 1266 | ? gt("Resume thread") |
| 1267 | : props.resumeCompactionTokens !== null && !props.keepFullHistory |
| 1268 | ? gt("Open composer to compact and send") |
| 1269 | : gt("Send message"); |
| 1270 | const showMobilePendingAnswerActions = |
| 1271 | isMobileViewport && !isComposerCollapsedMobile && pendingPrimaryAction !== null; |
| 1272 | |
| 1273 | const setPrompt = (nextPrompt: string) => { |
| 1274 | setComposerDraftPrompt(composerDraftTarget, nextPrompt); |
| 1275 | }; |
| 1276 | |
| 1277 | const addComposerImage = (image: ComposerImageAttachment) => |
| 1278 | addComposerDraftImages(attachmentDraftTarget, [image]); |
| 1279 | |
| 1280 | const addComposerImagesToDraft = (images: ComposerImageAttachment[]) => |
| 1281 | addComposerDraftImages(attachmentDraftTarget, images); |
| 1282 | |
| 1283 | const addComposerFilesToDraft = (files: ComposerFileAttachment[]) => |
| 1284 | addComposerDraftFiles(attachmentDraftTarget, files, { |
| 1285 | appendReference: questionAttachmentTarget === null, |
| 1286 | }); |
| 1287 | |
| 1288 | const removeComposerImageFromDraft = (imageId: string) => { |
| 1289 | if (questionAttachmentTarget && activePendingIsResponding) return; |
| 1290 | releaseAttachmentUpload(imageId); |
| 1291 | removeComposerDraftImage(attachmentDraftTarget, imageId); |
| 1292 | }; |
| 1293 | |
| 1294 | const removeComposerFileFromDraft = (fileId: string) => { |
| 1295 | if (questionAttachmentTarget && activePendingIsResponding) return; |
| 1296 | // Hydrated uploads use persisted attachment ids, not queue keys. |
| 1297 | const file = composerFilesRef.current.find((candidate) => candidate.id === fileId); |
| 1298 | if (file) { |
| 1299 | releaseDraftAttachment(file); |
| 1300 | } else { |
| 1301 | releaseAttachmentUpload(fileId); |
| 1302 | } |
| 1303 | removeComposerDraftFile(attachmentDraftTarget, fileId); |
| 1304 | }; |
| 1305 | |
| 1306 | const addComposerDraftReviewComment = useComposerDraftStore((store) => store.addReviewComment); |
| 1307 | const addComposerDraftPreviewAnnotation = useComposerDraftStore( |
| 1308 | (store) => store.addPreviewAnnotation, |
| 1309 | ); |
| 1310 | const addComposerDraftThreadContexts = useComposerDraftStore((store) => store.addThreadContexts); |
| 1311 | const setComposerDraftThreadContexts = useComposerDraftStore((store) => store.setThreadContexts); |
| 1312 | const addComposerDraftEnvironmentContexts = useComposerDraftStore( |
| 1313 | (store) => store.addEnvironmentContexts, |
| 1314 | ); |
| 1315 | const setComposerDraftEnvironmentContexts = useComposerDraftStore( |
| 1316 | (store) => store.setEnvironmentContexts, |
| 1317 | ); |
| 1318 | const buildContextClipboardFragment = (contextIds: ReadonlyArray<string>): string | null => { |
| 1319 | const wanted = new Set(contextIds); |
| 1320 | const copiedFiles = new Map<string, File>(); |
| 1321 | for (const annotation of composerPreviewAnnotations) { |
| 1322 | if ( |
| 1323 | wanted.has(previewAnnotationContextId(annotation.id)) && |
| 1324 | composerImages.some((image) => image.id === annotation.id) |
| 1325 | ) { |
| 1326 | wanted.add(toKindScopedComposerContextId("image", annotation.id)); |
| 1327 | } |
| 1328 | } |
| 1329 | const records: ComposerContextRecord[] = [ |
| 1330 | ...composerTerminalContexts |
| 1331 | .filter((c) => wanted.has(terminalContextReference(c).contextId)) |
| 1332 | .map(terminalContextRecord), |
| 1333 | ...composerThreadContexts.filter((record) => wanted.has(record.contextId)), |
| 1334 | ...composerEnvironmentContexts.filter((record) => wanted.has(record.contextId)), |
| 1335 | ...composerReviewComments |
| 1336 | .filter((c) => wanted.has(reviewCommentContextId(c.id))) |
| 1337 | .map(reviewCommentContextRecord), |
| 1338 | ...composerPreviewAnnotations |
| 1339 | .filter((a) => wanted.has(previewAnnotationContextId(a.id))) |
| 1340 | .map((annotation) => |
| 1341 | previewAnnotationContextRecord(annotation, { |
| 1342 | screenshotContextId: composerImages.some((image) => image.id === annotation.id) |
| 1343 | ? annotation.id |
| 1344 | : undefined, |
| 1345 | }), |
| 1346 | ), |
| 1347 | ...[...composerImages, ...composerFiles] |
| 1348 | .filter((attachment) => |
| 1349 | wanted.has(toKindScopedComposerContextId(attachment.type, attachment.id)), |
| 1350 | ) |
| 1351 | .flatMap((attachment) => { |
| 1352 | const record = |
| 1353 | uploadedAttachmentContextRecord(attachment, uploadsByImageId[attachment.id]) ?? |
| 1354 | (attachment.file |
| 1355 | ? attachmentContextRecord({ attachment, attachmentId: attachment.id }) |
| 1356 | : null); |
| 1357 | if (!record) return []; |
| 1358 | if (attachment.file) copiedFiles.set(record.attachmentId, attachment.file); |
| 1359 | return [ |
| 1360 | record.kind === "image" && attachment.type === "image" && attachment.source |
| 1361 | ? { ...record, source: attachment.source } |
| 1362 | : record, |
| 1363 | ]; |
| 1364 | }), |
| 1365 | ]; |
| 1366 | if (records.length === 0) return null; |
| 1367 | const fragment = encodeComposerContextFragment({ |
| 1368 | version: 1, |
| 1369 | source: { environmentId, ...(activeThread ? { threadId: activeThread.id } : {}) }, |
| 1370 | records, |
| 1371 | }); |
| 1372 | if (fragment) rememberCopiedComposerAttachments(environmentId, copiedFiles); |
| 1373 | return fragment; |
| 1374 | }; |
| 1375 | const copyComposerSnapshot = async (imageId: string) => { |
| 1376 | const image = composerImages.find((candidate) => candidate.id === imageId); |
| 1377 | if (!image) throw new Error(gt("Snapshot is no longer available.")); |
| 1378 | const contextId = toKindScopedComposerContextId("image", image.id); |
| 1379 | const fragment = buildContextClipboardFragment([contextId]); |
| 1380 | if (!fragment || !image.previewUrl) throw new Error(gt("The snapshot is not ready to copy.")); |
| 1381 | await copySnapshot( |
| 1382 | image.previewUrl, |
| 1383 | formatComposerContextReference({ kind: "image", contextId, label: image.name }), |
| 1384 | fragment, |
| 1385 | ); |
| 1386 | }; |
| 1387 | const copyComposerSnapshotStable = useStableCallback(copyComposerSnapshot); |
| 1388 | const buildContextClipboardFragmentStable = useStableCallback(buildContextClipboardFragment); |
| 1389 | const { |
| 1390 | loadThreadTranscript, |
| 1391 | countReservedAttachments, |
| 1392 | countReservedAttachmentsStable, |
| 1393 | importContextRecords, |
| 1394 | importContextFragment, |
| 1395 | importContextFragmentStable, |
| 1396 | } = useComposerContextImport({ |
| 1397 | environmentId, |
| 1398 | linkedEnvironments, |
| 1399 | activeThread, |
| 1400 | activeThreadId, |
| 1401 | composerDraftTarget, |
| 1402 | attachmentDraftTarget, |
| 1403 | attachmentTargetKey, |
| 1404 | attachmentTargetKeyRef, |
| 1405 | questionAttachmentTarget, |
| 1406 | pendingUserInputs, |
| 1407 | composerContextRecords, |
| 1408 | composerImages, |
| 1409 | composerFilesRef, |
| 1410 | promptRef, |
| 1411 | pendingThreadImportsRef, |
| 1412 | addComposerFilesToDraft, |
| 1413 | }); |
| 1414 | |
| 1415 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared prompt ref in step with the committed draft prompt for imperative handlers |
| 1416 | useEffect(() => { |
| 1417 | if (isLiteralPendingAnswer) return; |
| 1418 | promptRef.current = prompt; |
| 1419 | }, [isLiteralPendingAnswer, prompt, promptRef]); |
| 1420 | const [cursorClampedFor, setCursorClampedFor] = useState({ prompt, isLiteralPendingAnswer }); |
| 1421 | if ( |
| 1422 | cursorClampedFor.prompt !== prompt || |
| 1423 | cursorClampedFor.isLiteralPendingAnswer !== isLiteralPendingAnswer |
| 1424 | ) { |
| 1425 | setCursorClampedFor({ prompt, isLiteralPendingAnswer }); |
| 1426 | if (!isLiteralPendingAnswer) { |
| 1427 | setComposerCursor((existing) => clampCollapsedComposerCursor(prompt, existing)); |
| 1428 | } |
| 1429 | } |
| 1430 | |
| 1431 | if (composerSubmissionError !== null) { |
| 1432 | const nextError = getComposerPromptLengthValidationMessage(prompt, m); |
| 1433 | if (nextError !== composerSubmissionError) { |
| 1434 | setComposerSubmissionError(nextError); |
| 1435 | } |
| 1436 | } |
| 1437 | |
| 1438 | const providerInputInputs = [ |
| 1439 | composerPreviewAnnotations, |
| 1440 | composerReviewComments, |
| 1441 | composerTerminalContexts, |
| 1442 | prompt, |
| 1443 | selectedModel, |
| 1444 | selectedPromptEffort, |
| 1445 | selectedProvider, |
| 1446 | ] as const; |
| 1447 | const [providerInputValidatedFor, setProviderInputValidatedFor] = useState(providerInputInputs); |
| 1448 | if (providerInputInputs.some((value, index) => value !== providerInputValidatedFor[index])) { |
| 1449 | setProviderInputValidatedFor(providerInputInputs); |
| 1450 | setProviderInputSubmissionError(null); |
| 1451 | } |
| 1452 | |
| 1453 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared images ref in step with committed draft images for async handlers |
| 1454 | useEffect(() => { |
| 1455 | composerImagesRef.current = composerImages; |
| 1456 | }, [composerImages, composerImagesRef]); |
| 1457 | |
| 1458 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared files ref in step with committed draft files for async handlers |
| 1459 | useEffect(() => { |
| 1460 | composerFilesRef.current = composerFiles; |
| 1461 | }, [composerFiles, composerFilesRef]); |
| 1462 | |
| 1463 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- keeps the shared terminal contexts ref in step with committed draft contexts for async handlers |
| 1464 | useEffect(() => { |
| 1465 | composerTerminalContextsRef.current = composerTerminalContexts; |
| 1466 | }, [composerTerminalContexts, composerTerminalContextsRef]); |
| 1467 | |
| 1468 | const resolvedHighlightedItemId = composerMenuOpen ? activeComposerMenuItemId : null; |
| 1469 | const resolvedHighlightedSearchKey = composerMenuOpen ? composerMenuSearchKey : null; |
| 1470 | if (composerHighlightedItemId !== resolvedHighlightedItemId) { |
| 1471 | setComposerHighlightedItemId(resolvedHighlightedItemId); |
| 1472 | } |
| 1473 | if (composerHighlightedSearchKey !== resolvedHighlightedSearchKey) { |
| 1474 | setComposerHighlightedSearchKey(resolvedHighlightedSearchKey); |
| 1475 | } |
| 1476 | |
| 1477 | const lastSyncedPendingInputRef = useRef<{ |
| 1478 | requestId: string | null; |
| 1479 | questionId: string | null; |
| 1480 | } | null>(null); |
| 1481 | |
| 1482 | // 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 |
| 1483 | useEffect(() => { |
| 1484 | const nextCustomAnswer = activePendingProgress?.customAnswer; |
| 1485 | if (typeof nextCustomAnswer !== "string") { |
| 1486 | if (lastSyncedPendingInputRef.current !== null) { |
| 1487 | promptRef.current = prompt; |
| 1488 | const { cursor, trigger } = composerStateAtPromptEnd(prompt); |
| 1489 | setComposerCursor(cursor); |
| 1490 | resetComposerTrigger(trigger); |
| 1491 | } |
| 1492 | lastSyncedPendingInputRef.current = null; |
| 1493 | return; |
| 1494 | } |
| 1495 | |
| 1496 | const nextRequestId = activePendingUserInput?.requestId ?? null; |
| 1497 | const nextQuestionId = activePendingProgress?.activeQuestion?.id ?? null; |
| 1498 | const questionChanged = |
| 1499 | lastSyncedPendingInputRef.current?.requestId !== nextRequestId || |
| 1500 | lastSyncedPendingInputRef.current?.questionId !== nextQuestionId; |
| 1501 | const textChangedExternally = promptRef.current !== nextCustomAnswer; |
| 1502 | |
| 1503 | lastSyncedPendingInputRef.current = { |
| 1504 | requestId: nextRequestId, |
| 1505 | questionId: nextQuestionId, |
| 1506 | }; |
| 1507 | |
| 1508 | if (!questionChanged && !textChangedExternally) { |
| 1509 | return; |
| 1510 | } |
| 1511 | |
| 1512 | promptRef.current = nextCustomAnswer; |
| 1513 | const { cursor, trigger } = composerStateAtPromptEnd(nextCustomAnswer, isLiteralPendingAnswer); |
| 1514 | setComposerCursor(cursor); |
| 1515 | resetComposerTrigger(trigger); |
| 1516 | setComposerHighlightedItemId(null); |
| 1517 | }, [ |
| 1518 | activePendingProgress?.customAnswer, |
| 1519 | activePendingProgress?.activeQuestion?.id, |
| 1520 | isLiteralPendingAnswer, |
| 1521 | activePendingUserInput?.requestId, |
| 1522 | prompt, |
| 1523 | promptRef, |
| 1524 | resetComposerTrigger, |
| 1525 | ]); |
| 1526 | |
| 1527 | const composerSessionKey = `${draftId ?? ""}:${activeThreadId ?? ""}:${isLiteralPendingAnswer}`; |
| 1528 | const [shownComposerSessionKey, setShownComposerSessionKey] = useState(composerSessionKey); |
| 1529 | if (shownComposerSessionKey !== composerSessionKey) { |
| 1530 | setShownComposerSessionKey(composerSessionKey); |
| 1531 | setComposerHighlightedItemId(null); |
| 1532 | setComposerHighlightedSearchKey(null); |
| 1533 | setComposerSubmissionError(null); |
| 1534 | setProviderInputSubmissionError(null); |
| 1535 | const pendingAnswer = activePendingProgress?.customAnswer; |
| 1536 | const { cursor, trigger } = composerStateAtPromptEnd( |
| 1537 | typeof pendingAnswer === "string" ? pendingAnswer : prompt, |
| 1538 | isLiteralPendingAnswer, |
| 1539 | ); |
| 1540 | setComposerCursor(cursor); |
| 1541 | resetComposerTrigger(trigger); |
| 1542 | setIsDragOverComposer(false); |
| 1543 | } |
| 1544 | |
| 1545 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- observes composer form resizes to switch the footer and primary actions between compact layouts |
| 1546 | useLayoutEffect(() => { |
| 1547 | const composerForm = composerFormRef.current; |
| 1548 | if (!composerForm) return; |
| 1549 | const measureCompactLayouts = () => { |
| 1550 | const composerFormWidth = composerForm.clientWidth; |
| 1551 | const options = { hasWideActions: composerFooterHasWideActions }; |
| 1552 | setIsComposerFooterCompact(shouldUseCompactComposerFooter(composerFormWidth)); |
| 1553 | setIsComposerPrimaryActionsCompact( |
| 1554 | shouldUseCompactComposerFooter(composerFormWidth, options) && |
| 1555 | shouldUseCompactComposerPrimaryActions(composerFormWidth, options), |
| 1556 | ); |
| 1557 | }; |
| 1558 | |
| 1559 | measureCompactLayouts(); |
| 1560 | return observeResize(composerForm, measureCompactLayouts); |
| 1561 | }, [composerFooterHasWideActions]); |
| 1562 | |
| 1563 | // 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 |
| 1564 | useEffect(() => { |
| 1565 | let cancelled = false; |
| 1566 | void (async () => { |
| 1567 | if (composerImages.length === 0) { |
| 1568 | clearComposerDraftPersistedAttachments(attachmentDraftTarget); |
| 1569 | return; |
| 1570 | } |
| 1571 | const getPersistedAttachmentsForThread = () => |
| 1572 | getComposerDraft(attachmentDraftTarget)?.persistedAttachments ?? []; |
| 1573 | try { |
| 1574 | const currentPersistedAttachments = getPersistedAttachmentsForThread(); |
| 1575 | const serialized = await serializeComposerImages( |
| 1576 | composerImages, |
| 1577 | currentPersistedAttachments, |
| 1578 | ); |
| 1579 | if (cancelled) return; |
| 1580 | syncComposerDraftPersistedAttachments(attachmentDraftTarget, serialized); |
| 1581 | } catch { |
| 1582 | const currentImageIds = new Set(composerImages.map((image) => image.id)); |
| 1583 | const fallbackPersistedAttachments = getPersistedAttachmentsForThread(); |
| 1584 | const fallbackPersistedIds: Array<string> = []; |
| 1585 | for (const attachment of fallbackPersistedAttachments) { |
| 1586 | if (currentImageIds.has(attachment.id)) { |
| 1587 | fallbackPersistedIds.push(attachment.id); |
| 1588 | } |
| 1589 | } |
| 1590 | const fallbackPersistedIdSet = new Set(fallbackPersistedIds); |
| 1591 | const fallbackAttachments = fallbackPersistedAttachments.filter((attachment) => |
| 1592 | fallbackPersistedIdSet.has(attachment.id), |
| 1593 | ); |
| 1594 | if (cancelled) return; |
| 1595 | syncComposerDraftPersistedAttachments(attachmentDraftTarget, fallbackAttachments); |
| 1596 | } |
| 1597 | })(); |
| 1598 | return () => { |
| 1599 | cancelled = true; |
| 1600 | }; |
| 1601 | }, [ |
| 1602 | attachmentDraftTarget, |
| 1603 | clearComposerDraftPersistedAttachments, |
| 1604 | composerImages, |
| 1605 | getComposerDraft, |
| 1606 | syncComposerDraftPersistedAttachments, |
| 1607 | ]); |
| 1608 | |
| 1609 | const retainedContextPayloads = useRetainedContextPayloads(composerDraftTargetKey); |
| 1610 | |
| 1611 | const onPromptChange = ( |
| 1612 | nextPrompt: string, |
| 1613 | nextCursor: number, |
| 1614 | expandedCursor: number, |
| 1615 | cursorAdjacentToMention: boolean, |
| 1616 | contextIds: string[], |
| 1617 | textChanged: boolean, |
| 1618 | ) => { |
| 1619 | refreshWorkspaceSnapshotOnTyping(); |
| 1620 | const trigger = cursorAdjacentToMention |
| 1621 | ? null |
| 1622 | : detectComposerTrigger(nextPrompt, expandedCursor); |
| 1623 | const updateTrigger = textChanged ? setComposerTrigger : followComposerCaret; |
| 1624 | if (activePendingProgress?.activeQuestion && pendingUserInputs.length > 0) { |
| 1625 | if (activePendingProgress.activeQuestion.allowCustomAnswer === false) return; |
| 1626 | setComposerCursor(nextCursor); |
| 1627 | updateTrigger(trigger); |
| 1628 | onChangeActivePendingUserInputCustomAnswer( |
| 1629 | activePendingProgress.activeQuestion.id, |
| 1630 | nextPrompt, |
| 1631 | nextCursor, |
| 1632 | expandedCursor, |
| 1633 | cursorAdjacentToMention, |
| 1634 | ); |
| 1635 | return; |
| 1636 | } |
| 1637 | onTypingGuardDraftChange(); |
| 1638 | promptRef.current = nextPrompt; |
| 1639 | setPrompt(nextPrompt); |
| 1640 | if (promptHistoryPositionRef.current?.position.recalled !== nextPrompt) { |
| 1641 | promptHistoryPositionRef.current = null; |
| 1642 | } |
| 1643 | const referenced = new Set(contextIds); |
| 1644 | const retained = retainedContextPayloads; |
| 1645 | |
| 1646 | const liveTerminalIds = new Set<string>( |
| 1647 | composerTerminalContexts.map((context) => terminalContextReference(context).contextId), |
| 1648 | ); |
| 1649 | const restoredTerminals = [...referenced].flatMap((contextId) => { |
| 1650 | if (liveTerminalIds.has(contextId)) return []; |
| 1651 | const context = retained.terminals.get(contextId); |
| 1652 | return context ? [context] : []; |
| 1653 | }); |
| 1654 | const nextTerminals = [ |
| 1655 | ...composerTerminalContexts.filter((context) => |
| 1656 | referenced.has(terminalContextReference(context).contextId), |
| 1657 | ), |
| 1658 | ...restoredTerminals, |
| 1659 | ]; |
| 1660 | for (const context of composerTerminalContexts) { |
| 1661 | const contextId = terminalContextReference(context).contextId; |
| 1662 | if (!referenced.has(contextId)) retained.terminals.set(contextId, context); |
| 1663 | } |
| 1664 | if (nextTerminals.length !== composerTerminalContexts.length || restoredTerminals.length > 0) { |
| 1665 | setComposerDraftTerminalContexts(composerDraftTarget, nextTerminals); |
| 1666 | } |
| 1667 | |
| 1668 | const liveThreadIds = new Set<string>(composerThreadContexts.map((record) => record.contextId)); |
| 1669 | const restoredThreads = [...referenced].flatMap((contextId) => { |
| 1670 | if (liveThreadIds.has(contextId)) return []; |
| 1671 | const record = retained.threads.get(contextId); |
| 1672 | return record ? [record] : []; |
| 1673 | }); |
| 1674 | const nextThreads = [ |
| 1675 | ...composerThreadContexts.filter((record) => referenced.has(record.contextId)), |
| 1676 | ...restoredThreads, |
| 1677 | ]; |
| 1678 | for (const record of composerThreadContexts) { |
| 1679 | if (!referenced.has(record.contextId)) retained.threads.set(record.contextId, record); |
| 1680 | } |
| 1681 | if (nextThreads.length !== composerThreadContexts.length || restoredThreads.length > 0) { |
| 1682 | setComposerDraftThreadContexts(composerDraftTarget, nextThreads); |
| 1683 | } |
| 1684 | |
| 1685 | const liveEnvironmentIds = new Set<string>( |
| 1686 | composerEnvironmentContexts.map((record) => record.contextId), |
| 1687 | ); |
| 1688 | const restoredEnvironments = [...referenced].flatMap((contextId) => { |
| 1689 | if (liveEnvironmentIds.has(contextId)) return []; |
| 1690 | const record = retained.environments.get(contextId); |
| 1691 | return record ? [record] : []; |
| 1692 | }); |
| 1693 | const nextEnvironments = [ |
| 1694 | ...composerEnvironmentContexts.filter((record) => referenced.has(record.contextId)), |
| 1695 | ...restoredEnvironments, |
| 1696 | ]; |
| 1697 | for (const record of composerEnvironmentContexts) { |
| 1698 | if (!referenced.has(record.contextId)) retained.environments.set(record.contextId, record); |
| 1699 | } |
| 1700 | if ( |
| 1701 | nextEnvironments.length !== composerEnvironmentContexts.length || |
| 1702 | restoredEnvironments.length > 0 |
| 1703 | ) { |
| 1704 | setComposerDraftEnvironmentContexts(composerDraftTarget, nextEnvironments); |
| 1705 | } |
| 1706 | |
| 1707 | for (const comment of composerReviewComments) { |
| 1708 | const contextId = reviewCommentContextId(comment.id); |
| 1709 | if (!referenced.has(contextId)) { |
| 1710 | retained.reviewComments.set(contextId, comment); |
| 1711 | removeComposerDraftReviewComment(composerDraftTarget, comment.id); |
| 1712 | } |
| 1713 | } |
| 1714 | const liveReviewIds = new Set<string>( |
| 1715 | composerReviewComments.map((comment) => reviewCommentContextId(comment.id)), |
| 1716 | ); |
| 1717 | for (const contextId of referenced) { |
| 1718 | if (liveReviewIds.has(contextId)) continue; |
| 1719 | const comment = retained.reviewComments.get(contextId); |
| 1720 | if (comment) { |
| 1721 | addComposerDraftReviewComment(composerDraftTarget, comment, { appendReference: false }); |
| 1722 | } |
| 1723 | } |
| 1724 | |
| 1725 | const attachmentChanges = reconcileAttachmentContextReferences({ |
| 1726 | referencedContextIds: referenced, |
| 1727 | files: composerFiles, |
| 1728 | images: composerImages, |
| 1729 | previewAnnotations: composerPreviewAnnotations, |
| 1730 | retained: retainedContextPayloads, |
| 1731 | }); |
| 1732 | for (const annotationId of attachmentChanges.annotationIdsToRemove) { |
| 1733 | removeComposerDraftPreviewAnnotation(composerDraftTarget, annotationId); |
| 1734 | } |
| 1735 | for (const restored of attachmentChanges.annotationsToRestore) { |
| 1736 | if (restored.image) addComposerDraftImages(attachmentDraftTarget, [restored.image]); |
| 1737 | addComposerDraftPreviewAnnotation(composerDraftTarget, restored.annotation, { |
| 1738 | appendReference: false, |
| 1739 | }); |
| 1740 | } |
| 1741 | for (const fileId of attachmentChanges.filesToRemove) { |
| 1742 | removeComposerDraftFile(attachmentDraftTarget, fileId); |
| 1743 | } |
| 1744 | if (attachmentChanges.filesToRestore.length > 0) { |
| 1745 | addComposerDraftFiles(attachmentDraftTarget, attachmentChanges.filesToRestore); |
| 1746 | } |
| 1747 | setComposerCursor(nextCursor); |
| 1748 | updateTrigger(trigger); |
| 1749 | }; |
| 1750 | const onPromptChangeStable = useStableCallback(onPromptChange); |
| 1751 | |
| 1752 | const applyPromptReplacement = ( |
| 1753 | rangeStart: number, |
| 1754 | rangeEnd: number, |
| 1755 | replacement: string, |
| 1756 | options?: { |
| 1757 | expectedText?: string; |
| 1758 | expandedCursorAfterReplace?: number; |
| 1759 | focusEditorAfterReplace?: boolean; |
| 1760 | citationComment?: { |
| 1761 | start: number; |
| 1762 | sourceAnchor: AssistantCitationSourceAnchor; |
| 1763 | insertedSpaces: ComposerCitationCommentRequest["insertedSpaces"]; |
| 1764 | }; |
| 1765 | }, |
| 1766 | ): boolean => { |
| 1767 | if ( |
| 1768 | activePendingUserInput && |
| 1769 | activePendingProgress?.activeQuestion?.allowCustomAnswer === false |
| 1770 | ) { |
| 1771 | return false; |
| 1772 | } |
| 1773 | const currentText = promptRef.current; |
| 1774 | const safeStart = Math.max(0, Math.min(currentText.length, rangeStart)); |
| 1775 | const safeEnd = Math.max(safeStart, Math.min(currentText.length, rangeEnd)); |
| 1776 | if ( |
| 1777 | options?.expectedText !== undefined && |
| 1778 | currentText.slice(safeStart, safeEnd) !== options.expectedText |
| 1779 | ) { |
| 1780 | return false; |
| 1781 | } |
| 1782 | const next = replaceTextRange(promptRef.current, rangeStart, rangeEnd, replacement); |
| 1783 | const nextCursor = collapseExpandedComposerCursor( |
| 1784 | next.text, |
| 1785 | options?.expandedCursorAfterReplace ?? next.cursor, |
| 1786 | isLiteralPendingAnswer, |
| 1787 | ); |
| 1788 | const nextExpandedCursor = expandCollapsedComposerCursor( |
| 1789 | next.text, |
| 1790 | nextCursor, |
| 1791 | isLiteralPendingAnswer, |
| 1792 | ); |
| 1793 | if (options?.citationComment) { |
| 1794 | composerEditorRef.current?.requestCitationComment({ |
| 1795 | previousValue: currentText, |
| 1796 | value: next.text, |
| 1797 | citationStart: options.citationComment.start, |
| 1798 | sourceAnchor: options.citationComment.sourceAnchor, |
| 1799 | insertedSpaces: options.citationComment.insertedSpaces, |
| 1800 | }); |
| 1801 | } |
| 1802 | promptRef.current = next.text; |
| 1803 | const activePendingQuestion = activePendingProgress?.activeQuestion; |
| 1804 | if (activePendingQuestion && activePendingUserInput) { |
| 1805 | onChangeActivePendingUserInputCustomAnswer( |
| 1806 | activePendingQuestion.id, |
| 1807 | next.text, |
| 1808 | nextCursor, |
| 1809 | nextExpandedCursor, |
| 1810 | isLiteralPendingAnswer, |
| 1811 | ); |
| 1812 | } else { |
| 1813 | setPrompt(next.text); |
| 1814 | onTypingGuardDraftChange(); |
| 1815 | } |
| 1816 | setComposerCursor(nextCursor); |
| 1817 | setComposerTrigger( |
| 1818 | isLiteralPendingAnswer ? null : detectComposerTrigger(next.text, nextExpandedCursor), |
| 1819 | ); |
| 1820 | if (options?.focusEditorAfterReplace !== false) { |
| 1821 | window.requestAnimationFrame(() => { |
| 1822 | if (promptRef.current !== next.text) return; |
| 1823 | composerEditorRef.current?.focusAt(nextCursor); |
| 1824 | }); |
| 1825 | } |
| 1826 | return true; |
| 1827 | }; |
| 1828 | const applyPromptReplacementStable = useStableCallback(applyPromptReplacement); |
| 1829 | |
| 1830 | const readComposerSnapshot = (): { |
| 1831 | value: string; |
| 1832 | cursor: number; |
| 1833 | expandedCursor: number; |
| 1834 | contextIds: string[]; |
| 1835 | } => { |
| 1836 | const editorSnapshot = composerEditorRef.current?.readSnapshot(); |
| 1837 | if (editorSnapshot) { |
| 1838 | return editorSnapshot; |
| 1839 | } |
| 1840 | return { |
| 1841 | value: promptRef.current, |
| 1842 | cursor: composerCursor, |
| 1843 | expandedCursor: expandCollapsedComposerCursor( |
| 1844 | promptRef.current, |
| 1845 | composerCursor, |
| 1846 | isLiteralPendingAnswer, |
| 1847 | ), |
| 1848 | contextIds: isLiteralPendingAnswer ? [] : collectInlineContextIds(promptRef.current), |
| 1849 | }; |
| 1850 | }; |
| 1851 | const readComposerSnapshotStable = useStableCallback(readComposerSnapshot); |
| 1852 | |
| 1853 | const dictationDisabled = |
| 1854 | !canOperateThread || |
| 1855 | environmentUnavailable !== null || |
| 1856 | projectSelectionRequired || |
| 1857 | isComposerApprovalState || |
| 1858 | activePendingIsResponding || |
| 1859 | activePendingProgress?.activeQuestion?.allowCustomAnswer === false; |
| 1860 | const speechInput = useEnvironmentSpeechInput({ |
| 1861 | environmentId, |
| 1862 | projectId: activeProjectId, |
| 1863 | projectName, |
| 1864 | ownerKey: questionAttachmentTarget ?? composerDraftTargetKey, |
| 1865 | disabled: dictationDisabled, |
| 1866 | label: activeThread?.title ?? null, |
| 1867 | presented: !hiddenThread, |
| 1868 | // A question's answer lives only in this composer, so only the thread draft outlives it. |
| 1869 | persistentDraft: questionAttachmentTarget |
| 1870 | ? undefined |
| 1871 | : { |
| 1872 | readStoredText: () => readComposerDraftPrompt(composerDraftTarget), |
| 1873 | commitStoredText: (text) => { |
| 1874 | const live = resolveLiveComposerDraftTarget(composerDraftTarget); |
| 1875 | if (live !== null) setComposerDraftPrompt(live, text); |
| 1876 | }, |
| 1877 | // The route, not the draft target: a queued-message edit has a draft id but no route. |
| 1878 | open: () => |
| 1879 | void (routeKind === "draft" && typeof composerDraftTarget === "string" |
| 1880 | ? navigate({ |
| 1881 | to: "/draft/$draftId", |
| 1882 | params: buildDraftThreadRouteParams(composerDraftTarget), |
| 1883 | }) |
| 1884 | : navigate({ |
| 1885 | to: "/$environmentId/$threadId", |
| 1886 | params: buildThreadRouteParams(routeThreadRef), |
| 1887 | })), |
| 1888 | }, |
| 1889 | readDraft: () => { |
| 1890 | const snapshot = readComposerSnapshot(); |
| 1891 | return { |
| 1892 | text: snapshot.value, |
| 1893 | selection: composerEditorRef.current?.readSelectionRange() ?? { |
| 1894 | start: snapshot.expandedCursor, |
| 1895 | end: snapshot.expandedCursor, |
| 1896 | }, |
| 1897 | }; |
| 1898 | }, |
| 1899 | commitDraft: (text, selection) => { |
| 1900 | const snapshot = readComposerSnapshot(); |
| 1901 | const applied = applyPromptReplacement(0, snapshot.value.length, text, { |
| 1902 | expectedText: snapshot.value, |
| 1903 | focusEditorAfterReplace: false, |
| 1904 | }); |
| 1905 | if (!applied) return; |
| 1906 | const cursor = collapseExpandedComposerCursor(text, selection.start, isLiteralPendingAnswer); |
| 1907 | setComposerCursor(cursor); |
| 1908 | window.requestAnimationFrame(() => composerEditorRef.current?.focusAt(cursor)); |
| 1909 | }, |
| 1910 | }); |
| 1911 | const { blocksSubmission: voiceInputActive, submitAfterDictation } = speechInput; |
| 1912 | // A compact footer gives the dictation capsule the whole row beside the send button. |
| 1913 | const dictationTakesFooter = isComposerFooterCompact && speechInput.state.phase !== "idle"; |
| 1914 | const submissionTarget = activePendingProgress ? "pending-user-input" : "provider-turn"; |
| 1915 | const submissionBlocked = isComposerSubmissionBlocked({ |
| 1916 | submissionTarget, |
| 1917 | noProviderAvailable, |
| 1918 | sendDisabledReason, |
| 1919 | attachmentBlockReason, |
| 1920 | environmentUnavailable: environmentUnavailable !== null, |
| 1921 | }); |
| 1922 | const submitAfterPreparingImages = useSubmitAfterPreparingImages( |
| 1923 | attachmentTargetKey, |
| 1924 | submissionBlocked, |
| 1925 | ); |
| 1926 | // The pending Submit button follows the answer's own blockers, matching submitComposer. |
| 1927 | const primaryActionSendDisabledReason = |
| 1928 | (activePendingProgress ? attachmentBlockReason : sendDisabledReason) ?? |
| 1929 | (speechInput.preparing ? gt("Preparing voice input") : null); |
| 1930 | const primaryActionEnvironmentUnavailable = |
| 1931 | environmentUnavailable !== null || |
| 1932 | (!activePendingProgress && (noProviderAvailable || projectSelectionRequired)); |
| 1933 | const dictationShortcutLabel = useDictationShortcut({ |
| 1934 | keybindings, |
| 1935 | speech: speechInput, |
| 1936 | disabled: dictationDisabled, |
| 1937 | terminalOpen, |
| 1938 | modelPickerOpen: isComposerModelPickerOpen, |
| 1939 | ...(backgroundThread ? { targetRef: composerFormRef } : {}), |
| 1940 | }); |
| 1941 | |
| 1942 | const resolveActiveComposerTrigger = (): { |
| 1943 | snapshot: { value: string; cursor: number; expandedCursor: number }; |
| 1944 | trigger: ComposerTrigger | null; |
| 1945 | } => { |
| 1946 | const snapshot = readComposerSnapshot(); |
| 1947 | return { |
| 1948 | snapshot, |
| 1949 | trigger: isLiteralPendingAnswer |
| 1950 | ? null |
| 1951 | : resolveComposerTrigger(detectComposerTrigger(snapshot.value, snapshot.expandedCursor)), |
| 1952 | }; |
| 1953 | }; |
| 1954 | |
| 1955 | const { onUsageLimitsCommand } = props; |
| 1956 | const onSelectComposerItem = (item: ComposerCommandItem) => { |
| 1957 | if (composerSelectLockRef.current) return; |
| 1958 | composerSelectLockRef.current = true; |
| 1959 | window.requestAnimationFrame(() => { |
| 1960 | composerSelectLockRef.current = false; |
| 1961 | }); |
| 1962 | const { snapshot, trigger } = resolveActiveComposerTrigger(); |
| 1963 | if (!trigger) return; |
| 1964 | if (item.type === "path") { |
| 1965 | if (!isPathSuggestionCurrent(item.searchTarget, trigger, environmentId, gitCwd)) return; |
| 1966 | const replacement = `${serializeComposerFileLink(item.path)} `; |
| 1967 | const replacementRangeEnd = extendReplacementRangeForTrailingSpace( |
| 1968 | snapshot.value, |
| 1969 | trigger.rangeEnd, |
| 1970 | replacement, |
| 1971 | ); |
| 1972 | const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { |
| 1973 | expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), |
| 1974 | }); |
| 1975 | if (applied) { |
| 1976 | setComposerHighlightedItemId(null); |
| 1977 | } |
| 1978 | return; |
| 1979 | } |
| 1980 | if (item.type === "slash-command") { |
| 1981 | if (item.command === "model") { |
| 1982 | const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { |
| 1983 | expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), |
| 1984 | focusEditorAfterReplace: false, |
| 1985 | }); |
| 1986 | if (applied) { |
| 1987 | setComposerHighlightedItemId(null); |
| 1988 | setIsComposerModelPickerOpen(true); |
| 1989 | } |
| 1990 | return; |
| 1991 | } |
| 1992 | if (item.command === "clear") { |
| 1993 | const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { |
| 1994 | expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), |
| 1995 | }); |
| 1996 | if (applied) { |
| 1997 | setComposerHighlightedItemId(null); |
| 1998 | props.onFreshSession?.(); |
| 1999 | } |
| 2000 | return; |
| 2001 | } |
| 2002 | if (item.command === "side" || item.command === "btw") { |
| 2003 | if (props.sideChatDisabledReason) return; |
| 2004 | const applied = applyPromptReplacement( |
| 2005 | trigger.rangeStart, |
| 2006 | trigger.rangeEnd, |
| 2007 | `/${item.command} `, |
| 2008 | { expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd) }, |
| 2009 | ); |
| 2010 | if (applied) setComposerHighlightedItemId(null); |
| 2011 | return; |
| 2012 | } |
| 2013 | return; |
| 2014 | } |
| 2015 | if (item.type === "provider-slash-command") { |
| 2016 | if (item.command.name === USAGE_LIMITS_COMMAND.name && onUsageLimitsCommand) { |
| 2017 | const applied = applyPromptReplacement(trigger.rangeStart, trigger.rangeEnd, "", { |
| 2018 | expectedText: snapshot.value.slice(trigger.rangeStart, trigger.rangeEnd), |
| 2019 | focusEditorAfterReplace: false, |
| 2020 | }); |
| 2021 | if (applied) { |
| 2022 | setComposerHighlightedItemId(null); |
| 2023 | onUsageLimitsCommand(); |
| 2024 | } |
| 2025 | return; |
| 2026 | } |
| 2027 | const replacement = `/${item.command.name} `; |
| 2028 | const replacementRangeEnd = extendReplacementRangeForTrailingSpace( |
| 2029 | snapshot.value, |
| 2030 | trigger.rangeEnd, |
| 2031 | replacement, |
| 2032 | ); |
| 2033 | const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { |
| 2034 | expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), |
| 2035 | }); |
| 2036 | if (applied) { |
| 2037 | setComposerHighlightedItemId(null); |
| 2038 | } |
| 2039 | return; |
| 2040 | } |
| 2041 | if (item.type === "skill") { |
| 2042 | const replacement = `$${item.skill.name} `; |
| 2043 | const replacementRangeEnd = extendReplacementRangeForTrailingSpace( |
| 2044 | snapshot.value, |
| 2045 | trigger.rangeEnd, |
| 2046 | replacement, |
| 2047 | ); |
| 2048 | const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { |
| 2049 | expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), |
| 2050 | }); |
| 2051 | if (applied) { |
| 2052 | setComposerHighlightedItemId(null); |
| 2053 | } |
| 2054 | return; |
| 2055 | } |
| 2056 | if (item.type === "pull-request") { |
| 2057 | if ( |
| 2058 | trigger.kind !== "pull-request" || |
| 2059 | !composerMenuItemsRef.current.some((candidate) => candidate.id === item.id) |
| 2060 | ) { |
| 2061 | return; |
| 2062 | } |
| 2063 | const comment = buildPullRequestReferenceContext(item.pullRequest); |
| 2064 | const replacement = `${formatInlineContextReference( |
| 2065 | reviewCommentContextReference(comment), |
| 2066 | )} `; |
| 2067 | const replacementRangeEnd = extendReplacementRangeForTrailingSpace( |
| 2068 | snapshot.value, |
| 2069 | trigger.rangeEnd, |
| 2070 | replacement, |
| 2071 | ); |
| 2072 | const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { |
| 2073 | expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), |
| 2074 | }); |
| 2075 | if (applied) { |
| 2076 | addComposerDraftReviewComment(composerDraftTarget, comment, { |
| 2077 | appendReference: false, |
| 2078 | }); |
| 2079 | setComposerHighlightedItemId(null); |
| 2080 | } |
| 2081 | return; |
| 2082 | } |
| 2083 | if (item.type === "thread") { |
| 2084 | if (trigger.kind !== "path") return; |
| 2085 | const shell = readThreadShell(item.thread); |
| 2086 | if (!shell) return; |
| 2087 | const record = threadContextRecord(item.thread, shell.title); |
| 2088 | const replacement = `${formatInlineContextReference(threadContextReference(record))} `; |
| 2089 | const replacementRangeEnd = extendReplacementRangeForTrailingSpace( |
| 2090 | snapshot.value, |
| 2091 | trigger.rangeEnd, |
| 2092 | replacement, |
| 2093 | ); |
| 2094 | const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { |
| 2095 | expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), |
| 2096 | }); |
| 2097 | if (applied) { |
| 2098 | addComposerDraftThreadContexts(attachmentDraftTarget, [record], { |
| 2099 | appendReference: false, |
| 2100 | }); |
| 2101 | setComposerHighlightedItemId(null); |
| 2102 | } |
| 2103 | return; |
| 2104 | } |
| 2105 | if (item.type === "model") { |
| 2106 | if (trigger.kind !== "path") return; |
| 2107 | const replacement = `${formatComposerModelMention(item.instanceId, item.model)} `; |
| 2108 | const replacementRangeEnd = extendReplacementRangeForTrailingSpace( |
| 2109 | snapshot.value, |
| 2110 | trigger.rangeEnd, |
| 2111 | replacement, |
| 2112 | ); |
| 2113 | const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { |
| 2114 | expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), |
| 2115 | }); |
| 2116 | if (applied) { |
| 2117 | setComposerHighlightedItemId(null); |
| 2118 | } |
| 2119 | return; |
| 2120 | } |
| 2121 | if (item.type === "environment") { |
| 2122 | if (trigger.kind !== "path") return; |
| 2123 | const record = environmentContextRecord(item.environmentId, item.label); |
| 2124 | const replacement = `${formatInlineContextReference(environmentContextReference(record))} `; |
| 2125 | const replacementRangeEnd = extendReplacementRangeForTrailingSpace( |
| 2126 | snapshot.value, |
| 2127 | trigger.rangeEnd, |
| 2128 | replacement, |
| 2129 | ); |
| 2130 | const applied = applyPromptReplacement(trigger.rangeStart, replacementRangeEnd, replacement, { |
| 2131 | expectedText: snapshot.value.slice(trigger.rangeStart, replacementRangeEnd), |
| 2132 | }); |
| 2133 | if (applied) { |
| 2134 | addComposerDraftEnvironmentContexts(composerDraftTarget, [record], { |
| 2135 | appendReference: false, |
| 2136 | }); |
| 2137 | setComposerHighlightedItemId(null); |
| 2138 | } |
| 2139 | return; |
| 2140 | } |
| 2141 | }; |
| 2142 | const onSelectComposerItemStable = useStableCallback(onSelectComposerItem); |
| 2143 | |
| 2144 | const onComposerMenuItemHighlighted = (itemId: string | null) => { |
| 2145 | setComposerHighlightedItemId(itemId); |
| 2146 | setComposerHighlightedSearchKey(composerMenuSearchKey); |
| 2147 | }; |
| 2148 | const onComposerMenuItemHighlightedStable = useStableCallback(onComposerMenuItemHighlighted); |
| 2149 | |
| 2150 | const nudgeComposerMenuHighlight = (key: "ArrowDown" | "ArrowUp") => { |
| 2151 | if (composerMenuItems.length === 0) return; |
| 2152 | const highlightedIndex = composerMenuItems.findIndex( |
| 2153 | (item) => item.id === composerHighlightedItemId, |
| 2154 | ); |
| 2155 | const normalizedIndex = highlightedIndex >= 0 ? highlightedIndex : key === "ArrowDown" ? -1 : 0; |
| 2156 | const offset = key === "ArrowDown" ? 1 : -1; |
| 2157 | const nextIndex = |
| 2158 | (normalizedIndex + offset + composerMenuItems.length) % composerMenuItems.length; |
| 2159 | const nextItem = composerMenuItems[nextIndex]; |
| 2160 | setComposerHighlightedItemId(nextItem?.id ?? null); |
| 2161 | }; |
| 2162 | |
| 2163 | const blurMobileComposerAfterSend = () => { |
| 2164 | if (!isSoftwareKeyboardOpen) return; |
| 2165 | if (composerBlurFrameRef.current !== null) { |
| 2166 | window.cancelAnimationFrame(composerBlurFrameRef.current); |
| 2167 | composerBlurFrameRef.current = null; |
| 2168 | } |
| 2169 | const activeElement = document.activeElement; |
| 2170 | if (activeElement instanceof HTMLElement) { |
| 2171 | activeElement.blur(); |
| 2172 | } |
| 2173 | setIsComposerFocused(false); |
| 2174 | }; |
| 2175 | |
| 2176 | const shouldBlurMobileComposerOnSubmit = () => { |
| 2177 | if (!isSoftwareKeyboardOpen) return false; |
| 2178 | if (isSendBusy || submissionBlocked || environmentUnavailable !== null || phase === "running") { |
| 2179 | return false; |
| 2180 | } |
| 2181 | if (activePendingProgress) { |
| 2182 | return activePendingProgress.isLastQuestion && Boolean(activePendingResolvedAnswers); |
| 2183 | } |
| 2184 | return composerSendState.hasSendableContent; |
| 2185 | }; |
| 2186 | |
| 2187 | const submitComposerRef = useRef< |
| 2188 | (dispatchMode?: ComposerDispatchMode, submissionIntent?: ComposerSubmissionIntent) => void |
| 2189 | >(() => {}); |
| 2190 | const submitComposer = ( |
| 2191 | event?: { preventDefault: () => void }, |
| 2192 | dispatchMode?: ComposerDispatchMode, |
| 2193 | submissionIntent?: ComposerSubmissionIntent, |
| 2194 | ) => { |
| 2195 | if (voiceInputActive) { |
| 2196 | event?.preventDefault(); |
| 2197 | submitAfterDictation(() => submitComposerRef.current(dispatchMode, submissionIntent)); |
| 2198 | return false; |
| 2199 | } |
| 2200 | if (submissionBlocked || !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope)) { |
| 2201 | event?.preventDefault(); |
| 2202 | return false; |
| 2203 | } |
| 2204 | // Sending now would leave a still-compressing image out of the turn, so wait for it. |
| 2205 | if ( |
| 2206 | activeThreadId && |
| 2207 | submitAfterPreparingImages(() => submitComposerRef.current(dispatchMode, submissionIntent)) |
| 2208 | ) { |
| 2209 | event?.preventDefault(); |
| 2210 | return false; |
| 2211 | } |
| 2212 | if (pendingDraftWork.has(attachmentTargetKey)) { |
| 2213 | event?.preventDefault(); |
| 2214 | toastManager.add({ |
| 2215 | type: "info", |
| 2216 | title: gt("Still bringing attached context into this message."), |
| 2217 | description: gt("Send again once its chip resolves."), |
| 2218 | }); |
| 2219 | return false; |
| 2220 | } |
| 2221 | // An empty draft has nothing to send; Enter does what the Resume thread button does. |
| 2222 | if (showResumeAction && !activePendingProgress) { |
| 2223 | event?.preventDefault(); |
| 2224 | if (isSendBusy || environmentUnavailable !== null) return false; |
| 2225 | onResume(); |
| 2226 | return true; |
| 2227 | } |
| 2228 | const submission = submitComposerDraft({ |
| 2229 | prompt: promptRef.current, |
| 2230 | submissionTarget, |
| 2231 | event, |
| 2232 | onSend: (sendEvent) => { |
| 2233 | providerInputRejectedRef.current = false; |
| 2234 | onSend( |
| 2235 | sendEvent, |
| 2236 | dispatchMode ?? |
| 2237 | resolveComposerDispatchMode({ |
| 2238 | running: phase === "running" || phase === "connecting", |
| 2239 | alternateModifier: false, |
| 2240 | activeTurnDefault: followUpBehavior, |
| 2241 | canSteer, |
| 2242 | }), |
| 2243 | submissionIntent, |
| 2244 | ); |
| 2245 | return !providerInputRejectedRef.current; |
| 2246 | }, |
| 2247 | }); |
| 2248 | setComposerSubmissionError(submission.validationMessage); |
| 2249 | if (!submission.didDispatch) return false; |
| 2250 | onTypingGuardSend(); |
| 2251 | if (shouldBlurMobileComposerOnSubmit()) { |
| 2252 | blurMobileComposerAfterSend(); |
| 2253 | } |
| 2254 | return true; |
| 2255 | }; |
| 2256 | const submitComposerStable = useStableCallback(submitComposer); |
| 2257 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- publishes the committed submission handler to the asynchronous dictation completion |
| 2258 | useLayoutEffect(() => { |
| 2259 | submitComposerRef.current = (mode, intent) => submitComposerStable(undefined, mode, intent); |
| 2260 | }, [submitComposerStable]); |
| 2261 | useDictationSubmissionShortcut({ |
| 2262 | enabled: voiceInputActive && !speechInput.preparing, |
| 2263 | formRef: composerFormRef, |
| 2264 | onKeyDown: (event) => { |
| 2265 | const intent = composerSubmissionIntentForKey({ |
| 2266 | event, |
| 2267 | keybindings, |
| 2268 | context: getShortcutContext(event.target), |
| 2269 | isSoftwareKeyboardOpen, |
| 2270 | isDraftThread: routeKind === "draft", |
| 2271 | isRunning: phase === "running" || phase === "connecting", |
| 2272 | sendShortcut: settings.sendShortcut, |
| 2273 | prompt: promptRef.current, |
| 2274 | }); |
| 2275 | if (!intent) return; |
| 2276 | event.preventDefault(); |
| 2277 | event.stopImmediatePropagation(); |
| 2278 | submitComposer( |
| 2279 | undefined, |
| 2280 | resolveComposerDispatchMode({ |
| 2281 | running: phase === "running" || phase === "connecting", |
| 2282 | alternateModifier: intent === "alternate", |
| 2283 | canSteer, |
| 2284 | activeTurnDefault: followUpBehavior, |
| 2285 | }), |
| 2286 | intent, |
| 2287 | ); |
| 2288 | }, |
| 2289 | }); |
| 2290 | const handleSubmitMessage = (event: React.MouseEvent<HTMLButtonElement>) => { |
| 2291 | event.preventDefault(); |
| 2292 | const running = phase === "running" || phase === "connecting"; |
| 2293 | const alternateModifier = event.metaKey || event.ctrlKey; |
| 2294 | submitComposer( |
| 2295 | event, |
| 2296 | resolveComposerDispatchMode({ |
| 2297 | running, |
| 2298 | alternateModifier, |
| 2299 | activeTurnDefault: followUpBehavior, |
| 2300 | canSteer, |
| 2301 | }), |
| 2302 | running && alternateModifier ? "alternate" : undefined, |
| 2303 | ); |
| 2304 | }; |
| 2305 | const handleSubmitMessageStable = useStableCallback(handleSubmitMessage); |
| 2306 | const submitCitationAndSend = () => { |
| 2307 | return submitComposer( |
| 2308 | undefined, |
| 2309 | resolveComposerDispatchMode({ |
| 2310 | running: phase === "running" || phase === "connecting", |
| 2311 | alternateModifier: false, |
| 2312 | activeTurnDefault: followUpBehavior, |
| 2313 | canSteer, |
| 2314 | }), |
| 2315 | ); |
| 2316 | }; |
| 2317 | const submitCitationAndSendStable = useStableCallback(submitCitationAndSend); |
| 2318 | // A question took the editor while a citation comment was |
| 2319 | // unsaved. Keep the comment in the prompt that comes back afterward. |
| 2320 | const saveCitationDraftToPrompt = (replacedValue: string, savedValue: string) => { |
| 2321 | if (replacedValue !== prompt) return; |
| 2322 | if (promptRef.current === replacedValue) promptRef.current = savedValue; |
| 2323 | setPrompt(savedValue); |
| 2324 | }; |
| 2325 | const saveCitationDraftToPromptStable = useStableCallback(saveCitationDraftToPrompt); |
| 2326 | const compactThreadContext = () => { |
| 2327 | if ( |
| 2328 | !readEnvironmentScope(environmentId, AuthOrchestrationOperateScope) || |
| 2329 | compactDisabled || |
| 2330 | noProviderAvailable || |
| 2331 | activePendingApproval !== null || |
| 2332 | pendingUserInputs.length > 0 || |
| 2333 | phase === "running" || |
| 2334 | isSendBusy || |
| 2335 | !activeThreadId |
| 2336 | ) { |
| 2337 | return; |
| 2338 | } |
| 2339 | onCompactContext(); |
| 2340 | }; |
| 2341 | const compactThreadContextStable = useStableCallback(compactThreadContext); |
| 2342 | const expandMobileComposer = () => { |
| 2343 | if (composerBlurFrameRef.current !== null) { |
| 2344 | window.cancelAnimationFrame(composerBlurFrameRef.current); |
| 2345 | composerBlurFrameRef.current = null; |
| 2346 | } |
| 2347 | if (mobileComposerExpandFrameRef.current !== null) { |
| 2348 | window.cancelAnimationFrame(mobileComposerExpandFrameRef.current); |
| 2349 | } |
| 2350 | if (mobileComposerExpandReleaseFrameRef.current !== null) { |
| 2351 | window.cancelAnimationFrame(mobileComposerExpandReleaseFrameRef.current); |
| 2352 | } |
| 2353 | mobileComposerExpandInFlightRef.current = true; |
| 2354 | setIsComposerFocused(true); |
| 2355 | mobileComposerExpandFrameRef.current = window.requestAnimationFrame(() => { |
| 2356 | mobileComposerExpandFrameRef.current = null; |
| 2357 | composerEditorRef.current?.focusAtEnd(); |
| 2358 | mobileComposerExpandReleaseFrameRef.current = window.requestAnimationFrame(() => { |
| 2359 | mobileComposerExpandReleaseFrameRef.current = null; |
| 2360 | mobileComposerExpandInFlightRef.current = false; |
| 2361 | }); |
| 2362 | }); |
| 2363 | }; |
| 2364 | const expandMobileComposerStable = useStableCallback(expandMobileComposer); |
| 2365 | |
| 2366 | // Escape dismisses the suggestion so Tab moves focus again. |
| 2367 | const { suggestion: promptSuggestion, dismiss: dismissPromptSuggestion } = usePromptSuggestion( |
| 2368 | environmentId, |
| 2369 | activeThread, |
| 2370 | activeThreadRuns, |
| 2371 | ); |
| 2372 | // After /clear the next message starts a fresh session that cannot see what the suggestion refers to. |
| 2373 | const freshSessionArmed = useFreshSessionArmed(scopedThreadKey(routeThreadRef)); |
| 2374 | // Offered only where the default placeholder would show, so it never hides a pending question. |
| 2375 | const offeredPromptSuggestion = |
| 2376 | phase !== "running" && |
| 2377 | !isSendBusy && |
| 2378 | !freshSessionArmed && |
| 2379 | !speechInput.freezesEditor && |
| 2380 | composerContextRecords.size === 0 && |
| 2381 | !isComposerApprovalState && |
| 2382 | !activePendingProgress && |
| 2383 | !projectSelectionRequired && |
| 2384 | !showProviderUnavailable |
| 2385 | ? promptSuggestion |
| 2386 | : null; |
| 2387 | |
| 2388 | const onComposerCommandKey = (key: string, event: KeyboardEvent, isTaskItem?: boolean) => |
| 2389 | composerCommandKeyHandler({ |
| 2390 | keybindings, |
| 2391 | getShortcutContext, |
| 2392 | sendShortcut: settings.sendShortcut, |
| 2393 | routeKind, |
| 2394 | phase, |
| 2395 | canSteer, |
| 2396 | followUpBehavior, |
| 2397 | isSoftwareKeyboardOpen, |
| 2398 | isLiteralPendingAnswer, |
| 2399 | pendingUserInputs, |
| 2400 | promptHistoryEntries, |
| 2401 | promptHistoryPositionRef, |
| 2402 | composerDraftTarget, |
| 2403 | promptRef, |
| 2404 | composerImagesRef, |
| 2405 | composerFilesRef, |
| 2406 | composerTerminalContextsRef, |
| 2407 | composerPreviewAnnotations, |
| 2408 | composerReviewComments, |
| 2409 | composerEditorRef, |
| 2410 | composerMenuItemsRef, |
| 2411 | activeComposerMenuItemRef, |
| 2412 | setComposerDraftPrompt, |
| 2413 | setComposerDraftThreadContexts, |
| 2414 | setComposerDraftEnvironmentContexts, |
| 2415 | setComposerCursor, |
| 2416 | setComposerTrigger, |
| 2417 | setComposerHighlightedItemId, |
| 2418 | dismissComposerTrigger, |
| 2419 | nudgeComposerMenuHighlight, |
| 2420 | onSelectComposerItem, |
| 2421 | resolveActiveComposerTrigger, |
| 2422 | readComposerSnapshot, |
| 2423 | applyPromptReplacement, |
| 2424 | submitComposer, |
| 2425 | promptSuggestion: offeredPromptSuggestion, |
| 2426 | dismissPromptSuggestion, |
| 2427 | })(key, event, isTaskItem); |
| 2428 | |
| 2429 | const { |
| 2430 | stashQueue, |
| 2431 | isStashMenuOpen, |
| 2432 | setIsStashMenuOpen, |
| 2433 | stashPulseKey, |
| 2434 | restoreStashEntryStable, |
| 2435 | deleteStashEntryStable, |
| 2436 | toggleStashMenuStable, |
| 2437 | } = useComposerStash({ |
| 2438 | environmentId, |
| 2439 | composerDraftTarget, |
| 2440 | promptRef, |
| 2441 | readAttachmentDraft: () => ({ |
| 2442 | images: composerImagesRef.current, |
| 2443 | files: composerFilesRef.current, |
| 2444 | }), |
| 2445 | readTerminalContexts: () => composerTerminalContextsRef.current, |
| 2446 | routeThreadRef, |
| 2447 | projectSelectionRequired, |
| 2448 | pendingUserInputs, |
| 2449 | activePendingProgress, |
| 2450 | prompt, |
| 2451 | composerMenuOpen, |
| 2452 | isComposerCollapsedMobile, |
| 2453 | composerPreviewAnnotations, |
| 2454 | composerReviewComments, |
| 2455 | composerThreadContexts, |
| 2456 | attachmentTargetKey, |
| 2457 | isComposerDraftTargetOpen: (key) => composerDraftTargetKeyRef.current === key, |
| 2458 | composerEditorRef, |
| 2459 | isRevertingCheckpoint: () => isRevertingCheckpointRef.current, |
| 2460 | pendingThreadImportsRef, |
| 2461 | setComposerCursor, |
| 2462 | setComposerTrigger, |
| 2463 | importContextRecords, |
| 2464 | expandMobileComposer: expandMobileComposerStable, |
| 2465 | }); |
| 2466 | const hasBlockingComposerTopDrawer = pendingUserInputs.length > 0; |
| 2467 | const composerControlsCollapsed = isComposerCollapsedMobile; |
| 2468 | // The collapsed mobile web composer keeps a second controls row inside the card. |
| 2469 | const showInlineRestingControls = isComposerCollapsedMobile; |
| 2470 | const composerControlsHidden = showInlineRestingControls && !restingControlsVisible; |
| 2471 | if (composerControlsHidden && isComposerModelPickerOpen) { |
| 2472 | setIsComposerModelPickerOpen(false); |
| 2473 | } |
| 2474 | const collapsedComposerImagePreviews = |
| 2475 | standaloneComposerImages.length > 0 ? ( |
| 2476 | <ComposerRestingImagePreviews |
| 2477 | images={standaloneComposerImages} |
| 2478 | allImages={composerImages} |
| 2479 | resolvedTheme={resolvedTheme} |
| 2480 | onExpandImage={onExpandImage} |
| 2481 | onCopySnapshot={copyComposerSnapshotStable} |
| 2482 | onShowMore={expandMobileComposer} |
| 2483 | /> |
| 2484 | ) : null; |
| 2485 | const { active: panelAnimationsActive, durationMs: panelAnimationDurationMs } = |
| 2486 | usePanelAnimationSettings(); |
| 2487 | const composerMainSurfaceRef = useComposerRestingTransition( |
| 2488 | composerControlsCollapsed, |
| 2489 | restingComposerControlsRef, |
| 2490 | onComposerOverlayHeightChange, |
| 2491 | panelAnimationsActive, |
| 2492 | panelAnimationDurationMs, |
| 2493 | ); |
| 2494 | const restingHiddenBlockCount = showInlineRestingControls |
| 2495 | ? restingControlsHiddenBlockCount |
| 2496 | : composerControlsCollapsed |
| 2497 | ? 0 |
| 2498 | : expandedControlsHiddenBlockCount; |
| 2499 | const iconOnlyBlockCount = showInlineRestingControls |
| 2500 | ? restingControlsIconOnlyBlockCount |
| 2501 | : composerControlsCollapsed |
| 2502 | ? 0 |
| 2503 | : expandedControlsIconOnlyBlockCount; |
| 2504 | const composerControls = ( |
| 2505 | <ComposerControlsBar |
| 2506 | environmentId={environmentId} |
| 2507 | workspaceCwd={gitCwd} |
| 2508 | routeKind={routeKind} |
| 2509 | routeThreadRef={routeThreadRef} |
| 2510 | draftId={draftId} |
| 2511 | selectedProvider={selectedProvider} |
| 2512 | selectedInstanceId={selectedInstanceId} |
| 2513 | selectedModel={selectedModel} |
| 2514 | selectedProviderModels={selectedProviderModels} |
| 2515 | composerModelOptions={composerModelOptions} |
| 2516 | reportedModelSelection={reportedModelSelection} |
| 2517 | promptUltrathink={promptUltrathink} |
| 2518 | onPromptEdit={editPromptFromTraitsStable} |
| 2519 | compatibleRuntimeMode={compatibleRuntimeMode} |
| 2520 | defaultRuntimeMode={props.defaultRuntimeMode} |
| 2521 | compatibleRuntimeModeOptions={compatibleRuntimeModeOptions} |
| 2522 | handleRuntimeModeChange={handleRuntimeModeChange} |
| 2523 | composerControlsCollapsed={composerControlsCollapsed} |
| 2524 | effortDisplay={settings.effortDisplay} |
| 2525 | permissionsShownInStrip={props.permissionsShownInStrip} |
| 2526 | composerControlsHidden={composerControlsHidden} |
| 2527 | restingHiddenBlockCount={restingHiddenBlockCount} |
| 2528 | iconOnlyBlockCount={iconOnlyBlockCount} |
| 2529 | showProviderUnavailable={showProviderUnavailable} |
| 2530 | providerSetupInstanceId={providerSetupInstanceId} |
| 2531 | onOpenProviderSetup={onOpenProviderSetup} |
| 2532 | providerCatalogPending={providerCatalogPending} |
| 2533 | isSendBusy={isSendBusy} |
| 2534 | multipleModelsEnabled={routeKind === "draft" && supportsMultipleModels} |
| 2535 | multipleModelSelections={multipleModelSelections} |
| 2536 | onMultipleModelSelectionsChange={setMultipleModelSelections} |
| 2537 | selectedModelSelection={selectedModelSelection} |
| 2538 | onProviderModelSelect={onProviderModelSelect} |
| 2539 | activeThreadModelSelection={activeThreadModelSelection} |
| 2540 | selectedModelForPickerWithCustomFallback={selectedModelForPickerWithCustomFallback} |
| 2541 | lockedProvider={lockedProvider} |
| 2542 | lockedContinuationGroupKey={lockedContinuationGroupKey} |
| 2543 | providerInstanceEntries={providerInstanceEntries} |
| 2544 | keybindings={keybindings} |
| 2545 | modelOptionsByInstance={modelOptionsByInstance} |
| 2546 | terminalOpen={terminalOpen} |
| 2547 | modelPickerOpen={isComposerModelPickerOpen} |
| 2548 | onModelPickerOpenChange={setIsComposerModelPickerOpen} |
| 2549 | modelPickerIconClassName={composerProviderState.modelPickerIconClassName} |
| 2550 | getModelDisabledReason={getModelDisabledReason} |
| 2551 | /> |
| 2552 | ); |
| 2553 | // An open question owns the space above the composer. Only a machine problem, |
| 2554 | // which is why an answer could not go through, stays beside it. |
| 2555 | const replyTo = composerDraft?.replyTo ?? null; |
| 2556 | const draftRunsLocally = composerRunsDraftLocally({ |
| 2557 | text: prompt, |
| 2558 | holdsOnlyText: |
| 2559 | composerImages.length + composerFiles.length === 0 && |
| 2560 | composerSendState.sendableTerminalContexts.length === 0 && |
| 2561 | composerPreviewAnnotations.length === 0 && |
| 2562 | composerReviewComments.length === 0 && |
| 2563 | composerThreadContexts.length === 0 && |
| 2564 | composerEnvironmentContexts.length === 0 && |
| 2565 | replyTo === null, |
| 2566 | sideChat: props.sideChatAvailable === true || (props.sideChatDisabledReason ?? null) !== null, |
| 2567 | usageLimits: props.onUsageLimitsCommand !== undefined, |
| 2568 | codexFeedback: selectedProvider === "codex" && multipleModelSelections === null, |
| 2569 | freshSession: props.onFreshSession !== undefined, |
| 2570 | }); |
| 2571 | const replyBannerItems: readonly ComposerBannerStackItem[] = replyTo |
| 2572 | ? [ |
| 2573 | { |
| 2574 | id: "reply-to", |
| 2575 | variant: "default", |
| 2576 | icon: <ReplyIcon />, |
| 2577 | title: replyTo.subagents |
| 2578 | ? gt("Replying to {titles}", { |
| 2579 | titles: replyTo.subagents.map((subagent) => subagent.title).join(", "), |
| 2580 | }) |
| 2581 | : gt("Replying to", { $context: "banner title; the message being replied to follows" }), |
| 2582 | description: ( |
| 2583 | <button |
| 2584 | type="button" |
| 2585 | className="cursor-pointer hover:text-foreground" |
| 2586 | onClick={() => { |
| 2587 | const { citation } = replyTo; |
| 2588 | const source = readThreadShell( |
| 2589 | scopeThreadRef(citation.environmentId, citation.threadId), |
| 2590 | ); |
| 2591 | void navigate(assistantCitationNavigation(citation, source)); |
| 2592 | }} |
| 2593 | > |
| 2594 | {assistantCitationLabel(replyTo.citation)} |
| 2595 | </button> |
| 2596 | ), |
| 2597 | dismissLabel: gt("Cancel reply"), |
| 2598 | onDismiss: () => setComposerDraftReplyTo(composerDraftTarget, null), |
| 2599 | }, |
| 2600 | ] |
| 2601 | : []; |
| 2602 | const bannerItems: readonly ComposerBannerStackItem[] = |
| 2603 | runtimeModeCeilingDenial === undefined || activePendingProgress |
| 2604 | ? [...props.bannerItems, ...replyBannerItems] |
| 2605 | : [ |
| 2606 | ...props.bannerItems, |
| 2607 | ...replyBannerItems, |
| 2608 | { |
| 2609 | id: "managed-runtime-mode", |
| 2610 | variant: "warning", |
| 2611 | icon: <BuildingIcon />, |
| 2612 | title: runtimeModeCeilingDenial, |
| 2613 | ...(runtimeModeCeilingFallback === undefined |
| 2614 | ? {} |
| 2615 | : { |
| 2616 | actions: ( |
| 2617 | <Button |
| 2618 | size="xs" |
| 2619 | variant="ghost" |
| 2620 | onClick={() => handleRuntimeModeChange(runtimeModeCeilingFallback)} |
| 2621 | > |
| 2622 | <T> |
| 2623 | Switch to{" "} |
| 2624 | <Var>{m(runtimeModeConfig[runtimeModeCeilingFallback].label)}</Var> |
| 2625 | </T> |
| 2626 | </Button> |
| 2627 | ), |
| 2628 | }), |
| 2629 | }, |
| 2630 | ]; |
| 2631 | const shelfItems = hasBlockingComposerTopDrawer |
| 2632 | ? bannerItems.filter( |
| 2633 | (item) => |
| 2634 | item.group === "environment" && (item.variant === "error" || item.variant === "warning"), |
| 2635 | ) |
| 2636 | : bannerItems; |
| 2637 | |
| 2638 | const insertComposerText = ( |
| 2639 | text: string, |
| 2640 | position: "cursor" | "end", |
| 2641 | options?: { |
| 2642 | ensureLeadingBoundary?: boolean; |
| 2643 | citationCommentAnchor?: AssistantCitationSourceAnchor; |
| 2644 | clipboardData?: DataTransfer; |
| 2645 | }, |
| 2646 | ): boolean => { |
| 2647 | if ( |
| 2648 | text.length === 0 || |
| 2649 | activePendingIsResponding || |
| 2650 | (pendingUserInputs.length > 0 && !activePendingProgress?.activeQuestion) || |
| 2651 | projectSelectionRequired || |
| 2652 | (options?.citationCommentAnchor && !composerEditorRef.current) |
| 2653 | ) { |
| 2654 | return false; |
| 2655 | } |
| 2656 | if (options?.clipboardData) { |
| 2657 | text = importPastedComposerText(options.clipboardData, importContextFragment); |
| 2658 | } |
| 2659 | const prompt = promptRef.current; |
| 2660 | const cursor = position === "cursor" ? readComposerSnapshot().expandedCursor : prompt.length; |
| 2661 | const needsLeadingSpace = |
| 2662 | (options?.ensureLeadingBoundary ?? false) && |
| 2663 | cursor > 0 && |
| 2664 | !/\s/.test(prompt[cursor - 1] ?? ""); |
| 2665 | const rangeEnd = extendReplacementRangeForTrailingSpace(prompt, cursor, text); |
| 2666 | return applyPromptReplacement( |
| 2667 | cursor, |
| 2668 | rangeEnd, |
| 2669 | needsLeadingSpace ? ` ${text}` : text, |
| 2670 | options?.citationCommentAnchor |
| 2671 | ? { |
| 2672 | citationComment: { |
| 2673 | start: cursor + (needsLeadingSpace ? 1 : 0), |
| 2674 | sourceAnchor: options.citationCommentAnchor, |
| 2675 | insertedSpaces: { before: needsLeadingSpace, after: rangeEnd === cursor }, |
| 2676 | }, |
| 2677 | focusEditorAfterReplace: false, |
| 2678 | } |
| 2679 | : undefined, |
| 2680 | ); |
| 2681 | }; |
| 2682 | const insertComposerTextStable = useStableCallback(insertComposerText); |
| 2683 | |
| 2684 | const insertAttachmentReferences = ( |
| 2685 | references: ReadonlyArray<ComposerContextReference>, |
| 2686 | selection?: { start: number; end: number }, |
| 2687 | pendingInsertion?: ComposerAttachmentInsertion, |
| 2688 | ): boolean => { |
| 2689 | if (references.length === 0) return false; |
| 2690 | // Question answers carry attachments beside the answer, never as chips. Falling back to |
| 2691 | // the thread prompt here would hide the file behind a reference the question never shows. |
| 2692 | if (questionAttachmentTarget) return false; |
| 2693 | return insertAttachmentReferencesForDraft({ |
| 2694 | target: composerDraftTarget, |
| 2695 | liveAttachmentTargetKey: attachmentTargetKeyRef.current, |
| 2696 | references, |
| 2697 | insertReferences: () => { |
| 2698 | if (pendingInsertion?.insert(references)) return true; |
| 2699 | if (selection) { |
| 2700 | const edit = inlineContextReferenceReplacement(promptRef.current, selection, references); |
| 2701 | return applyPromptReplacementStable(edit.start, edit.end, edit.text); |
| 2702 | } |
| 2703 | const text = references.map(formatInlineContextReference).join(" "); |
| 2704 | const inserted = insertComposerTextStable(`${text} `, "cursor", { |
| 2705 | ensureLeadingBoundary: true, |
| 2706 | }); |
| 2707 | if (!inserted) { |
| 2708 | setPrompt(ensureInlineContextReferences(promptRef.current, references)); |
| 2709 | } |
| 2710 | return true; |
| 2711 | }, |
| 2712 | }); |
| 2713 | }; |
| 2714 | |
| 2715 | const { addComposerAttachments, removeComposerImage, foldPastedText } = |
| 2716 | useComposerAttachmentIntake({ |
| 2717 | activeThreadId, |
| 2718 | activePendingProgress, |
| 2719 | activePendingIsResponding, |
| 2720 | pendingUserInputs, |
| 2721 | supportsQuestionAttachments, |
| 2722 | isLiteralPendingAnswer, |
| 2723 | projectSelectionRequired, |
| 2724 | questionAttachmentTarget, |
| 2725 | attachmentTargetKey, |
| 2726 | fileStagingLimit, |
| 2727 | promptRef, |
| 2728 | composerImagesRef, |
| 2729 | composerFilesRef, |
| 2730 | composerEditorRef, |
| 2731 | isRevertingCheckpointRef, |
| 2732 | setThreadError, |
| 2733 | countReservedAttachments, |
| 2734 | addComposerImage, |
| 2735 | addComposerImagesToDraft, |
| 2736 | addComposerFilesToDraft, |
| 2737 | removeComposerImageFromDraft, |
| 2738 | insertAttachmentReferences, |
| 2739 | }); |
| 2740 | |
| 2741 | const onComposerCommandKeyStable = useStableCallback(onComposerCommandKey); |
| 2742 | const isPathQueryActiveStable = useStableCallback( |
| 2743 | () => resolveActiveComposerTrigger().trigger?.kind === "path", |
| 2744 | ); |
| 2745 | |
| 2746 | const insertComposerTextAtEnd: ChatComposerHandle["insertTextAtEnd"] = (text, options) => { |
| 2747 | const inserted = insertComposerText(text, "end", options); |
| 2748 | if (inserted && isComposerCollapsedMobile) { |
| 2749 | // Reveal the mobile editor before its focus frame. |
| 2750 | expandMobileComposer(); |
| 2751 | } |
| 2752 | return inserted; |
| 2753 | }; |
| 2754 | const insertComposerTextAtEndStable = useStableCallback(insertComposerTextAtEnd); |
| 2755 | |
| 2756 | const insertComposerFolders = async ( |
| 2757 | folders: File[], |
| 2758 | target: FolderDropTarget, |
| 2759 | draftKey: string, |
| 2760 | ) => { |
| 2761 | const bridge = window.desktopBridge; |
| 2762 | for (const folder of folders) { |
| 2763 | const droppedPath = resolveDroppedFolderPath(folder, bridge?.getPathForFile); |
| 2764 | const path = |
| 2765 | droppedPath === null || typeof target === "string" |
| 2766 | ? droppedPath |
| 2767 | : ((await bridge |
| 2768 | ?.toLocalBackendPath(target.wslBackendId, droppedPath) |
| 2769 | .catch(() => null)) ?? null); |
| 2770 | // ChatView is reused across threads, so a slow conversion must not land in the next draft. |
| 2771 | if (!composerMountedRef.current || attachmentTargetKeyRef.current !== draftKey) return; |
| 2772 | if (path === null) { |
| 2773 | toastManager.add({ |
| 2774 | type: "error", |
| 2775 | title: gt('Couldn\'t get the path of "{name}"', { name: folder.name }), |
| 2776 | description: gt("Type the folder path with @ instead."), |
| 2777 | }); |
| 2778 | continue; |
| 2779 | } |
| 2780 | const inserted = insertComposerTextAtEndStable(`${serializeComposerFileLink(path)} `, { |
| 2781 | ensureLeadingBoundary: true, |
| 2782 | }); |
| 2783 | if (!inserted) { |
| 2784 | toastManager.add({ |
| 2785 | type: "error", |
| 2786 | title: gt("Unable to add folder"), |
| 2787 | description: gt("The composer is busy; try again once it is ready."), |
| 2788 | }); |
| 2789 | break; |
| 2790 | } |
| 2791 | } |
| 2792 | focusComposer(); |
| 2793 | }; |
| 2794 | |
| 2795 | const addComposerFolders = (folders: File[]) => { |
| 2796 | const target = folderDropTarget({ |
| 2797 | localEnvironmentDisabled: isLocalEnvironmentDisabled(), |
| 2798 | environmentId, |
| 2799 | primaryEnvironmentId, |
| 2800 | connection: readPreparedConnection(environmentId), |
| 2801 | isDesktopRenderer: window.desktopBridge !== undefined, |
| 2802 | primaryRunsInWsl: |
| 2803 | window.desktopBridge |
| 2804 | ?.getLocalEnvironmentBootstraps() |
| 2805 | .some( |
| 2806 | (bootstrap) => |
| 2807 | bootstrap.id === PRIMARY_LOCAL_ENVIRONMENT_ID && |
| 2808 | typeof bootstrap.runningDistro === "string", |
| 2809 | ) === true, |
| 2810 | }); |
| 2811 | if (target === "remote") { |
| 2812 | toastManager.add({ |
| 2813 | type: "error", |
| 2814 | title: gt("Folders can only be referenced on a server running on this computer"), |
| 2815 | }); |
| 2816 | return; |
| 2817 | } |
| 2818 | const draftKey = attachmentTargetKeyRef.current; |
| 2819 | // Hold send until every conversion lands, or the folder misses the message. |
| 2820 | pendingDraftWork.begin(draftKey); |
| 2821 | void insertComposerFolders(folders, target, draftKey).finally(() => |
| 2822 | pendingDraftWork.end(draftKey), |
| 2823 | ); |
| 2824 | }; |
| 2825 | const addComposerFoldersStable = useStableCallback(addComposerFolders); |
| 2826 | |
| 2827 | const onComposerPaste = (event: React.ClipboardEvent<HTMLElement>) => { |
| 2828 | const { files, folders } = splitTransferredFiles(event.clipboardData); |
| 2829 | const plainText = event.clipboardData.getData("text/plain"); |
| 2830 | const bypassAutoAttachment = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); |
| 2831 | const pastedContext = |
| 2832 | !isLiteralPendingAnswer && |
| 2833 | (readPastedComposerContext(event.clipboardData)?.records.length ?? 0) > 0; |
| 2834 | if ( |
| 2835 | folders.length > 0 || |
| 2836 | (!pastedContext && |
| 2837 | activeThreadId && |
| 2838 | files.length > 0 && |
| 2839 | shouldHandleComposerAttachmentPaste({ files, plainText, bypassAutoAttachment })) |
| 2840 | ) { |
| 2841 | event.preventDefault(); |
| 2842 | event.stopPropagation(); |
| 2843 | if (folders.length > 0) addComposerFoldersStable(folders); |
| 2844 | if (files.length > 0) { |
| 2845 | void addComposerAttachments(files, { skipImageInlineChip: bypassAutoAttachment }); |
| 2846 | } |
| 2847 | return; |
| 2848 | } |
| 2849 | |
| 2850 | if (pastedContext) return; |
| 2851 | if (!foldPastedText(plainText, bypassAutoAttachment)) { |
| 2852 | return; |
| 2853 | } |
| 2854 | |
| 2855 | event.preventDefault(); |
| 2856 | event.stopPropagation(); |
| 2857 | }; |
| 2858 | // The editor is memoized; fresh closures here re-render it on every parent |
| 2859 | // render, which during a stream is every delta. |
| 2860 | const onComposerPasteStable = useStableCallback(onComposerPaste); |
| 2861 | const insertContextReferencesAtCaret = ( |
| 2862 | references: ReadonlyArray<ComposerContextReference>, |
| 2863 | ): boolean => |
| 2864 | insertComposerText(`${references.map(formatInlineContextReference).join(" ")} `, "cursor", { |
| 2865 | ensureLeadingBoundary: true, |
| 2866 | }); |
| 2867 | const insertContextReferencesAtCaretStable = useStableCallback(insertContextReferencesAtCaret); |
| 2868 | const setContextInsertionHandler = useComposerDraftStore( |
| 2869 | (store) => store.setContextInsertionHandler, |
| 2870 | ); |
| 2871 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- registers this composer's context insertion handler in the draft store for the current target |
| 2872 | useEffect(() => { |
| 2873 | return setContextInsertionHandler(composerDraftTarget, insertContextReferencesAtCaretStable); |
| 2874 | }, [composerDraftTarget, insertContextReferencesAtCaretStable, setContextInsertionHandler]); |
| 2875 | |
| 2876 | // Capture drops before the editor; mention handlers own native propagation and moves. |
| 2877 | const composerMentionDragHandlers = makeComposerMentionDragHandlers({ |
| 2878 | insertMentionAtEnd: (text) => |
| 2879 | insertComposerTextAtEndStable(text, { ensureLeadingBoundary: true }), |
| 2880 | insertPullRequestAtEnd: (pullRequest) => { |
| 2881 | const comment = buildPullRequestReferenceContext(pullRequest); |
| 2882 | const inserted = insertComposerTextAtEndStable( |
| 2883 | `${formatInlineContextReference(reviewCommentContextReference(comment))} `, |
| 2884 | { ensureLeadingBoundary: true }, |
| 2885 | ); |
| 2886 | if (inserted) { |
| 2887 | addComposerDraftReviewComment(composerDraftTarget, comment, { appendReference: false }); |
| 2888 | } |
| 2889 | return inserted; |
| 2890 | }, |
| 2891 | setDragActive: setIsDragOverComposer, |
| 2892 | onInsertRejected: () => { |
| 2893 | toastManager.add({ |
| 2894 | type: "error", |
| 2895 | title: gt("Unable to add to chat"), |
| 2896 | description: gt("The composer is busy; try again once it is ready."), |
| 2897 | }); |
| 2898 | }, |
| 2899 | }); |
| 2900 | |
| 2901 | const attachDroppedThreadFile = useEffectEvent((file: File) => addComposerAttachments([file])); |
| 2902 | const importDroppedThread = useEffectEvent( |
| 2903 | async (ref: ScopedThreadRef, isActive: () => boolean) => { |
| 2904 | const targetKey = attachmentTargetKey; |
| 2905 | pendingDraftWork.begin(targetKey); |
| 2906 | const loadingToast = toastManager.add({ |
| 2907 | type: "loading", |
| 2908 | title: gt("Loading thread context…"), |
| 2909 | timeout: 0, |
| 2910 | data: { threadRef: routeThreadRef, hideCopyButton: true }, |
| 2911 | }); |
| 2912 | const importResult = await settlePromise(() => |
| 2913 | importComposerThreadAttachment({ |
| 2914 | targetKey, |
| 2915 | pendingImports: pendingThreadImportsRef.current, |
| 2916 | countReservedAttachments: countReservedAttachmentsStable, |
| 2917 | load: async () => { |
| 2918 | const result = await loadThreadTranscript({ |
| 2919 | environmentId: ref.environmentId, |
| 2920 | input: { threadId: ref.threadId }, |
| 2921 | }); |
| 2922 | if (result._tag !== "Success") { |
| 2923 | throw squashAtomCommandFailure(result); |
| 2924 | } |
| 2925 | return threadContextAttachment(ref.environmentId, result.value); |
| 2926 | }, |
| 2927 | isActive, |
| 2928 | attach: attachDroppedThreadFile, |
| 2929 | onLimitReached: () => { |
| 2930 | if (activeThreadId) { |
| 2931 | setThreadError( |
| 2932 | activeThreadId, |
| 2933 | gt( |
| 2934 | "{count, plural, one {You can attach up to {count} files per message.} other {You can attach up to {count} files per message.}}", |
| 2935 | { |
| 2936 | count: PROVIDER_SEND_TURN_MAX_ATTACHMENTS, |
| 2937 | }, |
| 2938 | ), |
| 2939 | ); |
| 2940 | } |
| 2941 | }, |
| 2942 | }), |
| 2943 | ); |
| 2944 | if (importResult._tag === "Failure" && isActive()) { |
| 2945 | const error = squashAtomCommandFailure(importResult); |
| 2946 | toastManager.add({ |
| 2947 | type: "error", |
| 2948 | title: gt("Unable to read the dropped thread"), |
| 2949 | description: |
| 2950 | isEnvironmentRequestInvalidError(error) && |
| 2951 | error.reason === "thread_transcript_too_large" |
| 2952 | ? gt("This thread exceeds the attachment size limit. Try a shorter thread.") |
| 2953 | : gt("Check that its environment is connected and up to date, then try again."), |
| 2954 | }); |
| 2955 | } |
| 2956 | toastManager.close(loadingToast); |
| 2957 | pendingDraftWork.end(targetKey); |
| 2958 | }, |
| 2959 | ); |
| 2960 | |
| 2961 | useThreadContextDrop(composerFormRef, environmentId, attachmentTargetKey, (refs, isActive) => { |
| 2962 | const records = refs.flatMap((ref) => { |
| 2963 | // The agent reads a linked machine's thread itself, like the `@` picker's; any other |
| 2964 | // machine's comes in as its transcript. |
| 2965 | if (ref.environmentId !== environmentId && !linkedEnvironments.has(ref.environmentId)) { |
| 2966 | void importDroppedThread( |
| 2967 | ref, |
| 2968 | () => isActive() && attachmentTargetKeyRef.current === attachmentTargetKey, |
| 2969 | ); |
| 2970 | return []; |
| 2971 | } |
| 2972 | const record = droppedThreadContextRecord(ref, readThreadShell(ref)); |
| 2973 | return record ? [record] : []; |
| 2974 | }); |
| 2975 | if (records.length === 0) return; |
| 2976 | if (questionAttachmentTarget !== null) { |
| 2977 | const canAnswer = |
| 2978 | canOperateThread && |
| 2979 | !activePendingIsResponding && |
| 2980 | activePendingProgress?.activeQuestion?.allowCustomAnswer !== false; |
| 2981 | const text = `${records |
| 2982 | .map((record) => formatInlineContextReference(threadContextReference(record))) |
| 2983 | .join(" ")} `; |
| 2984 | const snapshot = readComposerSnapshotStable(); |
| 2985 | const cursor = snapshot.expandedCursor; |
| 2986 | const leadingSpace = cursor > 0 && !/\s/.test(snapshot.value[cursor - 1] ?? ""); |
| 2987 | const inserted = |
| 2988 | canAnswer && |
| 2989 | applyPromptReplacementStable( |
| 2990 | cursor, |
| 2991 | extendReplacementRangeForTrailingSpace(snapshot.value, cursor, text), |
| 2992 | leadingSpace ? ` ${text}` : text, |
| 2993 | ); |
| 2994 | if (!inserted) { |
| 2995 | toastManager.add({ |
| 2996 | type: "error", |
| 2997 | title: gt("Unable to add thread"), |
| 2998 | description: gt("The composer is busy; try again once it is ready."), |
| 2999 | }); |
| 3000 | return; |
| 3001 | } |
| 3002 | addComposerDraftThreadContexts(questionAttachmentTarget, records, { |
| 3003 | appendReference: false, |
| 3004 | }); |
| 3005 | if (isComposerCollapsedMobile) expandMobileComposerStable(); |
| 3006 | } else { |
| 3007 | addComposerDraftThreadContexts(composerDraftTarget, records); |
| 3008 | } |
| 3009 | }); |
| 3010 | |
| 3011 | const onComposerMentionDragLeaveCapture = (event: React.DragEvent<HTMLFormElement>) => { |
| 3012 | if (!dataTransferHasComposerMention(event.dataTransfer.types)) return; |
| 3013 | event.stopPropagation(); |
| 3014 | const nextTarget = event.relatedTarget; |
| 3015 | if (nextTarget instanceof Node && event.currentTarget.contains(nextTarget)) return; |
| 3016 | setIsDragOverComposer(false); |
| 3017 | }; |
| 3018 | |
| 3019 | // Escape can cancel without dragleave; clear highlights on bubbling dragend. |
| 3020 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- window dragend listener clears the drop highlight when a drag is cancelled without dragleave |
| 3021 | useEffect(() => { |
| 3022 | if (!isDragOverComposer) return; |
| 3023 | const onWindowDragEnd = () => { |
| 3024 | setIsDragOverComposer(false); |
| 3025 | }; |
| 3026 | window.addEventListener("dragend", onWindowDragEnd); |
| 3027 | return () => window.removeEventListener("dragend", onWindowDragEnd); |
| 3028 | }, [isDragOverComposer]); |
| 3029 | const handleInterruptPrimaryAction = () => { |
| 3030 | void onInterrupt(); |
| 3031 | }; |
| 3032 | const handleInterruptPrimaryActionStable = useStableCallback(handleInterruptPrimaryAction); |
| 3033 | const scheduleComposerCollapseCheck = () => { |
| 3034 | if (!isMobileViewport || mobileComposerExpandInFlightRef.current) { |
| 3035 | return; |
| 3036 | } |
| 3037 | if (composerBlurFrameRef.current !== null) { |
| 3038 | window.cancelAnimationFrame(composerBlurFrameRef.current); |
| 3039 | } |
| 3040 | composerBlurFrameRef.current = window.requestAnimationFrame(() => { |
| 3041 | composerBlurFrameRef.current = null; |
| 3042 | if (mobileComposerExpandInFlightRef.current) { |
| 3043 | return; |
| 3044 | } |
| 3045 | const composerSurface = composerSurfaceRef.current; |
| 3046 | const composerForm = composerFormRef.current; |
| 3047 | const activeElement = document.activeElement; |
| 3048 | if (isInsideRestingComposerControlScope(activeElement)) { |
| 3049 | return; |
| 3050 | } |
| 3051 | if ( |
| 3052 | activeElement instanceof Node && |
| 3053 | ((composerSurface && composerSurface.contains(activeElement)) || |
| 3054 | (composerForm && composerForm.contains(activeElement))) |
| 3055 | ) { |
| 3056 | return; |
| 3057 | } |
| 3058 | setIsComposerFocused(false); |
| 3059 | }); |
| 3060 | }; |
| 3061 | const scheduleComposerCollapseCheckStable = useStableCallback(scheduleComposerCollapseCheck); |
| 3062 | |
| 3063 | // Question dismissal unmounts focused controls without firing blur. |
| 3064 | const activePendingUserInputRequestId = activePendingUserInput?.requestId ?? null; |
| 3065 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- schedules the collapse check after a dismissed question unmounts focused controls without a blur |
| 3066 | useEffect(() => { |
| 3067 | if (activePendingUserInputRequestId !== null) return; |
| 3068 | scheduleComposerCollapseCheckStable(); |
| 3069 | }, [activePendingUserInputRequestId, scheduleComposerCollapseCheckStable]); |
| 3070 | |
| 3071 | // oxlint-disable-next-line t3code/no-unreasoned-state-sync -- cancels pending blur and mobile expand animation frames when the composer unmounts |
| 3072 | useEffect(() => { |
| 3073 | return () => { |
| 3074 | if (composerBlurFrameRef.current !== null) { |
| 3075 | window.cancelAnimationFrame(composerBlurFrameRef.current); |
| 3076 | } |
| 3077 | if (mobileComposerExpandFrameRef.current !== null) { |
| 3078 | window.cancelAnimationFrame(mobileComposerExpandFrameRef.current); |
| 3079 | } |
| 3080 | if (mobileComposerExpandReleaseFrameRef.current !== null) { |
| 3081 | window.cancelAnimationFrame(mobileComposerExpandReleaseFrameRef.current); |
| 3082 | } |
| 3083 | }; |
| 3084 | }, []); |
| 3085 | |
| 3086 | const openModelPicker = () => { |
| 3087 | if (composerControlsHidden) { |
| 3088 | if (composerBlurFrameRef.current !== null) { |
| 3089 | window.cancelAnimationFrame(composerBlurFrameRef.current); |
| 3090 | composerBlurFrameRef.current = null; |
| 3091 | } |
| 3092 | setIsComposerFocused(true); |
| 3093 | } |
| 3094 | setIsComposerModelPickerOpen(true); |
| 3095 | }; |
| 3096 | const openModelPickerStable = useStableCallback(openModelPicker); |
| 3097 | |
| 3098 | useImperativeHandle( |
| 3099 | composerRef, |
| 3100 | () => ({ |
| 3101 | focusAtEnd: () => { |
| 3102 | composerEditorRef.current?.focusAtEnd(); |
| 3103 | }, |
| 3104 | focusAt: (cursor: number) => { |
| 3105 | composerEditorRef.current?.focusAt(cursor); |
| 3106 | }, |
| 3107 | addDroppedFiles: (files: File[]) => { |
| 3108 | void addComposerAttachments(files).then((inserted) => { |
| 3109 | if (!inserted) focusComposer(); |
| 3110 | }); |
| 3111 | }, |
| 3112 | addDroppedFolders: addComposerFoldersStable, |
| 3113 | hasPendingAttachments: () => |
| 3114 | countPreparingComposerImages(attachmentTargetKey) > 0 || |
| 3115 | pendingDraftWork.has(attachmentTargetKey), |
| 3116 | insertTextAtEnd: insertComposerTextAtEndStable, |
| 3117 | pasteTextAtEnd: (text: string, options) => { |
| 3118 | const shortcutArmed = consumePasteAsTextShortcut(pasteAsTextShortcutUntilRef); |
| 3119 | const bypassAutoAttachment = options?.bypassAutoAttachment === true || shortcutArmed; |
| 3120 | const promptLength = promptRef.current.length; |
| 3121 | if ( |
| 3122 | !foldPastedText(text, bypassAutoAttachment, { |
| 3123 | start: promptLength, |
| 3124 | end: promptLength, |
| 3125 | }) |
| 3126 | ) { |
| 3127 | return false; |
| 3128 | } |
| 3129 | focusComposer(); |
| 3130 | return true; |
| 3131 | }, |
| 3132 | citeAssistantText: (citation, sourceAnchor) => |
| 3133 | insertComposerTextStable( |
| 3134 | formatAssistantCitationForComposer(citation, citation.comment), |
| 3135 | "cursor", |
| 3136 | { ensureLeadingBoundary: true, citationCommentAnchor: sourceAnchor }, |
| 3137 | ), |
| 3138 | replyToResponse: (response) => { |
| 3139 | // An open question owns the composer, and its answer would not carry the reply. |
| 3140 | if (pendingUserInputs.length > 0 || projectSelectionRequired) return false; |
| 3141 | setComposerDraftReplyTo(composerDraftTarget, response); |
| 3142 | focusComposer(); |
| 3143 | return true; |
| 3144 | }, |
| 3145 | openModelPicker: openModelPickerStable, |
| 3146 | stepReasoningEffort: (direction) => { |
| 3147 | if (noProviderAvailable || pendingUserInputs.length > 0 || isEditingQueuedMessage) { |
| 3148 | return; |
| 3149 | } |
| 3150 | const change = getComposerReasoningStep({ |
| 3151 | provider: selectedProvider, |
| 3152 | instanceId: selectedInstanceId, |
| 3153 | model: selectedModel, |
| 3154 | models: selectedProviderModels, |
| 3155 | modelOptions: composerModelOptions?.[selectedInstanceId], |
| 3156 | reportedModelSelection, |
| 3157 | prompt: promptRef.current, |
| 3158 | cursor: readComposerSnapshotStable().expandedCursor, |
| 3159 | direction, |
| 3160 | }); |
| 3161 | if (!change) return; |
| 3162 | useComposerDraftStore |
| 3163 | .getState() |
| 3164 | .setProviderModelOptions(composerDraftTarget, selectedProvider, change.modelOptions, { |
| 3165 | instanceId: selectedInstanceId, |
| 3166 | model: selectedModel, |
| 3167 | persistSticky: true, |
| 3168 | }); |
| 3169 | applyThreadModelPick(composerDraftTarget); |
| 3170 | if (change.prompt !== promptRef.current) { |
| 3171 | applyPromptReplacementStable(0, promptRef.current.length, change.prompt, { |
| 3172 | expandedCursorAfterReplace: change.cursor, |
| 3173 | }); |
| 3174 | } |
| 3175 | }, |
| 3176 | toggleModelPicker: () => { |
| 3177 | if (isComposerModelPickerOpen) { |
| 3178 | setIsComposerModelPickerOpen(false); |
| 3179 | } else { |
| 3180 | openModelPickerStable(); |
| 3181 | } |
| 3182 | }, |
| 3183 | openControl: (command) => { |
| 3184 | if (composerBlurFrameRef.current !== null) { |
| 3185 | window.cancelAnimationFrame(composerBlurFrameRef.current); |
| 3186 | composerBlurFrameRef.current = null; |
| 3187 | } |
| 3188 | flushSync(() => setIsComposerFocused(true)); |
| 3189 | const shell = composerFormRef.current?.closest('[data-slot="composer-shell"]'); |
| 3190 | const trigger = Array.from( |
| 3191 | shell?.querySelectorAll<HTMLButtonElement>( |
| 3192 | `button[data-composer-shortcut~="${command}"]:not(:disabled)`, |
| 3193 | ) ?? [], |
| 3194 | ).find( |
| 3195 | (element) => |
| 3196 | !element.closest("[inert]") && element.checkVisibility({ visibilityProperty: true }), |
| 3197 | ); |
| 3198 | if (!trigger) return; |
| 3199 | trigger.focus({ preventScroll: true }); |
| 3200 | if (command === "composer.mode") markOpenToPermissions(trigger); |
| 3201 | if (command === "composer.effort") markOpenToEffort(trigger); |
| 3202 | trigger.click(); |
| 3203 | }, |
| 3204 | compactContext: compactThreadContextStable, |
| 3205 | isModelPickerOpen: () => isComposerModelPickerOpen, |
| 3206 | isCaretAtStart: () => { |
| 3207 | const range = composerEditorRef.current?.readSelectionRange(); |
| 3208 | return range !== undefined && range.start === 0 && range.end === 0; |
| 3209 | }, |
| 3210 | readSnapshot: () => { |
| 3211 | return readComposerSnapshotStable(); |
| 3212 | }, |
| 3213 | resetCursorState: (options?: { |
| 3214 | cursor?: number; |
| 3215 | prompt?: string; |
| 3216 | detectTrigger?: boolean; |
| 3217 | }) => { |
| 3218 | const promptForState = options?.prompt ?? promptRef.current; |
| 3219 | const cursor = clampCollapsedComposerCursor( |
| 3220 | promptForState, |
| 3221 | options?.cursor ?? 0, |
| 3222 | isLiteralPendingAnswer, |
| 3223 | ); |
| 3224 | setComposerHighlightedItemId(null); |
| 3225 | setComposerCursor(cursor); |
| 3226 | resetComposerTrigger( |
| 3227 | options?.detectTrigger && !isLiteralPendingAnswer |
| 3228 | ? detectComposerTrigger( |
| 3229 | promptForState, |
| 3230 | expandCollapsedComposerCursor(promptForState, cursor), |
| 3231 | ) |
| 3232 | : null, |
| 3233 | ); |
| 3234 | }, |
| 3235 | addTerminalContext: (selection: TerminalContextSelection) => { |
| 3236 | if (!activeThread) return; |
| 3237 | // Answers are plain text, so a terminal excerpt cannot ride along with one. Writing it |
| 3238 | // to the thread draft instead would hide it until the question closes. |
| 3239 | if (activePendingProgress) { |
| 3240 | toastManager.add({ |
| 3241 | type: "info", |
| 3242 | title: resolveMessage(msg("Terminal output can't be added to a question answer.")), |
| 3243 | description: resolveMessage( |
| 3244 | msg("Answer or dismiss the question first, then add it to chat."), |
| 3245 | ), |
| 3246 | }); |
| 3247 | return; |
| 3248 | } |
| 3249 | const snapshot = readComposerSnapshotStable(); |
| 3250 | const context = { |
| 3251 | id: randomUUID(), |
| 3252 | threadId: activeThread.id, |
| 3253 | createdAt: new Date().toISOString(), |
| 3254 | ...selection, |
| 3255 | }; |
| 3256 | const insertion = insertInlineContextReference( |
| 3257 | snapshot.value, |
| 3258 | snapshot.expandedCursor, |
| 3259 | terminalContextReference(context), |
| 3260 | ); |
| 3261 | const nextCollapsedCursor = collapseExpandedComposerCursor( |
| 3262 | insertion.prompt, |
| 3263 | insertion.cursor, |
| 3264 | ); |
| 3265 | const inserted = insertComposerDraftTerminalContext( |
| 3266 | composerDraftTarget, |
| 3267 | insertion.prompt, |
| 3268 | context, |
| 3269 | composerTerminalContexts.length, |
| 3270 | ); |
| 3271 | if (!inserted) return; |
| 3272 | promptRef.current = insertion.prompt; |
| 3273 | setComposerCursor(nextCollapsedCursor); |
| 3274 | setComposerTrigger(detectComposerTrigger(insertion.prompt, insertion.cursor)); |
| 3275 | window.requestAnimationFrame(() => { |
| 3276 | composerEditorRef.current?.focusAt(nextCollapsedCursor); |
| 3277 | }); |
| 3278 | }, |
| 3279 | getSendContext: () => ({ |
| 3280 | answeringPendingUserInput: activePendingProgress !== null, |
| 3281 | shownPendingApprovalIds: pendingApprovals |
| 3282 | .map((approval) => approval.requestId) |
| 3283 | .filter((requestId) => !heldRequestIds.has(requestId)), |
| 3284 | prompt: promptRef.current, |
| 3285 | images: composerImagesRef.current, |
| 3286 | files: composerFilesRef.current, |
| 3287 | terminalContexts: composerTerminalContextsRef.current, |
| 3288 | previewAnnotations: composerPreviewAnnotations, |
| 3289 | reviewComments: composerReviewComments, |
| 3290 | threadContexts: composerThreadContexts, |
| 3291 | environmentContexts: composerEnvironmentContexts, |
| 3292 | selectedPromptEffort, |
| 3293 | selectedModelSelection, |
| 3294 | multipleModelSelections: |
| 3295 | routeKind === "draft" && multipleModelSelections !== null |
| 3296 | ? multipleModelSelections.map((selection) => |
| 3297 | selection.instanceId === selectedModelSelection.instanceId && |
| 3298 | selection.model === selectedModelSelection.model |
| 3299 | ? selectedModelSelection |
| 3300 | : selection, |
| 3301 | ) |
| 3302 | : null, |
| 3303 | providerAvailable: |
| 3304 | multipleModelSelections !== null || |
| 3305 | (!noProviderAvailable && providerSendBlockReason === null), |
| 3306 | selectedProvider, |
| 3307 | selectedModel, |
| 3308 | selectedProviderModels, |
| 3309 | }), |
| 3310 | setMultipleModelSelections, |
| 3311 | validateProviderInput: (providerInput: string) => { |
| 3312 | const validationMessage = getComposerSubmissionValidationMessage({ |
| 3313 | prompt: promptRef.current, |
| 3314 | providerInput, |
| 3315 | submissionTarget: "provider-turn", |
| 3316 | }); |
| 3317 | providerInputRejectedRef.current = validationMessage !== null; |
| 3318 | setProviderInputSubmissionError(validationMessage); |
| 3319 | return validationMessage === null; |
| 3320 | }, |
| 3321 | }), |
| 3322 | [ |
| 3323 | activeThread, |
| 3324 | addComposerAttachments, |
| 3325 | addComposerFoldersStable, |
| 3326 | foldPastedText, |
| 3327 | composerDraftTarget, |
| 3328 | composerModelOptions, |
| 3329 | isEditingQueuedMessage, |
| 3330 | composerCursor, |
| 3331 | activePendingProgress, |
| 3332 | pendingApprovals, |
| 3333 | heldRequestIds, |
| 3334 | composerTerminalContexts, |
| 3335 | insertComposerDraftTerminalContext, |
| 3336 | setComposerDraftReplyTo, |
| 3337 | insertComposerTextStable, |
| 3338 | insertComposerTextAtEndStable, |
| 3339 | promptRef, |
| 3340 | composerImagesRef, |
| 3341 | composerFilesRef, |
| 3342 | composerTerminalContextsRef, |
| 3343 | composerPreviewAnnotations, |
| 3344 | composerReviewComments, |
| 3345 | composerThreadContexts, |
| 3346 | composerEnvironmentContexts, |
| 3347 | focusComposer, |
| 3348 | environmentId, |
| 3349 | primaryEnvironmentId, |
| 3350 | isLiteralPendingAnswer, |
| 3351 | pendingUserInputs.length, |
| 3352 | projectSelectionRequired, |
| 3353 | applyPromptReplacementStable, |
| 3354 | isComposerModelPickerOpen, |
| 3355 | openModelPickerStable, |
| 3356 | readComposerSnapshotStable, |
| 3357 | resetComposerTrigger, |
| 3358 | setComposerTrigger, |
| 3359 | selectedModel, |
| 3360 | selectedInstanceId, |
| 3361 | reportedModelSelection, |
| 3362 | selectedModelSelection, |
| 3363 | multipleModelSelections, |
| 3364 | setMultipleModelSelections, |
| 3365 | routeKind, |
| 3366 | noProviderAvailable, |
| 3367 | providerSendBlockReason, |
| 3368 | selectedPromptEffort, |
| 3369 | selectedProvider, |
| 3370 | selectedProviderModels, |
| 3371 | compactThreadContextStable, |
| 3372 | ], |
| 3373 | ); |
| 3374 | |
| 3375 | // Built outside the form's JSX so typing, which rebuilds that JSX, leaves them cached. |
| 3376 | const composerAttachmentMediaRow = |
| 3377 | !isComposerCollapsedMobile && |
| 3378 | (uncommittedSnapShotIds.length > 0 || |
| 3379 | composerVideos.length > 0 || |
| 3380 | standaloneComposerImages.length > 0 || |
| 3381 | preparingComposerImages.length > 0) ? ( |
| 3382 | <ComposerAttachmentMediaRow |
| 3383 | images={composerImages} |
| 3384 | expandedImages={standaloneComposerImages} |
| 3385 | preparingImages={preparingComposerImages} |
| 3386 | videos={composerVideos} |
| 3387 | pendingSnapShotAnimations={pendingSnapShotAnimations} |
| 3388 | pendingSnapShotIds={pendingSnapShotIds} |
| 3389 | uncommittedSnapShotIds={uncommittedSnapShotIds} |
| 3390 | nonPersistedImageIds={nonPersistedComposerImageIds} |
| 3391 | snapShotAnimations={settings.snapShotAnimations} |
| 3392 | supportsAttachmentUploads={supportsAttachmentUploads} |
| 3393 | maxFileAttachmentBytes={maxFileAttachmentBytes} |
| 3394 | environmentId={environmentId} |
| 3395 | attachmentDraftTarget={attachmentDraftTarget} |
| 3396 | canOperateThread={canOperateThread} |
| 3397 | onCopySnapshot={copyComposerSnapshotStable} |
| 3398 | onExpandImage={onExpandImage} |
| 3399 | onFileOpen={onFileOpen} |
| 3400 | onRemoveImage={removeComposerImage} |
| 3401 | onRemoveFile={removeComposerFileFromDraft} |
| 3402 | /> |
| 3403 | ) : null; |
| 3404 | const composerAttachmentFileList = |
| 3405 | !isComposerCollapsedMobile && composerOtherFiles.length > 0 ? ( |
| 3406 | <ComposerAttachmentFileList |
| 3407 | files={composerOtherFiles} |
| 3408 | resolvedTheme={resolvedTheme} |
| 3409 | supportsAttachmentUploads={supportsAttachmentUploads} |
| 3410 | maxFileAttachmentBytes={maxFileAttachmentBytes} |
| 3411 | fileStagingLimit={fileStagingLimit} |
| 3412 | environmentId={environmentId} |
| 3413 | attachmentDraftTarget={attachmentDraftTarget} |
| 3414 | canOperateThread={canOperateThread} |
| 3415 | onPreviewFile={setPreviewFileId} |
| 3416 | onRemoveFile={removeComposerFileFromDraft} |
| 3417 | /> |
| 3418 | ) : null; |
| 3419 | const composerAttachButton = showComposerAttachAction ? ( |
| 3420 | <ComposerAttachButton |
| 3421 | addComposerAttachments={addComposerAttachments} |
| 3422 | focusComposer={focusComposer} |
| 3423 | /> |
| 3424 | ) : null; |
| 3425 | return ( |
| 3426 | <form |
| 3427 | ref={composerFormRef} |
| 3428 | onSubmit={submitComposerStable} |
| 3429 | onFocusCapture={(event) => { |
| 3430 | const activeElement = event.target; |
| 3431 | if ( |
| 3432 | activeElement instanceof Element && |
| 3433 | activeElement.closest('[data-testid="composer-editor"]') |
| 3434 | ) { |
| 3435 | onTypingGuardFocus(); |
| 3436 | } |
| 3437 | if (composerControlsCollapsed && isInsideRestingComposerControlScope(activeElement)) { |
| 3438 | return; |
| 3439 | } |
| 3440 | if (isInsideCollapsedComposerControls(activeElement)) { |
| 3441 | return; |
| 3442 | } |
| 3443 | if (composerBlurFrameRef.current !== null) { |
| 3444 | window.cancelAnimationFrame(composerBlurFrameRef.current); |
| 3445 | composerBlurFrameRef.current = null; |
| 3446 | } |
| 3447 | setIsComposerFocused(true); |
| 3448 | }} |
| 3449 | onBlurCapture={(event) => { |
| 3450 | if ( |
| 3451 | event.target instanceof Element && |
| 3452 | event.target.closest('[data-testid="composer-editor"]') |
| 3453 | ) { |
| 3454 | onTypingGuardBlur(); |
| 3455 | } |
| 3456 | scheduleComposerCollapseCheck(); |
| 3457 | }} |
| 3458 | onDragEnterCapture={(event) => { |
| 3459 | if (isInsideRestingComposerControlScope(event.target)) return; |
| 3460 | composerMentionDragHandlers.onDragEnter(event); |
| 3461 | }} |
| 3462 | onDragOverCapture={(event) => { |
| 3463 | if (isInsideRestingComposerControlScope(event.target)) return; |
| 3464 | composerMentionDragHandlers.onDragOver(event); |
| 3465 | }} |
| 3466 | onDragLeaveCapture={(event) => { |
| 3467 | if (isInsideRestingComposerControlScope(event.target)) return; |
| 3468 | onComposerMentionDragLeaveCapture(event); |
| 3469 | }} |
| 3470 | onDropCapture={(event) => { |
| 3471 | if (isInsideRestingComposerControlScope(event.target)) return; |
| 3472 | composerMentionDragHandlers.onDrop(event); |
| 3473 | }} |
| 3474 | className="mx-auto w-full min-w-0 max-w-(--chat-content-max-width)" |
| 3475 | data-chat-composer-form="true" |
| 3476 | {...threadContextDropTargetProps()} |
| 3477 | > |
| 3478 | <ComposerBanner.Dock> |
| 3479 | <ComposerBanner.Column> |
| 3480 | <ComposerBannerStack items={shelfItems} /> |
| 3481 | {showComposerTopDrawer ? ( |
| 3482 | <ComposerBanner.Attachment> |
| 3483 | <ComposerBanner.Root data-chat-composer-top-drawer="true" variant="info"> |
| 3484 | {pendingUserInputs.length > 0 ? ( |
| 3485 | <ComposerPendingUserInputPanel |
| 3486 | pendingUserInputs={pendingUserInputs} |
| 3487 | cwd={gitCwd ?? undefined} |
| 3488 | threadRef={routeThreadRef} |
| 3489 | disabled={!canOperateThread} |
| 3490 | respondingRequestIds={ |
| 3491 | activePendingIsResponding && activePendingUserInput |
| 3492 | ? [...respondingRequestIds, activePendingUserInput.requestId] |
| 3493 | : respondingRequestIds |
| 3494 | } |
| 3495 | answers={activePendingDraftAnswers} |
| 3496 | questionIndex={activePendingQuestionIndex} |
| 3497 | onToggleOption={onSelectActivePendingUserInputOption} |
| 3498 | onAdvance={onAdvanceActivePendingUserInput} |
| 3499 | onDismiss={onDismissActivePendingUserInput} |
| 3500 | /> |
| 3501 | ) : null} |
| 3502 | </ComposerBanner.Root> |
| 3503 | </ComposerBanner.Attachment> |
| 3504 | ) : null} |
| 3505 | </ComposerBanner.Column> |
| 3506 | <ComposerStashBadge |
| 3507 | count={stashQueue.length} |
| 3508 | menuOpen={isStashMenuOpen} |
| 3509 | pulseKey={stashPulseKey} |
| 3510 | onToggleMenu={toggleStashMenuStable} |
| 3511 | /> |
| 3512 | </ComposerBanner.Dock> |
| 3513 | <div className="relative"> |
| 3514 | <ComposerSurface.Main |
| 3515 | ref={composerMainSurfaceRef} |
| 3516 | data-inline-resting-controls="true" |
| 3517 | className={composerProviderState.composerFrameClassName} |
| 3518 | > |
| 3519 | <div |
| 3520 | ref={composerSurfaceRef} |
| 3521 | data-chat-composer-surface="true" |
| 3522 | data-chat-composer-mobile-collapsed={isComposerCollapsedMobile ? "true" : "false"} |
| 3523 | className={cn( |
| 3524 | "rounded-2xl transition-[background-color] duration-200", |
| 3525 | "in-data-[thread-context-over]:bg-accent/45 in-data-[thread-context-over]:ring-1 in-data-[thread-context-over]:ring-inset in-data-[thread-context-over]:ring-primary/70", |
| 3526 | isDragOverComposer ? "bg-accent/45 ring-1 ring-inset ring-primary/70" : null, |
| 3527 | projectSelectionRequired ? "opacity-75" : null, |
| 3528 | composerProviderState.composerSurfaceClassName, |
| 3529 | )} |
| 3530 | > |
| 3531 | {showCollapsedMobilePromptRow ? ( |
| 3532 | <div className="flex items-center justify-between gap-2 px-3 py-2"> |
| 3533 | <button |
| 3534 | type="button" |
| 3535 | data-chat-composer-transition-prompt="true" |
| 3536 | className={cn( |
| 3537 | "min-w-0 flex-1 truncate bg-transparent p-0 text-left text-sm focus:outline-none", |
| 3538 | prompt.trim() ? "text-foreground" : "text-placeholder", |
| 3539 | )} |
| 3540 | onPointerDown={(event) => event.preventDefault()} |
| 3541 | onClick={expandMobileComposerStable} |
| 3542 | aria-label={gt("Expand composer")} |
| 3543 | > |
| 3544 | {prompt.trim() ? ( |
| 3545 | <CollapsedComposerPromptPreview |
| 3546 | prompt={prompt} |
| 3547 | skills={selectedProviderSkills} |
| 3548 | contextRecords={composerContextRecords} |
| 3549 | theme={resolvedTheme} |
| 3550 | /> |
| 3551 | ) : showProviderUnavailable ? ( |
| 3552 | gt("Enable a provider in Settings") |
| 3553 | ) : ( |
| 3554 | gt("Ask anything...") |
| 3555 | )} |
| 3556 | </button> |
| 3557 | {collapsedComposerImagePreviews} |
| 3558 | <CollapsedComposerStopAction |
| 3559 | key={`${environmentId}:${activeThreadId ?? "new"}`} |
| 3560 | canOperateThread={canOperateThread} |
| 3561 | canInterrupt={canInterrupt} |
| 3562 | runId={activeThread?.runtime?.activeRunId ?? null} |
| 3563 | hasSendableContent={composerSendState.hasSendableContent} |
| 3564 | isEditingQueuedMessage={isEditingQueuedMessage} |
| 3565 | onInterrupt={handleInterruptPrimaryActionStable} |
| 3566 | > |
| 3567 | <button |
| 3568 | type="button" |
| 3569 | data-chat-composer-transition-actions="true" |
| 3570 | className="flex size-8 shrink-0 items-center justify-center rounded-full bg-message-action text-message-action-foreground hover:bg-message-action-hover disabled:opacity-64" |
| 3571 | disabled={collapsedComposerPrimaryActionDisabled} |
| 3572 | aria-label={collapsedComposerPrimaryActionLabel} |
| 3573 | onPointerDown={(event) => event.preventDefault()} |
| 3574 | onClick={(event) => { |
| 3575 | event.stopPropagation(); |
| 3576 | if (showResumeAction) onResume(); |
| 3577 | else if (props.resumeCompactionTokens !== null && !props.keepFullHistory) |
| 3578 | expandMobileComposer(); |
| 3579 | else submitComposer(); |
| 3580 | }} |
| 3581 | > |
| 3582 | {showResumeAction ? ( |
| 3583 | <PlayIcon className="size-4 fill-current" aria-hidden="true" /> |
| 3584 | ) : ( |
| 3585 | <svg |
| 3586 | width="16" |
| 3587 | height="16" |
| 3588 | viewBox="0 0 16 16" |
| 3589 | fill="none" |
| 3590 | aria-hidden="true" |
| 3591 | > |
| 3592 | <path |
| 3593 | d="M8 3L8 13M8 3L4 7M8 3L12 7" |
| 3594 | stroke="currentColor" |
| 3595 | strokeWidth="2" |
| 3596 | strokeLinecap="round" |
| 3597 | strokeLinejoin="round" |
| 3598 | /> |
| 3599 | </svg> |
| 3600 | )} |
| 3601 | </button> |
| 3602 | </CollapsedComposerStopAction> |
| 3603 | </div> |
| 3604 | ) : null} |
| 3605 | |
| 3606 | <div |
| 3607 | ref={(node) => { |
| 3608 | setComposerMenuAnchor(node); |
| 3609 | const stopObserving = observeWrappedPrompt(node); |
| 3610 | return () => { |
| 3611 | setComposerMenuAnchor(null); |
| 3612 | stopObserving?.(); |
| 3613 | }; |
| 3614 | }} |
| 3615 | data-chat-composer-body="true" |
| 3616 | className={cn( |
| 3617 | "relative px-4 pb-2", |
| 3618 | "pt-3.5 sm:pt-4", |
| 3619 | isComposerCollapsedMobile && "hidden", |
| 3620 | )} |
| 3621 | > |
| 3622 | {isStashMenuOpen && !composerMenuOpen && ( |
| 3623 | <ComposerCommandMenuLayer anchor={composerMenuAnchor} canOverflowTop> |
| 3624 | <ComposerStashMenu |
| 3625 | composerFormRef={composerFormRef} |
| 3626 | entries={stashQueue} |
| 3627 | stashShortcutLabel={shortcutLabelForCommand(keybindings, "composer.stash", { |
| 3628 | context: { |
| 3629 | terminalFocus: false, |
| 3630 | terminalOpen, |
| 3631 | modelPickerOpen: false, |
| 3632 | }, |
| 3633 | })} |
| 3634 | onRestore={restoreStashEntryStable} |
| 3635 | onDelete={deleteStashEntryStable} |
| 3636 | onClose={() => setIsStashMenuOpen(false)} |
| 3637 | /> |
| 3638 | </ComposerCommandMenuLayer> |
| 3639 | )} |
| 3640 | |
| 3641 | <div role="status" aria-atomic="true" className="sr-only"> |
| 3642 | {composerSuggestionsVisible && composerMenuItems.length === 0 |
| 3643 | ? isComposerMenuLoading |
| 3644 | ? composerTriggerKind === "pull-request" |
| 3645 | ? gt("Finding pull request...") |
| 3646 | : composerTriggerKind === "skill" || composerTriggerKind === "slash-command" |
| 3647 | ? gt("Searching workspace skills...") |
| 3648 | : gt("Searching workspace files...") |
| 3649 | : composerMenuEmptyState |
| 3650 | : ""} |
| 3651 | </div> |
| 3652 | {composerSuggestionsVisible && ( |
| 3653 | <ComposerCommandMenuLayer anchor={composerMenuAnchor}> |
| 3654 | <ComposerCommandMenu |
| 3655 | listId={composerSuggestionListId} |
| 3656 | items={composerMenuItems} |
| 3657 | resolvedTheme={resolvedTheme} |
| 3658 | isLoading={isComposerMenuLoading} |
| 3659 | triggerKind={composerTriggerKind} |
| 3660 | emptyStateText={composerMenuEmptyState} |
| 3661 | activeItemId={activeComposerMenuItem?.id ?? null} |
| 3662 | onHighlightedItemChange={onComposerMenuItemHighlightedStable} |
| 3663 | onSelect={onSelectComposerItemStable} |
| 3664 | /> |
| 3665 | </ComposerCommandMenuLayer> |
| 3666 | )} |
| 3667 | |
| 3668 | {!isComposerCollapsedMobile && |
| 3669 | pendingUserInputs.length === 0 && |
| 3670 | editingQueuedAttachments !== null && |
| 3671 | editingQueuedAttachments.length > 0 && ( |
| 3672 | <ComposerQueuedAttachmentRow |
| 3673 | attachments={editingQueuedAttachments} |
| 3674 | onRemove={onRemoveEditingQueuedAttachment} |
| 3675 | /> |
| 3676 | )} |
| 3677 | |
| 3678 | {composerAttachmentMediaRow} |
| 3679 | |
| 3680 | {composerAttachmentFileList} |
| 3681 | |
| 3682 | <div className="relative"> |
| 3683 | {previewFile ? ( |
| 3684 | <ComposerFilePreviewDialog |
| 3685 | file={previewFile} |
| 3686 | onRemove={removeComposerFileFromDraft} |
| 3687 | onPreviewFileIdChange={setPreviewFileId} |
| 3688 | /> |
| 3689 | ) : null} |
| 3690 | <ComposerContextActionsContext value={composerContextActions}> |
| 3691 | <ComposerPromptEditor |
| 3692 | draftKey={composerDraftTargetKey} |
| 3693 | // Switching threads lands focus here, so the label names the thread. |
| 3694 | ariaLabel={ |
| 3695 | activeThread |
| 3696 | ? gt("Message {title}", { title: activeThread.title }) |
| 3697 | : gt("Message", { $context: "noun, label of the message input" }) |
| 3698 | } |
| 3699 | suggestionListId={composerSuggestionListId} |
| 3700 | activeSuggestionId={ |
| 3701 | composerSuggestionListVisible && activeComposerMenuItem |
| 3702 | ? composerSuggestionOptionId( |
| 3703 | composerSuggestionListId, |
| 3704 | activeComposerMenuItem.id, |
| 3705 | ) |
| 3706 | : undefined |
| 3707 | } |
| 3708 | editorRef={composerEditorRef} |
| 3709 | richTextEnabled={settings.composerRichTextEnabled} |
| 3710 | literalText={isLiteralPendingAnswer} |
| 3711 | isPathQueryActive={isPathQueryActiveStable} |
| 3712 | value={activePendingProgress ? activePendingProgress.customAnswer : prompt} |
| 3713 | cursor={composerCursor} |
| 3714 | contextRecords={composerContextRecords} |
| 3715 | buildContextClipboardFragment={buildContextClipboardFragmentStable} |
| 3716 | importContextFragment={importContextFragmentStable} |
| 3717 | skills={selectedProviderSkills} |
| 3718 | className={cn(showMobilePendingAnswerActions && "max-sm:pb-12")} |
| 3719 | onChange={onPromptChangeStable} |
| 3720 | onCommandKeyDown={onComposerCommandKeyStable} |
| 3721 | onPageScrollKeyDown={onPageScrollKeyDown} |
| 3722 | onPageScrollKeyUp={onPageScrollKeyUp} |
| 3723 | onPageScrollRelease={onPageScrollRelease} |
| 3724 | onCitationSubmitAndSend={submitCitationAndSendStable} |
| 3725 | onCitationDraftSave={saveCitationDraftToPromptStable} |
| 3726 | onPaste={onComposerPasteStable} |
| 3727 | placeholder={ |
| 3728 | isComposerApprovalState |
| 3729 | ? activePendingApproval?.supportsFeedback |
| 3730 | ? gt("Send feedback to decline this request") |
| 3731 | : gt("Send a message to decline and redirect the agent") |
| 3732 | : activePendingProgress |
| 3733 | ? isChoiceOnlyPendingQuestion |
| 3734 | ? gt("Choose an option above") |
| 3735 | : activePendingProgress.activeQuestion?.options.length === 0 |
| 3736 | ? gt("Type your answer") |
| 3737 | : gt( |
| 3738 | "Type your own answer, or leave this blank to use the selected option", |
| 3739 | ) |
| 3740 | : projectSelectionRequired |
| 3741 | ? gt("Choose a project above to start a thread") |
| 3742 | : showProviderUnavailable |
| 3743 | ? gt("Enable a provider in Settings to send a message") |
| 3744 | : (offeredPromptSuggestion ?? m(DEFAULT_COMPOSER_PLACEHOLDER)) |
| 3745 | } |
| 3746 | placeholderSuffix={ |
| 3747 | offeredPromptSuggestion !== null ? ( |
| 3748 | <span className="ml-2 inline-flex align-[1px]"> |
| 3749 | <Kbd variant="outline">⇥ Tab</Kbd> |
| 3750 | </span> |
| 3751 | ) : undefined |
| 3752 | } |
| 3753 | disabled={ |
| 3754 | projectSelectionRequired || |
| 3755 | isChoiceOnlyPendingQuestion || |
| 3756 | activePendingIsResponding || |
| 3757 | speechInput.freezesEditor |
| 3758 | } |
| 3759 | /> |
| 3760 | </ComposerContextActionsContext> |
| 3761 | {showMobilePendingAnswerActions ? ( |
| 3762 | <div |
| 3763 | data-chat-composer-mobile-pending-actions="true" |
| 3764 | className="absolute bottom-0 right-0 flex items-center justify-end gap-1" |
| 3765 | > |
| 3766 | <ComposerPrimaryActions |
| 3767 | compact |
| 3768 | canOperateThread={canOperateThread} |
| 3769 | pendingAction={pendingPrimaryAction} |
| 3770 | isRunning={false} |
| 3771 | canInterrupt={false} |
| 3772 | isSendBusy={isSendBusy} |
| 3773 | sendDisabledReason={primaryActionSendDisabledReason} |
| 3774 | isEnvironmentUnavailable={primaryActionEnvironmentUnavailable} |
| 3775 | isPreparingWorktree={false} |
| 3776 | hasSendableContent={false} |
| 3777 | preserveComposerFocusOnPointerDown |
| 3778 | onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} |
| 3779 | onInterrupt={handleInterruptPrimaryActionStable} |
| 3780 | /> |
| 3781 | </div> |
| 3782 | ) : null} |
| 3783 | </div> |
| 3784 | </div> |
| 3785 | |
| 3786 | <ComposerPromptLengthValidation |
| 3787 | message={providerInputSubmissionError ?? composerSubmissionError} |
| 3788 | /> |
| 3789 | |
| 3790 | {speechInput.preview ? ( |
| 3791 | // column-reverse pins the scroll to the bottom; the single inner div keeps the text in normal order. |
| 3792 | <div |
| 3793 | aria-label={gt("Live transcription")} |
| 3794 | className="mx-3 mb-3 flex max-h-32 flex-col-reverse overflow-y-auto rounded-lg border border-border/60 bg-muted/30 px-3 py-2 text-sm leading-relaxed break-words whitespace-pre-wrap sm:mx-4" |
| 3795 | > |
| 3796 | <div> |
| 3797 | <span>{speechInput.preview.committed}</span> |
| 3798 | <span className="text-muted-foreground">{speechInput.preview.tentative}</span> |
| 3799 | </div> |
| 3800 | </div> |
| 3801 | ) : null} |
| 3802 | |
| 3803 | {isComposerCollapsedMobile && speechInput.state.phase === "idle" ? null : ( |
| 3804 | <div |
| 3805 | data-chat-composer-footer="true" |
| 3806 | className={cn( |
| 3807 | "flex min-w-0 flex-nowrap items-center overflow-visible px-2 pb-2", |
| 3808 | pendingUserInputs.length > 0 && "pt-2", |
| 3809 | showMobilePendingAnswerActions && |
| 3810 | speechInput.state.phase === "idle" && |
| 3811 | "hidden sm:flex", |
| 3812 | )} |
| 3813 | > |
| 3814 | {composerAttachButton && !dictationTakesFooter ? ( |
| 3815 | <div className="me-2">{composerAttachButton}</div> |
| 3816 | ) : null} |
| 3817 | <div |
| 3818 | data-chat-composer-actions="right" |
| 3819 | data-chat-composer-transition-actions="true" |
| 3820 | data-chat-composer-primary-actions-compact={ |
| 3821 | isComposerPrimaryActionsCompact ? "true" : "false" |
| 3822 | } |
| 3823 | className="flex min-w-0 flex-1 flex-nowrap items-center justify-end gap-2" |
| 3824 | > |
| 3825 | <div |
| 3826 | ref={attachExpandedComposerControls} |
| 3827 | data-chat-composer-controls="footer" |
| 3828 | data-chat-composer-footer-controls="true" |
| 3829 | className={cn( |
| 3830 | "relative flex min-w-0 flex-1 items-center justify-end gap-0.5", |
| 3831 | dictationTakesFooter && "hidden", |
| 3832 | )} |
| 3833 | > |
| 3834 | {composerControls} |
| 3835 | </div> |
| 3836 | <ComposerFooterPrimaryActions |
| 3837 | // Stop state belongs to one thread; the composer stays mounted across threads. |
| 3838 | key={`${environmentId}:${activeThreadId ?? "new"}`} |
| 3839 | compact={isComposerPrimaryActionsCompact} |
| 3840 | canOperateThread={canOperateThread} |
| 3841 | pendingAction={pendingPrimaryAction} |
| 3842 | isRunning={(phase === "running" || phase === "connecting") && !draftRunsLocally} |
| 3843 | canInterrupt={canInterrupt} |
| 3844 | runId={activeThread?.runtime?.activeRunId ?? null} |
| 3845 | followUpBehavior={followUpBehavior} |
| 3846 | canSteer={canSteer} |
| 3847 | alternateShortcutLabel={shortcutLabelForCommand( |
| 3848 | keybindings, |
| 3849 | "composer.sendAlternate", |
| 3850 | { |
| 3851 | context: { |
| 3852 | composerFocus: true, |
| 3853 | draftThreadRoute: routeKind === "draft", |
| 3854 | turnRunning: true, |
| 3855 | composerRequiresModifier: composerRequiresModifier( |
| 3856 | settings.sendShortcut, |
| 3857 | prompt, |
| 3858 | ), |
| 3859 | }, |
| 3860 | }, |
| 3861 | )} |
| 3862 | voiceInputActive={voiceInputActive} |
| 3863 | isSendBusy={isSendBusy} |
| 3864 | sendDisabledReason={primaryActionSendDisabledReason} |
| 3865 | isEnvironmentUnavailable={primaryActionEnvironmentUnavailable} |
| 3866 | isPreparingWorktree={isPreparingWorktree} |
| 3867 | hasSendableContent={composerSendState.hasSendableContent || voiceInputActive} |
| 3868 | canResume={showResumeAction} |
| 3869 | preserveComposerFocusOnPointerDown={isMobileViewport} |
| 3870 | isEditingQueuedMessage={isEditingQueuedMessage} |
| 3871 | onSubmitMessage={handleSubmitMessageStable} |
| 3872 | onResume={onResume} |
| 3873 | onPreviousPendingQuestion={onPreviousActivePendingUserInputQuestion} |
| 3874 | onInterrupt={handleInterruptPrimaryActionStable} |
| 3875 | compactBeforeSendTokens={props.resumeCompactionTokens} |
| 3876 | hideCompactToggle={dictationTakesFooter} |
| 3877 | keepFullHistory={props.keepFullHistory} |
| 3878 | onToggleKeepFullHistory={props.onToggleKeepFullHistory} |
| 3879 | > |
| 3880 | {speechInput.available ? ( |
| 3881 | <> |
| 3882 | <ComposerSpeechRecordingPill |
| 3883 | state={speechInput.state} |
| 3884 | progress={null} |
| 3885 | finishShortcutLabel={dictationShortcutLabel} |
| 3886 | cancelShortcutLabel="Esc" |
| 3887 | level={speechInput.level} |
| 3888 | recordingStartedAt={speechInput.recordingStartedAt} |
| 3889 | disabled={dictationDisabled} |
| 3890 | onStart={() => void speechInput.start()} |
| 3891 | onStop={() => void speechInput.stop()} |
| 3892 | onCancel={() => speechInput.cancel()} |
| 3893 | onSkipPostProcessing={() => speechInput.skipPostProcessing()} |
| 3894 | /> |
| 3895 | <ComposerSpeechButton |
| 3896 | state={speechInput.state} |
| 3897 | shortcutLabel={dictationShortcutLabel} |
| 3898 | disabled={dictationDisabled} |
| 3899 | onStart={() => void speechInput.start()} |
| 3900 | /> |
| 3901 | </> |
| 3902 | ) : null} |
| 3903 | <VoiceInputSetup |
| 3904 | environmentId={speechInput.transcriptionEnvironmentId} |
| 3905 | open={speechInput.setup.open} |
| 3906 | step={speechInput.setup.step} |
| 3907 | status={speechInput.status} |
| 3908 | model={speechInput.setup.model} |
| 3909 | language={speechInput.setup.language} |
| 3910 | downloading={speechInput.setup.downloading} |
| 3911 | error={speechInput.setup.error} |
| 3912 | onOpenChange={speechInput.setup.setOpen} |
| 3913 | onRetryCatalog={speechInput.setup.retryCatalog} |
| 3914 | onDownload={() => void speechInput.setup.download()} |
| 3915 | onCancelDownload={() => void speechInput.setup.cancelDownload()} |
| 3916 | onStartRecording={() => void speechInput.setup.startRecording()} |
| 3917 | /> |
| 3918 | </ComposerFooterPrimaryActions> |
| 3919 | </div> |
| 3920 | </div> |
| 3921 | )} |
| 3922 | {showInlineRestingControls ? ( |
| 3923 | <div className="h-8"> |
| 3924 | <div |
| 3925 | ref={setInlineRestingControlsHost} |
| 3926 | className="absolute bottom-2 inset-x-4 min-w-0" |
| 3927 | > |
| 3928 | <div |
| 3929 | ref={attachRestingComposerControls} |
| 3930 | data-chat-composer-resting-controls="true" |
| 3931 | aria-hidden={restingControlsVisible ? undefined : true} |
| 3932 | inert={restingControlsVisible ? undefined : true} |
| 3933 | className={cn( |
| 3934 | "relative flex w-max min-w-0 max-w-full items-center gap-1 text-muted-foreground/70 [&_button]:text-xs!", |
| 3935 | !restingControlsVisible && "invisible", |
| 3936 | )} |
| 3937 | > |
| 3938 | {composerControls} |
| 3939 | </div> |
| 3940 | </div> |
| 3941 | </div> |
| 3942 | ) : null} |
| 3943 | </div> |
| 3944 | </ComposerSurface.Main> |
| 3945 | </div> |
| 3946 | </form> |
| 3947 | ); |
| 3948 | }); |