feat(UI-Overhaul-Phase2): AI Assistent in Kommunikation integriert
Check Cross-Plugin Imports / check (push) Has been cancelled

Migration 0137: Drop AI chat tables (ai_chat_sessions, ai_chat_messages, ai_chat_attachments, ai_conversations, ai_messages)

Backend:
- Remove AIChatSession, AIChatMessage, AIChatAttachment models from ai_assistant/models.py
- Remove AIConversation, AIMessage from app/models/__init__.py
- Remove session/message/stream/attachment routes from ai_assistant/routes.py
- Add new streaming route POST /ai/conversations/{conversation_id}/stream using comm tables
- Add new messages route GET /ai/conversations/{conversation_id}/messages using comm tables
- Add stream_chat_comm, get_comm_messages, save_comm_message to services.py
- Update external_api.py to use CommConversation/CommMessage instead of AIChatSession/AIChatMessage
- Update unified_search ai_chat_provider to search comm_messages with conversation_type=ai
- Remove ai_copilot router from main.py and routes/__init__.py
- Remove ai_conversation from entity_permissions.py and owner_transfer_service.py
- Update ai_assistant/plugin.py get_entity_models to remove AIChatSession
- Guard ai_copilot_service.py imports with try/except

Frontend:
- Remove AIAssistant.tsx, AIAssistantStandalone.tsx, SessionList.tsx, ChatWindow.tsx
- Remove AI Assistant routes from routes/index.tsx
- Update api/ai.ts: streamChat uses /ai/conversations/{id}/stream, fetchMessages uses /ai/conversations/{id}/messages
- Update Communication.tsx: use convId for AI streaming, remove aiSessionId, use fetchAiMessages for AI conversations
- Update AiChatPanel.tsx: create comm conversation instead of AI session, use new fetchMessages
- Update AISidebar.tsx: remove ChatWindow import, show placeholder

tsc clean, build successful, backend import OK
This commit is contained in:
Agent Zero
2026-08-21 13:34:54 +02:00
parent 94c7c8fff5
commit 7f61dfb25b
22 changed files with 361 additions and 1472 deletions
+4 -4
View File
@@ -166,8 +166,8 @@ export const deleteSession = (id: string) => apiDelete(`/ai/sessions/${id}`);
// ─── Messages ───
export const fetchMessages = (sessionId: string) =>
apiGet<ChatMessage[]>(`/ai/sessions/${sessionId}/messages`);
export const fetchMessages = (conversationId: string) =>
apiGet<{ role: string; content: string }[]>(`/ai/conversations/${conversationId}/messages`);
// ─── Attachments ───
@@ -205,12 +205,12 @@ export interface StreamEvent {
}
export async function* streamChat(
sessionId: string,
conversationId: string,
content: string,
agentId?: string
): AsyncGenerator<StreamEvent> {
const csrfToken = sessionStorage.getItem('leocrm_csrf_token');
const response = await fetch(`/api/v1/ai/sessions/${sessionId}/stream`, {
const response = await fetch(`/api/v1/ai/conversations/${conversationId}/stream`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
-196
View File
@@ -1,196 +0,0 @@
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,
} 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`;
}
function MessageContent({ content, role }: { content: string; role: string }) {
if (role === 'user') {
return <div className="whitespace-pre-wrap break-words">{content}</div>;
}
return (
<div className="ai-markdown max-w-none break-words">
<ReactMarkdown remarkPlugins={[remarkGfm]}>{content}</ReactMarkdown>
</div>
);
}
function ActivityIndicator({ status }: { status: string | null }) {
if (!status) return null;
return (
<div className="flex items-center gap-2 px-4 py-2 text-xs text-secondary-500">
<div className="flex gap-1">
<span className="w-1.5 h-1.5 rounded-full bg-primary-400 animate-bounce [animation-delay:0ms]" />
<span className="w-1.5 h-1.5 rounded-full bg-primary-400 animate-bounce [animation-delay:150ms]" />
<span className="w-1.5 h-1.5 rounded-full bg-primary-400 animate-bounce [animation-delay:300ms]" />
</div>
<span>{status}</span>
</div>
);
}
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 [activity, setActivity] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
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'));
fetchAttachments(sessionId).then(setAttachments).catch(() => {});
}, [sessionId]);
useEffect(() => {
if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}, [messages, streamingContent, activity]);
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('');
setActivity('Denke nach...');
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);
setActivity(null);
} else if (event.type === 'tool_calls' && event.tools) {
setActivity(`Rufe Tool auf: ${event.tools.join(', ')}`);
} else if (event.type === 'tool_result' && event.tool) {
setActivity(`Tool '${event.tool}' ausgeführt`);
} else if (event.type === 'done') {
setActivity(null);
const msgs = await fetchMessages(sessionId);
setMessages(msgs);
setStreamingContent('');
} else if (event.type === 'error') {
setError(event.content || 'Unknown error');
setActivity(null);
}
}
} catch (e) {
setError(e instanceof Error ? e.message : 'Stream failed');
} finally {
setIsStreaming(false);
setStreamingContent('');
setActivity(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.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>
)}
<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="mb-6">
<div className={clsx('text-xs font-medium mb-1', msg.role === 'user' ? 'text-primary-600' : 'text-secondary-400')}>
{msg.role === 'user' ? 'Du' : 'KI'}
</div>
<div className={clsx('rounded-lg px-4 py-2 text-sm', msg.role === 'user' ? 'bg-primary-50 border border-primary-100' : '')}>
<MessageContent content={msg.content} role={msg.role} />
{msg.tool_calls && msg.tool_calls.length > 0 && (
<div className="mt-2 text-xs text-secondary-400 border-l-2 border-secondary-200 pl-2">
Tools: {msg.tool_calls.map((tc: any) => tc.function?.name).join(', ')}
</div>
)}
</div>
</div>
))}
{streamingContent && (
<div className="mb-6">
<div className="text-xs font-medium mb-1 text-secondary-400">KI</div>
<div className="text-sm text-secondary-900">
<MessageContent content={streamingContent} role="assistant" />
</div>
</div>
)}
<ActivityIndicator status={activity} />
{error && <div className="mb-4 text-sm text-red-600">{typeof error === "string" ? error : (error as any)?.message || "Ein Fehler ist aufgetreten"}</div>}
</div>
<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>
);
}
-385
View File
@@ -1,385 +0,0 @@
import React, { useEffect, useState, useRef, useCallback } from 'react';
import clsx from 'clsx';
import { useQueryClient } from '@tanstack/react-query';
import {
fetchSessions, createSession, deleteSession, updateSession,
fetchFolders, createFolder, deleteFolder, updateFolder,
type ChatSession, type ChatFolder,
} from '@/api/ai';
interface SessionListProps {
activeSessionId: string | null;
onSelectSession: (id: string) => void;
isSidebar?: boolean;
className?: string;
}
interface TreeNode {
folder: ChatFolder | null;
sessions: ChatSession[];
children: TreeNode[];
}
interface ContextMenuState {
x: number;
y: number;
type: 'session' | 'folder' | 'root';
id: string | null;
}
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, onContextMenu, onDragSession, onDragFolder, onDropToFolder, onDelete, onRename,
}: {
node: TreeNode;
activeSessionId: string | null;
onSelectSession: (id: string) => void;
depth: number;
onContextMenu: (e: React.MouseEvent, type: 'session' | 'folder' | 'root', id: string | null) => void;
onDragSession: (sessionId: string) => void;
onDragFolder: (folderId: string) => void;
onDropToFolder: (folderId: string | null) => void;
onDelete: (id: string, type: 'session' | 'folder') => void;
onRename: (id: string, type: 'session' | 'folder') => void;
}) {
const [expanded, setExpanded] = useState(true);
const [isDragOver, setIsDragOver] = useState(false);
const isRoot = node.folder === null;
const folderId = node.folder?.id || null;
const handleDrop = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
setIsDragOver(false);
const data = e.dataTransfer.getData('text/plain');
if (data.startsWith('folder:')) {
const draggedFolderId = data.slice(7);
if (draggedFolderId !== folderId) {
onDropToFolder(folderId);
}
} else {
onDropToFolder(folderId);
}
};
const handleDragOver = (e: React.DragEvent) => {
e.preventDefault();
e.stopPropagation();
if (!isRoot) setIsDragOver(true);
};
return (
<div>
{/* Folder header - drop target */}
{!isRoot && (
<div
onDragOver={handleDragOver}
onDragLeave={() => setIsDragOver(false)}
onDrop={handleDrop}
onContextMenu={(e) => onContextMenu(e, 'folder', node.folder!.id)}
className={clsx(
'group flex items-center gap-1 px-2 py-1.5 text-sm font-medium rounded-md cursor-pointer',
isDragOver ? 'bg-primary-100 ring-2 ring-primary-400' : 'text-secondary-700 hover:bg-secondary-100'
)}
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>
<span
draggable
onDragStart={(e) => {
e.dataTransfer.setData('text/plain', `folder:${node.folder!.id}`);
e.dataTransfer.effectAllowed = 'move';
onDragFolder(node.folder!.id);
}}
className="cursor-grab active:cursor-grabbing flex items-center"
title="Ordner verschieben"
>
<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>
<span className="flex-1 truncate">{node.folder!.name}</span>
<button onClick={(e) => { e.stopPropagation(); onRename(node.folder!.id, 'folder'); }} className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-primary-600 p-0.5" title="Umbenennen">
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
</button>
<button onClick={(e) => { e.stopPropagation(); onDelete(node.folder!.id, 'folder'); }} className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-red-600 p-0.5" title="Löschen">
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
</button>
</div>
)}
{/* Sessions */}
{(isRoot || expanded) && (
<div>
{node.sessions.map((session) => (
<div
key={session.id}
draggable
onDragStart={(e) => {
e.dataTransfer.setData('text/plain', session.id);
e.dataTransfer.effectAllowed = 'move';
onDragSession(session.id);
}}
onContextMenu={(e) => onContextMenu(e, 'session', 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-50'
)}
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={clsx('flex-1 truncate', activeSessionId === session.id && 'font-bold text-primary-700')}>
{session.title}
</span>
<button onClick={(e) => { e.stopPropagation(); onRename(session.id, 'session'); }} className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-primary-600 p-0.5" title="Umbenennen">
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z" /></svg>
</button>
<button onClick={(e) => { e.stopPropagation(); onDelete(session.id, 'session'); }} className="opacity-0 group-hover:opacity-100 text-secondary-400 hover:text-red-600 p-0.5" title="Löschen">
<svg className="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" /></svg>
</button>
</div>
))}
</div>
)}
{/* Root drop zone */}
{isRoot && (
<div
onDragOver={handleDragOver}
onDragLeave={() => setIsDragOver(false)}
onDrop={handleDrop}
onContextMenu={(e) => onContextMenu(e, 'root', null)}
className={clsx(
'min-h-[12px] mt-1 rounded-md transition-colors',
isDragOver ? 'bg-primary-50 ring-1 ring-primary-300' : 'hover:bg-secondary-50'
)}
/>
)}
{/* Child folders */}
{(isRoot || expanded) && node.children.map((child) => (
<TreeItem
key={child.folder!.id}
node={child}
activeSessionId={activeSessionId}
onSelectSession={onSelectSession}
depth={depth + 1}
onContextMenu={onContextMenu}
onDragSession={onDragSession}
onDragFolder={onDragFolder}
onDropToFolder={onDropToFolder}
onDelete={onDelete}
onRename={onRename}
/>
))}
</div>
);
}
function ContextMenu({
state, onClose, onRename, onDelete, onNewFolder, onNewChat,
}: {
state: ContextMenuState;
onClose: () => void;
onRename: (id: string, type: 'session' | 'folder') => void;
onDelete: (id: string, type: 'session' | 'folder') => void;
onNewFolder: () => void;
onNewChat: () => void;
}) {
const ref = useRef<HTMLDivElement>(null);
useEffect(() => {
const handler = (e: MouseEvent) => {
if (ref.current && !ref.current.contains(e.target as Node)) onClose();
};
document.addEventListener('mousedown', handler);
return () => document.removeEventListener('mousedown', handler);
}, [onClose]);
const items: { label: string; action: () => void; danger?: boolean }[] = [];
if (state.type === 'session') {
items.push({ label: 'Umbenennen', action: () => { onRename(state.id!, 'session'); onClose(); } });
items.push({ label: 'Löschen', action: () => { onDelete(state.id!, 'session'); onClose(); }, danger: true });
} else if (state.type === 'folder') {
items.push({ label: 'Umbenennen', action: () => { onRename(state.id!, 'folder'); onClose(); } });
items.push({ label: 'Neuer Unterordner', action: () => { onClose(); /* TODO */ } });
items.push({ label: 'Löschen', action: () => { onDelete(state.id!, 'folder'); onClose(); }, danger: true });
} else {
items.push({ label: 'Neuer Chat', action: () => { onNewChat(); onClose(); } });
items.push({ label: 'Neuer Ordner', action: () => { onNewFolder(); onClose(); } });
}
return (
<div
ref={ref}
className="fixed z-50 bg-white border border-secondary-200 rounded-lg shadow-lg py-1 min-w-[160px]"
style={{ left: state.x, top: state.y }}
>
{items.map((item, i) => (
<button
key={i}
onClick={item.action}
className={clsx(
'w-full text-left px-3 py-1.5 text-sm hover:bg-secondary-100',
item.danger && 'text-red-600 hover:bg-red-50'
)}
>
{item.label}
</button>
))}
</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 [dragSessionId, setDragSessionId] = useState<string | null>(null);
const [dragFolderId, setDragFolderId] = useState<string | null>(null);
const [contextMenu, setContextMenu] = useState<ContextMenuState | null>(null);
const queryClient = useQueryClient();
const loadData = async () => {
try {
setLoading(true);
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'); }
finally { setLoading(false); }
};
useEffect(() => { loadData(); }, [isSidebar]);
const handleContextMenu = useCallback((e: React.MouseEvent, type: 'session' | 'folder' | 'root', id: string | null) => {
e.preventDefault();
e.stopPropagation();
setContextMenu({ x: e.clientX, y: e.clientY, type, id });
}, []);
const handleRename = async (id: string, type: 'session' | 'folder') => {
const newName = prompt('Neuer Name:', type === 'session'
? sessions.find(s => s.id === id)?.title || ''
: folders.find(f => f.id === id)?.name || ''
);
if (!newName) return;
try {
if (type === 'session') await updateSession(id, { title: newName });
else {
await updateFolder(id, { name: newName });
queryClient.invalidateQueries({ queryKey: ['ai', 'folders'] });
}
loadData();
} catch (e) { setError(e instanceof Error ? e.message : 'Rename failed'); }
};
const handleDelete = async (id: string, type: 'session' | 'folder') => {
if (!confirm(type === 'session' ? 'Chat löschen?' : 'Ordner löschen? Chats bleiben erhalten.')) return;
try {
if (type === 'session') {
await deleteSession(id);
if (activeSessionId === id) onSelectSession('');
} else {
await deleteFolder(id);
}
loadData();
} catch (e) { setError(e instanceof Error ? e.message : 'Delete failed'); }
};
const handleNewFolder = () => {
const name = prompt('Ordnername:');
if (!name) return;
createFolder({ name }).then(() => loadData()).catch((e) => setError(e?.message));
};
const handleNewChat = async () => {
try {
const session = await createSession({ is_sidebar: isSidebar || false });
onSelectSession(session.id);
loadData();
} catch (e) { setError(e instanceof Error ? e.message : 'Failed'); }
};
const handleDropToFolder = async (folderId: string | null) => {
if (dragFolderId) {
try {
await updateFolder(dragFolderId, { parent_id: folderId });
setDragFolderId(null);
loadData();
} catch (e) { setError(e instanceof Error ? e.message : 'Failed to move folder'); }
return;
}
if (!dragSessionId) return;
try {
await updateSession(dragSessionId, { folder_id: folderId });
setDragSessionId(null);
loadData();
} catch (e) { setError(e instanceof Error ? e.message : 'Failed to move'); }
};
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)}>
{error && <div className="p-2 text-xs text-red-600">{typeof error === "string" ? error : (error as any)?.message || "Ein Fehler ist aufgetreten"}</div>}
<div
className="flex-1 overflow-y-auto p-2"
onContextMenu={(e) => {
if (e.target === e.currentTarget) handleContextMenu(e, 'root', null);
}}
>
{tree.map((node) => (
<TreeItem
key={node.folder?.id || 'root'}
node={node}
activeSessionId={activeSessionId}
onSelectSession={onSelectSession}
depth={0}
onContextMenu={handleContextMenu}
onDragSession={setDragSessionId}
onDragFolder={setDragFolderId}
onDropToFolder={handleDropToFolder}
onDelete={handleDelete}
onRename={handleRename}
/>
))}
</div>
{contextMenu && (
<ContextMenu
state={contextMenu}
onClose={() => setContextMenu(null)}
onRename={handleRename}
onDelete={handleDelete}
onNewFolder={handleNewFolder}
onNewChat={handleNewChat}
/>
)}
</div>
);
}
+2 -2
View File
@@ -1,5 +1,5 @@
import React, { useState, useEffect } from 'react';
import { ChatWindow } from '@/components/ai/ChatWindow';
import { ResizablePanel } from '@/components/ui/ResizablePanel';
import { SuggestionList } from '@/components/ai/SuggestionSidebar';
import { ImprovementPanel } from '@/components/ai/ImprovementPanel';
@@ -216,7 +216,7 @@ export function AISidebar() {
);
}
if (sessionId) {
return <ChatWindow sessionId={sessionId} compact className="h-full" />;
return <div className="flex items-center justify-center h-full text-secondary-400 text-sm">KI Chat im Kommunikations-Plugin verfügbar</div>;
}
return (
<div className="flex items-center justify-center h-full text-sm text-red-500">
+16 -14
View File
@@ -1,12 +1,8 @@
import { asError } from '@/utils/errorTypes';
import React, { useState, useRef, useEffect, useCallback } from 'react';
import { Sparkles, Send } from 'lucide-react';
import {
streamChat,
createSession,
fetchMessages,
type ChatMessage,
} from '@/api/ai';
import { streamChat, fetchMessages } from '@/api/ai';
import { apiClient } from '@/api/client';
interface AiChatPanelProps {
windowTitle: string;
@@ -30,24 +26,30 @@ export function AiChatPanel({ windowTitle, windowType }: AiChatPanelProps) {
const scrollRef = useRef<HTMLDivElement>(null);
const msgIdCounter = useRef(0);
// Create a sidebar session on mount
// Create a comm conversation for AI chat on mount
useEffect(() => {
let cancelled = false;
setLoadingSession(true);
createSession({ title: `KI: ${windowTitle}`, is_sidebar: true })
.then((session) => {
apiClient.post('/comm/conversations', {
title: `KI: ${windowTitle}`,
participant_ids: [],
is_direct: false,
metadata: { conversation_type: 'ai' },
})
.then((res) => {
if (cancelled) return;
setSessionId(session.id);
return fetchMessages(session.id).then((msgs: ChatMessage[]) => {
const convId = res.data.id;
setSessionId(convId);
return fetchMessages(convId).then((msgs) => {
if (cancelled) return;
setMessages(
msgs.map((m) => ({ id: m.id, role: m.role, content: m.content }))
msgs.map((m, i) => ({ id: `msg-${i}`, role: m.role, content: m.content }))
);
});
})
.catch((e) => {
if (!cancelled) {
console.error('AI session creation failed:', e);
console.error('AI conversation creation failed:', e);
setError('KI Chat ist in diesem Kontext nicht verfügbar');
}
})
@@ -90,7 +92,7 @@ export function AiChatPanel({ windowTitle, windowType }: AiChatPanelProps) {
} else if (event.type === 'done') {
const msgs = await fetchMessages(sessionId);
setMessages(
msgs.map((m) => ({ id: m.id, role: m.role, content: m.content }))
msgs.map((m, i) => ({ id: `msg-${i}`, role: m.role, content: m.content }))
);
setStreamingContent('');
} else if (event.type === 'error') {
-132
View File
@@ -1,132 +0,0 @@
import React, { useState, useEffect } from 'react';
import { SessionList } from '@/components/ai/SessionList';
import { ChatWindow } from '@/components/ai/ChatWindow';
import { ResizablePanel } from '@/components/ui/ResizablePanel';
import { usePluginToolbarStore } from '@/store/pluginToolbarStore';
import { fetchAgents, createSession, type AIAgent } from '@/api/ai';
import { ChevronLeft, ExternalLink, Folder, Plus } from 'lucide-react';
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 [refreshKey, setRefreshKey] = useState(0);
const { registerItems, unregisterPlugin } = usePluginToolbarStore();
useEffect(() => { fetchAgents().then(setAgents).catch(() => {}); }, []);
useEffect(() => {
registerItems('ai_assistant', [
{
id: 'agent-select',
plugin: 'ai_assistant',
label: 'Agent',
type: 'select',
group: 'agent',
selectOptions: agents.map((a) => ({ value: a.id, label: a.name })),
selectValue: selectedAgentId || '',
onSelect: (val: string) => setSelectedAgentId(val || null),
onClick: () => {},
},
{
id: 'new-chat',
plugin: 'ai_assistant',
label: 'Neuer Chat',
type: 'button',
group: 'actions',
icon: (
<Plus className="w-3.5 h-3.5" strokeWidth={2} />
),
onClick: async () => {
try {
const session = await createSession({ is_sidebar: false });
setActiveSessionId(session.id);
setMobileView('chat');
setRefreshKey(k => k + 1);
} catch (e) {
console.error('Failed to create session:', e);
}
},
},
{
id: 'new-folder',
plugin: 'ai_assistant',
label: 'Ordner',
type: 'button',
group: 'actions',
icon: (
<Folder className="w-3.5 h-3.5" strokeWidth={2} />
),
onClick: () => {
const name = prompt('Ordnername:');
if (name) {
import('@/api/ai').then(({ createFolder }) => {
createFolder({ name }).then(() => setRefreshKey(k => k + 1)).catch(() => {});
});
}
},
},
{
id: 'open-standalone',
plugin: 'ai_assistant',
label: 'In neuem Fenster',
type: 'button',
group: 'actions',
icon: (
<ExternalLink className="w-3.5 h-3.5" strokeWidth={2} />
),
onClick: () => {
window.open('/ai-assistant-standalone', '_blank', 'width=800,height=600');
},
},
]);
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">
{/* Desktop: two-pane layout */}
<div className="hidden md:flex">
<ResizablePanel
initialWidth={288}
minWidth={200}
maxWidth={500}
className="border-r border-secondary-200 bg-white"
data-testid="ai-session-pane"
>
<SessionList key={refreshKey} activeSessionId={activeSessionId} onSelectSession={setActiveSessionId} className="h-full" />
</ResizablePanel>
</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">
<SessionList key={refreshKey} 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">
<ChevronLeft className="w-5 h-5" strokeWidth={2} />
</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>
);
}
@@ -1,10 +0,0 @@
import React from 'react';
import { AIAssistantPage } from './AIAssistant';
export function AIAssistantStandalonePage() {
return (
<div className="h-screen w-screen overflow-hidden bg-white">
<AIAssistantPage />
</div>
);
}
+56 -30
View File
@@ -11,7 +11,7 @@ import {
import { ResizablePanel } from '@/components/ui/ResizablePanel';
import { usePluginToolbarStore } from '@/store/pluginToolbarStore';
import { apiClient } from '@/api/client';
import { streamChat, fetchAgents, type AIAgent } from '@/api/ai';
import { streamChat, fetchAgents, fetchMessages as fetchAiMessages, type AIAgent } from '@/api/ai';
// ─── Types ───
@@ -322,7 +322,6 @@ function ChatWindow({ convId, category, onBack }: ChatWindowProps) {
const [miniApps, setMiniApps] = useState<MiniApp[]>([]);
const [agents, setAgents] = useState<AIAgent[]>([]);
const [selectedAgentId, setSelectedAgentId] = useState<string | null>(null);
const [aiSessionId, setAiSessionId] = useState<string | null>(null);
const scrollRef = useRef<HTMLDivElement>(null);
const wsRef = useRef<WebSocket | null>(null);
@@ -331,11 +330,38 @@ function ChatWindow({ convId, category, onBack }: ChatWindowProps) {
if (!convId) return;
setLoading(true);
setError(null);
fetchMessages(convId)
.then(msgs => { setMessages(msgs); setLoading(false); })
.catch(e => { setError(e?.message || 'Fehler beim Laden'); setLoading(false); });
if (category === 'ai') {
// AI conversations load messages from the AI endpoint
fetchAiMessages(convId)
.then(msgs => {
// Convert {role, content}[] to Message[] format
const mapped: Message[] = msgs.map((m, i) => ({
id: `ai-msg-${i}`,
conversation_id: convId,
sender_id: null,
sender_type: m.role === 'user' ? 'user' : 'ai',
content: m.content,
content_format: 'text',
created_at: null,
edited_at: null,
is_pinned: false,
blocks: [],
attachments: [],
reactions: [],
reply_to_id: null,
}));
setMessages(mapped);
setLoading(false);
})
.catch(e => { setError(e?.message || 'Fehler beim Laden'); setLoading(false); });
} else {
// Regular conversations load from comm endpoint
fetchMessages(convId)
.then(msgs => { setMessages(msgs as unknown as Message[]); setLoading(false); })
.catch(e => { setError(e?.message || 'Fehler beim Laden'); setLoading(false); });
}
markConversationRead(convId).catch(() => {});
}, [convId]);
}, [convId, category]);
// Load agents and mini-apps
useEffect(() => {
@@ -386,12 +412,12 @@ function ChatWindow({ convId, category, onBack }: ChatWindowProps) {
setError(null);
try {
if (category === 'ai' && aiSessionId) {
// AI streaming chat
if (category === 'ai') {
// AI streaming chat via comm conversation
setAiStreaming(true);
setStreamingContent('');
let accumulated = '';
for await (const event of streamChat(aiSessionId, content, selectedAgentId || undefined)) {
for await (const event of streamChat(convId, content, selectedAgentId || undefined)) {
if (event.type === 'token' && event.content) {
accumulated += event.content;
setStreamingContent(accumulated);
@@ -405,8 +431,23 @@ function ChatWindow({ convId, category, onBack }: ChatWindowProps) {
setAiStreaming(false);
setStreamingContent('');
// Reload messages to get the AI response
const msgs = await fetchMessages(convId);
setMessages(msgs);
const msgs = await fetchAiMessages(convId);
const mapped: Message[] = msgs.map((m, i) => ({
id: `ai-msg-${i}`,
conversation_id: convId,
sender_id: null,
sender_type: m.role === 'user' ? 'user' : 'ai',
content: m.content,
content_format: 'text',
created_at: null,
edited_at: null,
is_pinned: false,
blocks: [],
attachments: [],
reactions: [],
reply_to_id: null,
}));
setMessages(mapped);
} else {
// Regular message
const msg = await sendMessage(convId, content);
@@ -426,25 +467,10 @@ function ChatWindow({ convId, category, onBack }: ChatWindowProps) {
}
};
const startAiSession = async () => {
try {
const r = await apiClient.post('/ai/sessions', {
title: 'KI Chat',
agent_id: selectedAgentId,
is_sidebar: false,
});
setAiSessionId(r.data.id);
} catch (e: unknown) { const errObj = asError(e);
setError('KI Session konnte nicht gestartet werden');
}
};
// Auto-start AI session for AI conversations
// Auto-scroll
useEffect(() => {
if (category === 'ai' && !aiSessionId && selectedAgentId) {
startAiSession();
}
}, [category, aiSessionId, selectedAgentId]);
if (scrollRef.current) scrollRef.current.scrollTop = scrollRef.current.scrollHeight;
}, [messages, streamingContent]);
return (
<div className="flex flex-col h-full bg-white">
@@ -462,7 +488,7 @@ function ChatWindow({ convId, category, onBack }: ChatWindowProps) {
{category === 'ai' && agents.length > 0 && (
<select
value={selectedAgentId || ''}
onChange={(e) => { setSelectedAgentId(e.target.value || null); setAiSessionId(null); }}
onChange={(e) => { setSelectedAgentId(e.target.value || null); }}
className="text-xs border border-secondary-200 rounded px-2 py-1 bg-white"
>
{agents.map(a => (
-6
View File
@@ -38,12 +38,10 @@ const TrashPage = React.lazy(() => import('@/pages/Trash').then(m => ({ default:
const MailPage = React.lazy(() => import('@/pages/Mail').then(m => ({ default: m.MailPage })));
const MailSettingsPage = React.lazy(() => import('@/pages/MailSettings').then(m => ({ default: m.MailSettingsPage })));
const SettingsNotificationsPage = React.lazy(() => import('@/pages/SettingsNotifications').then(m => ({ default: m.SettingsNotificationsPage })));
const AIAssistantPage = React.lazy(() => import('@/pages/AIAssistant').then(m => ({ default: m.AIAssistantPage })));
const AISettingsPage = React.lazy(() => import('@/pages/AISettings').then(m => ({ default: m.AISettingsPage })));
const ProactiveAISettings = React.lazy(() => import('@/pages/ProactiveAISettings').then(m => ({ default: m.ProactiveAISettings })));
const SettingsThemePage = React.lazy(() => import('@/pages/SettingsTheme').then(m => ({ default: m.SettingsThemePage })));
const SettingsMcpPage = React.lazy(() => import('@/pages/SettingsMcp').then(m => ({ default: m.SettingsMcpPage })));
const AIAssistantStandalonePage = React.lazy(() => import('@/pages/AIAssistantStandalone').then(m => ({ default: m.AIAssistantStandalonePage })));
const DmsStandalonePage = React.lazy(() => import('@/pages/DmsStandalone').then(m => ({ default: m.DmsStandalonePage })));
const CalendarStandalonePage = React.lazy(() => import('@/pages/CalendarStandalone').then(m => ({ default: m.CalendarStandalonePage })));
const MailStandalonePage = React.lazy(() => import('@/pages/MailStandalone').then(m => ({ default: m.MailStandalonePage })));
@@ -111,8 +109,6 @@ const router = createBrowserRouter([
element: <LoginPage />,
},
{
path: '/ai-assistant-standalone',
element: <ErrorBoundary>{withSuspense(<AIAssistantStandalonePage />)}</ErrorBoundary>,
},
{
path: '/dms-standalone',
@@ -178,7 +174,6 @@ const router = createBrowserRouter([
{ path: 'overview', element: withSuspense(<AgentsOverviewPage />) },
{ path: 'automation', element: withSuspense(<AutomationDashboardPage />) },
{ path: 'automation-settings', element: withSuspense(<AutomationSettingsPage />) },
{ path: 'ai-assistant', element: withSuspense(<AIAssistantPage />) },
{ path: 'ai-settings', element: withSuspense(<AISettingsPage />) },
{ path: 'ai-proactive', element: withSuspense(<ProactiveAISettings />) },
{ path: '*', element: withSuspense(<AgentsPlaceholderPage />) },
@@ -258,7 +253,6 @@ const router = createBrowserRouter([
{ path: '/trash', element: <PermissionRoute permission="contacts:read">{withSuspense(<TrashPage />)}</PermissionRoute> },
{ path: '/mail', element: <PermissionRoute permission="mail:read">{withSuspense(<MailPage />)}</PermissionRoute> },
{ path: '/mail/settings', element: <PermissionRoute permission="mail:read">{withSuspense(<MailSettingsPage />)}</PermissionRoute> },
{ path: '/ai-assistant', element: <PermissionRoute permission="ai:read">{withSuspense(<AIAssistantPage />)}</PermissionRoute> },
{ path: '/reports', element: <PermissionRoute permission="reports:read">{withSuspense(<ReportsPage />)}</PermissionRoute> },
{ path: '/tasks', element: <PermissionRoute permission="tasks:read">{withSuspense(<TasksPage />)}</PermissionRoute> },
{ path: '/communication', element: <PermissionRoute permission="communication:read">{withSuspense(<CommunicationPage />)}</PermissionRoute> },