/* eslint-disable max-lines -- groups all create-dialog selector subcomponents; splitting per-selector files is a separate refactor. */ "use client"; import { useEffect, useLayoutEffect, useRef, useState, memo, useCallback, useMemo } from "react"; import { Textarea } from "@kandev/ui/textarea"; import { Tooltip, TooltipContent, TooltipTrigger } from "@kandev/ui/tooltip"; import { IconPaperclip } from "@tabler/icons-react"; import { Combobox } from "./combobox"; import { formatBytes } from "@/lib/utils/format-bytes"; import { processFile, MAX_FILES, MAX_TOTAL_SIZE, type FileAttachment, } from "@/components/task/chat/file-attachment"; import { useAttachmentCountFeedback, useAttachmentFileFeedback, useAttachmentTotalSizeFeedback, useUnreadablePastedImageFeedback, } from "@/components/task/chat/use-attachment-file-feedback"; import { readClipboardAttachments, type ImagePasteIssue, } from "@/components/task/chat/clipboard-attachments"; import { ContextZone } from "@/components/task/chat/context-items/context-zone"; import { MentionMenu } from "@/components/task/chat/mention-menu"; import type { ContextItem, ImageContextItem, FileAttachmentContextItem } from "@/lib/types/context"; import type { TaskFormInputsHandle } from "@/components/task-create-dialog-types"; import type { TaskCreateLaunchPreview } from "@/components/task-create-dialog-launch-preview"; import { composeLaunchPreviewPrompt } from "@/components/task-create-dialog-launch-preview"; import { TaskCreateLaunchPreviewContent, TaskCreateLaunchPreviewToggle, } from "@/components/task-create-dialog-launch-preview-control"; import { EnhancePromptButton } from "@/components/enhance-prompt-button"; import { JiraImportBar } from "@/components/jira/jira-import-bar"; import { LinearImportBar } from "@/components/linear/linear-import-bar"; import type { JiraTicket } from "@/lib/types/jira"; import type { LinearIssue } from "@/lib/types/linear"; import { useTaskCreatePromptMention } from "@/hooks/use-task-create-prompt-mention"; import { cn } from "@/lib/utils"; import { useTaskTitleSelectionRestore } from "@/hooks/use-task-title-selection-restore"; import { deleteAttachment, uploadAttachment } from "@/lib/api/domains/attachment-api"; import { ApiError } from "@/lib/api/client"; import { useTranslation } from "react-i18next"; import { t } from "@/lib/i18n"; import { PluginSlot } from "@/components/plugins/plugin-slot"; import { composerIdentity, composerInsertionText, useStablePluginComposerCapability, } from "@/lib/plugins/composer-capability"; import { useResponsiveBreakpoint } from "@/hooks/use-responsive-breakpoint"; export { BranchSelector } from "./branch-selector"; export type { BranchOption, BranchSelectorProps } from "./branch-selector"; const CURSOR_POINTER_CLASS = "cursor-pointer"; type AttachmentLimitRejection = "count" | "total-size" | null; function acceptAttachmentsWithinLimits( existing: FileAttachment[], processed: FileAttachment[], ): { accepted: FileAttachment[]; rejection: AttachmentLimitRejection } { let nextCount = existing.length; let nextTotalSize = existing.reduce((sum, att) => sum + att.size, 0); const accepted: FileAttachment[] = []; for (const att of processed) { if (nextCount >= MAX_FILES) return { accepted, rejection: "count" }; if (nextTotalSize + att.size > MAX_TOTAL_SIZE) { return { accepted, rejection: "total-size" }; } accepted.push(att); nextCount += 1; nextTotalSize += att.size; } return { accepted, rejection: null }; } type RepositoryOption = { value: string; label: string; renderLabel: () => React.ReactNode; }; type RepositorySelectorProps = { options: RepositoryOption[]; value: string; onValueChange: (value: string) => void; disabled: boolean; placeholder: string; searchPlaceholder: string; emptyMessage: string; triggerClassName?: string; }; export const RepositorySelector = memo(function RepositorySelector({ options, value, onValueChange, disabled, placeholder, searchPlaceholder, emptyMessage, triggerClassName, }: RepositorySelectorProps) { return ( ); }); type AgentSelectorProps = { options: Array<{ value: string; label: string; renderLabel: () => React.ReactNode }>; value: string; onValueChange: (value: string) => void; disabled: boolean; placeholder: string; triggerClassName?: string; popoverPortal?: boolean; }; export const AgentSelector = memo(function AgentSelector({ options, value, onValueChange, disabled, placeholder, triggerClassName, popoverPortal, }: AgentSelectorProps) { const { t } = useTranslation(); return ( ); }); type ExecutorSelectorProps = { options: Array<{ value: string; label: string; renderLabel?: () => React.ReactNode }>; value: string; onValueChange: (value: string) => void; disabled: boolean; placeholder: string; triggerClassName?: string; popoverPortal?: boolean; }; export const ExecutorSelector = memo(function ExecutorSelector({ options, value, onValueChange, disabled, placeholder, triggerClassName, popoverPortal, }: ExecutorSelectorProps) { const { t } = useTranslation(); return ( ); }); type ExecutorProfileSelectorProps = { options: Array<{ value: string; label: string; renderLabel?: () => React.ReactNode }>; value: string; onValueChange: (value: string) => void; disabled: boolean; placeholder: string; triggerClassName?: string; popoverPortal?: boolean; }; export const ExecutorProfileSelector = memo(function ExecutorProfileSelector({ options, value, onValueChange, disabled, placeholder, triggerClassName, popoverPortal, }: ExecutorProfileSelectorProps) { const { t } = useTranslation(); return ( ); }); type InlineTaskNameProps = { value: string; onChange: (value: string) => void; autoFocus?: boolean; }; export const InlineTaskName = memo(function InlineTaskName({ value, onChange, autoFocus, }: InlineTaskNameProps) { const { t } = useTranslation(); const { inputRef, clampChange } = useTaskTitleSelectionRestore(value); const hasFocusedRef = useRef(false); useEffect(() => { if (autoFocus && !hasFocusedRef.current && inputRef.current) { hasFocusedRef.current = true; inputRef.current.focus(); inputRef.current.select(); } }, [autoFocus]); return ( onChange(clampChange(e))} placeholder={t("task:taskName")} data-testid="task-title-input" className="w-full min-w-0 max-w-full border border-input bg-input/20 dark:bg-input/30 text-sm font-medium rounded-md px-3 py-2 placeholder:text-muted-foreground/70 outline-none focus-visible:border-ring transition-colors" /> ); }); // Memoized description input to prevent re-rendering the entire dialog on every keystroke type TaskFormInputsProps = { isSessionMode: boolean; taskId?: string | null; workspaceId?: string | null; autoFocus?: boolean; initialDescription: string; onDescriptionChange: (hasContent: boolean) => void; onPendingAttachmentUploadsChange?: (pending: boolean) => void; onKeyDown: (e: React.KeyboardEvent) => void; descriptionValueRef: React.RefObject; disabled?: boolean; placeholder?: string; onEnhancePrompt?: () => void; isEnhancingPrompt?: boolean; isUtilityConfigured?: boolean; launchPreview?: TaskCreateLaunchPreview | null; jiraImport?: { workspaceId: string | null; disabled?: boolean; onImport: (ticket: JiraTicket) => void; }; linearImport?: { workspaceId: string | null; disabled?: boolean; onImport: (issue: LinearIssue) => void; }; /** * Submits the form the way the native submit control does, for a plugin * composer action that finished producing text (dictation, for instance). * The dialog wires this to its own submit handler, so validation, gating * and error handling stay native. */ onComposerSubmit?: () => boolean | Promise; }; // eslint-disable-next-line max-lines-per-function function useFileAttachments( workspaceId: string | null | undefined, onPendingAttachmentUploadsChange?: (pending: boolean) => void, ) { const [attachments, setAttachments] = useState([]); const attachmentsRef = useRef([]); const updateAttachment = useCallback((id: string, update: Partial) => { setAttachments((prev) => { const next = prev.map((attachment) => attachment.id === id ? { ...attachment, ...update } : attachment, ); attachmentsRef.current = next; return next; }); }, []); const uploadPendingAttachment = useCallback( async (attachment: FileAttachment) => { if (!workspaceId || !attachment.file || attachment.attachmentId) return; updateAttachment(attachment.id, { uploadStatus: "uploading" }); try { const uploaded = await uploadAttachment(attachment.file, { workspaceId, kind: attachment.isImage ? "image" : "resource", deliveryMode: attachment.deliveryMode, }); if (!attachmentsRef.current.some((current) => current.id === attachment.id)) { void deleteAttachment(uploaded.attachment_id).catch(() => undefined); return; } updateAttachment(attachment.id, { attachmentId: uploaded.attachment_id, uploadStatus: "ready", size: uploaded.size_bytes, }); } catch (error) { updateAttachment(attachment.id, { uploadStatus: "failed", uploadError: error instanceof ApiError ? error.message : t("task:uploadFailed"), }); } }, [updateAttachment, workspaceId], ); useEffect(() => { if (!workspaceId) return; for (const attachment of attachmentsRef.current) { if (attachment.file && !attachment.attachmentId && attachment.uploadStatus !== "uploading") { void uploadPendingAttachment(attachment); } } }, [uploadPendingAttachment, workspaceId]); const [isDragging, setIsDragging] = useState(false); const warnAttachmentCountLimit = useAttachmentCountFeedback(); const rejectOversizedFile = useAttachmentFileFeedback(); const warnAttachmentTotalSizeLimit = useAttachmentTotalSizeFeedback(); const warnUnreadablePastedImage = useUnreadablePastedImageFeedback(); useEffect(() => { onPendingAttachmentUploadsChange?.( attachments.some((attachment) => attachment.file && !attachment.attachmentId), ); }, [attachments, onPendingAttachmentUploadsChange, workspaceId]); const addFiles = useCallback( async (files: File[], issue?: ImagePasteIssue) => { if (issue === "unreadable-image") { warnUnreadablePastedImage(); return; } const processed: FileAttachment[] = []; for (const file of files) { if (rejectOversizedFile(file)) continue; const attachment = await processFile(file); if (attachment) processed.push(attachment); } if (processed.length === 0) return; const { accepted, rejection } = acceptAttachmentsWithinLimits( attachmentsRef.current, processed, ); if (rejection === "count") { warnAttachmentCountLimit(); } else if (rejection === "total-size") { warnAttachmentTotalSizeLimit(); } if (accepted.length === 0) return; const next = [...attachmentsRef.current, ...accepted]; attachmentsRef.current = next; setAttachments(next); for (const attachment of accepted) void uploadPendingAttachment(attachment); }, [ rejectOversizedFile, warnAttachmentCountLimit, warnAttachmentTotalSizeLimit, warnUnreadablePastedImage, uploadPendingAttachment, ], ); const handleRemoveAttachment = useCallback((id: string) => { const removed = attachmentsRef.current.find((attachment) => attachment.id === id); const next = attachmentsRef.current.filter((att) => att.id !== id); attachmentsRef.current = next; setAttachments(next); if (removed?.attachmentId) void deleteAttachment(removed.attachmentId).catch(() => undefined); }, []); const handleRetryAttachment = useCallback( (id: string) => { const attachment = attachmentsRef.current.find((item) => item.id === id); if (attachment) void uploadPendingAttachment(attachment); }, [uploadPendingAttachment], ); return { attachments, isDragging, setIsDragging, addFiles, handleRemoveAttachment, handleRetryAttachment, }; } function useAttachmentHandlers( disabled: boolean | undefined, addFiles: (files: File[], issue?: ImagePasteIssue) => Promise, setIsDragging: (v: boolean) => void, ) { const handlePaste = useCallback( (e: React.ClipboardEvent) => { if (disabled) return; const { files, issue } = readClipboardAttachments(e.clipboardData); if (files.length > 0 || issue) { e.preventDefault(); void addFiles(files, issue); } }, [disabled, addFiles], ); const handleDragOver = useCallback( (e: React.DragEvent) => { if (disabled) return; e.preventDefault(); e.stopPropagation(); setIsDragging(true); }, [disabled, setIsDragging], ); const handleDragLeave = useCallback( (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); const rect = e.currentTarget.getBoundingClientRect(); const { clientX, clientY } = e; if ( clientX <= rect.left || clientX >= rect.right || clientY <= rect.top || clientY >= rect.bottom ) { setIsDragging(false); } }, [setIsDragging], ); const handleDrop = useCallback( (e: React.DragEvent) => { e.preventDefault(); e.stopPropagation(); setIsDragging(false); if (disabled) return; const files = Array.from(e.dataTransfer.files).filter((f) => f.size > 0 || f.type !== ""); if (files.length > 0) { void addFiles(files); } }, [disabled, addFiles, setIsDragging], ); return { handlePaste, handleDragOver, handleDragLeave, handleDrop }; } function toContextItems( attachments: FileAttachment[], onRemove: (id: string) => void, onRetry: (id: string) => void, ): ContextItem[] { return attachments.map((att) => att.isImage ? ({ kind: "image" as const, id: `image:${att.id}`, label: t("task:imageWithSize", { bytes: formatBytes(att.size) }), attachment: att, onRemove: () => onRemove(att.id), onRetry: () => onRetry(att.id), } as ImageContextItem) : ({ kind: "file-attachment" as const, id: `file:${att.id}`, label: att.fileName, attachment: att, onRemove: () => onRemove(att.id), onRetry: () => onRetry(att.id), } as FileAttachmentContextItem), ); } function AttachButton({ onClick, disabled }: { onClick: () => void; disabled?: boolean }) { const { t } = useTranslation(); return (
{t("task:attachFiles")}
); } function useDescriptionInput( initialDescription: string, autoFocus: boolean | undefined, descriptionValueRef: React.RefObject, onDescriptionChange: (hasContent: boolean) => void, attachments: FileAttachment[], ) { const [description, setDescription] = useState(initialDescription); const descriptionRef = useRef(initialDescription); const textareaRef = useRef(null); // Caret offset to restore after a non-typed value mutation (e.g. a plugin // transcript splice). Consumed inside useLayoutEffect so the cursor lands // before the next paint and the user sees no jump. const pendingCursorRef = useRef(null); const setDescriptionValue = useCallback( (newValue: string) => { const hadContent = descriptionRef.current.trim().length > 0; const hasContent = newValue.trim().length > 0; descriptionRef.current = newValue; setDescription(newValue); if (hadContent !== hasContent) onDescriptionChange(hasContent); }, [onDescriptionChange], ); useEffect(() => { const ref = descriptionValueRef as React.MutableRefObject; if (ref) { ref.current = { getValue: () => descriptionRef.current, setValue: setDescriptionValue, getAttachments: () => attachments, }; } }, [attachments, descriptionValueRef, setDescriptionValue]); useEffect(() => { const textarea = textareaRef.current; if (!textarea) return; textarea.style.height = "auto"; textarea.style.height = `${textarea.scrollHeight}px`; }, [description]); useLayoutEffect(() => { const pos = pendingCursorRef.current; if (pos === null) return; pendingCursorRef.current = null; const textarea = textareaRef.current; if (!textarea) return; textarea.focus(); textarea.setSelectionRange(pos, pos); }, [description]); useEffect(() => { if (!autoFocus) return; const textarea = textareaRef.current; if (!textarea) return; textarea.focus(); textarea.setSelectionRange(textarea.value.length, textarea.value.length); }, [autoFocus]); const insertAtCursor = useCallback( (text: string) => { // Read the synchronous ref, not the render snapshot: a plugin can // insert twice (or insert then submit) inside one callback, before React // has re-rendered with the first insertion. const current = descriptionRef.current; const textarea = textareaRef.current; // A caret we set but have not applied yet outranks the DOM's: after a // programmatic insertion the textarea still reports the pre-insert // selection until the layout effect below runs, so a second insertion in // the same callback would splice at the old offset. const pending = pendingCursorRef.current; const start = pending ?? textarea?.selectionStart ?? current.length; const end = pending ?? textarea?.selectionEnd ?? current.length; const insert = composerInsertionText(text, start > 0 ? current.charAt(start - 1) : ""); if (!insert) return; const next = current.slice(0, start) + insert + current.slice(end); pendingCursorRef.current = start + insert.length; setDescriptionValue(next); }, [setDescriptionValue], ); return { description, descriptionRef, textareaRef, setDescriptionValue, insertAtCursor }; } type FormInputsToolbarProps = { onAttach: () => void; disabled?: boolean; onEnhancePrompt?: () => void; isEnhancingPrompt?: boolean; isUtilityConfigured?: boolean; launchPreview?: TaskCreateLaunchPreview | null; isLaunchPromptPreview: boolean; onToggleLaunchPromptPreview: () => void; jiraImport?: TaskFormInputsProps["jiraImport"]; linearImport?: TaskFormInputsProps["linearImport"]; pluginActions?: React.ReactNode; }; function FormInputsToolbar({ onAttach, disabled, onEnhancePrompt, isEnhancingPrompt, isUtilityConfigured, launchPreview, isLaunchPromptPreview, onToggleLaunchPromptPreview, jiraImport, linearImport, pluginActions, }: FormInputsToolbarProps) { return (
{onEnhancePrompt && ( )} {launchPreview?.stepPrompt.trim() && ( )} {jiraImport && ( )} {linearImport && ( )}
{pluginActions}
); } function PromptMentionPopover({ mention, }: { mention: ReturnType; }) { return ( ); } function useCreationComposerPluginActions(args: { isSessionMode: boolean; taskId: string | null; disabled: boolean; description: string; descriptionRef: React.RefObject; textareaRef: React.RefObject; insertAtCursor: (text: string) => void; submit?: () => boolean | Promise; }) { const { isMobile } = useResponsiveBreakpoint(); const surface = args.isSessionMode ? "new-session" : "task-create"; const composer = useStablePluginComposerCapability( { insertText: (text) => { args.insertAtCursor(text); return true; }, focus: () => { if (!args.textareaRef.current) return false; args.textareaRef.current.focus(); return true; }, // Gate on the synchronous ref for the same reason the chat composer // reads its editor: insert-then-submit in one callback happens before // React re-renders with the new description. submit: async () => { if (args.disabled || !args.descriptionRef.current.trim() || !args.submit) return false; return await args.submit(); }, }, composerIdentity(surface, args.taskId, null), ); return ( 0, composer, }} /> ); } function useTextareaHandlers( mention: ReturnType, onKeyDown: TaskFormInputsProps["onKeyDown"], ) { const { handleChange: mentionHandleChange, handleKeyDown: mentionHandleKeyDown } = mention; const handleChange = useCallback( (e: React.ChangeEvent) => mentionHandleChange(e.target.value, e.target.selectionStart), [mentionHandleChange], ); const handleKeyDownCapture = useCallback( (e: React.KeyboardEvent) => mentionHandleKeyDown(e), [mentionHandleKeyDown], ); const handleKeyDown = useCallback( (e: React.KeyboardEvent) => { if (e.defaultPrevented) return; onKeyDown?.(e); }, [onKeyDown], ); return { handleChange, handleKeyDownCapture, handleKeyDown }; } function useFileInputClick(addFiles: (files: File[]) => Promise | void) { const fileInputRef = useRef(null); const handleAttachClick = useCallback(() => fileInputRef.current?.click(), []); const handleFileInputChange = useCallback( (e: React.ChangeEvent) => { const files = e.target.files; if (files && files.length > 0) void addFiles(Array.from(files)); e.target.value = ""; }, [addFiles], ); return { fileInputRef, handleAttachClick, handleFileInputChange }; } function HiddenFileInput({ inputRef, onChange, }: { inputRef: React.RefObject; onChange: (e: React.ChangeEvent) => void; }) { return ( ); } function DraggingOverlay({ isDragging }: { isDragging: boolean }) { const { t } = useTranslation(); if (!isDragging) return null; return (
{t("task:dropFilesHere")}
); } // The input coordinates existing attachment, mention and plugin controls in one field. // eslint-disable-next-line max-lines-per-function export const TaskFormInputs = memo(function TaskFormInputs({ workspaceId, isSessionMode, autoFocus, initialDescription, onDescriptionChange, onPendingAttachmentUploadsChange, onKeyDown, descriptionValueRef, disabled, placeholder, onEnhancePrompt, isEnhancingPrompt, isUtilityConfigured, launchPreview, jiraImport, linearImport, onComposerSubmit, taskId = null, }: TaskFormInputsProps) { const { t } = useTranslation(); const [isLaunchPromptPreview, setIsLaunchPromptPreview] = useState(false); const hasLaunchPromptPreview = Boolean(launchPreview?.stepPrompt.trim()); useEffect(() => { if (!hasLaunchPromptPreview) setIsLaunchPromptPreview(false); }, [hasLaunchPromptPreview]); const { attachments, isDragging, setIsDragging, addFiles, handleRemoveAttachment, handleRetryAttachment, } = useFileAttachments(workspaceId, onPendingAttachmentUploadsChange); const { handlePaste, handleDragOver, handleDragLeave, handleDrop } = useAttachmentHandlers( disabled, addFiles, setIsDragging, ); const contextItems = useMemo( () => toContextItems(attachments, handleRemoveAttachment, handleRetryAttachment), [attachments, handleRemoveAttachment, handleRetryAttachment], ); const { description, descriptionRef, textareaRef, setDescriptionValue, insertAtCursor } = useDescriptionInput( initialDescription, autoFocus, descriptionValueRef, onDescriptionChange, attachments, ); const mention = useTaskCreatePromptMention({ textareaRef, value: description, onChange: setDescriptionValue, }); const { handleChange, handleKeyDownCapture, handleKeyDown } = useTextareaHandlers( mention, onKeyDown, ); const { fileInputRef, handleAttachClick, handleFileInputChange } = useFileInputClick(addFiles); const pluginActions = useCreationComposerPluginActions({ isSessionMode, taskId, disabled: Boolean(disabled), description, descriptionRef, textareaRef, insertAtCursor, submit: onComposerSubmit, }); const launchPromptPreview = hasLaunchPromptPreview && launchPreview ? composeLaunchPreviewPrompt(launchPreview.stepPrompt, description) : ""; return (
0 ? "ring-0" : ""}`} > {isLaunchPromptPreview ? ( ) : (