feat(UI-Overhaul-Phase2): AI Assistent in Kommunikation integriert
Check Cross-Plugin Imports / check (push) Has been cancelled
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:
@@ -6,20 +6,16 @@ from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
|
||||
import aiofiles
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request, UploadFile
|
||||
from fastapi.responses import FileResponse, StreamingResponse
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Request
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.core.db import get_db, set_tenant_context
|
||||
from app.core.visibility import apply_visibility_filter
|
||||
from app.deps import get_current_user, require_permission
|
||||
from app.plugins.builtins.ai_assistant.models import (
|
||||
AIAgent,
|
||||
AIChatAttachment,
|
||||
AIChatFolder,
|
||||
AIChatSession,
|
||||
AIModel,
|
||||
AIPreset,
|
||||
AIProvider,
|
||||
@@ -36,25 +32,19 @@ from app.plugins.builtins.ai_assistant.schemas import (
|
||||
ChatFolderCreate,
|
||||
ChatFolderUpdate,
|
||||
ChatSendRequest,
|
||||
ChatSessionCreate,
|
||||
ChatSessionUpdate,
|
||||
)
|
||||
from app.plugins.builtins.ai_assistant.services import (
|
||||
agent_to_response,
|
||||
attachment_to_response,
|
||||
folder_to_response,
|
||||
get_agent_by_id,
|
||||
get_comm_messages,
|
||||
get_default_agent,
|
||||
get_preset_by_id,
|
||||
get_provider_by_id,
|
||||
get_session_by_id,
|
||||
get_session_messages,
|
||||
message_to_response,
|
||||
model_to_response,
|
||||
preset_to_response,
|
||||
provider_to_response,
|
||||
session_to_response,
|
||||
stream_chat,
|
||||
stream_chat_comm,
|
||||
)
|
||||
from app.plugins.builtins.ai_assistant.tool_registry import get_tool_registry
|
||||
|
||||
@@ -417,207 +407,6 @@ async def list_tools(
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
# ─── Chat Sessions ───
|
||||
|
||||
@router.get("/sessions", dependencies=[Depends(require_permission("ai:read"))])
|
||||
async def list_sessions(
|
||||
is_sidebar: bool | None = Query(None),
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
is_system_admin = current_user.get("is_system_admin", False)
|
||||
stmt = (
|
||||
select(AIChatSession)
|
||||
.where(AIChatSession.tenant_id == tenant_id)
|
||||
)
|
||||
stmt = await apply_visibility_filter(
|
||||
db, stmt, "ai_chat_session", AIChatSession, user_id, tenant_id, is_system_admin
|
||||
)
|
||||
if is_sidebar is not None:
|
||||
stmt = stmt.where(AIChatSession.is_sidebar == is_sidebar)
|
||||
stmt = stmt.order_by(AIChatSession.updated_at.desc())
|
||||
result = await db.execute(stmt)
|
||||
sessions = list(result.scalars().all())
|
||||
return [session_to_response(s) for s in sessions]
|
||||
|
||||
|
||||
@router.post("/sessions", dependencies=[Depends(require_permission("ai:write"))])
|
||||
async def create_session(
|
||||
data: ChatSessionCreate,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
await set_tenant_context(db, tenant_id)
|
||||
|
||||
agent_id = None
|
||||
if data.agent_id:
|
||||
agent_id = uuid.UUID(data.agent_id)
|
||||
elif not data.is_sidebar:
|
||||
# Use default agent for non-sidebar sessions
|
||||
default_agent = await get_default_agent(db, tenant_id)
|
||||
if default_agent:
|
||||
agent_id = default_agent.id
|
||||
else:
|
||||
# Sidebar also gets default agent
|
||||
default_agent = await get_default_agent(db, tenant_id)
|
||||
if default_agent:
|
||||
agent_id = default_agent.id
|
||||
|
||||
folder_id = None
|
||||
if data.folder_id:
|
||||
folder_id = uuid.UUID(data.folder_id)
|
||||
|
||||
session = AIChatSession(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
title=data.title,
|
||||
is_sidebar=data.is_sidebar,
|
||||
folder_id=folder_id,
|
||||
tenant_id=tenant_id,
|
||||
owner_id=user_id,
|
||||
)
|
||||
db.add(session)
|
||||
await db.commit()
|
||||
await db.refresh(session)
|
||||
return session_to_response(session)
|
||||
|
||||
|
||||
@router.put("/sessions/{session_id}", dependencies=[Depends(require_permission("ai:write"))])
|
||||
async def update_session(
|
||||
session_id: str,
|
||||
data: ChatSessionUpdate,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
session = await get_session_by_id(db, uuid.UUID(session_id), user_id, tenant_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
update_data = data.model_dump(exclude_unset=True)
|
||||
if "agent_id" in update_data and update_data["agent_id"]:
|
||||
update_data["agent_id"] = uuid.UUID(update_data["agent_id"])
|
||||
if "folder_id" in update_data:
|
||||
if update_data["folder_id"]:
|
||||
update_data["folder_id"] = uuid.UUID(update_data["folder_id"])
|
||||
else:
|
||||
update_data["folder_id"] = None
|
||||
for field, val in update_data.items():
|
||||
setattr(session, field, val)
|
||||
await db.commit()
|
||||
await db.refresh(session)
|
||||
return session_to_response(session)
|
||||
|
||||
|
||||
@router.delete("/sessions/{session_id}", dependencies=[Depends(require_permission("ai:write"))])
|
||||
async def delete_session(
|
||||
session_id: str,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
session = await get_session_by_id(db, uuid.UUID(session_id), user_id, tenant_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
await db.delete(session)
|
||||
await db.commit()
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ─── Chat Messages ───
|
||||
|
||||
@router.get("/sessions/{session_id}/messages", dependencies=[Depends(require_permission("ai:read"))])
|
||||
async def list_messages(
|
||||
session_id: str,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
session = await get_session_by_id(db, uuid.UUID(session_id), user_id, tenant_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
messages = await get_session_messages(db, session.id, tenant_id)
|
||||
return [message_to_response(m) for m in messages]
|
||||
|
||||
|
||||
# ─── Streaming Chat ───
|
||||
|
||||
@router.post("/sessions/{session_id}/stream", dependencies=[Depends(require_permission("ai:write"))])
|
||||
async def chat_stream(
|
||||
session_id: str,
|
||||
data: ChatSendRequest,
|
||||
request: Request,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
|
||||
# Rate limit — AI policy (cost-sensitive LLM call)
|
||||
from app.core.rate_limit import RateLimitPolicy, check_rate_limit_policy
|
||||
await check_rate_limit_policy(
|
||||
f"rate:ai:chat:{tenant_id}:{user_id}",
|
||||
RateLimitPolicy.AI,
|
||||
)
|
||||
|
||||
await set_tenant_context(db, tenant_id)
|
||||
session = await get_session_by_id(db, uuid.UUID(session_id), user_id, tenant_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
# Get agent
|
||||
agent = None
|
||||
if data.agent_id:
|
||||
agent = await get_agent_by_id(db, uuid.UUID(data.agent_id), tenant_id)
|
||||
elif session.agent_id:
|
||||
agent = await get_agent_by_id(db, session.agent_id, tenant_id)
|
||||
if not agent:
|
||||
agent = await get_default_agent(db, tenant_id)
|
||||
if not agent:
|
||||
raise HTTPException(status_code=400, detail="No agent available")
|
||||
|
||||
# Build user context for RBAC checks in tools
|
||||
user_context = {
|
||||
"user_id": current_user["user_id"],
|
||||
"tenant_id": current_user["tenant_id"],
|
||||
"role": current_user.get("role", ""),
|
||||
"permissions": current_user.get("permissions", []),
|
||||
"denied_permissions": current_user.get("denied_permissions", []),
|
||||
"is_system_admin": current_user.get("is_system_admin", False),
|
||||
"field_permissions": current_user.get("field_permissions", {}),
|
||||
}
|
||||
|
||||
async def event_stream():
|
||||
# Use a fresh DB session — the Depends(get_db) session closes after response
|
||||
from app.core.db import get_session_factory
|
||||
factory = get_session_factory()
|
||||
async with factory() as stream_db:
|
||||
await set_tenant_context(stream_db, tenant_id)
|
||||
async for chunk in stream_chat(
|
||||
stream_db, session, agent, data.content, user_context, tenant_id
|
||||
):
|
||||
yield chunk
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
# ─── Chat Folders ───
|
||||
|
||||
@router.get("/folders", dependencies=[Depends(require_permission("ai:read"))])
|
||||
@@ -713,93 +502,78 @@ async def delete_folder(
|
||||
return {"ok": True}
|
||||
|
||||
|
||||
# ─── Attachments ───
|
||||
# ─── AI Chat Streaming (via comm_conversations) ───
|
||||
|
||||
import os # noqa: E402
|
||||
from pathlib import Path # noqa: E402
|
||||
|
||||
ATTACHMENT_DIR = Path(os.environ.get("STORAGE_PATH", "/data/storage")) / "ai_attachments"
|
||||
MAX_ATTACHMENT_SIZE = 25 * 1024 * 1024 # 25MB
|
||||
|
||||
|
||||
@router.post("/sessions/{session_id}/attachments", response_model=None, dependencies=[Depends(require_permission("ai:write"))])
|
||||
async def upload_attachment(
|
||||
session_id: str,
|
||||
file: UploadFile,
|
||||
@router.post("/conversations/{conversation_id}/stream", dependencies=[Depends(require_permission("ai:write"))])
|
||||
async def chat_stream_comm(
|
||||
conversation_id: str,
|
||||
data: ChatSendRequest,
|
||||
request: Request,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""Stream AI chat response for a comm conversation with conversation_type='ai'."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
session = await get_session_by_id(db, uuid.UUID(session_id), user_id, tenant_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
content = await file.read()
|
||||
if len(content) > MAX_ATTACHMENT_SIZE:
|
||||
raise HTTPException(status_code=413, detail="File too large (max 25MB)")
|
||||
|
||||
ATTACHMENT_DIR.mkdir(parents=True, exist_ok=True)
|
||||
file_id = str(uuid.uuid4())
|
||||
safe_filename = file.filename or "unnamed"
|
||||
storage_path = str(ATTACHMENT_DIR / f"{file_id}_{safe_filename}")
|
||||
async with aiofiles.open(storage_path, "wb") as f:
|
||||
await f.write(content)
|
||||
|
||||
attachment = AIChatAttachment(
|
||||
session_id=session.id,
|
||||
filename=safe_filename,
|
||||
mime_type=file.content_type or "application/octet-stream",
|
||||
size_bytes=len(content),
|
||||
storage_path=storage_path,
|
||||
tenant_id=tenant_id,
|
||||
from app.core.rate_limit import RateLimitPolicy, check_rate_limit_policy
|
||||
await check_rate_limit_policy(
|
||||
f"rate:ai:chat:{tenant_id}:{user_id}",
|
||||
RateLimitPolicy.AI,
|
||||
)
|
||||
|
||||
await set_tenant_context(db, tenant_id)
|
||||
|
||||
agent = None
|
||||
if data.agent_id:
|
||||
agent = await get_agent_by_id(db, uuid.UUID(data.agent_id), tenant_id)
|
||||
if not agent:
|
||||
agent = await get_default_agent(db, tenant_id)
|
||||
if not agent:
|
||||
raise HTTPException(status_code=400, detail="No agent available")
|
||||
|
||||
user_context = {
|
||||
"user_id": current_user["user_id"],
|
||||
"tenant_id": current_user["tenant_id"],
|
||||
"role": current_user.get("role", ""),
|
||||
"permissions": current_user.get("permissions", []),
|
||||
"denied_permissions": current_user.get("denied_permissions", []),
|
||||
"is_system_admin": current_user.get("is_system_admin", False),
|
||||
"field_permissions": current_user.get("field_permissions", {}),
|
||||
}
|
||||
|
||||
async def event_stream():
|
||||
from app.core.db import get_session_factory
|
||||
factory = get_session_factory()
|
||||
async with factory() as stream_db:
|
||||
await set_tenant_context(stream_db, tenant_id)
|
||||
async for chunk in stream_chat_comm(
|
||||
stream_db, uuid.UUID(conversation_id), agent, data.content, user_context, tenant_id, user_id
|
||||
):
|
||||
yield chunk
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
event_stream(),
|
||||
media_type="text/event-stream",
|
||||
headers={
|
||||
"Cache-Control": "no-cache",
|
||||
"Connection": "keep-alive",
|
||||
"X-Accel-Buffering": "no",
|
||||
},
|
||||
)
|
||||
db.add(attachment)
|
||||
await db.commit()
|
||||
await db.refresh(attachment)
|
||||
return attachment_to_response(attachment)
|
||||
|
||||
|
||||
@router.get("/sessions/{session_id}/attachments", dependencies=[Depends(require_permission("ai:read"))])
|
||||
async def list_attachments(
|
||||
session_id: str,
|
||||
@router.get("/conversations/{conversation_id}/messages", dependencies=[Depends(require_permission("ai:read"))])
|
||||
async def list_comm_messages(
|
||||
conversation_id: str,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
"""List messages for an AI comm conversation."""
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
user_id = uuid.UUID(current_user["user_id"])
|
||||
session = await get_session_by_id(db, uuid.UUID(session_id), user_id, tenant_id)
|
||||
if not session:
|
||||
raise HTTPException(status_code=404, detail="Session not found")
|
||||
|
||||
result = await db.execute(
|
||||
select(AIChatAttachment)
|
||||
.where(AIChatAttachment.session_id == session.id)
|
||||
.where(AIChatAttachment.tenant_id == tenant_id)
|
||||
.order_by(AIChatAttachment.created_at.asc())
|
||||
)
|
||||
attachments = list(result.scalars().all())
|
||||
return [attachment_to_response(a) for a in attachments]
|
||||
await set_tenant_context(db, tenant_id)
|
||||
messages = await get_comm_messages(db, uuid.UUID(conversation_id), tenant_id)
|
||||
return [{"role": m["role"], "content": m["content"]} for m in messages]
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}/download", dependencies=[Depends(require_permission("ai:read"))])
|
||||
async def download_attachment(
|
||||
attachment_id: str,
|
||||
current_user: dict = Depends(get_current_user),
|
||||
db: AsyncSession = Depends(get_db),
|
||||
):
|
||||
tenant_id = uuid.UUID(current_user["tenant_id"])
|
||||
result = await db.execute(
|
||||
select(AIChatAttachment)
|
||||
.where(AIChatAttachment.id == uuid.UUID(attachment_id))
|
||||
.where(AIChatAttachment.tenant_id == tenant_id)
|
||||
)
|
||||
attachment = result.scalar_one_or_none()
|
||||
if not attachment:
|
||||
raise HTTPException(status_code=404, detail="Attachment not found")
|
||||
|
||||
return FileResponse(
|
||||
attachment.storage_path,
|
||||
filename=attachment.filename,
|
||||
media_type=attachment.mime_type,
|
||||
)
|
||||
|
||||
Reference in New Issue
Block a user