"use client" import { useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react" import { ArrowUp, AtSign, AudioLines, Check, ChevronDown, ChevronRight, Cpu, File, FileText, Image as ImageIcon, Plus, Search, Square, X, Zap, } from "lucide-react" import { cn } from "@/lib/utils" import { Popover, PopoverContent, PopoverTrigger } from "@/components/ui/popover" import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuPortal, DropdownMenuRadioGroup, DropdownMenuRadioItem, DropdownMenuSeparator, DropdownMenuSub, DropdownMenuSubContent, DropdownMenuSubTrigger, DropdownMenuTrigger } from "@/components/ui/dropdown-menu" import { MACHINE_SIZES, isPremiumMachineSize, machineSizeLabel, machineSizeSchema } from "@/modules/nova/sandbox/machine-sizes" import { useMachineSettings } from "@/modules/nova-web/machine-settings" import { imageDataUrl, type LocalAttachment } from "@/modules/nova/attachments/contracts" import type { NovaReference, ReferenceKind } from "@/modules/nova/references/contracts" import { filesFromClipboard, filesFromDataTransfer, mergeLocalAttachments, pickLocalFiles, readLocalFile, } from "@/modules/nova-web/local-files" import { isLocalFileReferenceId, localPathFromReferenceId, pickLocalWorkspaceFolder, readLocalWorkspaceFile, type LocalWorkspaceState, } from "@/modules/nova-web/local-workspace" import { addReference, filterReferenceCategories, insertMentionTrigger, moveMentionIndex, parseMentionQuery, REFERENCE_CATEGORIES, replaceMentionQuery, type MentionQuery, } from "@/modules/nova-web/mention-helpers" import { BYOK_PROVIDERS, CLOUD_MODELS, DEFAULT_NOVA_MODEL, DEFAULT_NOVA_PROVIDER, HARNESS_PROVIDERS, menuId, modelChipLabel, modelsForProvider, NOVA_EFFORTS, CODEX_EFFORT_LABELS, type HarnessProvider, type NovaAgentMode, type NovaEffort, type NovaModelEntry, } from "@/modules/nova-web/models" import { useCodexCatalog } from "../codex-catalog" import { codexModelEntries } from "../model-settings" import { MentionPicker, mentionOptionId, ReferenceIcon, useReferenceSearch } from "./mention-picker" import { useProviderConnectionStates } from "./provider-connections" import { PROVIDER_INTEGRATION_BY_ID } from "@/modules/nova-web/provider-integrations" const EMPTY_REFERENCES: NovaReference[] = [] const EMPTY_LOCAL_FILES: LocalAttachment[] = [] type MentionState = { draft: string range: MentionQuery kind: ReferenceKind | null activeIndex: number session: number } export function Composer({ value, onChange, onSubmit, onStop, large = false, disabled = false, streaming = false, placeholder, className, model = DEFAULT_NOVA_MODEL, provider = DEFAULT_NOVA_PROVIDER, effort = "high", mode = "agent", onModelChange, onEffortChange, onModeChange, references = EMPTY_REFERENCES, onReferencesChange, localFiles = EMPTY_LOCAL_FILES, onLocalFilesChange, onLocalProjectChange, projectLocked = false, modelLocked = false, }: { value: string onChange: (value: string) => void onSubmit: () => void onStop?: () => void large?: boolean disabled?: boolean streaming?: boolean placeholder?: string className?: string model?: string provider?: HarnessProvider effort?: NovaEffort mode?: NovaAgentMode onModelChange?: (selection: { provider: HarnessProvider; model: string }) => void onEffortChange?: (effort: NovaEffort) => void onModeChange?: (mode: NovaAgentMode) => void references?: NovaReference[] onReferencesChange?: (references: NovaReference[]) => void localFiles?: LocalAttachment[] onLocalFilesChange?: (files: LocalAttachment[]) => void onLocalProjectChange?: (project: LocalWorkspaceState) => void projectLocked?: boolean modelLocked?: boolean }) { const textareaRef = useRef(null) const attachRef = useRef(null) const machine = useMachineSettings() const pickerRef = useRef(null) const composingRef = useRef(false) const [attachMenuOpen, setAttachMenuOpen] = useState(false) const [localFileBusy, setLocalFileBusy] = useState(false) const [localFileError, setLocalFileError] = useState(null) const [dragOver, setDragOver] = useState(false) const dragDepthRef = useRef(0) const sessionRef = useRef(0) const pendingCaretRef = useRef<{ value: string; caret: number } | null>(null) const [mention, setMention] = useState(null) const [referenceAnnouncement, setReferenceAnnouncement] = useState("") const pickerId = useId() const hintId = `${pickerId}-hint` const referencesEnabled = !!onReferencesChange && !disabled && !streaming const localFilesEnabled = !!onLocalFilesChange && !disabled && !streaming && !localFileBusy const attachEnabled = !disabled && !streaming const pickerOpen = referencesEnabled && mention !== null && mention.draft === value const categories = filterReferenceCategories(pickerOpen ? mention.range.query : "") const search = useReferenceSearch(pickerOpen ? mention.kind : null, pickerOpen ? mention.range.query : "", mention?.session ?? 0) const optionCount = pickerOpen && mention.kind ? search.items.length : categories.length const activeIndex = Math.max(0, Math.min(mention?.activeIndex ?? 0, optionCount - 1)) const canSend = (value.trim().length > 0 || localFiles.length > 0) && !disabled && !streaming && !localFileBusy const codex = useCodexCatalog() const codexModel = codex.models.find((item) => item.id === model) const effortOptions = provider === "codex" ? CODEX_EFFORT_LABELS.filter((item) => codexModel?.efforts.includes(item.id)) : NOVA_EFFORTS const effortMeta = CODEX_EFFORT_LABELS.find((item) => item.id === effort)! const chip = provider === "codex" ? `Codex · ${codexModel?.label ?? model}` : modelChipLabel(provider, model) const dismissMention = useCallback(() => setMention(null), []) useEffect(() => { if (!pickerOpen) return function onPointer(event: PointerEvent) { const target = event.target as Node if (pickerRef.current?.contains(target) || textareaRef.current?.contains(target) || attachRef.current?.contains(target)) return dismissMention() } document.addEventListener("pointerdown", onPointer) return () => document.removeEventListener("pointerdown", onPointer) }, [dismissMention, pickerOpen]) useLayoutEffect(() => { const pending = pendingCaretRef.current const textarea = textareaRef.current if (!pending || !textarea || pending.value !== value) return pendingCaretRef.current = null textarea.focus({ preventScroll: true }) textarea.setSelectionRange(pending.caret, pending.caret) }, [value, mention]) function syncMention(textarea: HTMLTextAreaElement, userInput: boolean) { if (!userInput && pendingCaretRef.current) return const draft = textarea.value const range = parseMentionQuery(draft, textarea.selectionStart, textarea.selectionEnd) if (!referencesEnabled || !range) { setMention(null) return } const session = ++sessionRef.current setMention((previous) => { const current = previous?.draft === value || previous?.draft === draft ? previous : null if (!current && !userInput) return null const sameTrigger = current?.range.start === range.start return { draft, range, kind: sameTrigger ? current.kind : null, activeIndex: sameTrigger && current.range.query === range.query ? current.activeIndex : 0, session: sameTrigger ? current.session : session, } }) } function openMention() { const textarea = textareaRef.current if (!referencesEnabled || !textarea) return setAttachMenuOpen(false) const range = parseMentionQuery(value, textarea.selectionStart, textarea.selectionEnd) const edit = range ? { value, caret: textarea.selectionStart } : insertMentionTrigger(value, textarea.selectionStart, textarea.selectionEnd) const nextRange = range ?? parseMentionQuery(edit.value, edit.caret) if (!nextRange) return pendingCaretRef.current = edit setMention({ draft: edit.value, range: nextRange, kind: null, activeIndex: 0, session: ++sessionRef.current }) if (edit.value !== value) onChange(edit.value) } async function ingestLocalFiles(picked: File[], source: "picker" | "paste" | "drop") { if (!localFilesEnabled || !onLocalFilesChange || picked.length === 0) return setAttachMenuOpen(false) setLocalFileError(null) setLocalFileBusy(true) try { const read = await Promise.all(picked.map((file) => readLocalFile(file))) const ok = read.flatMap((item) => (item.ok ? [item.attachment] : [])) const failed = read.flatMap((item) => (item.ok ? [] : [`${item.name}: ${item.error}`])) const merged = mergeLocalAttachments(localFiles, ok) onLocalFilesChange(merged.attachments) const notes = [...failed, ...merged.skipped] if (notes.length > 0) setLocalFileError(notes.slice(0, 3).join(" · ")) const verb = source === "paste" ? "pasted" : source === "drop" ? "dropped" : "attached" setReferenceAnnouncement( ok.length > 0 ? `${ok.length} file${ok.length === 1 ? "" : "s"} ${verb}.` : "No files attached.", ) } catch (error) { setLocalFileError(error instanceof Error ? error.message : "Could not attach files") } finally { setLocalFileBusy(false) textareaRef.current?.focus({ preventScroll: true }) } } async function handlePickLocalFiles() { if (!localFilesEnabled) return try { const picked = await pickLocalFiles() await ingestLocalFiles(picked, "picker") } catch (error) { setLocalFileError(error instanceof Error ? error.message : "Could not open the file picker") } } function onComposerDragEnter(event: React.DragEvent) { if (!localFilesEnabled) return if (![...event.dataTransfer.types].includes("Files")) return event.preventDefault() dragDepthRef.current += 1 setDragOver(true) } function onComposerDragLeave(event: React.DragEvent) { if (!localFilesEnabled) return event.preventDefault() dragDepthRef.current = Math.max(0, dragDepthRef.current - 1) if (dragDepthRef.current === 0) setDragOver(false) } function onComposerDragOver(event: React.DragEvent) { if (!localFilesEnabled) return if (![...event.dataTransfer.types].includes("Files")) return event.preventDefault() event.dataTransfer.dropEffect = "copy" } function onComposerDrop(event: React.DragEvent) { if (!localFilesEnabled) return event.preventDefault() dragDepthRef.current = 0 setDragOver(false) const files = filesFromDataTransfer(event.dataTransfer) void ingestLocalFiles(files, "drop") } function onComposerPaste(event: React.ClipboardEvent) { if (!localFilesEnabled) return const files = filesFromClipboard(event.clipboardData) if (files.length === 0) return event.preventDefault() void ingestLocalFiles(files, "paste") } function pickCategory(kind: ReferenceKind | null) { if (!pickerOpen || !mention) return const edit = replaceMentionQuery(value, mention.range, "@") const range = parseMentionQuery(edit.value, edit.caret) if (!range) return pendingCaretRef.current = edit setMention({ ...mention, draft: edit.value, range, kind, activeIndex: kind ? 0 : Math.max(0, REFERENCE_CATEGORIES.findIndex((category) => category.kind === mention.kind)), }) if (edit.value !== value) onChange(edit.value) } async function pickReference(reference: NovaReference) { if (!pickerOpen || !mention) return // Local workspace files → attach file contents (browser can't resolve them server-side). if (isLocalFileReferenceId(reference.id)) { if (!localFilesEnabled || !onLocalFilesChange) return const path = localPathFromReferenceId(reference.id) if (!path) return setLocalFileBusy(true) setLocalFileError(null) try { const read = await readLocalWorkspaceFile(path) if (!read.ok) { setLocalFileError(`${read.name}: ${read.error}`) return } const merged = mergeLocalAttachments(localFiles, [read.attachment]) onLocalFilesChange(merged.attachments) if (merged.skipped.length) setLocalFileError(merged.skipped.slice(0, 2).join(" · ")) setReferenceAnnouncement(`${reference.label} attached from local folder.`) const edit = replaceMentionQuery(value, mention.range, "") pendingCaretRef.current = edit dismissMention() onChange(edit.value) } finally { setLocalFileBusy(false) textareaRef.current?.focus({ preventScroll: true }) } return } if (!onReferencesChange) return const result = addReference(references, reference) if (result.status === "limit") return if (result.status === "added") onReferencesChange(result.references) setReferenceAnnouncement(`${reference.label} ${result.status === "added" ? "attached" : "is already attached"}.`) const edit = replaceMentionQuery(value, mention.range, "") pendingCaretRef.current = edit dismissMention() onChange(edit.value) } async function handleOpenLocalFolder() { if (!localFilesEnabled || projectLocked) return setLocalFileBusy(true) setLocalFileError(null) try { const state = await pickLocalWorkspaceFolder() if (!state) return search.refreshLocalWorkspace() onLocalProjectChange?.(state) setReferenceAnnouncement( state.projectId ? `Local project “${state.displayName}” saved · ${state.entries.length} files indexed and searchable.` : `Local folder “${state.rootName}” linked · ${state.entries.length} files searchable.`, ) } catch (error) { setLocalFileError(error instanceof Error ? error.message : "Could not open local folder") } finally { setLocalFileBusy(false) textareaRef.current?.focus({ preventScroll: true }) } } return (
{dragOver ? (
Drop files, photos, or documents
) : null}