"use client"; import type { Message } from "@langchain/langgraph-sdk"; import { useQueryClient } from "@tanstack/react-query"; import type { ChatStatus } from "ai"; import { CheckIcon, GraduationCapIcon, LightbulbIcon, Loader2Icon, MicIcon, PaperclipIcon, PlusIcon, RocketIcon, SparklesIcon, SquareIcon, TargetIcon, Undo2Icon, XIcon, ZapIcon, } from "lucide-react"; import { useSearchParams } from "next/navigation"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type ChangeEvent, type ComponentProps, type ClipboardEvent, type FormEvent, type KeyboardEvent, } from "react"; import { toast } from "sonner"; import { PromptInput, PromptInputActionMenu, PromptInputActionMenuContent, PromptInputActionMenuItem, PromptInputActionMenuTrigger, PromptInputAttachment, PromptInputAttachments, PromptInputButton, PromptInputFooter, PromptInputHeader, PromptInputSubmit, PromptInputTextarea, PromptInputTools, usePromptInputAttachments, usePromptInputController, type PromptInputMessage, } from "@/components/ai-elements/prompt-input"; import { Button } from "@/components/ui/button"; import { ConfettiButton } from "@/components/ui/confetti-button"; import { Dialog, DialogContent, DialogDescription, DialogFooter, DialogHeader, DialogTitle, } from "@/components/ui/dialog"; import { DropdownMenuGroup, DropdownMenuLabel, DropdownMenuSeparator, } from "@/components/ui/dropdown-menu"; import { fetch } from "@/core/api/fetcher"; import { useAuth } from "@/core/auth/AuthProvider"; import { getBackendBaseURL } from "@/core/config"; import { useI18n } from "@/core/i18n/hooks"; import { polishInputDraft } from "@/core/input-polish/api"; import { isHiddenFromUIMessage } from "@/core/messages/utils"; import { useModels } from "@/core/models/hooks"; import { buildReferenceMessageMetadata, type SidecarContext, } from "@/core/sidecar"; import { useSkills } from "@/core/skills/hooks"; import { DEFAULT_MAX_SUGGESTIONS } from "@/core/suggestions/api"; import { useSuggestionsConfig } from "@/core/suggestions/hooks"; import type { AgentThreadContext, GoalState } from "@/core/threads"; import { compactThreadContext } from "@/core/threads/api"; import { buildComposerDraftKey, clearComposerDraft, getSessionComposerDraftStorage, readComposerDraft, resolveComposerDraft, type ComposerDraft, writeComposerDraft, } from "@/core/threads/composer-draft"; import { threadTokenUsageQueryKey } from "@/core/threads/token-usage"; import { textOfMessage } from "@/core/threads/utils"; import { formatUploadSize, splitUnsupportedUploadFiles, useUploadLimits, validateUploadLimits, type UploadLimits, type UploadLimitViolation, } from "@/core/uploads"; import { appendSpeechTranscript, getSpeechRecognitionConstructor, getSpeechRecognitionLanguage, mapSpeechRecognitionError, readSpeechRecognitionTranscript, shouldRestartSpeechRecognition, type BrowserSpeechRecognition, type SpeechRecognitionErrorKind, } from "@/core/voice-input/speech-recognition"; import { isIMEComposing } from "@/lib/ime"; import { cn } from "@/lib/utils"; import { ModelSelector, ModelSelectorContent, ModelSelectorInput, ModelSelectorItem, ModelSelectorList, ModelSelectorName, ModelSelectorTrigger, } from "../ai-elements/model-selector"; import { Suggestion, Suggestions } from "../ai-elements/suggestion"; import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger, } from "../ui/dropdown-menu"; import { abortGoalRequest, beginGoalRequest, canPolishInput, createGoalRequestState, findSuggestionTemplatePlaceholder, finishGoalRequest, getGoalObjectiveCounter, getInputSubmitAction, getLeadingSlashSkillQuery, getMatchingSkillSuggestions, type GoalCommand, isAbortError, isCurrentGoalRequest, isGoalObjectiveTooLong, MAX_GOAL_OBJECTIVE_CHARS, readGoalResponseError, type SlashSuggestion, } from "./input-box-helpers"; import { useThread } from "./messages/context"; import { ModeHoverGuide } from "./mode-hover-guide"; import { ReferenceAttachmentSummary, useMaybeSidecar } from "./sidecar"; import { SlashSkillChip } from "./slash-skill-chip"; import { Tooltip } from "./tooltip"; type InputMode = "flash" | "thinking" | "pro" | "ultra"; const COMPOSER_DRAFT_SAVE_DELAY_MS = 300; function focusContentEditableEnd(element: HTMLElement | null) { if (!element) { return; } element.focus(); const selection = window.getSelection(); if (!selection) { return; } const range = document.createRange(); range.selectNodeContents(element); range.collapse(false); selection.removeAllRanges(); selection.addRange(range); } function insertPlainTextAtSelection(container: HTMLElement, text: string) { const selection = window.getSelection(); if (!selection || selection.rangeCount === 0) { return false; } const range = selection.getRangeAt(0); const ancestor = range.commonAncestorContainer; if (ancestor !== container && !container.contains(ancestor)) { return false; } range.deleteContents(); const node = document.createTextNode(text); range.insertNode(node); range.setStartAfter(node); range.setEndAfter(node); selection.removeAllRanges(); selection.addRange(range); return true; } function getResolvedMode( mode: InputMode | undefined, supportsThinking: boolean, ): InputMode { if (!supportsThinking && mode !== "flash") { return "flash"; } if (mode) { return mode; } return supportsThinking ? "pro" : "flash"; } function escapeXmlAttribute(value: string) { return value .replace(/&/g, "&") .replace(/"/g, """) .replace(//g, ">"); } export type InputBoxSubmitOptions = { additionalKwargs?: Record; additionalInputMessages?: Message[]; onSent?: () => void; }; type VoiceRecognitionStartOptions = { focusAfterStart?: boolean; }; function buildHiddenConversationQuoteMessage({ contexts, }: { contexts: SidecarContext[]; }): Message { return { type: "human", content: [ { type: "text", text: [ contexts.length === 1 ? "The user added the following quoted context to this conversation." : `The user added the following ${contexts.length} quoted contexts to this conversation.`, "Use the referenced_message blocks as reference material for the user's next message.", "", ...contexts.flatMap((context, index) => [ ``, `Role: ${context.role === "user" ? "User" : "Assistant"}`, context.messageId ? `Message ID: ${context.messageId}` : null, "", context.content, "", "", ].filter((line): line is string => line !== null), ), ] .filter((line): line is string => line !== null) .join("\n"), }, ], additional_kwargs: { hide_from_ui: true, conversation_quote_context: true, // Keep ids/roles/count 1:1 parallel with `contexts` so consumers can zip // them safely; do not dedupe ids here. referenced_message_ids: contexts.map( (context) => context.messageId ?? "", ), referenced_message_roles: contexts.map((context) => context.role), quote_context_count: contexts.length, }, } as Message; } export function InputBox({ className, disabled, autoFocus, status = "ready", context, extraHeader, isWelcomeMode, threadId, draftThreadId = threadId, draftAgentName, defaultModelName, initialValue, onContextChange, onFollowupsVisibilityChange, onGoalChange, onSubmit, onStop, ...props }: Omit, "onSubmit"> & { assistantId?: string | null; status?: ChatStatus; disabled?: boolean; context: Omit< AgentThreadContext, "thread_id" | "is_plan_mode" | "thinking_enabled" | "subagent_enabled" > & { mode: "flash" | "thinking" | "pro" | "ultra" | undefined; reasoning_effort?: "minimal" | "low" | "medium" | "high"; }; extraHeader?: React.ReactNode; /** * Whether to render the input in welcome layout (vertically centered, * with hero + quick action suggestions). This is purely a visual flag, * decoupled from "the backend has created the thread" — see issue #2746. */ isWelcomeMode?: boolean; threadId: string; draftThreadId?: string; draftAgentName?: string | null; /** * The active custom agent's configured default model, if any. Used as the * auto-selection fallback so an agent chat honors the agent's own default * model instead of silently snapping to the first configured model * (issue #4336). ``null`` / undefined = no agent default → use models[0]. */ defaultModelName?: string | null; initialValue?: string; onContextChange?: ( context: Omit< AgentThreadContext, "thread_id" | "is_plan_mode" | "thinking_enabled" | "subagent_enabled" > & { mode: "flash" | "thinking" | "pro" | "ultra" | undefined; reasoning_effort?: "minimal" | "low" | "medium" | "high"; }, ) => void; onFollowupsVisibilityChange?: (visible: boolean) => void; onGoalChange?: (goal: GoalState | null) => void; onSubmit?: ( message: PromptInputMessage, options?: InputBoxSubmitOptions, ) => void | Promise; onStop?: () => void; }) { const { locale, t } = useI18n(); const queryClient = useQueryClient(); const searchParams = useSearchParams(); const [modelDialogOpen, setModelDialogOpen] = useState(false); const { models } = useModels(); const { user } = useAuth(); const { thread, isMock } = useThread(); const { attachments, textInput } = usePromptInputController(); const setTextInput = textInput.setInput; const sidecar = useMaybeSidecar(); const attachmentParts = attachments.files; const removeAttachment = attachments.remove; const { skills, isLoading: skillsLoading } = useSkills(); const { data: uploadLimits } = useUploadLimits(threadId); const promptRootRef = useRef(null); const textareaRef = useRef(null); const inlineSkillTextRef = useRef(null); const inlineSkillComposingRef = useRef(false); const goalRequestStateRef = useRef(createGoalRequestState()); const compactRequestStateRef = useRef(createGoalRequestState()); const inputPolishRequestRef = useRef<{ controller: AbortController | null; sequence: number; }>({ controller: null, sequence: 0, }); const voiceRecognitionRef = useRef(null); const voiceBaseTextRef = useRef(""); const voiceLatestTextRef = useRef(""); const voiceLastErrorKindRef = useRef(null); const voiceStopRequestedRef = useRef(false); const voiceRestartTimerRef = useRef | null>( null, ); const startVoiceRecognitionRef = useRef< ((options?: VoiceRecognitionStartOptions) => boolean) | null >(null); const promptHistoryIndexRef = useRef(null); const promptHistoryDraftRef = useRef(""); const pendingDraftSubmissionKeyRef = useRef(null); const latestDraftRef = useRef<{ key: string; draft: { text: string; skillName: string | null }; } | null>(null); const draftSaveTimerRef = useRef(null); const draftSaveGenerationRef = useRef(0); const [followups, setFollowups] = useState([]); const { data: suggestionsConfig } = useSuggestionsConfig(); const suggestionsConfigLoaded = suggestionsConfig !== undefined; const suggestionsEnabled = suggestionsConfig?.enabled; const maxFollowupSuggestions = suggestionsConfig?.max_suggestions ?? DEFAULT_MAX_SUGGESTIONS; const [followupsHidden, setFollowupsHidden] = useState(false); const [followupsLoading, setFollowupsLoading] = useState(false); const [polishingInput, setPolishingInput] = useState(false); const [voiceListening, setVoiceListening] = useState(false); const [inputPolishUndo, setInputPolishUndo] = useState<{ originalText: string; rewrittenText: string; } | null>(null); const [textareaFocused, setTextareaFocused] = useState(false); const [skillSuggestionIndex, setSkillSuggestionIndex] = useState(0); const [selectedSlashSkill, setSelectedSlashSkill] = useState(null); const [hydratedDraftKey, setHydratedDraftKey] = useState(null); const [dismissedSkillSuggestionValue, setDismissedSkillSuggestionValue] = useState(null); const lastGeneratedForAiIdRef = useRef(null); const wasStreamingRef = useRef(false); const messagesRef = useRef(thread.messages); const clearVoiceRestartTimer = useCallback(() => { if (voiceRestartTimerRef.current === null) { return; } clearTimeout(voiceRestartTimerRef.current); voiceRestartTimerRef.current = null; }, []); const cleanupVoiceRecognition = useCallback( ( recognition: BrowserSpeechRecognition | null, options: { keepListening?: boolean } = {}, ) => { clearVoiceRestartTimer(); if (!recognition) { if (!options.keepListening) { voiceLastErrorKindRef.current = null; voiceStopRequestedRef.current = false; setVoiceListening(false); } return; } recognition.onend = null; recognition.onerror = null; recognition.onresult = null; if (voiceRecognitionRef.current === recognition) { voiceRecognitionRef.current = null; } if (!options.keepListening) { voiceLastErrorKindRef.current = null; voiceStopRequestedRef.current = false; setVoiceListening(false); } }, [clearVoiceRestartTimer], ); const abortVoiceInput = useCallback(() => { const recognition = voiceRecognitionRef.current; voiceStopRequestedRef.current = true; if (!recognition) { cleanupVoiceRecognition(null); return; } cleanupVoiceRecognition(recognition); try { recognition.abort(); } catch { // Browser implementations can throw when the recognizer already ended. } }, [cleanupVoiceRecognition]); const [confirmOpen, setConfirmOpen] = useState(false); const [pendingSuggestion, setPendingSuggestion] = useState( null, ); const builtinSlashCommands = useMemo( () => [ { name: "goal", description: t.inputBox.goalCommandDescription, kind: "builtin", }, { name: "compact", description: t.inputBox.compactCommandDescription, kind: "builtin", }, ], [t.inputBox.compactCommandDescription, t.inputBox.goalCommandDescription], ); const reportUploadLimitViolations = useCallback( (violations: UploadLimitViolation[]) => { for (const violation of violations) { if (violation.code === "max_file_size") { toast.error( t.uploads.filesTooLarge( violation.files.map((file) => file.name).join(", "), formatUploadSize(violation.limit), ), ); } else if (violation.code === "max_files") { toast.error( t.uploads.tooManyFiles(violation.files.length, violation.limit), ); } else { toast.error( t.uploads.totalSizeTooLarge( violation.files.length, formatUploadSize(violation.limit), ), ); } } }, [t.uploads], ); useEffect(() => { if (!uploadLimits) { return; } const attachmentEntries = attachmentParts.flatMap((attachment) => attachment.file instanceof File ? [{ id: attachment.id, file: attachment.file }] : [], ); const validation = validateUploadLimits( [], attachmentEntries.map(({ file }) => file), uploadLimits, ); if (validation.rejected.length === 0) { return; } const rejected = new Set(validation.rejected); for (const entry of attachmentEntries) { if (rejected.has(entry.file)) { removeAttachment(entry.id); } } reportUploadLimitViolations(validation.violations); }, [ attachmentParts, removeAttachment, reportUploadLimitViolations, uploadLimits, ]); useEffect(() => { if (models.length === 0) { return; } const currentModel = models.find((m) => m.name === context.model_name); // Prefer the active agent's configured default model over models[0] as the // auto-selection fallback, so an agent chat respects the agent's own // default instead of snapping to the first model (issue #4336). const agentDefaultModel = defaultModelName ? models.find((m) => m.name === defaultModelName) : undefined; const fallbackModel = currentModel ?? agentDefaultModel ?? models[0]!; const supportsThinking = fallbackModel.supports_thinking ?? false; const nextModelName = fallbackModel.name; const nextMode = getResolvedMode(context.mode, supportsThinking); if (context.model_name === nextModelName && context.mode === nextMode) { return; } onContextChange?.({ ...context, model_name: nextModelName, mode: nextMode, }); }, [context, models, defaultModelName, onContextChange]); const selectedModel = useMemo(() => { if (models.length === 0) { return undefined; } return models.find((m) => m.name === context.model_name) ?? models[0]; }, [context.model_name, models]); const resolvedModelName = selectedModel?.name; const supportThinking = useMemo( () => selectedModel?.supports_thinking ?? false, [selectedModel], ); const supportReasoningEffort = useMemo( () => selectedModel?.supports_reasoning_effort ?? false, [selectedModel], ); const draftKey = useMemo( () => buildComposerDraftKey({ userId: user?.id ?? "anonymous", agentName: draftAgentName ?? (typeof context.agent_name === "string" ? context.agent_name : null), threadId: draftThreadId, }), [context.agent_name, draftAgentName, draftThreadId, user?.id], ); const enabledSkillNames = useMemo( () => new Set( skills.filter((skill) => skill.enabled).map((skill) => skill.name), ), [skills], ); const cancelDraftSaveTimer = useCallback(() => { if (draftSaveTimerRef.current === null) { return; } window.clearTimeout(draftSaveTimerRef.current); draftSaveTimerRef.current = null; }, []); const invalidateDraftSaveTimer = useCallback(() => { draftSaveGenerationRef.current += 1; cancelDraftSaveTimer(); }, [cancelDraftSaveTimer]); const scheduleDraftSave = useCallback( (draft: ComposerDraft, key = draftKey) => { if ( !draft.text && !draft.skillName && pendingDraftSubmissionKeyRef.current === key ) { return null; } if (draft.text || draft.skillName) { pendingDraftSubmissionKeyRef.current = null; } latestDraftRef.current = { key, draft }; cancelDraftSaveTimer(); draftSaveGenerationRef.current += 1; const generation = draftSaveGenerationRef.current; const timer = window.setTimeout(() => { if ( draftSaveGenerationRef.current !== generation || draftSaveTimerRef.current !== timer ) { return; } draftSaveTimerRef.current = null; writeComposerDraft(getSessionComposerDraftStorage(), key, draft); }, COMPOSER_DRAFT_SAVE_DELAY_MS); draftSaveTimerRef.current = timer; return timer; }, [cancelDraftSaveTimer, draftKey], ); const flushLatestDraft = useCallback( (expectedKey?: string) => { const latest = latestDraftRef.current; if (!latest || (expectedKey && latest.key !== expectedKey)) { return; } cancelDraftSaveTimer(); writeComposerDraft( getSessionComposerDraftStorage(), latest.key, latest.draft, ); }, [cancelDraftSaveTimer], ); const promptHistory = useMemo(() => { const history: string[] = []; for (const message of thread.messages) { if (message.type !== "human") { continue; } const additionalKwargs = message.additional_kwargs; if ( additionalKwargs && typeof additionalKwargs === "object" && Reflect.get(additionalKwargs, "hide_from_ui") === true ) { continue; } const text = textOfMessage(message)?.trim(); if (!text) { continue; } if (history.at(-1) !== text) { history.push(text); } } return history; }, [thread.messages]); useLayoutEffect(() => { promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; setTextInput(""); setSelectedSlashSkill(null); setInputPolishUndo(null); setHydratedDraftKey(null); pendingDraftSubmissionKeyRef.current = null; latestDraftRef.current = null; invalidateDraftSaveTimer(); return () => flushLatestDraft(draftKey); }, [draftKey, flushLatestDraft, invalidateDraftSaveTimer, setTextInput]); useLayoutEffect(() => { const handlePageHide = () => flushLatestDraft(); window.addEventListener("pagehide", handlePageHide); return () => window.removeEventListener("pagehide", handlePageHide); }, [flushLatestDraft]); useEffect(() => { if (skillsLoading || hydratedDraftKey === draftKey) { return; } const savedDraft = readComposerDraft( getSessionComposerDraftStorage(), draftKey, ); if (!savedDraft) { if (!textInput.value && initialValue) { setTextInput(initialValue); } setHydratedDraftKey(draftKey); return; } const resolvedDraft = resolveComposerDraft(savedDraft, enabledSkillNames); setTextInput(resolvedDraft.text); const restoredSkill = resolvedDraft.skillName ? skills.find( (skill) => skill.enabled && skill.name === resolvedDraft.skillName, ) : undefined; setSelectedSlashSkill( restoredSkill ? { name: restoredSkill.name, description: restoredSkill.description, kind: "skill", } : null, ); setHydratedDraftKey(draftKey); }, [ draftKey, enabledSkillNames, hydratedDraftKey, initialValue, setTextInput, skills, skillsLoading, textInput.value, ]); useEffect(() => { if (hydratedDraftKey !== draftKey) { return; } const draft: ComposerDraft = { text: textInput.value ?? "", skillName: selectedSlashSkill?.kind === "skill" ? selectedSlashSkill.name : null, }; const timer = scheduleDraftSave(draft, draftKey); return () => { if (timer === null) { return; } window.clearTimeout(timer); if (draftSaveTimerRef.current === timer) { draftSaveTimerRef.current = null; } }; }, [ draftKey, hydratedDraftKey, scheduleDraftSave, selectedSlashSkill, textInput.value, ]); useEffect(() => { const goalRequestState = goalRequestStateRef.current; const compactRequestState = compactRequestStateRef.current; return () => { abortGoalRequest(goalRequestState); abortGoalRequest(compactRequestState); }; }, [threadId]); const abortInputPolishRequest = useCallback(() => { inputPolishRequestRef.current.controller?.abort(); inputPolishRequestRef.current.controller = null; inputPolishRequestRef.current.sequence += 1; setPolishingInput(false); }, []); useEffect(() => { return () => abortInputPolishRequest(); }, [abortInputPolishRequest, threadId]); useEffect(() => { const currentIndex = promptHistoryIndexRef.current; if (currentIndex !== null && currentIndex >= promptHistory.length) { promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; } }, [promptHistory.length]); const handleModelSelect = useCallback( (model_name: string) => { if (disabled || polishingInput) { return; } const model = models.find((m) => m.name === model_name); if (!model) { return; } onContextChange?.({ ...context, model_name, mode: getResolvedMode(context.mode, model.supports_thinking ?? false), reasoning_effort: context.reasoning_effort, }); setModelDialogOpen(false); }, [disabled, onContextChange, context, models, polishingInput], ); const handleModeSelect = useCallback( (mode: InputMode) => { if (disabled || polishingInput) { return; } onContextChange?.({ ...context, mode: getResolvedMode(mode, supportThinking), reasoning_effort: mode === "ultra" ? "high" : mode === "pro" ? "medium" : mode === "thinking" ? "low" : "minimal", }); }, [disabled, onContextChange, context, polishingInput, supportThinking], ); const handleReasoningEffortSelect = useCallback( (effort: "minimal" | "low" | "medium" | "high") => { if (disabled || polishingInput) { return; } onContextChange?.({ ...context, reasoning_effort: effort, }); }, [disabled, onContextChange, context, polishingInput], ); const handleGoalCommand = useCallback( async (command: GoalCommand): Promise => { const request = beginGoalRequest(goalRequestStateRef.current, threadId); const signal = request.controller.signal; try { let goal: GoalState | null = null; if (command.kind === "status") { const response = await fetch( `${getBackendBaseURL()}/api/threads/${encodeURIComponent( threadId, )}/goal`, { method: "GET", signal }, ); if (!response.ok) { throw new Error(await readGoalResponseError(response)); } goal = ((await response.json()) as { goal?: GoalState | null }).goal ?? null; if ( !isCurrentGoalRequest( goalRequestStateRef.current, request, threadId, ) ) { return false; } const objective = goal?.objective; toast.info( objective !== undefined ? // Function replacer so a goal containing `$&`/`$1` isn't // interpreted as a replacement pattern. t.inputBox.goalActive.replace("{goal}", () => objective) : t.inputBox.goalNone, ); onGoalChange?.(goal); } else if (command.kind === "clear") { const response = await fetch( `${getBackendBaseURL()}/api/threads/${encodeURIComponent( threadId, )}/goal`, { method: "DELETE", signal }, ); if (!response.ok) { throw new Error(await readGoalResponseError(response)); } if ( !isCurrentGoalRequest( goalRequestStateRef.current, request, threadId, ) ) { return false; } toast.success(t.inputBox.goalCleared); onGoalChange?.(null); } else { const response = await fetch( `${getBackendBaseURL()}/api/threads/${encodeURIComponent( threadId, )}/goal`, { method: "PUT", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ objective: command.objective }), signal, }, ); if (!response.ok) { throw new Error(await readGoalResponseError(response)); } goal = ((await response.json()) as { goal?: GoalState | null }).goal ?? null; if ( !isCurrentGoalRequest( goalRequestStateRef.current, request, threadId, ) ) { return false; } toast.success(t.inputBox.goalSet); onGoalChange?.(goal); } textInput.setInput(""); return true; } catch (error) { if ( isAbortError(error) || !isCurrentGoalRequest(goalRequestStateRef.current, request, threadId) ) { return false; } toast.error( error instanceof Error ? error.message : t.inputBox.goalFailed, ); return false; } finally { finishGoalRequest(goalRequestStateRef.current, request); } }, [ onGoalChange, t.inputBox.goalActive, t.inputBox.goalCleared, t.inputBox.goalFailed, t.inputBox.goalNone, t.inputBox.goalSet, textInput, threadId, ], ); const handleCompactCommand = useCallback(async (): Promise => { if (isWelcomeMode) { textInput.setInput(""); toast.info(t.inputBox.compactSkipped); return; } const request = beginGoalRequest(compactRequestStateRef.current, threadId); const signal = request.controller.signal; try { const result = await compactThreadContext(threadId, { signal, agentName: typeof context.agent_name === "string" ? context.agent_name : null, modelName: typeof context.model_name === "string" ? context.model_name : null, }); if ( !isCurrentGoalRequest(compactRequestStateRef.current, request, threadId) ) { return; } textInput.setInput(""); promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; setFollowups([]); setFollowupsHidden(false); setFollowupsLoading(false); void queryClient.invalidateQueries({ queryKey: ["thread", threadId] }); void queryClient.invalidateQueries({ queryKey: threadTokenUsageQueryKey(threadId), }); if (result.compacted) { toast.success(t.inputBox.compactSuccess); } else { toast.info(t.inputBox.compactSkipped); } } catch (error) { if ( isAbortError(error) || !isCurrentGoalRequest(compactRequestStateRef.current, request, threadId) ) { return; } toast.error( error instanceof Error ? error.message : t.inputBox.compactFailed, ); } finally { finishGoalRequest(compactRequestStateRef.current, request); } }, [ context.agent_name, context.model_name, queryClient, t.inputBox.compactFailed, t.inputBox.compactSkipped, t.inputBox.compactSuccess, isWelcomeMode, textInput, threadId, ]); const submitThreadMessage = useCallback( (message: PromptInputMessage) => { const files = message.files.flatMap((file) => file.file instanceof File ? [file.file] : [], ); const uploadValidation = validateUploadLimits([], files, uploadLimits); if (uploadValidation.violations.length > 0) { reportUploadLimitViolations(uploadValidation.violations); return Promise.reject(new Error("Attachment limits exceeded.")); } const placeholder = findSuggestionTemplatePlaceholder(message.text); if (placeholder) { toast.warning(t.inputBox.suggestionPlaceholderRequired); requestAnimationFrame(() => { const textarea = textareaRef.current; if (!textarea) { return; } textarea.focus(); textarea.setSelectionRange(placeholder.start, placeholder.end); }); return Promise.reject( new Error("Suggestion template placeholder is unresolved."), ); } promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; setInputPolishUndo(null); setFollowups([]); setFollowupsHidden(false); setFollowupsLoading(false); const quotes = sidecar?.conversationQuotes ?? []; const quoteIds = quotes.map((quote) => quote.id); const quoteContexts = quotes.map((quote) => quote.context); pendingDraftSubmissionKeyRef.current = draftKey; const submitOptions: InputBoxSubmitOptions = { ...(quotes.length ? { additionalKwargs: buildReferenceMessageMetadata(quoteContexts), additionalInputMessages: [ buildHiddenConversationQuoteMessage({ contexts: quoteContexts, }), ], } : {}), // Clear one-time state only once the send genuinely proceeds. If the // send is dropped by the in-flight guard, `onSent` never fires. onSent: () => { if (pendingDraftSubmissionKeyRef.current === draftKey) { pendingDraftSubmissionKeyRef.current = null; latestDraftRef.current = null; invalidateDraftSaveTimer(); clearComposerDraft(getSessionComposerDraftStorage(), draftKey); } sidecar?.clearConversationQuotes(quoteIds); }, }; const submit = () => onSubmit?.(message, submitOptions); // Guard against submitting before the initial model auto-selection // effect has flushed thread settings to storage/state. if (resolvedModelName && context.model_name !== resolvedModelName) { onContextChange?.({ ...context, model_name: resolvedModelName, mode: getResolvedMode( context.mode, selectedModel?.supports_thinking ?? false, ), }); return new Promise((resolve, reject) => { setTimeout(() => { Promise.resolve(submit()).then(resolve).catch(reject); }, 0); }); } return submit(); }, [ context, draftKey, invalidateDraftSaveTimer, onContextChange, onSubmit, reportUploadLimitViolations, resolvedModelName, selectedModel?.supports_thinking, sidecar, t.inputBox.suggestionPlaceholderRequired, uploadLimits, ], ); const handleSubmit = useCallback( async (message: PromptInputMessage) => { if (status === "streaming") { toast.info(t.inputBox.pleaseWaitStreaming); return Promise.reject(new Error("streaming")); } abortVoiceInput(); const messageWithSlashSkill = selectedSlashSkill ? { ...message, text: `/${selectedSlashSkill.name} ${message.text}`, } : message; const submitAction = getInputSubmitAction({ text: messageWithSlashSkill.text, fileCount: messageWithSlashSkill.files.length, status, }); if (submitAction.kind === "goal") { if ( submitAction.command.kind === "set" && isGoalObjectiveTooLong(submitAction.command.objective) ) { toast.error( t.inputBox.goalTooLong.replace("{max}", () => String(MAX_GOAL_OBJECTIVE_CHARS), ), ); // Reject so the composer keeps the user's text for editing instead of // clearing it (PromptInput only preserves input on a rejected submit). return Promise.reject(new Error("goal-too-long")); } promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; setFollowups([]); setFollowupsHidden(false); setFollowupsLoading(false); const saved = await handleGoalCommand(submitAction.command); // Only start a run when a goal was actually saved; status/clear never run. if (saved && submitAction.command.kind === "set") { return submitThreadMessage({ ...message, text: submitAction.command.objective, files: [], }); } return; } if (submitAction.kind === "compact") { return handleCompactCommand(); } if (submitAction.kind === "stop") { onStop?.(); return; } if (submitAction.kind === "empty") { return; } await submitThreadMessage(messageWithSlashSkill); if (selectedSlashSkill) { setSelectedSlashSkill(null); } }, [ abortVoiceInput, handleCompactCommand, handleGoalCommand, onStop, selectedSlashSkill, status, submitThreadMessage, t.inputBox.goalTooLong, t.inputBox.pleaseWaitStreaming, ], ); const requestFormSubmit = useCallback(() => { const form = promptRootRef.current?.querySelector("form"); form?.requestSubmit(); }, []); const handleFollowupClick = useCallback( (suggestion: string) => { if (status === "streaming") { return; } const current = (textInput.value ?? "").trim(); if (current) { setPendingSuggestion(suggestion); setConfirmOpen(true); return; } textInput.setInput(suggestion); setFollowupsHidden(true); setTimeout(() => requestFormSubmit(), 0); }, [requestFormSubmit, status, textInput], ); const confirmReplaceAndSend = useCallback(() => { if (!pendingSuggestion) { setConfirmOpen(false); return; } textInput.setInput(pendingSuggestion); setFollowupsHidden(true); setConfirmOpen(false); setPendingSuggestion(null); setTimeout(() => requestFormSubmit(), 0); }, [pendingSuggestion, requestFormSubmit, textInput]); const confirmAppendAndSend = useCallback(() => { if (!pendingSuggestion) { setConfirmOpen(false); return; } const current = (textInput.value ?? "").trim(); const next = current ? `${current}\n${pendingSuggestion}` : pendingSuggestion; textInput.setInput(next); setFollowupsHidden(true); setConfirmOpen(false); setPendingSuggestion(null); setTimeout(() => requestFormSubmit(), 0); }, [pendingSuggestion, requestFormSubmit, textInput]); const slashSkillQuery = useMemo( () => getLeadingSlashSkillQuery(textInput.value ?? ""), [textInput.value], ); const goalObjectiveCounter = useMemo( () => getGoalObjectiveCounter(textInput.value ?? ""), [textInput.value], ); const skillSuggestions = useMemo( () => slashSkillQuery === null ? [] : getMatchingSkillSuggestions( skills, slashSkillQuery, builtinSlashCommands, ), [builtinSlashCommands, skills, slashSkillQuery], ); const showSkillSuggestions = !disabled && textareaFocused && !selectedSlashSkill && slashSkillQuery !== null && skillSuggestions.length > 0 && dismissedSkillSuggestionValue !== textInput.value; const isComposerDisabled = disabled === true; const isMockThread = isMock === true; const composerLocked = isComposerDisabled || polishingInput; const inputPolishUndoAvailable = !polishingInput && inputPolishUndo !== null && (textInput.value ?? "") === inputPolishUndo.rewrittenText; const inputPolishDisabled = isComposerDisabled || isMockThread || polishingInput || (!inputPolishUndoAvailable && (status === "streaming" || slashSkillQuery !== null || !canPolishInput(textInput.value ?? ""))); const speechRecognitionConstructor = useMemo( () => typeof window === "undefined" ? null : getSpeechRecognitionConstructor(window), [], ); const voiceInputSupported = speechRecognitionConstructor !== null; const getVoiceInputErrorMessage = useCallback( (kind: SpeechRecognitionErrorKind) => { switch (kind) { case "permission_denied": return t.inputBox.voiceInputPermissionDenied; case "microphone_unavailable": return t.inputBox.voiceInputMicrophoneUnavailable; case "unsupported_language": return t.inputBox.voiceInputUnsupportedLanguage; case "network": return t.inputBox.voiceInputNetworkError; case "no_speech": return t.inputBox.voiceInputNoSpeech; case "cancelled": return null; default: return t.inputBox.voiceInputFailed; } }, [t], ); const startVoiceRecognition = useCallback( (options: VoiceRecognitionStartOptions = {}) => { if (composerLocked || !speechRecognitionConstructor) { return false; } const recognition = new speechRecognitionConstructor(); recognition.continuous = true; recognition.interimResults = true; recognition.lang = getSpeechRecognitionLanguage(locale); recognition.maxAlternatives = 1; voiceLastErrorKindRef.current = null; voiceLatestTextRef.current = voiceBaseTextRef.current; voiceRecognitionRef.current = recognition; recognition.onresult = (event) => { if (voiceRecognitionRef.current !== recognition) { return; } const transcript = readSpeechRecognitionTranscript(event.results).text; const nextValue = appendSpeechTranscript( voiceBaseTextRef.current, transcript, ); voiceLatestTextRef.current = nextValue; textInput.setInput(nextValue); }; recognition.onerror = (event) => { const errorKind = mapSpeechRecognitionError(event.error); voiceLastErrorKindRef.current = errorKind; if ( !voiceStopRequestedRef.current && shouldRestartSpeechRecognition(errorKind) ) { return; } const message = getVoiceInputErrorMessage(errorKind); if (message) { toast.error(message); } }; recognition.onend = () => { const shouldRestart = voiceRecognitionRef.current === recognition && !voiceStopRequestedRef.current && shouldRestartSpeechRecognition(voiceLastErrorKindRef.current); if (shouldRestart) { voiceBaseTextRef.current = voiceLatestTextRef.current; cleanupVoiceRecognition(recognition, { keepListening: true }); voiceRestartTimerRef.current = setTimeout(() => { voiceRestartTimerRef.current = null; if (voiceStopRequestedRef.current) { cleanupVoiceRecognition(null); return; } const restarted = startVoiceRecognitionRef.current?.() ?? false; if (!restarted) { cleanupVoiceRecognition(null); } }, 150); return; } cleanupVoiceRecognition(recognition); }; setVoiceListening(true); try { recognition.start(); if (options.focusAfterStart) { requestAnimationFrame(() => { if (selectedSlashSkill) { focusContentEditableEnd(inlineSkillTextRef.current); } else { textareaRef.current?.focus(); } }); } return true; } catch { cleanupVoiceRecognition(recognition); toast.error(t.inputBox.voiceInputFailed); return false; } }, [ cleanupVoiceRecognition, composerLocked, getVoiceInputErrorMessage, locale, selectedSlashSkill, speechRecognitionConstructor, t.inputBox.voiceInputFailed, textInput, ], ); useEffect(() => { startVoiceRecognitionRef.current = startVoiceRecognition; }, [startVoiceRecognition]); const stopVoiceInput = useCallback(() => { const recognition = voiceRecognitionRef.current; voiceStopRequestedRef.current = true; if (!recognition) { cleanupVoiceRecognition(null); return; } try { recognition.stop(); } catch { cleanupVoiceRecognition(recognition); } }, [cleanupVoiceRecognition]); const toggleVoiceInput = useCallback(() => { if (voiceListening) { stopVoiceInput(); return; } if (composerLocked) { return; } if (!speechRecognitionConstructor) { toast.error(t.inputBox.voiceInputUnsupported); return; } abortInputPolishRequest(); setInputPolishUndo(null); promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; voiceStopRequestedRef.current = false; voiceBaseTextRef.current = textInput.value ?? ""; voiceLatestTextRef.current = voiceBaseTextRef.current; startVoiceRecognition({ focusAfterStart: true }); }, [ abortInputPolishRequest, composerLocked, speechRecognitionConstructor, startVoiceRecognition, stopVoiceInput, t.inputBox.voiceInputUnsupported, textInput, voiceListening, ]); useEffect(() => { if (composerLocked && voiceListening) { stopVoiceInput(); } }, [composerLocked, stopVoiceInput, voiceListening]); useEffect(() => { return () => abortVoiceInput(); }, [abortVoiceInput, threadId]); useEffect(() => { setSkillSuggestionIndex(0); }, [slashSkillQuery, skillSuggestions.length]); const applySkillSuggestion = useCallback( (suggestion: SlashSuggestion) => { if (suggestion.kind === "skill") { setSelectedSlashSkill(suggestion); textInput.setInput(""); setDismissedSkillSuggestionValue(null); requestAnimationFrame(() => { focusContentEditableEnd(inlineSkillTextRef.current); }); return; } const nextValue = `/${suggestion.name} `; textInput.setInput(nextValue); setDismissedSkillSuggestionValue(nextValue); requestAnimationFrame(() => { const textarea = textareaRef.current; if (!textarea) { return; } textarea.focus(); textarea.setSelectionRange(nextValue.length, nextValue.length); }); }, [textInput], ); const handleSkillSuggestionKeyDown = useCallback( (event: KeyboardEvent) => { if (!showSkillSuggestions) { return; } if (event.key === "ArrowDown") { event.preventDefault(); setSkillSuggestionIndex( (index) => (index + 1) % skillSuggestions.length, ); return; } if (event.key === "ArrowUp") { event.preventDefault(); setSkillSuggestionIndex( (index) => (index - 1 + skillSuggestions.length) % skillSuggestions.length, ); return; } if (event.key === "Enter" || event.key === "Tab") { if (event.shiftKey) { return; } event.preventDefault(); const selectedSkill = skillSuggestions[skillSuggestionIndex]; if (selectedSkill) { applySkillSuggestion(selectedSkill); } return; } if (event.key === "Escape") { event.preventDefault(); setDismissedSkillSuggestionValue(textInput.value); } }, [ applySkillSuggestion, showSkillSuggestions, skillSuggestionIndex, skillSuggestions, textInput.value, ], ); const setPromptHistoryValue = useCallback( (value: string) => { textInput.setInput(value); requestAnimationFrame(() => { const textarea = textareaRef.current; if (!textarea) { return; } textarea.focus(); textarea.setSelectionRange(value.length, value.length); }); }, [textInput], ); const handlePolishInput = useCallback(async () => { if (inputPolishDisabled) { return; } const originalText = textInput.value ?? ""; const controller = new AbortController(); inputPolishRequestRef.current.controller?.abort(); const sequence = inputPolishRequestRef.current.sequence + 1; inputPolishRequestRef.current = { controller, sequence, }; setPolishingInput(true); try { const result = await polishInputDraft( { text: originalText, locale, thread_id: threadId, }, { signal: controller.signal }, ); const isCurrentRequest = inputPolishRequestRef.current.controller === controller && inputPolishRequestRef.current.sequence === sequence && !controller.signal.aborted; if (!isCurrentRequest || (textInput.value ?? "") !== originalText) { return; } const rewrittenText = result.rewritten_text.trim(); if (!rewrittenText || !result.changed) { toast.info(t.inputBox.inputPolishNoChanges); return; } // Applying the rewrite replaces the draft outside the textarea change // handler, so clear any in-progress history browse state; otherwise a // stale index would let the next ArrowDown overwrite the rewrite. promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; setPromptHistoryValue(rewrittenText); setInputPolishUndo({ originalText, rewrittenText, }); } catch (error) { const isCurrentRequest = inputPolishRequestRef.current.controller === controller && inputPolishRequestRef.current.sequence === sequence; if (isAbortError(error) || !isCurrentRequest) { return; } toast.error( error instanceof Error ? error.message : t.inputBox.inputPolishFailed, ); } finally { if ( inputPolishRequestRef.current.controller === controller && inputPolishRequestRef.current.sequence === sequence ) { inputPolishRequestRef.current.controller = null; setPolishingInput(false); } } }, [ inputPolishDisabled, locale, setPromptHistoryValue, t.inputBox.inputPolishFailed, t.inputBox.inputPolishNoChanges, textInput, threadId, ]); const handleUndoInputPolish = useCallback(() => { if (!inputPolishUndoAvailable || inputPolishUndo === null) { return; } promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; setPromptHistoryValue(inputPolishUndo.originalText); setInputPolishUndo(null); }, [inputPolishUndo, inputPolishUndoAvailable, setPromptHistoryValue]); const handlePromptHistoryKeyDown = useCallback( (event: KeyboardEvent) => { if ( event.altKey || event.ctrlKey || event.metaKey || event.shiftKey || isIMEComposing(event) || selectedSlashSkill || promptHistory.length === 0 || (event.key !== "ArrowUp" && event.key !== "ArrowDown") ) { return; } const currentValue = textInput.value ?? ""; const currentHistoryIndex = promptHistoryIndexRef.current; const isBrowsingHistory = currentHistoryIndex !== null; if (!isBrowsingHistory && currentValue.length > 0) { return; } if (event.key === "ArrowUp") { event.preventDefault(); const nextIndex = isBrowsingHistory ? Math.max(currentHistoryIndex - 1, 0) : promptHistory.length - 1; if (!isBrowsingHistory) { promptHistoryDraftRef.current = currentValue; } promptHistoryIndexRef.current = nextIndex; setPromptHistoryValue(promptHistory[nextIndex] ?? ""); return; } if (!isBrowsingHistory) { return; } event.preventDefault(); if (currentHistoryIndex >= promptHistory.length - 1) { promptHistoryIndexRef.current = null; setPromptHistoryValue(promptHistoryDraftRef.current); promptHistoryDraftRef.current = ""; return; } const nextIndex = currentHistoryIndex + 1; promptHistoryIndexRef.current = nextIndex; setPromptHistoryValue(promptHistory[nextIndex] ?? ""); }, [promptHistory, selectedSlashSkill, setPromptHistoryValue, textInput.value], ); const handleSelectedSlashSkillKeyDown = useCallback( (event: KeyboardEvent) => { if ( event.key !== "Backspace" || !selectedSlashSkill || textInput.value.length > 0 || isIMEComposing(event) ) { return; } event.preventDefault(); setSelectedSlashSkill(null); requestAnimationFrame(() => { textareaRef.current?.focus(); }); }, [selectedSlashSkill, textInput.value], ); const handlePromptTextareaKeyDown = useCallback( (event: KeyboardEvent) => { handleSkillSuggestionKeyDown(event); if (event.defaultPrevented) { return; } handleSelectedSlashSkillKeyDown(event); if (event.defaultPrevented) { return; } handlePromptHistoryKeyDown(event); }, [ handlePromptHistoryKeyDown, handleSelectedSlashSkillKeyDown, handleSkillSuggestionKeyDown, ], ); const handlePromptTextareaChange = useCallback( (event: ChangeEvent) => { if (voiceListening) { abortVoiceInput(); } abortInputPolishRequest(); setInputPolishUndo(null); promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; scheduleDraftSave({ text: event.currentTarget.value, skillName: selectedSlashSkill?.kind === "skill" ? selectedSlashSkill.name : null, }); }, [ abortInputPolishRequest, abortVoiceInput, scheduleDraftSave, selectedSlashSkill, voiceListening, ], ); const updateInlineSkillTextInput = useCallback( (element: HTMLElement) => { if (voiceListening) { abortVoiceInput(); } promptHistoryIndexRef.current = null; promptHistoryDraftRef.current = ""; const nextText = element.textContent ?? ""; textInput.setInput(nextText); scheduleDraftSave({ text: nextText, skillName: selectedSlashSkill?.kind === "skill" ? selectedSlashSkill.name : null, }); }, [ abortVoiceInput, scheduleDraftSave, selectedSlashSkill, textInput, voiceListening, ], ); useEffect(() => { if (!selectedSlashSkill) { return; } const element = inlineSkillTextRef.current; if (element && element.textContent !== textInput.value) { element.textContent = textInput.value; } }, [selectedSlashSkill, textInput.value]); const handleInlineSkillInput = useCallback( (event: FormEvent) => { updateInlineSkillTextInput(event.currentTarget); }, [updateInlineSkillTextInput], ); const handleInlineSkillPaste = useCallback( (event: ClipboardEvent) => { const pastedFiles = Array.from(event.clipboardData.items) .filter((item) => item.kind === "file") .flatMap((item) => { const file = item.getAsFile(); return file ? [file] : []; }); if (pastedFiles.length > 0) { event.preventDefault(); const { accepted, message } = splitUnsupportedUploadFiles(pastedFiles); if (message) { toast.error(message); } if (accepted.length > 0) { attachments.add(accepted); } return; } const text = event.clipboardData.getData("text/plain"); if (!text) { return; } event.preventDefault(); if (insertPlainTextAtSelection(event.currentTarget, text)) { updateInlineSkillTextInput(event.currentTarget); } }, [attachments, updateInlineSkillTextInput], ); const handleInlineSkillKeyDown = useCallback( (event: KeyboardEvent) => { handleSelectedSlashSkillKeyDown(event); if (event.defaultPrevented) { return; } if (event.key !== "Enter") { return; } if (isIMEComposing(event, inlineSkillComposingRef.current)) { return; } event.preventDefault(); if (event.shiftKey) { if (insertPlainTextAtSelection(event.currentTarget, "\n")) { updateInlineSkillTextInput(event.currentTarget); } return; } event.currentTarget.closest("form")?.requestSubmit(); }, [handleSelectedSlashSkillKeyDown, updateInlineSkillTextInput], ); const clearSelectedSlashSkill = useCallback(() => { setSelectedSlashSkill(null); requestAnimationFrame(() => { textareaRef.current?.focus(); }); }, []); const showFollowups = !disabled && !isWelcomeMode && !showSkillSuggestions && !selectedSlashSkill && !followupsHidden && (followupsLoading || followups.length > 0); useEffect(() => { onFollowupsVisibilityChange?.(showFollowups); }, [onFollowupsVisibilityChange, showFollowups]); useEffect(() => { return () => onFollowupsVisibilityChange?.(false); }, [onFollowupsVisibilityChange]); useEffect(() => { messagesRef.current = thread.messages; }, [thread.messages]); useEffect(() => { const streaming = status === "streaming"; const wasStreaming = wasStreamingRef.current; wasStreamingRef.current = streaming; if (!wasStreaming || streaming) { return; } if (disabled || isMock) { return; } const lastAi = [...messagesRef.current] .reverse() .find((m) => m.type === "ai"); const lastAiId = lastAi?.id ?? null; if (!lastAiId || lastAiId === lastGeneratedForAiIdRef.current) { return; } if (!suggestionsConfigLoaded) { return; } lastGeneratedForAiIdRef.current = lastAiId; const recent = messagesRef.current .filter((m) => m.type === "human" || m.type === "ai") .filter((m) => !isHiddenFromUIMessage(m)) .map((m) => { const role = m.type === "human" ? "user" : "assistant"; const content = textOfMessage(m) ?? ""; return { role, content }; }) .filter((m) => m.content.trim().length > 0) .slice(-6); if (recent.length === 0) { return; } if (!suggestionsEnabled) { setFollowups([]); return; } const controller = new AbortController(); setFollowupsHidden(false); setFollowupsLoading(true); setFollowups([]); fetch(`${getBackendBaseURL()}/api/threads/${threadId}/suggestions`, { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ messages: recent, n: maxFollowupSuggestions, model_name: context.model_name ?? undefined, }), signal: controller.signal, }) .then(async (res) => { if (!res.ok) { return { suggestions: [] as string[] }; } return (await res.json()) as { suggestions?: string[] }; }) .then((data) => { const suggestions = (data.suggestions ?? []) .map((s) => (typeof s === "string" ? s.trim() : "")) .filter((s) => s.length > 0) .slice(0, maxFollowupSuggestions); setFollowups(suggestions); }) .catch(() => { setFollowups([]); }) .finally(() => { setFollowupsLoading(false); }); return () => controller.abort(); }, [ context.model_name, disabled, isMock, maxFollowupSuggestions, status, suggestionsConfigLoaded, suggestionsEnabled, threadId, ]); const onSelectPlaceholder = useCallback((newText: string) => { const placeholder = findSuggestionTemplatePlaceholder(newText); if (placeholder) { requestAnimationFrame(() => { const textarea = textareaRef.current; if (!textarea) return; textarea.focus(); textarea.setSelectionRange(placeholder.start, placeholder.end); }); } }, []); return (
{showFollowups && (
{followupsLoading ? (
{t.inputBox.followupLoading}
) : ( {followups.map((s) => ( handleFollowupClick(s)} /> ))} )}
)} {showSkillSuggestions && (
{skillSuggestions.map((suggestion, index) => { const selected = index === skillSuggestionIndex; return ( ); })}
)} {polishingInput && (