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
-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 => (