diff --git a/backend/app/api/chat.py b/backend/app/api/chat.py index 7848d23f..d84fd60f 100644 --- a/backend/app/api/chat.py +++ b/backend/app/api/chat.py @@ -12,16 +12,18 @@ import tempfile import os import subprocess import uuid +import json +from datetime import datetime from urllib.parse import urlparse import requests from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context -from sqlalchemy import func, desc +from sqlalchemy import func, desc, or_ from openpyxl import load_workbook from app.services.dify import DifyService from app.services.integration_api import IntegrationApiService from app.decorators import require_agent_permission -from app.models import Agent, ChatLog, Feedback +from app.models import Agent, ChatLog, ChatSession, Feedback from app import db # 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat @@ -30,6 +32,118 @@ chat_bp = Blueprint('chat', __name__) PLM_PREVIEW_SHARE_ROOT = (os.getenv("PLM_PREVIEW_SHARE_ROOT") or "\\\\192.168.0.11\\dss\\dssroot\\").strip() +def _session_title_from_text(text: str) -> str: + value = str(text or '').strip() + if not value: + return '' + return value[:30] + ('...' if len(value) > 30 else '') + + +def _serialize_session(session: ChatSession) -> dict: + last_active = session.last_active_at or session.created_at + return { + 'id': session.id, + 'conversation_id': session.session_id, + 'title': session.title or '', + 'created_at': last_active.isoformat() if last_active else '', + 'status': session.status, + } + + +def _get_chat_session(user_id: int, agent_id: int, session_id: str | None): + session_key = str(session_id or '').strip() + if not session_key: + return None + return db.session.query(ChatSession).filter_by( + user_id=user_id, + agent_id=agent_id, + session_id=session_key, + ).first() + + +def _ensure_chat_session( + user_id: int, + agent_id: int, + session_id: str | None, + title: str = '', + status: str = 'running', + external_conversation_id: str | None = None, +): + session_key = str(session_id or '').strip() + external_id = str(external_conversation_id or '').strip() or None + session = _get_chat_session(user_id, agent_id, session_key) + changed = False + if not session: + session = ChatSession( + session_id=session_key or uuid.uuid4().hex, + user_id=user_id, + agent_id=agent_id, + title=_session_title_from_text(title), + status=status, + external_conversation_id=external_id, + created_at=datetime.utcnow(), + updated_at=datetime.utcnow(), + last_active_at=datetime.utcnow(), + ) + db.session.add(session) + db.session.commit() + return session + + if not session.title and title: + session.title = _session_title_from_text(title) + changed = True + if status and session.status != status: + session.status = status + changed = True + if external_id and session.external_conversation_id != external_id: + session.external_conversation_id = external_id + changed = True + session.last_active_at = datetime.utcnow() + session.updated_at = datetime.utcnow() + changed = True + if changed: + db.session.commit() + return session + + +def _update_chat_session( + user_id: int, + agent_id: int, + session_id: str, + *, + status: str | None = None, + external_conversation_id: str | None = None, + title: str | None = None, + touch: bool = False, +): + session = _get_chat_session(user_id, agent_id, session_id) + if not session: + return None + + changed = False + if title and not session.title: + session.title = _session_title_from_text(title) + changed = True + + external_id = str(external_conversation_id or '').strip() or None + if external_id and session.external_conversation_id != external_id: + session.external_conversation_id = external_id + changed = True + + if status and session.status != status: + session.status = status + changed = True + + if touch or changed: + session.last_active_at = datetime.utcnow() + session.updated_at = datetime.utcnow() + changed = True + + if changed: + db.session.commit() + return session + + def _normalize_windows_share_path(path_value: str) -> str: normalized = str(path_value or "").strip().strip('"').replace("/", "\\") if normalized.startswith("\\\\"): @@ -681,24 +795,33 @@ def get_chat_sessions(): if user is None or agent is None: return jsonify({'error': 'Missing context'}), 500 - # 先查出最近活跃的会话,再为每个会话回溯最近一条非空 query 作为标题。 - # 这样本地表单/确认等“无 query 的助手消息”不会把原始用户问题覆盖成 New Chat。 + session_rows = db.session.query(ChatSession).filter_by( + user_id=user.id, + agent_id=agent.id, + ).order_by(desc(ChatSession.last_active_at), desc(ChatSession.id)).limit(20).all() + + sessions = [_serialize_session(item) for item in session_rows] + session_ids = {item['conversation_id'] for item in sessions} + + # 兼容旧数据:未迁移到 chat_sessions 的历史记录继续从 chat_logs 聚合出来。 subquery = db.session.query( ChatLog.conversation_id, func.max(ChatLog.created_at).label('last_active') - ).filter_by( - user_id=user.id, - agent_id=agent.id + ).filter( + ChatLog.user_id == user.id, + ChatLog.agent_id == agent.id, + ChatLog.session_id.is_(None), + ChatLog.conversation_id.isnot(None), + ChatLog.conversation_id != '', ).group_by(ChatLog.conversation_id).subquery() - - results = db.session.query( + + legacy_rows = db.session.query( subquery.c.conversation_id, subquery.c.last_active, ).order_by(desc(subquery.c.last_active)).limit(20).all() - sessions = [] - for row in results: - if not row.conversation_id: + for row in legacy_rows: + if not row.conversation_id or row.conversation_id in session_ids: continue latest_query_row = db.session.query(ChatLog.query).filter( ChatLog.user_id == user.id, @@ -709,13 +832,15 @@ def get_chat_sessions(): ).order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first() title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip() sessions.append({ - 'id': 0, # 前端需要 id key + 'id': 0, 'conversation_id': row.conversation_id, 'title': title[:30] + ('...' if len(title) > 30 else '') if title else '', - 'created_at': row.last_active.isoformat() + 'created_at': row.last_active.isoformat(), + 'status': 'done', }) - - return jsonify(sessions) + + sessions.sort(key=lambda item: item.get('created_at') or '', reverse=True) + return jsonify(sessions[:20]) @chat_bp.route('/sessions', methods=['DELETE']) @@ -737,8 +862,9 @@ def delete_all_chat_sessions(): db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) - db.session.commit() - + db.session.query(ChatSession).filter_by(user_id=user.id, agent_id=agent.id).delete(synchronize_session=False) + db.session.commit() + return jsonify({'status': 'ok'}) @@ -754,11 +880,22 @@ def delete_chat_session(conversation_id): if user is None or agent is None: return jsonify({'error': 'Missing context'}), 500 - chat_logs = db.session.query(ChatLog).filter_by( - user_id=user.id, - agent_id=agent.id, - conversation_id=conversation_id - ).all() + session = _get_chat_session(user.id, agent.id, conversation_id) + if session: + chat_logs = db.session.query(ChatLog).filter( + ChatLog.user_id == user.id, + ChatLog.agent_id == agent.id, + or_( + ChatLog.session_id == session.session_id, + ChatLog.conversation_id == session.external_conversation_id, + ) + ).all() + else: + chat_logs = db.session.query(ChatLog).filter_by( + user_id=user.id, + agent_id=agent.id, + conversation_id=conversation_id + ).all() chat_log_ids = [log.id for log in chat_logs] if chat_log_ids: @@ -766,8 +903,10 @@ def delete_chat_session(conversation_id): db.session.query(Feedback).filter(Feedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) db.session.query(GeneralFeedback).filter(GeneralFeedback.chat_log_id.in_(chat_log_ids)).delete(synchronize_session=False) db.session.query(ChatLog).filter(ChatLog.id.in_(chat_log_ids)).delete(synchronize_session=False) - db.session.commit() - + if session: + db.session.delete(session) + db.session.commit() + return jsonify({'status': 'ok'}) @@ -781,9 +920,17 @@ def get_chat_messages(): if not conversation_id: return jsonify([]) - logs = db.session.query(ChatLog).filter_by( - conversation_id=conversation_id - ).order_by(ChatLog.created_at.asc()).all() + session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id) + if session: + logs = db.session.query(ChatLog).filter( + ChatLog.user_id == g.current_user.id, + ChatLog.agent_id == g.current_agent.id, + ChatLog.session_id == session.session_id, + ).order_by(ChatLog.created_at.asc()).all() + else: + logs = db.session.query(ChatLog).filter_by( + conversation_id=conversation_id + ).order_by(ChatLog.created_at.asc()).all() messages = [] for log in logs: @@ -820,19 +967,27 @@ def save_local_message(): return jsonify({'error': 'Missing context'}), 500 data = request.get_json() or {} - conversation_id = data.get('conversation_id') + conversation_id = (data.get('conversation_id') or '').strip() message_type = data.get('type') content = data.get('content', '') payload = data.get('payload') user_query = data.get('query', '') - - if not conversation_id: - import uuid - conversation_id = str(uuid.uuid4()) - + if not message_type: return jsonify({'error': 'type is required'}), 400 + title = user_query or content + external_conversation_id = conversation_id if conversation_id and _get_chat_session(user.id, agent.id, conversation_id) is None else None + session = _ensure_chat_session( + user.id, + agent.id, + conversation_id or None, + title=title, + status='done', + external_conversation_id=external_conversation_id, + ) + conversation_id = session.session_id + # 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录 # 这样能保证前端表单状态(例如已确认)被持久化 local_id = payload.get('formId') if payload and isinstance(payload, dict) else None @@ -844,7 +999,7 @@ def save_local_message(): logs = db.session.query(ChatLog).filter_by( user_id=user.id, agent_id=agent.id, - conversation_id=conversation_id, + session_id=conversation_id, message_type=message_type ).order_by(ChatLog.created_at.desc()).limit(20).all() @@ -863,14 +1018,17 @@ def save_local_message(): chat_log = ChatLog( user_id=user.id, agent_id=agent.id, - conversation_id=conversation_id, + conversation_id=session.external_conversation_id or conversation_id, + session_id=conversation_id, query=user_query, answer=content, message_type=message_type, payload=payload ) db.session.add(chat_log) - + session.status = 'done' + session.last_active_at = datetime.utcnow() + session.updated_at = datetime.utcnow() db.session.commit() return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id}) @@ -894,7 +1052,7 @@ def chat_completions(): data = request.get_json() or {} # 提取用户提问内容 query = data.get('query') - # 提取会话 ID(可选) + # 前端传入的 conversation_id 在 B2 里代表本地 session_id conversation_id = data.get('conversation_id') # 知识库类型 kb_type = data.get('kb_type', '企业知识库') @@ -919,31 +1077,132 @@ def chat_completions(): current_app.logger.error("[chat-api] missing user/agent context user=%s agent=%s", bool(user), bool(agent)) return jsonify({'error': 'Missing user or agent context'}), 500 + user_id = getattr(user, 'id', None) + agent_id = getattr(agent, 'id', None) + + from types import SimpleNamespace + agent_proxy = SimpleNamespace( + id=agent_id, + name=getattr(agent, 'name', None), + dify_api_key=getattr(agent, 'dify_api_key', None), + api_base_url=getattr(agent, 'api_base_url', None), + ) + user_proxy = SimpleNamespace( + id=user_id, + username=getattr(user, 'username', None), + employee_id=getattr(user, 'employee_id', None), + real_name=getattr(user, 'real_name', None), + ) + from app.services.dify import DifyService from app.services.plm_oracle import PLMOracleService - if PLMOracleService.supports(query, agent): - generator = PLMOracleService.stream_chat(query, user, agent, conversation_id) + external_conversation_id = None + if conversation_id: + existing_session = _get_chat_session(user_id, agent_id, conversation_id) + if existing_session: + session = _ensure_chat_session( + user_id, + agent_id, + existing_session.session_id, + title=query, + status='running', + ) + external_conversation_id = session.external_conversation_id + else: + session = _ensure_chat_session( + user_id, + agent_id, + conversation_id, + title=query, + status='running', + external_conversation_id=conversation_id, + ) + external_conversation_id = session.external_conversation_id + else: + session = _ensure_chat_session(user_id, agent_id, None, title=query, status='running') + + if PLMOracleService.supports(query, agent_proxy): + generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) elif kb_type == 'ERP知识库': from app.services.hr_leave_sqlserver import HRLeaveSQLServerService from app.services.text2sql import Text2SQLService if HRLeaveSQLServerService.supports(query): - generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id) + generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) else: - generator = Text2SQLService.stream_chat(query, user.id, agent, conversation_id) + generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id) else: from app.services.hr_leave_sqlserver import HRLeaveSQLServerService if HRLeaveSQLServerService.supports(query): - generator = HRLeaveSQLServerService.stream_chat(query, user, agent, conversation_id) + generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id) else: - generator = DifyService.stream_chat(query, user.id, agent, conversation_id, request_id=request_id) + generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id) + + def relay_stream(): + created_event = { + 'event': 'session_created', + 'conversation_id': session.session_id, + 'provider_conversation_id': session.external_conversation_id, + 'session_status': session.status, + } + yield f"data: {json.dumps(created_event, ensure_ascii=False)}\n\n" + + known_provider_conversation_id = session.external_conversation_id + known_status = session.status + + try: + for chunk in generator: + if not isinstance(chunk, str) or not chunk.startswith('data: '): + yield chunk + continue + + raw_payload = chunk[6:].strip() + try: + event_data = json.loads(raw_payload) + except Exception: + yield chunk + continue + + provider_conversation_id = str(event_data.get('conversation_id') or known_provider_conversation_id or '').strip() or None + event_name = event_data.get('event') + should_touch = False + if provider_conversation_id and provider_conversation_id != known_provider_conversation_id: + known_provider_conversation_id = provider_conversation_id + should_touch = True + if event_name == 'message_end': + known_status = 'done' + should_touch = True + elif event_name == 'error': + known_status = 'error' + should_touch = True + + if should_touch: + updated_session = _update_chat_session( + user_id, + agent_id, + session.session_id, + status=known_status, + external_conversation_id=known_provider_conversation_id, + touch=True, + ) + if updated_session: + known_status = updated_session.status + + event_data['provider_conversation_id'] = provider_conversation_id + event_data['conversation_id'] = session.session_id + event_data['session_status'] = known_status + yield f"data: {json.dumps(event_data, ensure_ascii=False)}\n\n" + except Exception as exc: + current_app.logger.exception("[chat-api] relay stream failed request_id=%s session_id=%s", request_id, session.session_id) + payload = {'event': 'error', 'message': str(exc), 'conversation_id': session.session_id, 'session_status': 'error'} + yield f"data: {json.dumps(payload, ensure_ascii=False)}\n\n" # 返回 SSE 响应,mimetype 设为 text/event-stream return Response( stream_with_context( - generator + relay_stream() ), mimetype='text/event-stream', headers={ @@ -994,7 +1253,9 @@ def submit_feedback(): # 构造查询:限定在当前用户和 Agent 范围内 chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id) if conversation_id: - chat_logs_query = chat_logs_query.filter_by(conversation_id=conversation_id) + chat_logs_query = chat_logs_query.filter( + or_(ChatLog.session_id == conversation_id, ChatLog.conversation_id == conversation_id) + ) # 取最新一条对话日志 chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first() diff --git a/backend/app/models.py b/backend/app/models.py index 68d6a4e9..6f8ca90c 100644 --- a/backend/app/models.py +++ b/backend/app/models.py @@ -178,6 +178,27 @@ class Agent(Base): back_populates="agents" ) +class ChatSession(Base): + """ + 聊天会话表 + 用途:独立持久化会话元数据,使生成中会话也能立即出现在历史记录中 + """ + __tablename__ = 'chat_sessions' + __table_args__ = ( + Index('ix_chat_sessions_user_agent_last_active', 'user_id', 'agent_id', 'last_active_at'), + ) + + id: Mapped[int] = mapped_column(primary_key=True) + session_id: Mapped[str] = mapped_column(String(100), unique=True, index=True) + user_id: Mapped[int] = mapped_column(ForeignKey('users.id'), index=True) + agent_id: Mapped[int] = mapped_column(ForeignKey('agents.id'), index=True) + title: Mapped[str] = mapped_column(String(255), default='') + status: Mapped[str] = mapped_column(String(20), default='running') + external_conversation_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True) + created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + updated_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, onupdate=datetime.utcnow) + last_active_at: Mapped[datetime] = mapped_column(default=datetime.utcnow, index=True) + class ChatLog(Base): """ 对话日志表 @@ -192,6 +213,7 @@ class ChatLog(Base): answer: Mapped[str] = mapped_column(Text) latency: Mapped[int] = mapped_column(default=0) conversation_id: Mapped[Optional[str]] = mapped_column(String(100)) + session_id: Mapped[Optional[str]] = mapped_column(String(100), index=True, nullable=True) message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True) payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) tokens_used: Mapped[int] = mapped_column(default=0) diff --git a/backend/app/services/dify.py b/backend/app/services/dify.py index c9390516..60ca0f96 100644 --- a/backend/app/services/dify.py +++ b/backend/app/services/dify.py @@ -292,7 +292,7 @@ class DifyService: return {} @staticmethod - def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None): + def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, request_id: str | None = None, session_id: str | None = None): """ 主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE Stream chat completion from Dify and relay SSE events to caller. @@ -450,6 +450,7 @@ class DifyService: chat_log_id = DifyService._log_chat( user_id=user_id, agent_id=agent.id, + session_id=session_id, conversation_id=data.get('conversation_id') or normalized_conversation_id, query=query, answer=''.join(full_answer), @@ -494,6 +495,7 @@ class DifyService: def _log_chat( user_id, agent_id, + session_id, conversation_id, query, answer, @@ -520,6 +522,7 @@ class DifyService: user_id=user_id, agent_id=agent_id, conversation_id=conversation_id, + session_id=session_id, query=query, answer=answer, tokens_used=tokens or 0, diff --git a/backend/app/services/hr_leave_sqlserver.py b/backend/app/services/hr_leave_sqlserver.py index 464c863b..1d2b21da 100644 --- a/backend/app/services/hr_leave_sqlserver.py +++ b/backend/app/services/hr_leave_sqlserver.py @@ -263,7 +263,7 @@ WHERE c002001 = ? return "\n".join(sections) @classmethod - def stream_chat(cls, query: str, user, agent, conversation_id: str = None): + def stream_chat(cls, query: str, user, agent, conversation_id: str = None, session_id: str | None = None): start_time = time.time() final_conversation_id = conversation_id or f"hr_{int(time.time())}" try: @@ -319,6 +319,7 @@ WHERE c002001 = ? user_id=user.id, agent_id=agent.id, conversation_id=final_conversation_id, + session_id=session_id, query=query, answer=result_text, tokens_used=0, diff --git a/backend/app/services/plm_oracle.py b/backend/app/services/plm_oracle.py index 15e67d37..0e9ac3aa 100644 --- a/backend/app/services/plm_oracle.py +++ b/backend/app/services/plm_oracle.py @@ -319,7 +319,7 @@ select * return "\n".join(lines) @classmethod - def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None): + def stream_chat(cls, query: str, user, agent, conversation_id: str | None = None, session_id: str | None = None): start_time = time.time() final_conversation_id = conversation_id or f"plm_{int(time.time())}" material_no = cls.extract_material_no(query) @@ -340,6 +340,7 @@ select * user_id=user.id, agent_id=agent.id, conversation_id=final_conversation_id, + session_id=session_id, query=query, answer=answer, tokens_used=0, diff --git a/backend/app/services/text2sql.py b/backend/app/services/text2sql.py index 3103df8c..252e92ae 100644 --- a/backend/app/services/text2sql.py +++ b/backend/app/services/text2sql.py @@ -495,7 +495,7 @@ class Text2SQLService: return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}" @staticmethod - def stream_chat(query: str, user_id: int, agent, conversation_id: str = None): + def stream_chat(query: str, user_id: int, agent, conversation_id: str = None, session_id: str | None = None): """Yields SSE events to frontend just like DifyService""" start_time = time.time() final_conversation_id = conversation_id or f"erp_{int(time.time())}" @@ -590,6 +590,7 @@ class Text2SQLService: user_id=user_id, agent_id=agent.id, conversation_id=final_conversation_id, + session_id=session_id, query=query, answer=result_text, tokens_used=0, diff --git a/backend/migrations/versions/c9d8e7f6a5b4_add_chat_sessions_and_session_id_to_chat_.py b/backend/migrations/versions/c9d8e7f6a5b4_add_chat_sessions_and_session_id_to_chat_.py new file mode 100644 index 00000000..9ba319bb --- /dev/null +++ b/backend/migrations/versions/c9d8e7f6a5b4_add_chat_sessions_and_session_id_to_chat_.py @@ -0,0 +1,64 @@ +"""add chat_sessions table and session_id to chat_logs + +Revision ID: c9d8e7f6a5b4 +Revises: e3f4a5b6c7d8 +Create Date: 2026-06-01 16:30:00.000000 + +""" +from alembic import op +import sqlalchemy as sa + + +# revision identifiers, used by Alembic. +revision = 'c9d8e7f6a5b4' +down_revision = 'e3f4a5b6c7d8' +branch_labels = None +depends_on = None + + +def upgrade(): + op.create_table( + 'chat_sessions', + sa.Column('id', sa.Integer(), nullable=False), + sa.Column('session_id', sa.String(length=100), nullable=False), + sa.Column('user_id', sa.Integer(), nullable=False), + sa.Column('agent_id', sa.Integer(), nullable=False), + sa.Column('title', sa.String(length=255), nullable=False, server_default=''), + sa.Column('status', sa.String(length=20), nullable=False, server_default='running'), + sa.Column('external_conversation_id', sa.String(length=100), nullable=True), + sa.Column('created_at', sa.DateTime(), nullable=False), + sa.Column('updated_at', sa.DateTime(), nullable=False), + sa.Column('last_active_at', sa.DateTime(), nullable=False), + sa.ForeignKeyConstraint(['agent_id'], ['agents.id']), + sa.ForeignKeyConstraint(['user_id'], ['users.id']), + sa.PrimaryKeyConstraint('id'), + ) + op.create_index('ix_chat_sessions_session_id', 'chat_sessions', ['session_id'], unique=True) + op.create_index('ix_chat_sessions_user_id', 'chat_sessions', ['user_id'], unique=False) + op.create_index('ix_chat_sessions_agent_id', 'chat_sessions', ['agent_id'], unique=False) + op.create_index('ix_chat_sessions_external_conversation_id', 'chat_sessions', ['external_conversation_id'], unique=False) + op.create_index('ix_chat_sessions_created_at', 'chat_sessions', ['created_at'], unique=False) + op.create_index('ix_chat_sessions_last_active_at', 'chat_sessions', ['last_active_at'], unique=False) + op.create_index( + 'ix_chat_sessions_user_agent_last_active', + 'chat_sessions', + ['user_id', 'agent_id', 'last_active_at'], + unique=False, + ) + + op.add_column('chat_logs', sa.Column('session_id', sa.String(length=100), nullable=True)) + op.create_index('ix_chat_logs_session_id', 'chat_logs', ['session_id'], unique=False) + + +def downgrade(): + op.drop_index('ix_chat_logs_session_id', table_name='chat_logs') + op.drop_column('chat_logs', 'session_id') + + op.drop_index('ix_chat_sessions_user_agent_last_active', table_name='chat_sessions') + op.drop_index('ix_chat_sessions_last_active_at', table_name='chat_sessions') + op.drop_index('ix_chat_sessions_created_at', table_name='chat_sessions') + op.drop_index('ix_chat_sessions_external_conversation_id', table_name='chat_sessions') + op.drop_index('ix_chat_sessions_agent_id', table_name='chat_sessions') + op.drop_index('ix_chat_sessions_user_id', table_name='chat_sessions') + op.drop_index('ix_chat_sessions_session_id', table_name='chat_sessions') + op.drop_table('chat_sessions') diff --git a/frontend/src/components/FilePreviewModal.vue b/frontend/src/components/FilePreviewModal.vue index 9770c305..b674c376 100644 --- a/frontend/src/components/FilePreviewModal.vue +++ b/frontend/src/components/FilePreviewModal.vue @@ -48,6 +48,7 @@ const emit = defineEmits<{ const { t } = useI18n(); const isLoading = ref(false); +const isDownloading = ref(false); const error = ref(''); const markdownHtml = ref(''); const excelPreview = ref(null); @@ -298,6 +299,43 @@ const loadBinaryContent = async () => { officeObjectUrl.value = URL.createObjectURL(blob); }; +const downloadFile = async () => { + if (!props.file?.url || !props.agentId || isDownloading.value) return; + + isDownloading.value = true; + try { + const params = new URLSearchParams({ + agent_id: String(props.agentId), + url: props.file.url, + name: props.file.name || '', + download: '1', + }); + const res = await fetch(`/api/chat/preview-file-raw?${params.toString()}`, { + headers: props.authHeaders || {}, + }); + if (!res.ok) { + const err = await res.json().catch(() => ({})); + throw new Error(err?.error || `HTTP ${res.status}`); + } + + const blob = await res.blob(); + const downloadUrl = URL.createObjectURL(blob); + const link = document.createElement('a'); + link.href = downloadUrl; + link.download = props.file.name || 'download'; + document.body.appendChild(link); + link.click(); + link.remove(); + window.setTimeout(() => URL.revokeObjectURL(downloadUrl), 1000); + } catch (e: any) { + error.value = t('filePreview.msg.downloadFailed', { + reason: e?.message || t('filePreview.msg.unknownError'), + }); + } finally { + isDownloading.value = false; + } +}; + /** * 在弹窗/文件变化时加载预览内容。 * 流程: @@ -436,8 +474,18 @@ watch(
-
{{ t('filePreview.title') }}
-
{{ file.name }}
+
{{ t('filePreview.title') }}
+
{{ file.name }}
+
@@ -532,6 +580,20 @@ watch(
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
+
+ +