import { toast } from '@/client/components/ui/toast' import { TextAttachmentChip } from './attachments/text-attachment-chip' import { DrawingAttachmentChip } from './attachments/drawing-attachment-chip' import { FileAttachmentChip } from './attachments/file-attachment-chip' import { type RefObject, useEffect, useRef, useState } from 'react' import { draftSessionId, composerDraftKey } from '@/lib/session-drafts' import { useCurrentTabId } from '../sessions/use-selected-session' import { IconPaperclip, IconPlayerStopFilled, IconScribble } from '@tabler/icons-react' import { canSubmitComposerAction, Composer, ComposerFooter, ComposerSubmitButton, ComposerTextarea } from '@/client/components/shared/composer' import { Button } from '@/client/components/ui/button' import { Tooltip, TooltipContent, TooltipTrigger } from '@/client/components/ui/tooltip' import { stageComposerFiles } from '@/client/features/chat/composer/attachments/draft-attachments' import { cn } from '@/client/lib/cn' import type { AgentAvailability } from '@/client/lib/agent-availability' import { useWorkspaceId } from '@/client/features/workspace/workspace-context' import { useLatestRef } from '@/client/lib/use-latest-ref' import { attachmentKey, liveStore, useLive } from '@/client/features/chat/chat-store' import type { StagedAttachment } from '@/client/features/chat/composer/attachments/types' import { useUiStore } from '@/client/store/ui' import { ModelPicker } from './model-picker' export type ComposerAnnotationControls = { active: boolean finish: () => Promise onToggle: () => void onRemove: (localId: string) => void } type ChatComposerProps = { composerRef: RefObject onSend: (text: string) => void | Promise onStop: () => void processing: boolean sessionId: string | null modelSessionId: string | null availability: AgentAvailability chatReady: boolean annotation?: ComposerAnnotationControls onRemoveDrawing?: (localId: string) => void allowFiles?: boolean placeholder?: string } // Draft text is persisted per chat or fresh tab, while attachments remain ephemeral. Both stores are subscribed here so a keystroke or upload // re-renders only the composer. export function ChatComposer({ composerRef, onSend, onStop, processing, sessionId, modelSessionId, availability, chatReady, annotation, onRemoveDrawing, allowFiles = true, placeholder }: ChatComposerProps) { const fileRef = useRef(null) const workspaceId = useWorkspaceId() const tabId = useCurrentTabId() const draftKey = composerDraftKey(workspaceId, sessionId ?? draftSessionId(tabId)) const value = useUiStore(s => s.composerDrafts[draftKey] ?? '') useEffect(() => { if (tabId === 'overview') useUiStore.getState().moveComposerDraft(workspaceId, draftKey) }, [tabId, workspaceId, draftKey]) const valueRef = useLatestRef(value) const attachments = useLive(s => s.attachments[attachmentKey(workspaceId, sessionId)] ?? EMPTY) const [dragOver, setDragOver] = useState(false) const uploading = attachments.some(a => a.kind !== 'text' && a.status === 'uploading') // A draft annotation counts as sendable content: send() finishes the drawing // first, which uploads it before the message goes out. const hasSendable = attachments.some( a => a.kind === 'text' || a.status === 'ready' || a.status === 'draft' ) const hasContent = value.trim().length > 0 || hasSendable const canSend = chatReady && canSubmitComposerAction(hasContent, uploading, availability) const onChange = (next: string) => { valueRef.current = next useUiStore.getState().setComposerDraft(draftKey, next) } const addFiles = (files: File[]) => { if (allowFiles) stageComposerFiles({ workspaceId, sessionId }, files) } // Guards the await window while an annotation finishes: no re-entry from a // second Enter, and the draft is re-read afterwards so text typed during the // upload isn't lost. const sendingRef = useRef(false) const removeAttachment = (attachment: StagedAttachment) => { if (attachment.kind === 'drawing' && onRemoveDrawing) { onRemoveDrawing(attachment.localId) return } liveStore.getState().removeAttachment(workspaceId, attachment.localId) } const send = async () => { if (!canSend || sendingRef.current) return sendingRef.current = true try { await annotation?.finish() await onSend(valueRef.current) valueRef.current = '' useUiStore.getState().setComposerDraft(draftKey, null) } catch (error) { toast.add({ title: error instanceof Error ? error.message : 'Couldn’t send message', type: 'error' }) } finally { sendingRef.current = false } } return ( { e.preventDefault() void send() }} onDragOver={e => { if (!e.dataTransfer.types.includes('Files')) return e.preventDefault() if (allowFiles) setDragOver(true) }} onDragLeave={e => { if (!allowFiles) return // Ignore leaves into child elements — only reset when leaving the form. if (e.currentTarget.contains(e.relatedTarget as Node | null)) return setDragOver(false) }} onDrop={e => { if (!e.dataTransfer.types.includes('Files')) return e.preventDefault() setDragOver(false) addFiles(Array.from(e.dataTransfer.files)) }} className={cn(dragOver && 'ring-2 ring-ring/60')} > {attachments.length > 0 && (
{attachments .toSorted((a, b) => ATTACHMENT_ORDER[a.kind] - ATTACHMENT_ORDER[b.kind]) .map(a => a.kind === 'text' ? ( removeAttachment(a)} /> ) : a.kind === 'drawing' ? ( removeAttachment(a)} /> ) : ( removeAttachment(a)} /> ) )}
)} onChange(e.target.value)} onKeyDown={e => { if (e.key === 'Enter' && !e.shiftKey) { e.preventDefault() void send() } }} onPaste={e => { const files = Array.from(e.clipboardData?.files ?? []) if (files.length === 0) return e.preventDefault() addFiles(files) }} placeholder={processing ? 'Queue a follow-up' : (placeholder ?? 'Do anything')} rows={1} /> {allowFiles && ( { addFiles(Array.from(e.target.files ?? [])) e.target.value = '' }} /> )}
{allowFiles && ( fileRef.current?.click()} aria-label="Attach files" > {/* Paperclip is too heavy compared to the nearby scribble icon */} } /> Attach files )} {annotation && ( } /> Draw annotation )}
{processing ? ( } /> Stop answering ) : ( )}
) } const EMPTY: StagedAttachment[] = [] const ATTACHMENT_ORDER: Record = { file: 0, drawing: 1, text: 2 }