feat: treeview with folders, toolbar, file attachments in chat

This commit is contained in:
Agent Zero
2026-07-17 09:21:40 +02:00
parent 9a29206190
commit 202d80c750
4 changed files with 349 additions and 57 deletions
+51 -1
View File
@@ -61,6 +61,14 @@ export interface AIAgent {
updated_at?: string;
}
export interface ChatFolder {
id: string;
name: string;
parent_id: string | null;
user_id: string;
created_at?: string;
}
export interface ChatSession {
id: string;
user_id: string;
@@ -68,6 +76,7 @@ export interface ChatSession {
title: string;
is_pinned: boolean;
is_sidebar: boolean;
folder_id: string | null;
created_at?: string;
updated_at?: string;
}
@@ -84,6 +93,15 @@ export interface ChatMessage {
created_at?: string;
}
export interface ChatAttachment {
id: string;
message_id: string | null;
session_id: string;
filename: string;
mime_type: string;
size_bytes: number;
}
export interface AITool {
name: string;
description: string;
@@ -126,11 +144,18 @@ export const deleteAgent = (id: string) => apiDelete(`/ai/agents/${id}`);
export const fetchTools = () => apiGet<AITool[]>('/ai/tools');
// ─── Folders ───
export const fetchFolders = () => apiGet<ChatFolder[]>('/ai/folders');
export const createFolder = (data: { name: string; parent_id?: string }) => apiPost<ChatFolder>('/ai/folders', data);
export const updateFolder = (id: string, data: Partial<ChatFolder>) => apiPut<ChatFolder>(`/ai/folders/${id}`, data);
export const deleteFolder = (id: string) => apiDelete(`/ai/folders/${id}`);
// ─── Sessions ───
export const fetchSessions = (isSidebar?: boolean) =>
apiGet<ChatSession[]>('/ai/sessions', { params: isSidebar !== undefined ? { is_sidebar: isSidebar } : {} });
export const createSession = (data: { title?: string; agent_id?: string; is_sidebar?: boolean }) =>
export const createSession = (data: { title?: string; agent_id?: string; is_sidebar?: boolean; folder_id?: string }) =>
apiPost<ChatSession>('/ai/sessions', data);
export const updateSession = (id: string, data: Partial<ChatSession>) =>
apiPut<ChatSession>(`/ai/sessions/${id}`, data);
@@ -141,6 +166,31 @@ export const deleteSession = (id: string) => apiDelete(`/ai/sessions/${id}`);
export const fetchMessages = (sessionId: string) =>
apiGet<ChatMessage[]>(`/ai/sessions/${sessionId}/messages`);
// ─── Attachments ───
export const fetchAttachments = (sessionId: string) =>
apiGet<ChatAttachment[]>(`/ai/sessions/${sessionId}/attachments`);
export async function uploadAttachment(sessionId: string, file: File): Promise<ChatAttachment> {
const formData = new FormData();
formData.append('file', file);
const csrfToken = sessionStorage.getItem('leocrm_csrf_token');
const response = await fetch(`/api/v1/ai/sessions/${sessionId}/attachments`, {
method: 'POST',
headers: {
...(csrfToken ? { 'X-CSRF-Token': csrfToken } : {}),
},
credentials: 'include',
body: formData,
});
if (!response.ok) throw new Error(`Upload failed: ${response.status}`);
return response.json();
}
export function getAttachmentDownloadUrl(attachmentId: string): string {
return `/api/v1/ai/attachments/${attachmentId}/download`;
}
// ─── Streaming Chat ───
export interface StreamEvent {
+77 -4
View File
@@ -1,6 +1,9 @@
import React, { useState, useRef, useEffect } from 'react';
import clsx from 'clsx';
import { streamChat, fetchMessages, type ChatMessage } from '@/api/ai';
import {
streamChat, fetchMessages, fetchAttachments, uploadAttachment, getAttachmentDownloadUrl,
type ChatMessage, type ChatAttachment,
} from '@/api/ai';
interface ChatWindowProps {
sessionId: string;
@@ -9,23 +12,33 @@ interface ChatWindowProps {
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((msgs) => setMessages(msgs))
.catch((e) => setError(e?.message || 'Failed to load messages'));
fetchMessages(sessionId).then(setMessages).catch((e) => setError(e?.message || 'Failed to load messages'));
fetchAttachments(sessionId).then(setAttachments).catch(() => {});
}, [sessionId]);
useEffect(() => {
@@ -34,6 +47,23 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
}
}, [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;
@@ -94,6 +124,30 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
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">
@@ -128,8 +182,27 @@ export function ChatWindow({ sessionId, agentId, className, compact }: ChatWindo
</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}
+185 -46
View File
@@ -1,6 +1,10 @@
import React, { useEffect, useState } from 'react';
import clsx from 'clsx';
import { fetchSessions, createSession, deleteSession, updateSession, type ChatSession } from '@/api/ai';
import {
fetchSessions, createSession, deleteSession, updateSession,
fetchFolders, createFolder, deleteFolder, updateFolder,
type ChatSession, type ChatFolder,
} from '@/api/ai';
interface SessionListProps {
activeSessionId: string | null;
@@ -9,27 +13,160 @@ interface SessionListProps {
className?: string;
}
interface TreeNode {
folder: ChatFolder | null;
sessions: ChatSession[];
children: TreeNode[];
}
function buildTree(folders: ChatFolder[], sessions: ChatSession[]): TreeNode[] {
const rootSessions = sessions.filter((s) => !s.folder_id);
const root: TreeNode = { folder: null, sessions: rootSessions, children: [] };
const folderMap = new Map<string, TreeNode>();
for (const f of folders) {
folderMap.set(f.id, { folder: f, sessions: [], children: [] });
}
for (const f of folders) {
const node = folderMap.get(f.id)!;
if (f.parent_id && folderMap.has(f.parent_id)) {
folderMap.get(f.parent_id)!.children.push(node);
} else {
root.children.push(node);
}
}
for (const s of sessions) {
if (s.folder_id && folderMap.has(s.folder_id)) {
folderMap.get(s.folder_id)!.sessions.push(s);
}
}
return [root];
}
function TreeItem({
node, activeSessionId, onSelectSession, depth, onMoveSession, onDeleteFolder, onAddFolder,
}: {
node: TreeNode;
activeSessionId: string | null;
onSelectSession: (id: string) => void;
depth: number;
onMoveSession: (sessionId: string, folderId: string | null) => void;
onDeleteFolder: (folderId: string) => void;
onAddFolder: (parentId: string | null) => void;
}) {
const [expanded, setExpanded] = useState(true);
const isRoot = node.folder === null;
return (
<div>
{/* Folder header */}
{!isRoot && (
<div
className="group flex items-center gap-1 px-2 py-1.5 text-sm font-medium text-secondary-700 hover:bg-secondary-100 rounded-md cursor-pointer"
style={{ paddingLeft: depth * 12 + 8 }}
onClick={() => setExpanded(!expanded)}
>
<svg className={clsx('w-4 h-4 transition-transform', expanded && 'rotate-90')} fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 5l7 7-7 7" />
</svg>
<svg className="w-4 h-4 text-secondary-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z" />
</svg>
<span className="flex-1 truncate">{node.folder!.name}</span>
<button
onClick={(e) => { e.stopPropagation(); onAddFolder(node.folder!.id); }}
className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-primary-600"
title="Unterordner"
>+</button>
<button
onClick={(e) => { e.stopPropagation(); onDeleteFolder(node.folder!.id); }}
className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-red-600"
title="Löschen"
></button>
</div>
)}
{/* Sessions in this folder */}
{(isRoot || expanded) && (
<div>
{node.sessions.map((session) => (
<div
key={session.id}
onClick={() => onSelectSession(session.id)}
className={clsx(
'group flex items-center gap-2 px-3 py-1.5 text-sm cursor-pointer rounded-md',
'hover:bg-secondary-100',
activeSessionId === session.id && 'bg-primary-100 text-primary-700'
)}
style={{ paddingLeft: depth * 12 + 24 }}
>
<svg className="w-3.5 h-3.5 text-secondary-400 flex-shrink-0" fill="none" viewBox="0 0 24 24" stroke="currentColor">
<path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M8 12h8M8 8h8m-8 4h8m-8 4h8" />
</svg>
<span className="flex-1 truncate">{session.title}</span>
<button
onClick={(e) => {
e.stopPropagation();
const folderId = node.folder?.id || null;
onMoveSession(session.id, folderId ? null : 'root');
}}
className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-primary-600"
title="Verschieben"
></button>
<button
onClick={(e) => { e.stopPropagation(); deleteSession(session.id).then(() => window.location.reload()); }}
className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-red-600"
title="Löschen"
></button>
</div>
))}
</div>
)}
{/* Child folders */}
{(isRoot || expanded) && node.children.map((child) => (
<TreeItem
key={child.folder!.id}
node={child}
activeSessionId={activeSessionId}
onSelectSession={onSelectSession}
depth={depth + 1}
onMoveSession={onMoveSession}
onDeleteFolder={onDeleteFolder}
onAddFolder={onAddFolder}
/>
))}
</div>
);
}
export function SessionList({ activeSessionId, onSelectSession, isSidebar, className }: SessionListProps) {
const [sessions, setSessions] = useState<ChatSession[]>([]);
const [folders, setFolders] = useState<ChatFolder[]>([]);
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const loadSessions = async () => {
const loadData = async () => {
try {
setLoading(true);
const data = await fetchSessions(isSidebar ? true : undefined);
setSessions(data);
const [s, f] = await Promise.all([
fetchSessions(isSidebar ? true : undefined),
fetchFolders(),
]);
setSessions(s);
setFolders(f);
setError(null);
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to load sessions');
setError(e instanceof Error ? e.message : 'Failed to load');
} finally {
setLoading(false);
}
};
useEffect(() => {
loadSessions();
}, [isSidebar]);
useEffect(() => { loadData(); }, [isSidebar]);
const handleNewChat = async () => {
try {
@@ -41,62 +178,64 @@ export function SessionList({ activeSessionId, onSelectSession, isSidebar, class
}
};
const handleDelete = async (id: string, e: React.MouseEvent) => {
e.stopPropagation();
const handleAddFolder = (parentId: string | null) => {
const name = prompt('Ordnername:');
if (!name) return;
createFolder({ name, parent_id: parentId || undefined })
.then(() => loadData())
.catch((e) => setError(e?.message));
};
const handleDeleteFolder = (folderId: string) => {
if (!confirm('Ordner löschen? Chats bleiben erhalten.')) return;
deleteFolder(folderId).then(() => loadData()).catch((e) => setError(e?.message));
};
const handleMoveSession = async (sessionId: string, target: string) => {
const folderId = target === 'root' ? null : target;
try {
await deleteSession(id);
setSessions((prev) => prev.filter((s) => s.id !== id));
if (activeSessionId === id) {
onSelectSession('');
}
await updateSession(sessionId, { folder_id: folderId });
loadData();
} catch (e) {
setError(e instanceof Error ? e.message : 'Failed to delete session');
setError(e instanceof Error ? e.message : 'Failed to move');
}
};
if (loading) {
return <div className="p-4 text-sm text-secondary-400">Laden...</div>;
}
if (loading) return <div className="p-4 text-sm text-secondary-400">Laden...</div>;
const tree = buildTree(folders, sessions);
return (
<div className={clsx('flex flex-col h-full', className)}>
<div className="p-3 border-b border-secondary-200">
<div className="p-3 border-b border-secondary-200 flex gap-2">
<button
onClick={handleNewChat}
className="w-full rounded-lg bg-primary-600 text-white px-3 py-2 text-sm font-medium hover:bg-primary-700"
className="flex-1 rounded-lg bg-primary-600 text-white px-3 py-2 text-sm font-medium hover:bg-primary-700"
>
+ Neuer Chat
</button>
</div>
{error && <div className="p-2 text-xs text-red-600">{error}</div>}
<div className="flex-1 overflow-y-auto">
{sessions.length === 0 ? (
<div className="p-4 text-sm text-secondary-400 text-center">Keine Chats vorhanden</div>
) : (
<ul className="space-y-1 p-2">
{sessions.map((session) => (
<li key={session.id}>
<div
onClick={() => onSelectSession(session.id)}
className={clsx(
'group flex items-center gap-2 rounded-lg px-3 py-2 text-sm cursor-pointer',
'hover:bg-secondary-100',
activeSessionId === session.id && 'bg-primary-100 text-primary-700'
)}
>
<span className="flex-1 truncate">{session.title}</span>
<button
onClick={(e) => handleDelete(session.id, e)}
className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-red-600"
title="Loeschen"
onClick={() => handleAddFolder(null)}
className="rounded-lg border border-secondary-300 px-3 py-2 text-sm hover:bg-secondary-100"
title="Neuer Ordner"
>
📁+
</button>
</div>
</li>
{error && <div className="p-2 text-xs text-red-600">{error}</div>}
<div className="flex-1 overflow-y-auto p-2">
{tree.map((node) => (
<TreeItem
key={node.folder?.id || 'root'}
node={node}
activeSessionId={activeSessionId}
onSelectSession={onSelectSession}
depth={0}
onMoveSession={handleMoveSession}
onDeleteFolder={handleDeleteFolder}
onAddFolder={handleAddFolder}
/>
))}
</ul>
)}
</div>
</div>
);
+33 -3
View File
@@ -1,13 +1,43 @@
import React, { useState } from 'react';
import React, { useState, useEffect } from 'react';
import { SessionList } from '@/components/ai/SessionList';
import { ChatWindow } from '@/components/ai/ChatWindow';
import { usePluginToolbarStore } from '@/store/pluginToolbarStore';
import { fetchAgents, type AIAgent } from '@/api/ai';
export function AIAssistantPage() {
const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
const [agents, setAgents] = useState<AIAgent[]>([]);
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
const { registerItems, unregisterPlugin } = usePluginToolbarStore();
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),
},
]);
return () => unregisterPlugin('ai_assistant');
}, [agents, selectedAgentId, registerItems, unregisterPlugin]);
return (
<div className="flex h-full" data-testid="ai-assistant-page">
{/* Left: Session List */}
{/* 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>
@@ -21,7 +51,7 @@ export function AIAssistantPage() {
{/* Right: Chat Window */}
<div className="flex-1 flex flex-col">
{activeSessionId ? (
<ChatWindow sessionId={activeSessionId} className="flex-1" />
<ChatWindow sessionId={activeSessionId} agentId={selectedAgentId} className="flex-1" />
) : (
<div className="flex-1 flex items-center justify-center text-secondary-400">
<div className="text-center">