({ conversationId }: ChatInputProps)
| 12 | } |
| 13 | |
| 14 | export function ChatInput({ conversationId }: ChatInputProps) { |
| 15 | const [input, setInput] = useState(""); |
| 16 | const [isStreaming, setIsStreaming] = useState(false); |
| 17 | const textareaRef = useRef<HTMLTextAreaElement>(null); |
| 18 | const abortRef = useRef<AbortController | null>(null); |
| 19 | |
| 20 | const { conversations, settings, addMessage, updateMessage } = useChatStore(); |
| 21 | const conversation = conversations.find((c) => c.id === conversationId); |
| 22 | |
| 23 | const handleSubmit = useCallback(async () => { |
| 24 | const text = input.trim(); |
| 25 | if (!text || isStreaming) return; |
| 26 | |
| 27 | setInput(""); |
| 28 | setIsStreaming(true); |
| 29 | |
| 30 | // Add user message |
| 31 | addMessage(conversationId, { |
| 32 | role: "user", |
| 33 | content: text, |
| 34 | status: "complete", |
| 35 | }); |
| 36 | |
| 37 | // Add placeholder assistant message |
| 38 | const assistantId = addMessage(conversationId, { |
| 39 | role: "assistant", |
| 40 | content: "", |
| 41 | status: "streaming", |
| 42 | }); |
| 43 | |
| 44 | const controller = new AbortController(); |
| 45 | abortRef.current = controller; |
| 46 | |
| 47 | const messages = [ |
| 48 | ...(conversation?.messages ?? []).map((m) => ({ |
| 49 | role: m.role, |
| 50 | content: m.content, |
| 51 | })), |
| 52 | { role: "user" as const, content: text }, |
| 53 | ]; |
| 54 | |
| 55 | let fullText = ""; |
| 56 | |
| 57 | try { |
| 58 | for await (const chunk of streamChat(messages, settings.model, controller.signal)) { |
| 59 | if (chunk.type === "text" && chunk.content) { |
| 60 | fullText += chunk.content; |
| 61 | updateMessage(conversationId, assistantId, { |
| 62 | content: fullText, |
| 63 | status: "streaming", |
| 64 | }); |
| 65 | } else if (chunk.type === "done") { |
| 66 | break; |
| 67 | } else if (chunk.type === "error") { |
| 68 | updateMessage(conversationId, assistantId, { |
| 69 | content: chunk.error ?? "An error occurred", |
| 70 | status: "error", |
| 71 | }); |
nothing calls this directly
no test coverage detected