feat: attachment context for LLM, markdown rendering, mobile layout with back arrow

This commit is contained in:
Agent Zero
2026-07-17 13:45:21 +02:00
parent 202d80c750
commit 70b8a66fd4
5 changed files with 1490 additions and 131 deletions
+30 -83
View File
@@ -1,5 +1,7 @@
import React, { useState, useRef, useEffect } from 'react';
import clsx from 'clsx';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import {
streamChat, fetchMessages, fetchAttachments, uploadAttachment, getAttachmentDownloadUrl,
type ChatMessage, type ChatAttachment,
@@ -18,6 +20,17 @@ function formatSize(bytes: number): string {
return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
}
function MessageContent({ content, role }: { content: string; role: string }) {
if (role === 'user') {
return <div className="whitespace-pre-wrap break-words">{content}</div>;
}
return (
<div className="prose prose-sm max-w-none break-words">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
</div>
);
}
export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindowProps) {
const [messages, setMessages] = useState<ChatMessage[]>([]);
const [attachments, setAttachments] = useState<ChatAttachment[]>([]);
@@ -26,7 +39,6 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
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);
@@ -37,14 +49,12 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
setMessages([]);
setAttachments([]);
setError(null);
fetchMessages(sessionId).then(setMessages).catch((e) => setError(e?.message || 'Failed to load messages'));
fetchMessages(sessionId).then(setMessages).catch((e) => setError(e?.message || 'Failed to load'));
fetchAttachments(sessionId).then(setAttachments).catch(() => {});
}, [sessionId]);
useEffect(() => {
if (scrollRef.current) {
scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}
if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}, [messages, streamingContent]);
const handleFileSelect = async (e: React.ChangeEvent<HTMLInputElement>) => {
@@ -67,27 +77,18 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
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: '',
};
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;
@@ -116,29 +117,17 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
};
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter' && !e.shiftKey) {
e.preventDefault();
handleSend();
}
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>
<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>
@@ -146,22 +135,16 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
</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>
<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>
<MessageContent content={msg.content} role={msg.role} />
{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 className="mt-2 text-xs opacity-70">Tools: {msg.tool_calls.map((tc: any) => tc.function?.name).join(', ')}</div>
)}
</div>
</div>
@@ -169,57 +152,21 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
{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>
<MessageContent content={streamingContent} role="assistant" />
</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>
)}
{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'}
<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>
+35 -38
View File
@@ -8,58 +8,55 @@ export function AIAssistantPage() {
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
const [agents, setAgents] = useState<AIAgent[]>([]);
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
const [mobileView, setMobileView] = useState<'list' | 'chat'>('list');
const { registerItems, unregisterPlugin } = usePluginToolbarStore();
useEffect(() => {
fetchAgents().then(setAgents).catch(() => {});
}, []);
useEffect(() => { fetchAgents().then(setAgents).catch(() => {}); }, []);
useEffect(() => {
registerItems('ai_assistant', [
{
id: 'agent-select',
label: 'Agent',
type: 'select',
options: agents.map((a) => ({ value: a.id, label: a.name })),
value: selectedAgentId || '',
onChange: (val: string) => setSelectedAgentId(val || null),
},
{
id: 'new-chat',
label: 'Neuer Chat',
type: 'button',
onClick: () => setActiveSessionId(null),
},
{ id: 'agent-select', label: 'Agent', type: 'select', options: agents.map((a) => ({ value: a.id, label: a.name })), value: selectedAgentId || '', onChange: (val: string) => setSelectedAgentId(val || null) },
{ id: 'new-chat', label: 'Neuer Chat', type: 'button', onClick: () => { setActiveSessionId(null); setMobileView('list'); } },
]);
return () => unregisterPlugin('ai_assistant');
}, [agents, selectedAgentId, registerItems, unregisterPlugin]);
const handleSelectSession = (id: string) => { setActiveSessionId(id); setMobileView('chat'); };
return (
<div className="flex h-full" data-testid="ai-assistant-page">
{/* Left: Session List with TreeView */}
<div className="w-72 flex-shrink-0 border-r border-secondary-200 bg-white">
<div className="h-16 flex items-center px-6 border-b border-secondary-200">
<h1 className="text-lg font-bold text-secondary-900">KI Assistent</h1>
</div>
<SessionList
activeSessionId={activeSessionId}
onSelectSession={setActiveSessionId}
className="h-[calc(100%-4rem)]"
/>
{/* Desktop: two-pane layout */}
<div className="hidden md:flex w-72 flex-shrink-0 border-r border-secondary-200 bg-white flex-col">
<div className="h-16 flex items-center px-6 border-b border-secondary-200"><h1 className="text-lg font-bold text-secondary-900">KI Assistent</h1></div>
<SessionList activeSessionId={activeSessionId} onSelectSession={setActiveSessionId} className="h-[calc(100%-4rem)]" />
</div>
{/* Right: Chat Window */}
<div className="flex-1 flex flex-col">
{activeSessionId ? (
<ChatWindow sessionId={activeSessionId} agentId={selectedAgentId} className="flex-1" />
) : (
<div className="flex-1 flex items-center justify-center text-secondary-400">
<div className="text-center">
<div className="text-4xl mb-3">🤖</div>
<div className="text-sm">Wähle einen Chat oder erstelle einen neuen</div>
</div>
<div className="hidden md:flex flex-1 flex-col">
{activeSessionId ? <ChatWindow sessionId={activeSessionId} agentId={selectedAgentId} className="flex-1" /> : (
<div className="flex-1 flex items-center justify-center text-secondary-400"><div className="text-center"><div className="text-4xl mb-3">🤖</div><div className="text-sm">Wähle einen Chat oder erstelle einen neuen</div></div></div>
)}
</div>
{/* Mobile: single-pane view switching */}
<div className="flex md:hidden flex-1 flex-col overflow-hidden">
{mobileView === 'list' && (
<div className="flex-1 flex flex-col bg-white">
<div className="h-14 flex items-center px-4 border-b border-secondary-200"><h1 className="text-lg font-bold text-secondary-900">KI Assistent</h1></div>
<SessionList activeSessionId={activeSessionId} onSelectSession={handleSelectSession} className="flex-1" />
</div>
)}
{mobileView === 'chat' && activeSessionId && (
<div className="flex-1 flex flex-col">
<div className="h-14 flex items-center gap-2 px-3 border-b border-secondary-200 bg-white">
<button onClick={() => setMobileView('list')} className="p-2 rounded-lg hover:bg-secondary-100" aria-label="Zurück">
<svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 19l-7-7 7-7" /></svg>
</button>
<span className="text-sm font-medium text-secondary-700 truncate">Chat</span>
</div>
<ChatWindow sessionId={activeSessionId} agentId={selectedAgentId} className="flex-1" />
</div>
)}
{mobileView === 'chat' && !activeSessionId && (
<div className="flex-1 flex items-center justify-center text-secondary-400"><div className="text-center"><div className="text-4xl mb-3">🤖</div><div className="text-sm">Wähle einen Chat</div></div></div>
)}
</div>
</div>
);