import { useState, useRef, useEffect, useMemo, useImperativeHandle, forwardRef, memo, type KeyboardEvent } from 'react' import { useSendPrompt, useAbortSession, useSendShell, useAgents } from '@/hooks/useOpenCode' import { useCommands } from '@/hooks/useCommands' import { useCommandHandler } from '@/hooks/useCommandHandler' import { useFileSearch } from '@/hooks/useFileSearch' import { useModelSelection } from '@/hooks/useModelSelection' import { useVariants } from '@/hooks/useVariants' import { useSessionAgent } from '@/hooks/useSessionAgent' import { useSTT } from '@/hooks/useSTT' import { useUserBash } from '@/stores/userBashStore' import { useMobile } from '@/hooks/useMobile' import { usePermissions } from '@/contexts/EventContext' import { ChevronDown, Upload, X, Mic, MicOff } from 'lucide-react' import { SquareFill } from '@/components/ui/square-fill' import { CommandSuggestions } from '@/components/command/CommandSuggestions' import { MentionSuggestions, type MentionItem } from './MentionSuggestions' import { SessionStatusIndicator } from '@/components/ui/session-status-indicator' import { ModelQuickSelect } from '@/components/model/ModelQuickSelect' import { AgentQuickSelect } from '@/components/agent/AgentQuickSelect' import { detectMentionTrigger, parsePromptToParts, getFilename, filterAgentsByQuery } from '@/lib/promptParser' import type { components } from '@/api/opencode-types' import type { FileAttachmentInfo, ImageAttachment } from '@/api/types' const ACCEPTED_IMAGE_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "image/heic", "image/heif"] const revokeBlobUrls = (attachments: ImageAttachment[]) => { attachments.forEach((attachment) => { if (attachment.dataUrl.startsWith('blob:')) { URL.revokeObjectURL(attachment.dataUrl) } }) } const ACCEPTED_FILE_TYPES = [...ACCEPTED_IMAGE_TYPES, "application/pdf"] type CommandType = components['schemas']['Command'] export interface PromptInputHandle { setPromptValue: (value: string) => void clearPrompt: () => void triggerFileUpload: () => void } interface PromptInputProps { opcodeUrl: string directory?: string sessionID: string disabled?: boolean showScrollButton?: boolean hasActiveStream?: boolean onScrollToBottom?: () => void onShowSessionsDialog?: () => void onShowModelsDialog?: () => void onShowHelpDialog?: () => void onToggleDetails?: () => boolean onExportSession?: () => void onPromptChange?: (hasContent: boolean) => void } export const PromptInput = memo(forwardRef(function PromptInput({ opcodeUrl, directory, sessionID, disabled, showScrollButton, hasActiveStream = false, onScrollToBottom, onShowSessionsDialog, onShowModelsDialog, onShowHelpDialog, onToggleDetails, onExportSession, onPromptChange }, ref) { const [prompt, setPrompt] = useState('') const [isBashMode, setIsBashMode] = useState(false) const [showSuggestions, setShowSuggestions] = useState(false) const [suggestionQuery, setSuggestionQuery] = useState('') const [attachedFiles, setAttachedFiles] = useState(new Map()) const [imageAttachments, setImageAttachments] = useState([]) const [isDragging, setIsDragging] = useState(false) const [showMentionSuggestions, setShowMentionSuggestions] = useState(false) const [mentionQuery, setMentionQuery] = useState('') const [mentionRange, setMentionRange] = useState<{ start: number, end: number } | null>(null) const [selectedMentionIndex, setSelectedMentionIndex] = useState(0) const [selectedCommandIndex, setSelectedCommandIndex] = useState(0) const [selectedAgent, setSelectedAgent] = useState(null) const [localMode, setLocalMode] = useState(null) const [isFocused, setIsFocused] = useState(false) const [isTogglingRecording, setIsTogglingRecording] = useState(false) const lastAddedTranscriptRef = useRef('') const { isRecording, isProcessing, startRecording, stopRecording, abortRecording, isSupported: sttSupported, isEnabled: sttEnabled, interimTranscript, transcript, clear: clearSTT, } = useSTT() const textareaRef = useRef(null) const fileInputRef = useRef(null) useImperativeHandle(ref, () => ({ setPromptValue: (value: string) => { setPrompt(value) textareaRef.current?.focus() }, clearPrompt: () => { setPrompt('') setAttachedFiles(new Map()) revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) if (isRecording) { abortRecording() } else { clearSTT() } textareaRef.current?.focus() }, triggerFileUpload: () => { fileInputRef.current?.click() } }), [imageAttachments, clearSTT, isRecording, abortRecording]) const sendPrompt = useSendPrompt(opcodeUrl, directory) const sendShell = useSendShell(opcodeUrl, directory) const abortSession = useAbortSession(opcodeUrl, directory, sessionID) const { filterCommands } = useCommands(opcodeUrl) const { executeCommand } = useCommandHandler({ opcodeUrl, sessionID, directory, onShowSessionsDialog, onShowModelsDialog, onShowHelpDialog, onToggleDetails, onExportSession, currentAgent: localMode || undefined }) const { files: searchResults } = useFileSearch( opcodeUrl, mentionQuery, showMentionSuggestions, directory ) const { data: agents = [] } = useAgents(opcodeUrl, directory) const mentionItems = useMemo((): MentionItem[] => { const filteredAgents = filterAgentsByQuery( agents.map(a => ({ name: a.name, description: a.description })), mentionQuery ) const agentItems: MentionItem[] = filteredAgents.map(agent => ({ type: 'agent', value: agent.name, label: agent.name, description: agent.description })) const fileItems: MentionItem[] = searchResults.map(file => ({ type: 'file', value: file, label: getFilename(file), description: file })) return [...agentItems, ...fileItems] }, [agents, searchResults, mentionQuery]) const addUserBashCommand = useUserBash((s) => s.addUserBashCommand) const handleSubmit = () => { if (disabled) return if (!prompt.trim() && imageAttachments.length === 0) return if (hasActiveStream) { const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments) sendPrompt.mutate({ sessionID, parts, model: currentModel, agent: selectedAgent || currentMode, variant: currentVariant }) setPrompt('') setAttachedFiles(new Map()) revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) clearSTT() return } if (isBashMode) { const command = prompt.startsWith('!') ? prompt.slice(1) : prompt addUserBashCommand(command) sendShell.mutate({ sessionID, command, agent: currentMode }) setPrompt('') setIsBashMode(false) clearSTT() return } const commandMatch = prompt.match(/^\/([a-zA-Z0-9_-]+)(?:\s+(.*))?$/) if (commandMatch) { const [, commandName, commandArgs] = commandMatch const command = filterCommands(commandName)[0] if (command) { executeCommand(command, commandArgs?.trim() || '') setPrompt('') clearSTT() return } } const parts = parsePromptToParts(prompt, attachedFiles, imageAttachments) sendPrompt.mutate({ sessionID, parts, model: currentModel, agent: selectedAgent || currentMode, variant: currentVariant }) setPrompt('') setAttachedFiles(new Map()) revokeBlobUrls(imageAttachments) setImageAttachments([]) setSelectedAgent(null) clearSTT() } const handleStop = () => { abortSession.mutate(sessionID) } const handleCommandSelect = async (command: CommandType) => { if (!textareaRef.current) return setShowSuggestions(false) setSuggestionQuery('') if (command.template) { const cleanedTemplate = command.template .replace(/\$ARGUMENTS/g, '') .replace(/\$\d+/g, '') .trim() setPrompt(cleanedTemplate) setTimeout(() => { if (textareaRef.current) { textareaRef.current.focus() textareaRef.current.setSelectionRange(cleanedTemplate.length, cleanedTemplate.length) } }, 0) } else { const cursorPosition = textareaRef.current.selectionStart const commandMatch = prompt.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/) if (commandMatch) { const beforeCommand = prompt.slice(0, commandMatch.index) const afterCommand = prompt.slice(cursorPosition) const newPrompt = beforeCommand + '/' + command.name + ' ' + afterCommand setPrompt(newPrompt) setTimeout(() => { if (textareaRef.current) { const newCursorPos = beforeCommand.length + command.name.length + 2 textareaRef.current.focus() textareaRef.current.setSelectionRange(newCursorPos, newCursorPos) } }, 0) } } } const handleMentionSelect = (item: MentionItem) => { if (!mentionRange || !textareaRef.current) return const beforeMention = prompt.slice(0, mentionRange.start) const afterMention = prompt.slice(mentionRange.end) if (item.type === 'agent') { const newPrompt = beforeMention + '@' + item.value + ' ' + afterMention setPrompt(newPrompt) setSelectedAgent(item.value) setTimeout(() => { if (textareaRef.current) { const newCursorPos = beforeMention.length + item.value.length + 2 textareaRef.current.focus() textareaRef.current.setSelectionRange(newCursorPos, newCursorPos) } }, 0) } else { const filename = getFilename(item.value) const newPrompt = beforeMention + '@' + filename + ' ' + afterMention setPrompt(newPrompt) const absolutePath = item.value.startsWith('/') ? item.value : directory ? `${directory}/${item.value}` : item.value setAttachedFiles(prev => { const next = new Map(prev) next.set(filename.toLowerCase(), { path: absolutePath, name: filename }) return next }) setTimeout(() => { if (textareaRef.current) { const newCursorPos = beforeMention.length + filename.length + 2 textareaRef.current.focus() textareaRef.current.setSelectionRange(newCursorPos, newCursorPos) } }, 0) } setShowMentionSuggestions(false) setMentionQuery('') setMentionRange(null) } const handleAgentChange = (agent: string) => { setLocalMode(agent) } const handleVoiceToggle = async () => { if (isRecording) { stopRecording() } else { setIsTogglingRecording(true) try { await startRecording() if (textareaRef.current) { textareaRef.current.blur() } } catch { setIsTogglingRecording(false) } } } useEffect(() => { const textToUse = transcript || interimTranscript if (!isRecording && textToUse && textToUse !== 'Processing...' && textToUse !== 'Recording...') { const trimmedTranscript = textToUse.trim() if (trimmedTranscript && trimmedTranscript !== lastAddedTranscriptRef.current) { if (prompt === '' || prompt === 'Processing...' || prompt === 'Recording...') { setPrompt(trimmedTranscript) } else { setPrompt(prev => `${prev} ${trimmedTranscript}`) } lastAddedTranscriptRef.current = trimmedTranscript textareaRef.current?.focus() } } }, [isRecording, interimTranscript, transcript, prompt]) useEffect(() => { if (isRecording && isTogglingRecording) { setIsTogglingRecording(false) } }, [isRecording, isTogglingRecording]) useEffect(() => { if (isTogglingRecording) { lastAddedTranscriptRef.current = '' } }, [isTogglingRecording]) const addImageAttachment = (file: File) => { const generateId = () => { if (typeof crypto !== 'undefined' && crypto.randomUUID) { return crypto.randomUUID() } return `${Date.now()}-${Math.random().toString(36).substring(2, 11)}` } try { const reader = new FileReader() reader.onloadend = () => { try { if (reader.readyState !== 2) return const dataUrl = reader.result as string if (!dataUrl) { const blobUrl = URL.createObjectURL(file) const attachment: ImageAttachment = { id: generateId(), filename: file.name, mime: file.type || 'image/png', dataUrl: blobUrl, } setImageAttachments((prev) => [...prev, attachment]) return } const attachment: ImageAttachment = { id: generateId(), filename: file.name, mime: file.type || 'image/png', dataUrl, } setImageAttachments((prev) => [...prev, attachment]) } catch (innerError) { console.error('Error inside onloadend:', innerError) } } reader.onerror = () => { console.error('FileReader error:', reader.error?.message) } reader.readAsDataURL(file) } catch (error) { console.error('Error reading file:', error) } } const removeImageAttachment = (id: string) => { setImageAttachments((prev) => { const attachment = prev.find((a) => a.id === id) if (attachment?.dataUrl.startsWith('blob:')) { URL.revokeObjectURL(attachment.dataUrl) } return prev.filter((a) => a.id !== id) }) } const handlePaste = async (event: React.ClipboardEvent) => { const clipboardData = event.clipboardData if (!clipboardData) return const isIOS = /iPad|iPhone|iPod/.test(navigator.userAgent) && !(window as { MSStream?: boolean }).MSStream const isSecureContext = window.isSecureContext || (window.location.protocol === 'http:' && window.location.hostname === 'localhost') if (isIOS && isSecureContext && navigator.clipboard && navigator.clipboard.read) { try { const text = await navigator.clipboard.readText() if (text && text.trim()) { return } } catch { } event.preventDefault() try { const clipboardItems = await navigator.clipboard.read() for (const item of clipboardItems) { for (const type of item.types) { if (ACCEPTED_FILE_TYPES.includes(type) || type.startsWith('image/')) { try { const blob = await item.getType(type) const file = new File([blob], `pasted-${Date.now()}.${type.split('/')[1]}`, { type }) addImageAttachment(file) } catch (err) { console.error('Failed to read clipboard item type:', err) } } } } return } catch (error) { console.error('Clipboard read failed on iOS:', error) } } const items = Array.from(clipboardData.items) const imageItems = items.filter((item) => { if (item.kind !== 'file') return false const hasKnownType = ACCEPTED_FILE_TYPES.includes(item.type) const isLikelyImage = item.type.startsWith('image/') const hasNoType = !item.type || item.type === '' return hasKnownType || isLikelyImage || hasNoType }) if (imageItems.length > 0) { event.preventDefault() for (const item of imageItems) { const file = item.getAsFile() if (file) { const isValidImageFile = ACCEPTED_FILE_TYPES.includes(file.type) || file.type.startsWith('image/') || file.size > 0 if (isValidImageFile) { addImageAttachment(file) } } } } } const handleDragOver = (event: React.DragEvent) => { event.preventDefault() event.stopPropagation() if (event.dataTransfer?.types.includes('Files')) { setIsDragging(true) } } const handleDragLeave = (event: React.DragEvent) => { event.preventDefault() event.stopPropagation() setIsDragging(false) } const handleDrop = async (event: React.DragEvent) => { event.preventDefault() event.stopPropagation() setIsDragging(false) const files = event.dataTransfer?.files if (files) { for (const file of Array.from(files)) { if (ACCEPTED_FILE_TYPES.includes(file.type)) { addImageAttachment(file) } } } } const handleFileInputChange = (event: React.ChangeEvent) => { const file = event.currentTarget.files?.[0] if (file && ACCEPTED_FILE_TYPES.includes(file.type)) { addImageAttachment(file) } event.currentTarget.value = '' } const handleKeyDown = (e: KeyboardEvent) => { if (isBashMode && e.key === 'Escape') { e.preventDefault() setIsBashMode(false) setPrompt('') return } if (showMentionSuggestions && mentionItems.length > 0) { if (e.key === 'ArrowDown') { e.preventDefault() setSelectedMentionIndex(prev => prev < mentionItems.length - 1 ? prev + 1 : prev ) return } if (e.key === 'ArrowUp') { e.preventDefault() setSelectedMentionIndex(prev => prev > 0 ? prev - 1 : 0) return } if (e.key === 'Enter') { e.preventDefault() if (mentionItems[selectedMentionIndex]) { handleMentionSelect(mentionItems[selectedMentionIndex]) } return } if (e.key === 'Escape') { e.preventDefault() setShowMentionSuggestions(false) setMentionQuery('') setMentionRange(null) return } } if (showSuggestions) { const filteredCommands = filterCommands(suggestionQuery) if (e.key === 'ArrowDown') { e.preventDefault() setSelectedCommandIndex(prev => (prev + 1) % filteredCommands.length) return } if (e.key === 'ArrowUp') { e.preventDefault() setSelectedCommandIndex(prev => (prev - 1 + filteredCommands.length) % filteredCommands.length) return } if (e.key === 'Enter') { e.preventDefault() const selectedCommand = filteredCommands[selectedCommandIndex] if (selectedCommand) { handleCommandSelect(selectedCommand) } return } if (e.key === 'Escape') { e.preventDefault() setShowSuggestions(false) setSuggestionQuery('') setSelectedCommandIndex(0) return } } if (e.key === 'Enter' && (e.metaKey || e.ctrlKey || (isMobile && !e.shiftKey))) { e.preventDefault() if (isMobile) { textareaRef.current?.blur() } handleSubmit() } else if (e.key === 'Escape') { setShowSuggestions(false) setSuggestionQuery('') setShowMentionSuggestions(false) setMentionQuery('') setMentionRange(null) setPrompt('') revokeBlobUrls(imageAttachments) setImageAttachments([]) clearSTT() } else if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 't') { e.preventDefault() if (hasVariants) { cycleVariant() } } } const handleInput = (e: React.ChangeEvent) => { const value = e.target.value if (value === '!' && prompt === '') { setIsBashMode(true) setPrompt(value) return } if (isBashMode && value === '') { setIsBashMode(false) } setPrompt(value) if (isBashMode) { return } const cursorPosition = e.target.selectionStart const mentionTrigger = detectMentionTrigger(value, cursorPosition) if (mentionTrigger) { setMentionQuery(mentionTrigger.query) setMentionRange({ start: mentionTrigger.start, end: mentionTrigger.end }) setShowMentionSuggestions(true) setSelectedMentionIndex(0) } else { const commandMatch = value.slice(0, cursorPosition).match(/(^|\s)\/([a-zA-Z0-9_-]*)$/) if (commandMatch) { const query = commandMatch[2] setSuggestionQuery(query) setShowSuggestions(true) setSelectedCommandIndex(0) } else { setShowSuggestions(false) setSuggestionQuery('') } if (showMentionSuggestions) { setShowMentionSuggestions(false) setMentionQuery('') setMentionRange(null) } } } const sessionAgent = useSessionAgent(opcodeUrl, sessionID, directory) const currentMode = localMode ?? sessionAgent.agent const { model, modelString } = useModelSelection(opcodeUrl, directory) const currentModel = modelString || '' const displayModelName = model?.modelID || currentModel const isMobile = useMobile() const { setShowDialog, hasForSession: hasPermissionsForSession } = usePermissions() const hasPendingPermissionForSession = hasPermissionsForSession(sessionID) const { hasVariants, currentVariant, cycleVariant } = useVariants(opcodeUrl, directory) const showStopButton = hasActiveStream const hideSecondaryButtons = isMobile && hasActiveStream useEffect(() => { onPromptChange?.(prompt.trim().length > 0) }, [prompt, onPromptChange]) useEffect(() => { setLocalMode(null) }, [sessionID]) return (
{showStopButton && !(isFocused && prompt.trim().length > 0) && ( )}