Files
leocrm/frontend/src/components/ai/ChatWindow.tsx
T

155 lines
5.6 KiB
TypeScript
Raw Normal View History

import React, { useState, useRef, useEffect } from 'react';
import clsx from 'clsx';
import { streamChat, fetchMessages, type ChatMessage } from '@/api/ai';
interface ChatWindowProps {
sessionId: string;
agentId?: string | null;
className?: string;
compact?: boolean;
}
export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindowProps) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [input, setInput] = useState('');
const [isStreaming, setIsStreaming] = useState(false);
const [streamingContent, setStreamingContent] = useState('');
const [toolStatus, setToolStatus] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
useEffect(() => {
if (!sessionId) return;
setMessages([]);
setError(null);
fetchMessages(sessionId)
.then((msgs) => setMessages(msgs))
.catch((e) => setError(e?.message || 'Failed to load messages'));
}, [sessionId]);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages, streamingContent]);
const handleSend = async () => {
const content = input.trim();
if (!content || isStreaming) return;
setInput('');
setIsStreaming(true);
setStreamingContent('');
setToolStatus(null);
setError(null);
const userMsg: ChatMessage = {
id: 'temp-' + Date.now(),
session_id: sessionId,
role: 'user',
content,
tokens: 0,
model_used: '',
};
setMessages((prev) => [...prev, userMsg]);
try {
const stream = streamChat(sessionId, content, agentId || undefined);
let accumulated = '';
for await (const event of stream) {
if (event.type === 'token' && event.content) {
accumulated += event.content;
setStreamingContent(accumulated);
} else if (event.type === 'tool_calls' && event.tools) {
setToolStatus(`Tools: ${event.tools.join(', ')}`);
} else if (event.type === 'tool_result' && event.tool) {
setToolStatus(`Tool '${event.tool}' ausgefuehrt`);
} else if (event.type === 'done') {
setToolStatus(null);
const msgs = await fetchMessages(sessionId);
setMessages(msgs);
setStreamingContent('');
} else if (event.type === 'error') {
setError(event.content || 'Unknown error');
}
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Stream failed');
} finally {
setIsStreaming(false);
setStreamingContent('');
setToolStatus(null);
inputRef.current?.focus();
}
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
};
return (
<div className={clsx('flex flex-col h-full bg-white', className)}>
<div ref={scrollRef} className={clsx('flex-1 overflow-y-auto', compact ? 'p-3' : 'p-6')}>
{messages.length === 0 && !streamingContent && !error && (
<div className="flex items-center justify-center h-full text-secondary-400 text-sm">
Starte eine Konversation...
</div>
)}
{messages.map((msg) => (
<div key={msg.id} className={clsx('mb-4 flex', msg.role === 'user' ? 'justify-end' : 'justify-start')}>
<div className={clsx('max-w-[80%] rounded-lg px-4 py-2 text-sm', msg.role === 'user' ? 'bg-primary-600 text-white' : 'bg-secondary-100 text-secondary-900')}>
<div className="whitespace-pre-wrap break-words">{msg.content}</div>
{msg.tool_calls && msg.tool_calls.length > 0 && (
<div className="mt-2 text-xs opacity-70">
Tools: {msg.tool_calls.map((tc: any) => tc.function?.name).join(', ')}
</div>
)}
</div>
</div>
))}
{streamingContent && (
<div className="mb-4 flex justify-start">
<div className="max-w-[80%] rounded-lg px-4 py-2 text-sm bg-secondary-100 text-secondary-900">
<div className="whitespace-pre-wrap break-words">{streamingContent}</div>
</div>
</div>
)}
{toolStatus && (
<div className="mb-2 text-center text-xs text-secondary-500"> {toolStatus}</div>
)}
{error && (
<div className="mb-4 flex justify-center">
<div className="rounded-lg px-4 py-2 text-sm bg-red-50 text-red-700">{error}</div>
</div>
)}
</div>
<div className={clsx('border-t border-secondary-200', compact ? 'p-2' : 'p-4')}>
<div className="flex items-end gap-2">
<textarea
ref={inputRef}
value={input}
onChange={(e) => setInput(e.target.value)}
onKeyDown={handleKeyDown}
disabled={isStreaming}
placeholder="Nachricht eingeben..."
rows={compact ? 1 : 2}
className={clsx('flex-1 resize-none rounded-lg border border-secondary-300 px-3 py-2 text-sm', 'focus:outline-none focus:ring-2 focus:ring-primary-500', 'disabled:opacity-50')}
/>
<button
onClick={handleSend}
disabled={isStreaming || !input.trim()}
className={clsx('rounded-lg px-4 py-2 text-sm font-medium text-white', 'bg-primary-600 hover:bg-primary-700', 'disabled:opacity-50 disabled:cursor-not-allowed')}
>
{isStreaming ? '...' : 'Senden'}
</button>
</div>
</div>
</div>
);
}