import { pastedFilePath, PastedPathRange, type LocalAttachment } from "../../../../packages/client-events/attachments"; import { NewChatIcon, CompactIcon, StatusIcon, ModelsIcon, TriggerIcon, DreamLogIcon, PromptTemplateIcon, PairingIcon, ToolRunIcon, ActivityIcon, ArchiveIcon, SkillsIcon, MemoryIcon, HelpIcon, HistoryIcon, AttachIcon, RestartIcon, RestrictedAccessIcon, DreamIcon, StopIcon, EditIcon, GoalIcon, RestoreMemoryIcon, } from "@/components/icons/product-icons"; import { useCallback, useEffect, useLayoutEffect, useMemo, useRef, useState, type CSSProperties, type KeyboardEvent as ReactKeyboardEvent, type Ref, } from "react"; import { MarkdownText, preloadMarkdownText } from "@/components/MarkdownText"; import { CapabilityMentionToken, cliAppInitials, mcpPresetInitials, splitCapabilityMentionSegments, } from "@/components/CliAppMentionText"; import { SkillReferenceToken, withSkillReferences, type InlineReferenceSegment, } from "@/components/SkillReferenceText"; import { composerMentionText, isCapabilityMentionStart, type CapabilityMentionSegment, } from "@/lib/composer-mention-text"; import { INLINE_REFERENCE_HIGHLIGHT_COLOR, INLINE_TOKEN_HIGHLIGHT_COLOR, InlineTokenHighlight } from "@/components/InlineTokenHighlight"; import { SlashCommandText } from "@/components/SlashCommandText"; import { ChevronDown, ChevronUp, CornerDownRight, Loader2, Quote, Trash2, X, type LucideIcon, } from "lucide-react"; import { useTranslation } from "react-i18next"; import { Button } from "@/components/ui/button"; import { AttachmentCard, AttachmentTypeFace, attachmentCardActionClassName } from "@/components/AttachmentCard"; import { ComposerActionIcon, type ComposerActionState } from "@/components/thread/ComposerActionIcon"; import { floatingItemClassName, floatingItemFocusClassName, floatingSurfaceElevationClassName, floatingSurfaceVisualClassName, } from "@/components/ui/floating-surface"; import { Tooltip, TooltipContent, TooltipProvider, TooltipTrigger, } from "@/components/ui/tooltip"; import { WorkspaceAccessMenu, WorkspaceProjectPicker, } from "@/components/thread/WorkspaceControls"; import { ModelPresetBadge, type ModelPresetOption, } from "@/components/thread/ModelPresetBadge"; import type { ComposerUsageControl } from "@/components/thread/ComposerUsagePopover"; import { ACCEPT_ATTR, acceptedAttachmentKind, MAX_ATTACHMENTS_PER_MESSAGE, MAX_ATTACHMENT_BYTES, MAX_TOTAL_ATTACHMENT_BYTES, MAX_VIDEO_BYTES, MAX_VIDEOS_PER_MESSAGE, useAttachedImages, type AttachedImage, type AttachmentError, type RestoredReadyImage, } from "@/hooks/useAttachedImages"; import { useClipboardAndDrop } from "@/hooks/useClipboardAndDrop"; import { useComposerMentionInput } from "@/hooks/useComposerMentionInput"; import { useLogoFallback } from "@/hooks/useLogoFallback"; import { useMediaQuery } from "@/hooks/useMediaQuery"; import type { SendAttachment, SendOptions } from "@/hooks/useNanobotStream"; import { useVoiceRecorder, type VoiceRecorderErrorKey } from "@/hooks/useVoiceRecorder"; import type { CliAppInfo, ChatSummary, GoalStateWsPayload, McpPresetInfo, OutboundCliAppMention, OutboundMcpPresetMention, SessionMention, SlashCommand, SkillSummary, WebUIIngressLimits, WorkspaceScopePayload, WorkspacesPayload, ProjectDirectory, WorkspaceDirectoriesPayload, } from "@/lib/types"; import { logoFallbackUrls, } from "@/lib/provider-brand"; import { sessionHandleColor } from "@/lib/session-handle"; import { requestSkillsRefresh } from "@/lib/skill-events"; import { isRegisteredSlashCommand, isSideChannelLifecycle, matchingSlashCommand, slashCommandLifecycle, } from "@/lib/slash-command"; import { clearDraggedSession, hasDraggedSession, readDraggedSession, } from "@/lib/session-drag"; import { formatQuotedUserMessage } from "@/lib/user-message-quote"; import { cn } from "@/lib/utils"; import type { ComposerDraft, ComposerDraftStore } from "@/lib/composer-draft"; import { useLocalPreferences } from "@/hooks/useLocalPreferences"; import { queuedImagesToSendImages, queuedUploadBytes, readyImagesToQueuedImages, useQueuedPrompt, type QueuedPromptContent, } from "@/components/thread/useQueuedPrompt"; const VOICE_SHORTCUT_CODE = "KeyD"; const VOICE_SHORTCUT_ARIA = "Control+Shift+D"; const VOICE_ERROR_VISIBLE_MS = 3_500; const VOICE_ERROR_FADE_MS = 500; type VoiceShortcutPlatform = "apple" | "chromeos" | "linux" | "other" | "windows"; function formatBytes(n: number): string { if (n < 1024) return `${n} B`; if (n < 1024 * 1024) return `${(n / 1024).toFixed(1)} KiB`; return `${(n / (1024 * 1024)).toFixed(1)} MiB`; } function utf8Bytes(value: string): number { return new TextEncoder().encode(value).byteLength; } function isVoiceShortcutDown(event: KeyboardEvent): boolean { return ( event.code === VOICE_SHORTCUT_CODE && event.ctrlKey && event.shiftKey && !event.altKey && !event.metaKey ); } function isVoiceShortcutRelease(event: KeyboardEvent): boolean { return ( event.code === VOICE_SHORTCUT_CODE || event.key === "Control" || event.key === "Shift" ); } function getVoiceShortcutPlatform(): VoiceShortcutPlatform { if (typeof navigator === "undefined") return "other"; const userAgentData = (navigator as Navigator & { userAgentData?: { platform?: string } }) .userAgentData; const platform = [ userAgentData?.platform, navigator.platform, navigator.userAgent, ].filter(Boolean).join(" ").toLowerCase(); const isIpadPretendingToBeMac = navigator.platform === "MacIntel" && navigator.maxTouchPoints > 1; if (isIpadPretendingToBeMac || /mac|iphone|ipad|ipod/.test(platform)) return "apple"; if (/win/.test(platform)) return "windows"; if (/cros/.test(platform)) return "chromeos"; if (/linux|x11|android/.test(platform)) return "linux"; return "other"; } function getVoiceShortcutLabel(): string { switch (getVoiceShortcutPlatform()) { case "apple": return "⌃⇧D"; case "chromeos": case "linux": case "windows": case "other": return "Ctrl ⇧ D"; } } interface ThreadComposerProps { onSend: ( content: string, images?: SendAttachment[], options?: SendOptions, ) => boolean | void | Promise; disabled?: boolean; placeholder?: string; inputAriaLabel?: string; compactWhenIdle?: boolean; isStreaming?: boolean; activeTurnId?: string | null; completedTurnIds?: readonly string[]; modelLabel?: string | null; modelDetail?: string | null; modelPreset?: string | null; modelPresets?: ModelPresetOption[]; onModelPresetChange?: (name: string) => void; modelProvider?: string | null; modelProviderLabel?: string | null; modelNeedsSetup?: boolean; onModelBadgeClick?: () => void; onManageModels?: () => void; renderContextUsage?: ComposerUsageControl; variant?: "thread" | "hero"; slashCommands?: SlashCommand[]; onMentionSearch?: () => void; cliApps?: CliAppInfo[]; mcpPresets?: McpPresetInfo[]; sessions?: ChatSummary[]; skills?: SkillSummary[]; onStop?: () => void; surfaceRef?: Ref; onTranscribeAudio?: (dataUrl: string, options?: { durationMs?: number }) => Promise; onInspectAttachment?: (path: string) => Promise; /** Sustained objective for this chat (WebSocket ``goal_state``). */ goalState?: GoalStateWsPayload; workspaceScope?: WorkspaceScopePayload | null; workspaceControlsHidden?: boolean; workspacePickerLayoutAnchor?: HTMLElement | null; workspaceDefaultScope?: WorkspaceScopePayload | null; workspaceControls?: WorkspacesPayload["controls"] | null; workspaceScopeDisabled?: boolean; workspaceProjectLocked?: boolean; workspaceError?: string | null; onFavoriteWorkspaceProject?: (path: string, pinned: boolean) => Promise; onResolveWorkspaceProject?: (path: string) => Promise; onLoadWorkspaceProjects?: () => Promise; onBrowseWorkspaceDirectories?: (path: string, query: string, showHidden: boolean) => Promise; onWorkspaceScopeChange?: (scope: WorkspaceScopePayload) => void; pendingQueueKey?: string | null; draftKey?: string; draftStore?: ComposerDraftStore; persistDraft?: boolean; transcriptionProvider?: string | null; ingressLimits?: WebUIIngressLimits | null; quotedContext?: string | null; focusRequest?: number; onQuotedContextChange?: (text: string | null) => void; } const COMMAND_ICONS: Record = { activity: ActivityIcon, archive: ArchiveIcon, "book-open": SkillsIcon, brain: MemoryIcon, "circle-help": HelpIcon, history: HistoryIcon, "rotate-cw": RestartIcon, shield: RestrictedAccessIcon, sparkles: DreamIcon, square: StopIcon, "square-pen": EditIcon, "undo-2": RestoreMemoryIcon, zap: TriggerIcon, "file-text": PromptTemplateIcon, wrench: ToolRunIcon, }; const BUILTIN_COMMAND_ICONS: Record = { "/new": NewChatIcon, "/compact": CompactIcon, "/stop": StopIcon, "/restart": RestartIcon, "/status": StatusIcon, "/model": ModelsIcon, "/history": HistoryIcon, "/goal": GoalIcon, "/trigger": TriggerIcon, "/dream": DreamIcon, "/dream-log": DreamLogIcon, "/dream-restore": RestoreMemoryIcon, "/dream-prompt": PromptTemplateIcon, "/evaluator-prompt": PromptTemplateIcon, "/skill": SkillsIcon, "/help": HelpIcon, "/pairing": PairingIcon, }; const SLASH_PALETTE_GAP_PX = 8; const SLASH_PALETTE_MAX_HEIGHT_PX = 288; const SLASH_PALETTE_MIN_HEIGHT_PX = 144; const SLASH_PALETTE_CHROME_PX = 12; const SLASH_RECENTS_STORAGE_KEY = "nanobot.webui.slashCommandRecents"; const SLASH_RECENTS_LIMIT = 5; const SESSION_MENTIONS_LIMIT = 8; function VoiceRecordingMeter({ ariaLabel, className, elapsedLabel, isHero, levels, }: { ariaLabel: string; className?: string; elapsedLabel: string; isHero: boolean; levels: number[]; }) { return (
{levels.map((height, index) => ( ))} {elapsedLabel}
); } type SlashPalettePlacement = "above" | "below" | "beside"; interface SlashPaletteLayout { placement: SlashPalettePlacement; maxHeight: number; } interface CliAppMentionQuery { query: string; start: number; end: number; } type MentionCandidate = { name: string; displayName: string; } & ( | { kind: "session"; mention: SessionMention } | { kind: "cli" | "mcp"; brandColor: string | null; logoUrl: string | null; initials: string; } ); interface MentionInsertion { value: string; cursor: number; tokenStart: number; tokenEnd: number; } function mentionInsertion( value: string, name: string, start: number, end: number, ): MentionInsertion { const from = Math.min(Math.max(start, 0), value.length); const to = Math.min(Math.max(end, from), value.length); const prefix = value.slice(0, from); const suffix = value.slice(to); const leadingSpace = prefix && !isCapabilityMentionStart(value, from) ? " " : ""; const trailingSpace = /^\s/.test(suffix) ? "" : " "; const tokenStart = prefix.length + leadingSpace.length; const tokenEnd = tokenStart + name.length + 1; return { value: `${prefix}${leadingSpace}@${name}${trailingSpace}${suffix}`, cursor: tokenEnd + trailingSpace.length, tokenStart, tokenEnd, }; } function sessionMentionOptions(sessions: ChatSummary[]): SessionMention[] { return sessions.flatMap((session) => { if (!session.handle) return []; return [{ id: session.handle.id, name: session.handle.name, session_key: session.key, title: session.title?.trim() || session.preview.trim(), }]; }); } interface SlashPaletteCommand { command: string; title: string; description: string; icon: string; kind?: "skill"; argHint?: string; detail: string; badge?: string; recent: boolean; } function skillMatchRank(skill: SkillSummary, query: string): number | null { if (!query) return 0; const name = skill.name.toLowerCase(); if (name === query) return 0; if (name.startsWith(query)) return 1; if (name.includes(query)) return 2; if (skill.description.toLowerCase().includes(query)) return 3; return null; } function slashCommandI18nKey(command: string): string { return command.replace(/^\//, "").replace(/-/g, "_"); } function readSlashRecents(): string[] { if (typeof window === "undefined") return []; try { const raw = window.localStorage.getItem(SLASH_RECENTS_STORAGE_KEY); const parsed = raw ? JSON.parse(raw) : []; return Array.isArray(parsed) ? parsed.filter((item): item is string => typeof item === "string").slice(0, SLASH_RECENTS_LIMIT) : []; } catch { return []; } } function storeSlashRecents(commands: string[]): void { if (typeof window === "undefined") return; try { window.localStorage.setItem( SLASH_RECENTS_STORAGE_KEY, JSON.stringify(commands.slice(0, SLASH_RECENTS_LIMIT)), ); } catch { // localStorage may be unavailable in private contexts; command insertion still works. } } function queuedPromptLabel(prompt: QueuedPromptContent): string { const text = prompt.text.trim(); if (text) return text; return prompt.images?.map((img) => img.name).filter(Boolean).join(", ") || "File attachment"; } function visualViewportBounds(): { top: number; bottom: number; height: number } { const viewport = window.visualViewport; if (!viewport) { return { top: 0, bottom: window.innerHeight, height: window.innerHeight }; } const top = Math.max(0, viewport.offsetTop); const height = Math.max(0, viewport.height); return { top, bottom: top + height, height }; } function getVisibleBounds(el: HTMLElement): { top: number; bottom: number } { // The app already follows the visual viewport on touch browsers. Measure // its frame in the same coordinates as the composer, not WebKit's pan offset. // During pinch zoom the app stops fitting, so use the zoomed viewport again. const fittedRoot = window.visualViewport?.scale === 1 ? el.closest("#root.visual-viewport") : null; const viewport = fittedRoot?.getBoundingClientRect() ?? visualViewportBounds(); let top = viewport.top; let bottom = viewport.bottom; let parent = el.parentElement; while (parent) { const style = window.getComputedStyle(parent); if (/(auto|scroll|hidden|clip)/.test(style.overflowY)) { const rect = parent.getBoundingClientRect(); top = Math.max(top, rect.top); bottom = Math.min(bottom, rect.bottom); } parent = parent.parentElement; } return { top, bottom }; } function goalStateStripPreview( goal: GoalStateWsPayload | undefined, t: (key: string) => string, ): string | null { if (!goal?.active) return null; const summary = goal.ui_summary?.trim(); if (summary) return summary; const obj = goal.objective?.trim(); if (obj) return obj.length > 72 ? `${obj.slice(0, 72)}…` : obj; return t("thread.composer.goalStateFallback"); } const GOAL_PANEL_VIEWPORT_TOP_PAD = 20; const GOAL_PANEL_GAP_ABOVE_STRIP_PX = 10; const GOAL_PANEL_MIN_HEIGHT_PX = 112; const GOAL_PANEL_MAX_VIEWPORT_RATIO = 0.62; function measureGoalPanelMaxCssHeight(stripTopY: number): number { const viewport = visualViewportBounds(); const spaceAboveStrip = stripTopY - viewport.top - GOAL_PANEL_VIEWPORT_TOP_PAD - GOAL_PANEL_GAP_ABOVE_STRIP_PX; return Math.min( Math.max(spaceAboveStrip, GOAL_PANEL_MIN_HEIGHT_PX), Math.floor(viewport.height * GOAL_PANEL_MAX_VIEWPORT_RATIO), ); } function buildGoalMarkdownBody(summary: string, objective: string): string { const s = summary.trim(); const o = objective.trim(); if (s && o) return `${s}\n\n---\n\n${o}`; return o || s; } function cliAppMentionPayload(app: CliAppInfo): OutboundCliAppMention { return { name: app.name, display_name: app.display_name, category: app.category, entry_point: app.entry_point, logo_url: app.logo_url ?? null, brand_color: app.brand_color ?? null, }; } function mcpPresetMentionPayload(preset: McpPresetInfo): OutboundMcpPresetMention { return { name: preset.name, display_name: preset.display_name, category: preset.category, transport: preset.transport, status: preset.status, configured: preset.configured, logo_url: preset.logo_url ?? null, brand_color: preset.brand_color ?? null, }; } function GoalStateStrip({ goalState, }: { goalState?: GoalStateWsPayload; }) { const { t } = useTranslation(); const [goalPanelOpen, setGoalPanelOpen] = useState(false); const stripLabel = goalStateStripPreview(goalState, t); const active = !!stripLabel?.trim(); const [, setTick] = useState(0); const stripWrapperRef = useRef(null); const panelRef = useRef(null); const expandToggleRef = useRef(null); const stripSnapshotRef = useRef<{ goalState?: GoalStateWsPayload; stripLabel: string | null; } | null>(null); const [panelMaxPx, setPanelMaxPx] = useState(280); if (active) { stripSnapshotRef.current = { goalState, stripLabel }; } useEffect(() => { if (!active) setGoalPanelOpen(false); }, [active]); const display = active ? { goalState, stripLabel } : stripSnapshotRef.current; const displayGoalState = display?.goalState; const displayStripLabel = display?.stripLabel ?? null; const objectiveFull = displayGoalState?.objective?.trim() ?? ""; const summaryFull = displayGoalState?.ui_summary?.trim() ?? ""; const canExpandGoal = !!(active && displayGoalState?.active && (objectiveFull || summaryFull)); const markdownBody = objectiveFull || summaryFull ? buildGoalMarkdownBody(summaryFull, objectiveFull) : ""; useLayoutEffect(() => { if (!goalPanelOpen) return; function relayout(): void { const el = stripWrapperRef.current; if (!el) return; const top = el.getBoundingClientRect().top; setPanelMaxPx(measureGoalPanelMaxCssHeight(top)); } relayout(); void preloadMarkdownText(); const ro = typeof ResizeObserver !== "undefined" ? new ResizeObserver(() => relayout()) : null; if (stripWrapperRef.current && ro) { ro.observe(stripWrapperRef.current); } const viewport = window.visualViewport; viewport?.addEventListener("resize", relayout); viewport?.addEventListener("scroll", relayout); window.addEventListener("resize", relayout); window.addEventListener("scroll", relayout, true); return () => { ro?.disconnect(); viewport?.removeEventListener("resize", relayout); viewport?.removeEventListener("scroll", relayout); window.removeEventListener("resize", relayout); window.removeEventListener("scroll", relayout, true); }; }, [goalPanelOpen]); useEffect(() => { if (!goalPanelOpen) return; function onPointerDown(ev: MouseEvent): void { const target = ev.target as Node | null; if (!target) return; if (panelRef.current?.contains(target)) return; if (expandToggleRef.current?.contains(target)) return; setGoalPanelOpen(false); } function onKey(ev: KeyboardEvent): void { if (ev.key === "Escape") setGoalPanelOpen(false); } window.addEventListener("mousedown", onPointerDown); window.addEventListener("keydown", onKey); return () => { window.removeEventListener("mousedown", onPointerDown); window.removeEventListener("keydown", onKey); }; }, [goalPanelOpen]); if (!display) return null; const ariaLabel = displayStripLabel ? t("thread.composer.goalStateStrip", { label: displayStripLabel }) : t("thread.composer.goalStateFallback"); return (
{ if (active || event.target !== event.currentTarget) return; stripSnapshotRef.current = null; setTick((n) => n + 1); }} > {goalPanelOpen && canExpandGoal && markdownBody ? ( ) : null}
{display ? (
{displayStripLabel ? ( {t("thread.composer.goalStateStrip", { label: displayStripLabel })} ) : null} {canExpandGoal ? ( ) : null}
) : null}
); } function autosizeTextarea(input: HTMLTextAreaElement) { const container = input.parentElement!; const previousMinHeight = container.style.minHeight; // Measuring the one-row textarea must not expand the sibling transcript and // clamp its native scroll offset, even temporarily before paint. container.style.minHeight = `${container.getBoundingClientRect().height}px`; try { input.style.height = "auto"; input.style.height = `${Math.min(input.scrollHeight, 260)}px`; } finally { container.style.minHeight = previousMinHeight; } } export function ThreadComposer({ onSend, disabled, placeholder, inputAriaLabel, compactWhenIdle = false, isStreaming = false, activeTurnId = null, completedTurnIds, modelLabel = null, modelDetail = null, modelPreset = null, modelPresets = [], onModelPresetChange, modelProvider = null, modelProviderLabel = null, modelNeedsSetup = false, onModelBadgeClick, onManageModels, renderContextUsage, variant = "thread", slashCommands = [], onMentionSearch, cliApps = [], mcpPresets = [], sessions = [], skills = [], onStop, surfaceRef, onTranscribeAudio, onInspectAttachment, goalState, workspaceScope = null, workspaceControlsHidden = false, workspacePickerLayoutAnchor, workspaceDefaultScope = null, workspaceControls = null, workspaceScopeDisabled = false, workspaceProjectLocked = false, workspaceError = null, onLoadWorkspaceProjects, onResolveWorkspaceProject, onFavoriteWorkspaceProject, onBrowseWorkspaceDirectories, onWorkspaceScopeChange, pendingQueueKey = null, draftKey, draftStore, persistDraft = false, transcriptionProvider = null, ingressLimits = null, quotedContext = null, focusRequest = 0, onQuotedContextChange, }: ThreadComposerProps) { const { t } = useTranslation(); const [initialDraft] = useState(() => draftKey ? draftStore?.get(draftKey, persistDraft) : undefined); const [value, setValue] = useState(initialDraft?.text ?? ""); const [composerFocused, setComposerFocused] = useState(false); const [compactPlaceholder, setCompactPlaceholder] = useState(false); const [placeholderHintRequested, setPlaceholderHintRequested] = useState(false); const [placeholderHintOpen, setPlaceholderHintOpen] = useState(false); const [placeholderHintBottomGap, setPlaceholderHintBottomGap] = useState(0); const blurFrame = useRef(null); const [boundSessionMentions, setBoundSessionMentions] = useState( initialDraft?.sessionMentions ?? [], ); const [sessionDragPreview, setSessionDragPreview] = useState<{ mention: SessionMention; start: number; end: number; } | null>(null); const [inlineError, setInlineError] = useState(null); const [sendPending, setSendPending] = useState(false); const [pathInspection, setPathInspection] = useState<{ generation: number; scope: string; range: PastedPathRange; attachment?: LocalAttachment; } | null>(null); const pathCheckGeneration = useRef(0); const pathCheckScope = useRef(""); const scopeIdentity = `${workspaceScope?.project_path ?? ""}:${workspaceScope?.access_mode ?? ""}`; pathCheckScope.current = scopeIdentity; useEffect(() => () => { pathCheckGeneration.current += 1; }, []); const [modelSetupAttentionRequest, setModelSetupAttentionRequest] = useState(0); const textareaRef = useRef(null); const focusTextarea = useCallback(() => { requestAnimationFrame(() => textareaRef.current?.focus()); }, []); const maxAttachments = ingressLimits?.attachments.max_count ?? MAX_ATTACHMENTS_PER_MESSAGE; const maxFileBytes = ingressLimits?.attachments.max_file_bytes ?? MAX_ATTACHMENT_BYTES; const maxTextBytes = ingressLimits?.message.max_text_bytes ?? 64 * 1024; const formatRejection = useCallback( (reason: Exclude): string => { const key = `thread.composer.imageRejected.${reason}`; const fallback = reason === "too_many_videos" ? "Max 1 video per message" : reason === "too_many_attachments" ? `Max ${maxAttachments} attachments per message` : reason === "empty_file" ? "Empty files cannot be attached" : reason === "total_too_large" ? "Attachments are too large together — remove some or use smaller files" : "Unsupported file type"; return t(key, { max: maxAttachments, defaultValue: fallback }); }, [maxAttachments, t], ); const formatUploadTooLarge = useCallback( (size: number, maximum: number) => t("thread.composer.imageRejected.too_large", { size: formatBytes(size), max: formatBytes(maximum), }), [t], ); const textTooLargeMessage = useCallback( () => t("thread.composer.textTooLarge", { max: formatBytes(maxTextBytes), defaultValue: `Message text is too large (max ${formatBytes(maxTextBytes)})`, }), [maxTextBytes, t], ); const queuedPromptError = useCallback((prompt: QueuedPromptContent): string | null => { if (utf8Bytes(formatQuotedUserMessage(prompt.text, prompt.quotedContext)) > maxTextBytes) { return textTooLargeMessage(); } const attachments = prompt.images ?? []; const videos = attachments.filter((item) => item.kind === "video").length; if (videos > MAX_VIDEOS_PER_MESSAGE) return formatRejection("too_many_videos"); if (attachments.length - videos > maxAttachments) return formatRejection("too_many_attachments"); const oversized = attachments.find((item) => queuedUploadBytes(item) > (item.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes)); if (oversized) { return formatUploadTooLarge(queuedUploadBytes(oversized), oversized.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes); } const total = attachments.reduce((sum, item) => sum + (item.kind === "video" ? 0 : queuedUploadBytes(item)), 0); if (total > (ingressLimits?.attachments.max_total_bytes ?? MAX_TOTAL_ATTACHMENT_BYTES)) { return formatRejection("total_too_large"); } if ((prompt.sessionMentions?.length ?? 0) > SESSION_MENTIONS_LIMIT) { return t("thread.composer.queued.tooManyMentions", { max: SESSION_MENTIONS_LIMIT }); } return null; }, [formatRejection, formatUploadTooLarge, ingressLimits, maxAttachments, maxFileBytes, maxTextBytes, t, textTooLargeMessage]); const { snapshot: queueSnapshot, collect: collectQueuedPrompt, enqueue: enqueueQueuedPrompt, clear: clearQueuedPrompt, pause: pauseQueue, send: sendQueuedPrompt, } = useQueuedPrompt(pendingQueueKey, { isStreaming, activeTurnId, completedTurnIds }, { disabled: !!disabled || sendPending, onSend, validate: queuedPromptError, onValidationError: setInlineError, onSendAttempt: focusTextarea, }); const queuedPrompt = queueSnapshot.prompt; const interactionDisabled = !!disabled || sendPending || queueSnapshot.sending; useEffect(() => { if (queueSnapshot.error) setInlineError(queueSnapshot.error); }, [queueSnapshot.error]); const [voiceErrorFading, setVoiceErrorFading] = useState(false); const [slashMenuDismissed, setSlashMenuDismissed] = useState(false); const [selectedCommandIndex, setSelectedCommandIndex] = useState(0); const [cliAppMenuDismissed, setCliAppMenuDismissed] = useState(false); const [selectedCliAppIndex, setSelectedCliAppIndex] = useState(0); const [cursorPosition, setCursorPosition] = useState(0); const [recentSlashCommands, setRecentSlashCommands] = useState(() => readSlashRecents()); const hasTouchPrimaryPointer = useMediaQuery("(hover: none) and (pointer: coarse)"); // Coarser than hasTouchPrimaryPointer on purpose: tablets with a physical // keyboard still get the newline-on-Enter behavior. const hasCoarsePointer = useMediaQuery("(pointer: coarse)"); const mobileWorkspaceControls = useMediaQuery("(max-width: 639px)"); const { readingTextSize, customReadingTextSize } = useLocalPreferences(); const placeholderMeasureRef = useRef(null); const mentionOverlayRef = useRef(null); const formRef = useRef(null); const tabFocusRequested = useRef(false); const [compactControls, setCompactControls] = useState(false); useEffect(() => { // Automatic session focus should not open the hint; keyboard navigation should. const onKeyDown = (event: KeyboardEvent) => { tabFocusRequested.current = event.key === "Tab"; }; const onPointerDown = () => { tabFocusRequested.current = false; }; document.addEventListener("keydown", onKeyDown, true); document.addEventListener("pointerdown", onPointerDown, true); return () => { document.removeEventListener("keydown", onKeyDown, true); document.removeEventListener("pointerdown", onPointerDown, true); }; }, []); useLayoutEffect(() => { const form = formRef.current; if (!form) return; let previousWidth = 0; const update = () => { const width = form.getBoundingClientRect().width; if (width <= 0 || width === previousWidth) return; previousWidth = width; setCompactControls(width <= 512); const input = textareaRef.current; if (input) autosizeTextarea(input); }; update(); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(update); observer?.observe(form); window.addEventListener("resize", update); return () => { observer?.disconnect(); window.removeEventListener("resize", update); }; }, []); const fileInputRef = useRef(null); const chipRefs = useRef(new Map()); const previousPendingQueueKeyRef = useRef(pendingQueueKey); const voiceShortcutDownRef = useRef(false); const voiceErrorFadeTimerRef = useRef | null>(null); const isHero = variant === "hero"; const voiceShortcutLabel = useMemo(getVoiceShortcutLabel, []); const projectPickerAvailable = !workspaceProjectLocked && !!workspaceDefaultScope && !!onWorkspaceScopeChange && !!onLoadWorkspaceProjects && !!onBrowseWorkspaceDirectories && !!onResolveWorkspaceProject && !!onFavoriteWorkspaceProject && workspaceControls?.can_change_project !== false; const showProjectPicker = projectPickerAvailable && !workspaceControlsHidden; const resolvedPlaceholder = placeholder ?? t("thread.composer.placeholder"); const showCompactPlaceholder = placeholder === undefined && compactPlaceholder; const displayedPlaceholder = showCompactPlaceholder ? t("thread.composer.placeholderCompact") : resolvedPlaceholder; useLayoutEffect(() => { const input = textareaRef.current; const text = placeholderMeasureRef.current; if (!input || !text || placeholder !== undefined) return; const measure = () => { const style = getComputedStyle(input); const available = input.clientWidth - parseFloat(style.paddingLeft) - parseFloat(style.paddingRight); if (available > 0) setCompactPlaceholder(text.getBoundingClientRect().width > available); }; measure(); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure); observer?.observe(input); observer?.observe(text); window.addEventListener("resize", measure); let active = true; void document.fonts?.ready.then(() => { if (active) measure(); }); return () => { active = false; observer?.disconnect(); window.removeEventListener("resize", measure); }; }, [placeholder, resolvedPlaceholder, compactControls, readingTextSize, customReadingTextSize]); const { images, enqueue, addLocal, remove, clear, restoreReadyImages, encoding: encodingFiles, full } = useAttachedImages({ ingressLimits }); const encoding = encodingFiles || pathInspection !== null; const restoredDraftAttachments = useRef(false); const [draftAttachmentsReady, setDraftAttachmentsReady] = useState(!initialDraft?.attachments.length); useLayoutEffect(() => { if (restoredDraftAttachments.current) return; restoredDraftAttachments.current = true; for (const attachment of initialDraft?.attachments ?? []) { if (attachment instanceof File) enqueue([attachment], { restoringDraft: true }); else addLocal(attachment, { restoringDraft: true }); } setDraftAttachmentsReady(true); }, [enqueue, addLocal, initialDraft]); const addFiles = useCallback( (files: File[]) => { if (interactionDisabled || files.length === 0) return; const { rejected } = enqueue(files); if (rejected.length > 0) { const { reason, file } = rejected[0]; setInlineError(reason === "too_large" ? formatUploadTooLarge(file.size, acceptedAttachmentKind(file) === "video" ? MAX_VIDEO_BYTES : maxFileBytes) : formatRejection(reason)); } else { setInlineError(null); } }, [enqueue, formatRejection, formatUploadTooLarge, interactionDisabled, maxFileBytes], ); const { isDragging, onPaste: onAttachmentPaste, onDragEnter, onDragOver, onDragLeave, onDrop, } = useClipboardAndDrop(addFiles); useEffect(() => { if (compactWhenIdle || interactionDisabled || hasTouchPrimaryPointer || (workspaceError && showProjectPicker)) { return; } const el = textareaRef.current; if (!el) return; const id = requestAnimationFrame(() => el.focus()); return () => cancelAnimationFrame(id); }, [compactWhenIdle, hasTouchPrimaryPointer, interactionDisabled, showProjectPicker, workspaceError]); useEffect(() => () => { if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current); }, []); useEffect(() => { if (!focusRequest || interactionDisabled) return; const id = requestAnimationFrame(() => textareaRef.current?.focus()); return () => cancelAnimationFrame(id); }, [focusRequest, interactionDisabled]); const normalizedQuotedContext = quotedContext?.trim() || null; const readyImages = useMemo( () => images.filter((img) => img.status === "ready" && (typeof img.dataUrl === "string" || !!img.local), ), [images], ); const hasErrors = images.some((img) => img.status === "error"); const isUserShell = value.trimStart().startsWith("!"); const requiresModelSetup = modelNeedsSetup && !isUserShell; const hasComposerContent = value.trim().length > 0 || readyImages.length > 0; const canSend = !interactionDisabled && !requiresModelSetup && !encoding && !hasErrors && hasComposerContent; const canOpenModelSettings = Boolean( requiresModelSetup && onModelBadgeClick && !interactionDisabled, ); const canQueueGuidance = isStreaming && !isUserShell && !interactionDisabled && !modelNeedsSetup && !encoding && !hasErrors && hasComposerContent // Without command metadata, let the gateway classify slash input immediately. && (slashCommands.length > 0 ? !isRegisteredSlashCommand(value, slashCommands) : !value.trimStart().startsWith("/")); const slashQuery = useMemo(() => { if (interactionDisabled || slashMenuDismissed || !value.startsWith("/")) return null; const commandToken = value.slice(1); if (/\s/.test(commandToken)) return null; return commandToken.toLowerCase(); }, [interactionDisabled, slashMenuDismissed, value]); const skillQuery = useMemo(() => { if (interactionDisabled || isUserShell || slashMenuDismissed) return null; const caret = Math.min(Math.max(cursorPosition, 0), value.length); const beforeCaret = value.slice(0, caret); const match = /\$([A-Za-z0-9_-]*)$/i.exec(beforeCaret); if (!match) return null; return { end: caret, start: match.index, text: match[1].toLowerCase(), }; }, [cursorPosition, interactionDisabled, isUserShell, slashMenuDismissed, value]); const skillMenuActive = skillQuery !== null; useEffect(() => { // Also refresh an empty menu: skills may have been installed by the agent. if (skillMenuActive) requestSkillsRefresh(); }, [skillMenuActive]); const visibleSlashCommands = useMemo(() => { if (!(isStreaming && onStop)) return slashCommands; const stopCommand = slashCommands.find((command) => command.command === "/stop"); if (!stopCommand) return slashCommands; return [ stopCommand, ...slashCommands.filter((command) => command.command !== "/stop"), ]; }, [isStreaming, onStop, slashCommands]); const filteredSlashCommands = useMemo(() => { if (skillQuery !== null) { const query = skillQuery.text; return skills .filter((skill) => skill.enabled !== false && skill.available) .flatMap((skill) => { const matchRank = skillMatchRank(skill, query); return matchRank === null ? [] : [{ command: `$${skill.name}`, matchRank, skill, }]; }) .sort((a, b) => { if (a.matchRank !== b.matchRank) return a.matchRank - b.matchRank; if (query !== "") return 0; const aRecent = recentSlashCommands.indexOf(a.command); const bRecent = recentSlashCommands.indexOf(b.command); if (aRecent === -1 && bRecent === -1) return 0; if (aRecent === -1) return 1; if (bRecent === -1) return -1; return aRecent - bRecent; }) .slice(0, 8) .map(({ command, skill }) => { const description = skill.description || skill.name; return { command, title: skill.name, description, detail: description, icon: "brain", kind: "skill" as const, recent: recentSlashCommands.includes(command), }; }); } if (slashQuery === null) return []; const withDetails = visibleSlashCommands .filter((command) => { if ( slashQuery === "" && ( command.command === "/restart" || (command.command === "/stop" && !(isStreaming && onStop)) ) ) { return false; } const commandKey = slashCommandI18nKey(command.command); const title = t(`thread.composer.slash.commands.${commandKey}.title`, { defaultValue: command.title, }); const description = t(`thread.composer.slash.commands.${commandKey}.description`, { defaultValue: command.description, }); const haystack = [ command.command, command.title, command.description, command.argHint ?? "", title, description, ].join(" ").toLowerCase(); return haystack.includes(slashQuery); }) .map((command) => { const commandKey = slashCommandI18nKey(command.command); const description = t(`thread.composer.slash.commands.${commandKey}.description`, { defaultValue: command.description, }); let detail = description; let badge: string | undefined; if (command.command === "/model" && modelLabel) { detail = modelLabel; badge = t("thread.composer.slash.badges.current"); } else if (command.command === "/goal") { detail = goalState?.active ? t("thread.composer.slash.details.goalActive") : t("thread.composer.slash.details.goalReady"); } else if (command.command === "/stop" && isStreaming) { detail = t("thread.composer.slash.details.stopRunning"); } else if (command.command === "/history") { detail = t("thread.composer.slash.details.history"); } return { ...command, detail, badge, recent: recentSlashCommands.includes(command.command), }; }) .sort((a, b) => { if (isStreaming) { if (a.command === "/stop") return -1; if (b.command === "/stop") return 1; } if (slashQuery !== "") return 0; const aRecent = recentSlashCommands.indexOf(a.command); const bRecent = recentSlashCommands.indexOf(b.command); if (aRecent !== -1 || bRecent !== -1) { if (aRecent === -1) return 1; if (bRecent === -1) return -1; return aRecent - bRecent; } return 0; }); return withDetails .slice(0, 8); }, [goalState?.active, isStreaming, modelLabel, recentSlashCommands, skills, skillQuery, slashQuery, t, visibleSlashCommands]); const showSlashMenu = filteredSlashCommands.length > 0; const cliAppMention = useMemo(() => { if (interactionDisabled || isUserShell || cliAppMenuDismissed) return null; const caret = Math.min(Math.max(cursorPosition, 0), value.length); const beforeCaret = value.slice(0, caret); const match = /@([\p{L}\p{N}_-]*)$/iu.exec(beforeCaret); if (!match || !isCapabilityMentionStart(value, match.index)) return null; const query = match[1].toLowerCase(); return { query, start: match.index, end: caret, }; }, [cliAppMenuDismissed, cursorPosition, interactionDisabled, isUserShell, value]); const mentionSearchActive = cliAppMention !== null; useEffect(() => { if (mentionSearchActive) onMentionSearch?.(); }, [mentionSearchActive, onMentionSearch]); const availableSessionMentions = useMemo( () => sessionMentionOptions(sessions), [sessions], ); const sessionMentionCatalog = useMemo( () => [...availableSessionMentions, ...boundSessionMentions], [availableSessionMentions, boundSessionMentions], ); const mentionSegments = useMemo( () => isUserShell ? [{ kind: "text", text: value }] : splitCapabilityMentionSegments(value, cliApps, mcpPresets, sessionMentionCatalog), [cliApps, isUserShell, mcpPresets, sessionMentionCatalog, value], ); const editMentionInput = useCallback((next: string, cursor: number) => { setValue(next); setSlashMenuDismissed(false); setCliAppMenuDismissed(false); setCursorPosition(cursor); }, []); const mentionInput = useComposerMentionInput({ segments: mentionSegments, inputRef: textareaRef, onEdit: editMentionInput, resetKey: pendingQueueKey, }); const { rawSelection, replace: replaceMentionInput } = mentionInput; const onPaste = useCallback((event: React.ClipboardEvent) => { onAttachmentPaste(event); if (event.defaultPrevented || interactionDisabled || isUserShell || !onInspectAttachment) return; const raw = event.clipboardData.getData("text/plain"); const path = pastedFilePath(raw); if (!path) return; event.preventDefault(); const { start, end } = rawSelection(); const pasted = value.slice(0, start) + raw + value.slice(end); const generation = ++pathCheckGeneration.current; replaceMentionInput(pasted, start + raw.length); setPathInspection({ generation, scope: scopeIdentity, range: new PastedPathRange(pasted, start, start + raw.length) }); void onInspectAttachment(path).then((attachment) => { if (generation !== pathCheckGeneration.current) return; setPathInspection((current) => current?.generation === generation ? { ...current, attachment } : current); }).catch((error: unknown) => { if (generation !== pathCheckGeneration.current || pathCheckScope.current !== scopeIdentity) return; setPathInspection(null); if (error instanceof Error && "status" in error && error.status === 404) return; setInlineError(error instanceof Error ? error.message : t("message.attachmentUnavailable")); }); }, [interactionDisabled, isUserShell, onAttachmentPaste, onInspectAttachment, rawSelection, replaceMentionInput, scopeIdentity, t, value]); useLayoutEffect(() => { if (!pathInspection) return; if (isUserShell || pathInspection.scope !== scopeIdentity || !pathInspection.range.update(value)) { pathCheckGeneration.current += 1; setPathInspection(null); return; } // Let the native IME commit before removing the confirmed path from its text. if (!pathInspection.attachment || mentionInput.isComposing) return; const edited = pathInspection.range.replace("", rawSelection().start); if (edited) { const rejection = addLocal(pathInspection.attachment); if (rejection) setInlineError(formatRejection(rejection)); else { replaceMentionInput(edited.value, edited.cursor, { preserveFocus: true }); setInlineError(null); } } setPathInspection(null); }, [addLocal, formatRejection, isUserShell, mentionInput.isComposing, pathInspection, rawSelection, replaceMentionInput, scopeIdentity, value]); const draftText = composerMentionText(mentionInput.segments).raw; const sessionDragInsertion = sessionDragPreview ? mentionInsertion( value, sessionDragPreview.mention.name, sessionDragPreview.start, sessionDragPreview.end, ) : null; const displayMentionSegments = sessionDragInsertion && sessionDragPreview ? splitCapabilityMentionSegments( sessionDragInsertion.value, cliApps, mcpPresets, sessionMentionCatalog, ) : mentionInput.segments; const activeSessionMentions = useMemo(() => { const seen = new Set(); return mentionSegments.flatMap((segment) => { if (segment.kind !== "session" || seen.has(segment.mention.session_key)) return []; seen.add(segment.mention.session_key); return [segment.mention]; }); }, [mentionSegments]); useLayoutEffect(() => { // Pin resolved identities so a catalog refresh cannot retarget an existing reference. if (activeSessionMentions.length !== boundSessionMentions.length || activeSessionMentions.some((mention, index) => mention !== boundSessionMentions[index])) { setBoundSessionMentions(activeSessionMentions); } }, [activeSessionMentions, boundSessionMentions]); useLayoutEffect(() => { if (!draftKey || !draftStore || !draftAttachmentsReady) return; if (!draftText && images.length === 0 && !quotedContext) { draftStore.delete(draftKey); return; } draftStore.set(draftKey, { text: draftText, attachments: images.flatMap((image): ComposerDraft["attachments"] => ( image.local ? [image.local] : image.file instanceof File ? [image.file] : [] )), sessionMentions: activeSessionMentions, quotedContext, }, persistDraft); }, [activeSessionMentions, draftAttachmentsReady, draftKey, draftStore, images, persistDraft, quotedContext, draftText]); const insertableSessionMentions = useMemo(() => availableSessionMentions.filter((mention) => { const bound = activeSessionMentions.find( (active) => active.name.toLowerCase() === mention.name.toLowerCase(), ); return (!bound || bound.session_key === mention.session_key) && (activeSessionMentions.length < SESSION_MENTIONS_LIMIT || activeSessionMentions.some((active) => active.session_key === mention.session_key)); }), [activeSessionMentions, availableSessionMentions]); const filteredMentionCandidates = useMemo(() => { if (!cliAppMention) return []; const sessionCandidates: MentionCandidate[] = insertableSessionMentions .filter((mention) => [ mention.name, mention.title, ].join(" ").toLowerCase().includes(cliAppMention.query)) .map((mention) => ({ kind: "session", name: mention.name, displayName: mention.title || mention.name, mention, })); const sessionNames = new Set( sessionMentionCatalog.map((mention) => mention.name.toLowerCase()), ); const cliCandidates: MentionCandidate[] = cliApps .filter((app) => app.installed) .filter((app) => !sessionNames.has(app.name.toLowerCase())) .filter((app) => { const haystack = [ app.name, app.display_name, app.category, app.description, app.entry_point, ].join(" ").toLowerCase(); return haystack.includes(cliAppMention.query); }) .map((app) => ({ kind: "cli", name: app.name, displayName: app.display_name, brandColor: app.brand_color ?? null, logoUrl: app.logo_url ?? null, initials: cliAppInitials(app), })); const mcpCandidates: MentionCandidate[] = mcpPresets .filter((preset) => preset.installed && preset.configured) .filter((preset) => !sessionNames.has(preset.name.toLowerCase())) .filter((preset) => { const haystack = [ preset.name, preset.display_name, preset.category, preset.description, preset.transport, ].join(" ").toLowerCase(); return haystack.includes(cliAppMention.query); }) .map((preset) => ({ kind: "mcp", name: preset.name, displayName: preset.display_name, brandColor: preset.brand_color ?? null, logoUrl: preset.logo_url ?? null, initials: mcpPresetInitials(preset), })); const groups = [ { candidates: sessionCandidates, reserved: 4 }, { candidates: cliCandidates, reserved: 2 }, { candidates: mcpCandidates, reserved: 2 }, ]; let remaining = 8; const counts = groups.map(({ candidates, reserved }) => { const count = Math.min(candidates.length, reserved); remaining -= count; return count; }); for (const index of [0, 1, 2]) { const extra = Math.min(remaining, groups[index].candidates.length - counts[index]); counts[index] += extra; remaining -= extra; } return groups.flatMap(({ candidates }, index) => candidates.slice(0, counts[index])); }, [cliAppMention, cliApps, insertableSessionMentions, mcpPresets, sessionMentionCatalog]); const showCliAppMenu = filteredMentionCandidates.length > 0; const showAnyPalette = showSlashMenu || showCliAppMenu; const inlineSegments = useMemo( () => isUserShell ? displayMentionSegments : withSkillReferences(displayMentionSegments), [displayMentionSegments, isUserShell], ); const slashCommand = matchingSlashCommand(sessionDragInsertion?.value ?? draftText, slashCommands); const hasInlineDecorations = isUserShell || slashCommand !== null || inlineSegments.some((segment) => segment.kind !== "text"); const activeCliMentionApps = useMemo(() => { const seen = new Set(); return mentionSegments.flatMap((segment) => { if (segment.kind !== "cli" || seen.has(segment.app.name)) return []; seen.add(segment.app.name); return [segment.app]; }); }, [mentionSegments]); const activeMcpPresetMentions = useMemo(() => { const seen = new Set(); return mentionSegments.flatMap((segment) => { if (segment.kind !== "mcp" || seen.has(segment.preset.name)) return []; seen.add(segment.preset.name); return [segment.preset]; }); }, [mentionSegments]); const [slashPaletteLayout, setSlashPaletteLayout] = useState({ placement: "above", maxHeight: SLASH_PALETTE_MAX_HEIGHT_PX, }); useEffect(() => { setSelectedCommandIndex(0); }, [slashQuery]); useEffect(() => { setSelectedCliAppIndex(0); }, [cliAppMention?.query]); useEffect(() => { if (selectedCommandIndex >= filteredSlashCommands.length) { setSelectedCommandIndex(0); } }, [filteredSlashCommands.length, selectedCommandIndex]); useEffect(() => { if (selectedCliAppIndex >= filteredMentionCandidates.length) { setSelectedCliAppIndex(0); } }, [filteredMentionCandidates.length, selectedCliAppIndex]); useEffect(() => { if (!showAnyPalette) return; const dismissOnPointerDown = (event: PointerEvent) => { const target = event.target; if (target instanceof Node && formRef.current?.contains(target)) return; setSlashMenuDismissed(true); setCliAppMenuDismissed(true); }; document.addEventListener("pointerdown", dismissOnPointerDown, true); return () => { document.removeEventListener("pointerdown", dismissOnPointerDown, true); }; }, [showAnyPalette]); useLayoutEffect(() => { if (!showAnyPalette) return; const updateLayout = () => { const form = formRef.current; if (!form) return; const rect = form.getBoundingClientRect(); if (rect.width === 0 && rect.height === 0) return; const bounds = getVisibleBounds(form); const spaceAbove = Math.max(0, rect.top - bounds.top - SLASH_PALETTE_GAP_PX); const spaceBelow = Math.max(0, bounds.bottom - rect.bottom - SLASH_PALETTE_GAP_PX); // A landscape keyboard can leave less height than one input and option. // Use the available width instead of clipping an absolute menu in the // short viewport's scrollable composer footer. const beside = rect.width >= 640 && !!form.closest("#root.short-visual-viewport"); const placement: SlashPalettePlacement = beside ? "beside" : spaceAbove >= SLASH_PALETTE_MIN_HEIGHT_PX || spaceAbove >= spaceBelow ? "above" : "below"; const available = beside ? Math.max(0, bounds.bottom - bounds.top) : placement === "above" ? spaceAbove : spaceBelow; const maxHeight = Math.min(SLASH_PALETTE_MAX_HEIGHT_PX, available); setSlashPaletteLayout((current) => current.placement === placement && current.maxHeight === maxHeight ? current : { placement, maxHeight }, ); }; updateLayout(); const viewport = window.visualViewport; viewport?.addEventListener("resize", updateLayout); viewport?.addEventListener("scroll", updateLayout); window.addEventListener("resize", updateLayout); document.addEventListener("scroll", updateLayout, true); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(updateLayout); if (formRef.current) observer?.observe(formRef.current); return () => { observer?.disconnect(); viewport?.removeEventListener("resize", updateLayout); viewport?.removeEventListener("scroll", updateLayout); window.removeEventListener("resize", updateLayout); document.removeEventListener("scroll", updateLayout, true); }; }, [filteredMentionCandidates.length, filteredSlashCommands.length, showAnyPalette]); useLayoutEffect(() => { const el = textareaRef.current; if (!el || mentionInput.isComposing) return; autosizeTextarea(el); if (mentionOverlayRef.current) mentionOverlayRef.current.scrollTop = el.scrollTop; }, [compactControls, mentionInput.isComposing, mentionInput.value]); useEffect(() => { // The parent projects typography tokens in its layout effect; measure after it. const input = textareaRef.current; if (input) autosizeTextarea(input); }, [readingTextSize, customReadingTextSize]); useLayoutEffect(() => { const input = textareaRef.current; if (!input || document.activeElement !== input || !placeholderHintRequested || input.value || !input.placeholder) { setPlaceholderHintOpen(false); return; } const form = formRef.current!; const measure = () => { setPlaceholderHintOpen(showCompactPlaceholder || input.scrollWidth > input.clientWidth); setPlaceholderHintBottomGap(form.getBoundingClientRect().bottom - input.getBoundingClientRect().bottom); }; measure(); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure); observer?.observe(input); observer?.observe(form); let active = true; void document.fonts?.ready.then(() => { if (active) measure(); }); return () => { active = false; observer?.disconnect(); }; }, [placeholderHintRequested, mentionInput.value, resolvedPlaceholder, showCompactPlaceholder, sessionDragPreview, readingTextSize, customReadingTextSize]); // Runs before paint so switching sessions never flashes stale draft text. useLayoutEffect(() => { if (previousPendingQueueKeyRef.current === pendingQueueKey) return; previousPendingQueueKeyRef.current = pendingQueueKey; setValue(""); setInlineError(null); setSlashMenuDismissed(false); setCliAppMenuDismissed(false); setCursorPosition(0); clear(); }, [clear, pendingQueueKey]); const appendTranscription = useCallback((text: string) => { const transcript = text.trim(); if (!transcript) return; setValue((current) => { if (!current.trim()) return transcript; const separator = /[\s\n]$/.test(current) ? "" : " "; return `${current}${separator}${transcript}`; }); setSlashMenuDismissed(false); setCliAppMenuDismissed(false); setInlineError(null); focusTextarea(); }, [focusTextarea]); const clearVoiceErrorTimers = useCallback(() => { if (voiceErrorFadeTimerRef.current !== null) clearTimeout(voiceErrorFadeTimerRef.current); voiceErrorFadeTimerRef.current = null; }, []); const clearInlineError = useCallback(() => { clearVoiceErrorTimers(); setVoiceErrorFading(false); setInlineError(null); }, [clearVoiceErrorTimers]); const setVoiceError = useCallback((key: VoiceRecorderErrorKey) => { clearVoiceErrorTimers(); setVoiceErrorFading(false); setInlineError(t(`thread.composer.voiceErrors.${key}`)); voiceErrorFadeTimerRef.current = setTimeout(() => { setVoiceErrorFading(true); voiceErrorFadeTimerRef.current = setTimeout(() => { setInlineError(null); setVoiceErrorFading(false); voiceErrorFadeTimerRef.current = null; }, VOICE_ERROR_FADE_MS); }, VOICE_ERROR_VISIBLE_MS); }, [clearVoiceErrorTimers, t]); const voiceRecorder = useVoiceRecorder({ disabled: interactionDisabled, onClearError: clearInlineError, onError: setVoiceError, onTranscript: appendTranscription, onTranscribeAudio, wantsWav: transcriptionProvider === "xiaomi_mimo", }); useEffect(() => () => clearVoiceErrorTimers(), [clearVoiceErrorTimers]); useEffect(() => { if (!onTranscribeAudio) return; function onKeyDown(event: KeyboardEvent): void { if (!isVoiceShortcutDown(event) || event.repeat || voiceShortcutDownRef.current) return; event.preventDefault(); voiceShortcutDownRef.current = true; voiceRecorder.beginShortcutHold(); } function onKeyUp(event: KeyboardEvent): void { if (!voiceShortcutDownRef.current || !isVoiceShortcutRelease(event)) return; event.preventDefault(); voiceShortcutDownRef.current = false; voiceRecorder.endShortcutHold(); } function onWindowBlur(): void { if (!voiceShortcutDownRef.current) return; voiceShortcutDownRef.current = false; voiceRecorder.endShortcutHold(); } window.addEventListener("keydown", onKeyDown); window.addEventListener("keyup", onKeyUp); window.addEventListener("blur", onWindowBlur); return () => { window.removeEventListener("keydown", onKeyDown); window.removeEventListener("keyup", onKeyUp); window.removeEventListener("blur", onWindowBlur); }; }, [onTranscribeAudio, voiceRecorder.beginShortcutHold, voiceRecorder.endShortcutHold]); const handleStop = useCallback(() => { pauseQueue(); onStop?.(); }, [onStop, pauseQueue]); const chooseSlashCommand = useCallback( (command: SlashPaletteCommand) => { if (command.command === "/stop" && isStreaming && onStop) { handleStop(); setValue(""); setSlashMenuDismissed(true); setCliAppMenuDismissed(false); setInlineError(null); focusTextarea(); return; } const nextRecents = [ command.command, ...recentSlashCommands.filter((item) => item !== command.command), ].slice(0, SLASH_RECENTS_LIMIT); setRecentSlashCommands(nextRecents); storeSlashRecents(nextRecents); if (skillQuery !== null) { const suffix = value.slice(skillQuery.end); const inserted = `${command.command}${suffix.startsWith(" ") ? "" : " "}`; const next = `${value.slice(0, skillQuery.start)}${inserted}${suffix}`; const nextCursor = skillQuery.start + inserted.length; replaceMentionInput(next, nextCursor); } else { setValue(command.argHint ? `${command.command} ` : command.command); } setSlashMenuDismissed(true); setCliAppMenuDismissed(false); setInlineError(null); focusTextarea(); }, [handleStop, isStreaming, onStop, recentSlashCommands, replaceMentionInput, focusTextarea, skillQuery, value], ); const insertMention = useCallback( (name: string, start: number, end: number) => { const insertion = mentionInsertion(value, name, start, end); replaceMentionInput(insertion.value, insertion.cursor); setCliAppMenuDismissed(true); setSlashMenuDismissed(false); setInlineError(null); focusTextarea(); }, [replaceMentionInput, focusTextarea, value], ); const chooseMentionCandidate = useCallback( (candidate: MentionCandidate) => { if (!cliAppMention) return; insertMention(candidate.name, cliAppMention.start, cliAppMention.end); }, [cliAppMention, insertMention], ); const handleSessionDrop = useCallback((event: React.DragEvent) => { if (!hasDraggedSession(event.dataTransfer)) return false; event.preventDefault(); clearDraggedSession(); const preview = sessionDragPreview; setSessionDragPreview(null); if (interactionDisabled) return true; const sessionKey = readDraggedSession(event.dataTransfer); const mention = insertableSessionMentions.find( (candidate) => candidate.session_key === (sessionKey ?? preview?.mention.session_key), ); if (!mention) return true; const caret = preview?.start ?? rawSelection().start; insertMention(mention.name, caret, preview?.end ?? rawSelection().end); return true; }, [insertableSessionMentions, insertMention, interactionDisabled, rawSelection, sessionDragPreview]); const previewSessionDrop = useCallback((event: React.DragEvent) => { if (!hasDraggedSession(event.dataTransfer)) return false; if (interactionDisabled) { event.dataTransfer.dropEffect = "none"; setSessionDragPreview(null); return true; } const sessionKey = readDraggedSession(event.dataTransfer); const mention = insertableSessionMentions.find( (candidate) => candidate.session_key === sessionKey, ); if (!mention) { event.dataTransfer.dropEffect = "none"; setSessionDragPreview(null); return true; } event.preventDefault(); event.dataTransfer.dropEffect = "copy"; const { start, end } = rawSelection(); setSessionDragPreview((current) => ( current?.mention.session_key === mention.session_key && current.start === start && current.end === end ? current : { mention, start, end } )); return true; }, [insertableSessionMentions, interactionDisabled, rawSelection]); useEffect(() => { if (!sessionDragPreview) return; const clearPreview = () => { clearDraggedSession(); setSessionDragPreview(null); }; document.addEventListener("dragend", clearPreview); return () => document.removeEventListener("dragend", clearPreview); }, [sessionDragPreview]); const clearComposerText = useCallback((restoreFocus = true) => { setValue(""); setInlineError(null); setSlashMenuDismissed(false); setCliAppMenuDismissed(false); setCursorPosition(0); if (restoreFocus) focusTextarea(); }, [focusTextarea]); const collectGuidancePrompt = useCallback(() => collectQueuedPrompt({ text: value, images: readyImagesToQueuedImages(readyImages), ...(normalizedQuotedContext ? { quotedContext: normalizedQuotedContext } : {}), sessionMentions: activeSessionMentions, }), [activeSessionMentions, collectQueuedPrompt, normalizedQuotedContext, readyImages, value]); const queueGuidancePrompt = useCallback(() => { if (!canQueueGuidance) return; if (!enqueueQueuedPrompt(collectGuidancePrompt())) return; clear(); clearComposerText(); onQuotedContextChange?.(null); }, [canQueueGuidance, clear, clearComposerText, collectGuidancePrompt, onQuotedContextChange, enqueueQueuedPrompt]); const removeQueuedPrompt = useCallback(() => { clearQueuedPrompt(); requestAnimationFrame(() => textareaRef.current?.focus()); }, [clearQueuedPrompt]); const editQueuedPrompt = useCallback((pending: QueuedPromptContent) => { const prompt = hasComposerContent || normalizedQuotedContext ? collectGuidancePrompt() : pending; clearQueuedPrompt(); replaceMentionInput(prompt.text, prompt.text.length); setBoundSessionMentions(prompt.sessionMentions ?? []); setInlineError(null); setSlashMenuDismissed(false); setCliAppMenuDismissed(false); onQuotedContextChange?.(prompt.quotedContext ?? null); if (prompt.images?.length) { restoreReadyImages(prompt.images as RestoredReadyImage[]); } else { clear(); } focusTextarea(); }, [clear, collectGuidancePrompt, hasComposerContent, normalizedQuotedContext, onQuotedContextChange, replaceMentionInput, focusTextarea, restoreReadyImages, clearQueuedPrompt]); const submit = useCallback(() => { if (requiresModelSetup) { if (hasComposerContent) { setModelSetupAttentionRequest((request) => request + 1); } return; } if (!canSend) return; if (isUserShell && (images.length > 0 || normalizedQuotedContext)) { setInlineError(t("thread.composer.shell.removeContext")); return; } const trimmed = value.trim(); const content = trimmed; if (utf8Bytes(formatQuotedUserMessage(content, normalizedQuotedContext)) > maxTextBytes) { setInlineError(textTooLargeMessage()); return; } // Keep self-contained local previews across drafts and optimistic bubbles. // The client decodes these to HTTP binary; WS messages contain only refs. const payload = queuedImagesToSendImages(readyImagesToQueuedImages(readyImages)); const attachedCliApps = activeCliMentionApps.map(cliAppMentionPayload); const attachedMcpPresets = activeMcpPresetMentions.map(mcpPresetMentionPayload); const options: SendOptions | undefined = !isUserShell && ( attachedCliApps.length > 0 || attachedMcpPresets.length > 0 || activeSessionMentions.length > 0 || normalizedQuotedContext ) ? { ...(attachedCliApps.length > 0 ? { cliApps: attachedCliApps } : {}), ...(attachedMcpPresets.length > 0 ? { mcpPresets: attachedMcpPresets } : {}), ...(activeSessionMentions.length > 0 ? { sessionMentions: activeSessionMentions } : {}), ...(normalizedQuotedContext ? { quotedContext: normalizedQuotedContext } : {}), } : undefined; const hasPlainTextCommandPayload = payload === undefined && attachedCliApps.length === 0 && attachedMcpPresets.length === 0 && activeSessionMentions.length === 0; const slashLifecycle = hasPlainTextCommandPayload ? slashCommandLifecycle(content, slashCommands) : null; if ( slashLifecycle === "stop_active_turn" && isStreaming && onStop ) { handleStop(); clear(); clearComposerText(); onQuotedContextChange?.(null); return; } const isSideChannel = isUserShell || isSideChannelLifecycle(slashLifecycle); const finalizeActiveTurn = slashLifecycle === "finalize_active_turn"; if (!isUserShell && !slashLifecycle) { const prompt = collectGuidancePrompt(); const error = queuedPromptError(prompt); if (error) { setInlineError(error); return; } if (queuedPrompt) { sendQueuedPrompt(prompt, options); if (draftKey) draftStore?.delete(draftKey); clear(); clearComposerText(!hasTouchPrimaryPointer); onQuotedContextChange?.(null); return; } } const submittedDraft = draftKey ? draftStore?.get(draftKey) : undefined; const finishSend = () => { // A pending send can finish after this composer unmounts and a newer draft is started. if (draftKey && draftStore && draftStore.get(draftKey) !== submittedDraft) return; if (draftKey) draftStore?.delete(draftKey); if (hasTouchPrimaryPointer) textareaRef.current?.blur(); if ((!isStreaming && !isUserShell) || finalizeActiveTurn) clearQueuedPrompt(); // Bubble owns the data URL copy; safe to revoke every staged blob // preview here without affecting the rendered message. clear(); clearComposerText(!hasTouchPrimaryPointer); onQuotedContextChange?.(null); }; const result = onSend( content, payload, isSideChannel ? { ...options, sideChannel: true, ...(isUserShell ? { userShell: true } : {}), ...(finalizeActiveTurn ? { finalizeActiveTurn } : {}), } : isStreaming ? { ...options, continueActiveTurn: true } : options, ); if (result instanceof Promise) { setSendPending(true); void result .then((accepted) => { if (accepted !== false) finishSend(); }) .catch((error: unknown) => { setInlineError(error instanceof Error ? error.message : "Failed to send message"); }) .finally(() => setSendPending(false)); return; } if (result !== false) finishSend(); }, [ activeCliMentionApps, activeMcpPresetMentions, activeSessionMentions, canSend, draftKey, draftStore, clear, clearComposerText, collectGuidancePrompt, queuedPrompt, queuedPromptError, sendQueuedPrompt, clearQueuedPrompt, hasTouchPrimaryPointer, hasComposerContent, handleStop, images.length, isStreaming, isUserShell, maxTextBytes, requiresModelSetup, onSend, onStop, onQuotedContextChange, normalizedQuotedContext, readyImages, slashCommands, t, textTooLargeMessage, value, ]); const onKeyDown = (e: ReactKeyboardEvent) => { mentionInput.onKeyDown(e); if (e.defaultPrevented || e.nativeEvent.isComposing || mentionInput.isComposing) return; if (showCliAppMenu) { if (e.key === "ArrowDown") { e.preventDefault(); setSelectedCliAppIndex((idx) => (idx + 1) % filteredMentionCandidates.length); return; } if (e.key === "ArrowUp") { e.preventDefault(); setSelectedCliAppIndex( (idx) => (idx - 1 + filteredMentionCandidates.length) % filteredMentionCandidates.length, ); return; } if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) { e.preventDefault(); chooseMentionCandidate(filteredMentionCandidates[selectedCliAppIndex]); return; } if (e.key === "Escape") { e.preventDefault(); setCliAppMenuDismissed(true); return; } } if (showSlashMenu) { if (e.key === "ArrowDown") { e.preventDefault(); setSelectedCommandIndex((idx) => (idx + 1) % filteredSlashCommands.length); return; } if (e.key === "ArrowUp") { e.preventDefault(); setSelectedCommandIndex( (idx) => (idx - 1 + filteredSlashCommands.length) % filteredSlashCommands.length, ); return; } if (e.key === "Tab" || (e.key === "Enter" && !e.shiftKey)) { e.preventDefault(); chooseSlashCommand(filteredSlashCommands[selectedCommandIndex]); return; } if (e.key === "Escape") { e.preventDefault(); setSlashMenuDismissed(true); return; } } // Touch keyboards: a plain Enter inserts a newline; sending stays on the // send button. The select-on-Enter menu branches above take precedence. if ( e.key === "Enter" && !e.shiftKey && !e.altKey && !e.ctrlKey && !e.metaKey && !e.nativeEvent.isComposing && hasCoarsePointer ) { return; } if (e.key === "Enter" && !e.shiftKey && !e.nativeEvent.isComposing) { e.preventDefault(); if (canQueueGuidance) { if (!e.repeat) queueGuidancePrompt(); return; } // Empty Enter explicitly sends the visible pending message, including restored drafts. if ( queuedPrompt && value.length === 0 && images.length === 0 && !e.altKey && !e.ctrlKey && !e.metaKey ) { if (!e.repeat && voiceRecorder.state === "idle" && !voiceShortcutDownRef.current) { sendQueuedPrompt(queuedPrompt); } return; } submit(); } }; const onFilePick: React.ChangeEventHandler = (e) => { const files = Array.from(e.target.files ?? []); e.target.value = ""; addFiles(files); }; const removeChip = useCallback( (id: string) => { const { nextFocusId } = remove(id); setInlineError(null); requestAnimationFrame(() => { const el = nextFocusId ? chipRefs.current.get(nextFocusId) : null; if (el) { el.focus(); } else { textareaRef.current?.focus(); } }); }, [remove], ); const onChipKey = useCallback( (id: string) => (e: ReactKeyboardEvent) => { if ( e.key === "Delete" || e.key === "Backspace" || e.key === "Enter" || e.key === " " ) { e.preventDefault(); removeChip(id); } }, [removeChip], ); const attachButtonDisabled = interactionDisabled || full; const showVoiceButton = Boolean(onTranscribeAudio) && ( voiceRecorder.state !== "idle" || (!hasComposerContent && images.length === 0 && !isStreaming && !modelNeedsSetup) ); const voiceRecordingStatusLabel = t("thread.composer.voice.recordingStatus", { time: voiceRecorder.elapsedLabel, defaultValue: `Recording ${voiceRecorder.elapsedLabel}`, }); const voiceButtonLabel = voiceRecorder.state === "recording" ? t("thread.composer.voice.stop") : voiceRecorder.state === "transcribing" ? t("thread.composer.voice.transcribing") : t("thread.composer.tools.voice"); const voiceButtonTooltip = voiceRecorder.state === "recording" ? t("thread.composer.voice.stop") : voiceRecorder.state === "transcribing" ? t("thread.composer.voice.transcribing") : t("thread.composer.voice.hint"); // Touch users need an explicit send action; keep Stop while sending is unavailable. const showStopButton = isStreaming && !!onStop && !canSend; const actionState: ComposerActionState = showVoiceButton ? voiceRecorder.state === "transcribing" ? "busy" : voiceRecorder.isRecording ? "recording" : "voice" : showStopButton ? "stop" : requiresModelSetup ? "setup" : canSend || !isStreaming ? "send" : "busy"; const relaxedHeroInput = isHero && images.length === 0 && !isStreaming; const compactIdle = compactWhenIdle && !compactControls && !isHero && !composerFocused && value.length === 0 && images.length === 0 && !inlineError && !normalizedQuotedContext && !queuedPrompt && !goalState?.active && !isDragging && !sessionDragPreview && !voiceRecorder.isRecording && !showProjectPicker; useLayoutEffect(() => { if (!compactWhenIdle || compactControls) return; const form = formRef.current; const primary = form?.querySelector(".thread-composer-footer-primary"); const actions = form?.querySelector(".thread-composer-footer-actions"); if (!form || !primary || !actions) return; const controls = Array.from(primary.children).filter((child) => getComputedStyle(child).display !== "none"); // Reserve the real toolbar width, including translated model labels, while // the footer slides beneath the input. Neither control is remounted. const measure = () => { const gap = parseFloat(getComputedStyle(primary).columnGap) || 0; const width = controls.reduce((sum, child) => sum + child.getBoundingClientRect().width, 0) + Math.max(0, controls.length - 1) * gap + actions.getBoundingClientRect().width; form.style.setProperty("--composer-compact-controls-width", `${width}px`); }; measure(); const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure); controls.forEach((control) => observer?.observe(control)); observer?.observe(actions); return () => observer?.disconnect(); }, [compactControls, compactWhenIdle, modelLabel, voiceRecorder.isRecording, workspaceScope]); const accessControl = workspaceScope && !workspaceControlsHidden ? ( ) : null; const workspaceControl = showProjectPicker ? ( ) : null; const modelControl = modelLabel && !voiceRecorder.isRecording ? ( textareaRef.current?.focus()} provider={modelProvider} providerLabel={modelProviderLabel} needsSetup={modelNeedsSetup} attentionRequest={modelSetupAttentionRequest} isHero={isHero && !compactControls} onClick={modelNeedsSetup ? onModelBadgeClick : undefined} /> ) : null; const usageInMeta = mobileWorkspaceControls || compactControls; const usageControl = !voiceRecorder.isRecording ? renderContextUsage?.({ showLabel: usageInMeta, compactLabel: mobileWorkspaceControls }) : null; const inputTextClasses = cn( // Keep the overlay's CJK/Latin spacing aligned with the native textarea caret. "w-full resize-none bg-transparent text-composer [text-autospace:no-autospace]", compactControls ? "min-h-[52px] px-4 pb-2 pt-3" : isHero ? cn( "min-h-[78px] px-4 sm:px-5", relaxedHeroInput ? "pb-2 pt-[27px]" : "pb-1.5 pt-4", ) : "min-h-[50px] px-3.5 pb-1.5 pt-3 sm:px-4", ); const paletteBeside = showAnyPalette && slashPaletteLayout.placement === "beside"; return (
{ if (!compactWhenIdle) return; // Portaled model controls belong to this composer too: keep its layout // stable while moving between the input, toolbar, and model picker. if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current); }} onBlurCapture={() => { if (!compactWhenIdle) return; if (blurFrame.current !== null) cancelAnimationFrame(blurFrame.current); blurFrame.current = requestAnimationFrame(() => { blurFrame.current = null; setComposerFocused(false); }); }} onSubmit={(e) => { e.preventDefault(); submit(); }} onDragEnter={(event) => { if (!previewSessionDrop(event)) onDragEnter(event); }} onDragOver={(event) => { if (!previewSessionDrop(event)) onDragOver(event); }} onDragLeave={(event) => { if (!hasDraggedSession(event.dataTransfer)) { onDragLeave(event); return; } const nextTarget = event.relatedTarget; if (!(nextTarget instanceof Node) || !event.currentTarget.contains(nextTarget)) { setSessionDragPreview(null); } }} onDrop={(event) => { if (!handleSessionDrop(event)) onDrop(event); }} className={cn( "thread-composer-form relative w-full [--composer-action-margin:0px]", isHero ? "px-0 [--composer-action-size:2rem] [--composer-footer-inset:0.75rem] sm:[--composer-footer-inset:1rem]" : "px-1 pb-0 pt-1 [--composer-action-size:2.25rem] [--composer-footer-inset:0.625rem] sm:px-0 sm:pb-1.5 sm:[--composer-footer-inset:0.75rem]", compactWhenIdle && "thread-composer-collapsible-layout", paletteBeside && "grid grid-cols-2 items-start gap-2 p-0", )} > {showSlashMenu ? ( ) : null} {showCliAppMenu ? ( ) : null}
{queuedPrompt ? ( sendQueuedPrompt(queuedPrompt)} onDelete={removeQueuedPrompt} onEdit={() => editQueuedPrompt(queuedPrompt)} /> ) : null} {images.length > 0 ? (
{images.map((img) => ( t("thread.composer.normalizedSizeHint", { orig: formatBytes(orig), current: formatBytes(current), }) } formatError={(reason) => reason === "too_large" ? formatUploadTooLarge(img.file.size, img.kind === "video" ? MAX_VIDEO_BYTES : maxFileBytes) : formatRejection(reason)} onRemove={() => removeChip(img.id)} onKeyDown={onChipKey(img.id)} registerRef={(el) => { if (el) chipRefs.current.set(img.id, el); else chipRefs.current.delete(img.id); }} /> ))}
) : null} {normalizedQuotedContext ? (

{normalizedQuotedContext}

) : null}
{placeholder === undefined ? ( {resolvedPlaceholder} ) : null} {hasInlineDecorations ? ( ) : null}