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

228 lines
8.8 KiB
TypeScript
Raw Normal View History

import React, { useState, useRef, useEffect } from 'react';
import clsx from 'clsx';
import {
streamChat, fetchMessages, fetchAttachments, uploadAttachment, getAttachmentDownloadUrl,
type ChatMessage, type ChatAttachment,
} from '@/api/ai';
interface ChatWindowProps {
sessionId: string;
agentId?: string | null;
className?: string;
compact?: boolean;
}
function formatSize(bytes: number): string {
if (bytes < 1024) return `${bytes} B`;
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindowProps) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [attachments, setAttachments] = useState<ChatAttachment[]>([]);
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 [pendingFiles, setPendingFiles] = useState<File[]>([]);
const [uploadingFile, setUploadingFile] = useState(false);
const scrollRef = useRef<HTMLDivElement>(null);
const inputRef = useRef<HTMLTextAreaElement>(null);
const fileInputRef = useRef<HTMLInputElement>(null);
useEffect(() => {
if (!sessionId) return;
setMessages([]);
setAttachments([]);
setError(null);
fetchMessages(sessionId).then(setMessages).catch((e) => setError(e?.message || 'Failed to load messages'));
fetchAttachments(sessionId).then(setAttachments).catch(() => {});
}, [sessionId]);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
}, [messages, streamingContent]);
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(e.target.files || []);
if (files.length === 0) return;
setUploadingFile(true);
try {
for (const file of files) {
const att = await uploadAttachment(sessionId, file);
setAttachments((prev) => [...prev, att]);
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Upload failed');
} finally {
setUploadingFile(false);
if (fileInputRef.current) fileInputRef.current.value = '';
}
};
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)}>
{/* Attachments bar */}
{attachments.length > 0 && (
<div className={clsx('border-b border-secondary-200 bg-secondary-50', compact ? 'px-2 py-1' : 'px-4 py-2')}>
<div className="flex flex-wrap gap-2">
{attachments.map((att) => (
<a
key={att.id}
href={getAttachmentDownloadUrl(att.id)}
target="_blank"
rel="noopener noreferrer"
className="flex items-center gap-1.5 rounded-md bg-white border border-secondary-200 px-2 py-1 text-xs hover:border-primary-400"
>
<svg className="w-3.5 h-3.5 text-secondary-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
</svg>
<span className="max-w-32 truncate">{att.filename}</span>
<span className="text-secondary-400">{formatSize(att.size_bytes)}</span>
</a>
))}
</div>
</div>
)}
{/* Messages */}
<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>
{/* Input */}
<div className={clsx('border-t border-secondary-200', compact ? 'p-2' : 'p-4')}>
<div className="flex items-end gap-2">
<input
ref={fileInputRef}
type="file"
multiple
onChange={handleFileSelect}
className="hidden"
/>
<button
onClick={() => fileInputRef.current?.click()}
disabled={uploadingFile || isStreaming}
className="rounded-lg border border-secondary-300 p-2 text-secondary-500 hover:bg-secondary-100 disabled:opacity-50"
title="Datei anhängen"
>
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15.172 7l-6.586 6.586a2 2 0 102.828 2.828l6.414-6.586a4 4 0 00-5.656-5.656l-6.415 6.585a6 6 0 108.486 8.486L20.5 13" />
</svg>
</button>
<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>
);
}