合并代码,解决冲突

(cherry picked from commit 8b23bd771f04ceb1b9c1e3ae021d75001af5ba2f)
This commit is contained in:
hugo authored and sophie committed 2026-06-01 17:52:50 +08:00
1 parent 23badf7456
commit 93e99793d8
10 files changed
+621 -79

No files matched your search

+302 -41
View File
@@ -12,16 +12,18 @@ import tempfile
import os import os
import subprocess import subprocess
import uuid import uuid
import json
from datetime import datetime
from urllib.parse import urlparse from urllib.parse import urlparse
import requests import requests
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app, has_request_context 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 openpyxl import load_workbook
from app.services.dify import DifyService from app.services.dify import DifyService
from app.services.integration_api import IntegrationApiService from app.services.integration_api import IntegrationApiService
from app.decorators import require_agent_permission 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 from app import db
# 定义 Blueprint,用于在应用工厂中注册路由前缀 /api/chat # 定义 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() 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: def _normalize_windows_share_path(path_value: str) -> str:
normalized = str(path_value or "").strip().strip('"').replace("/", "\\") normalized = str(path_value or "").strip().strip('"').replace("/", "\\")
if normalized.startswith("\\\\"): if normalized.startswith("\\\\"):
@@ -681,24 +795,33 @@ def get_chat_sessions():
if user is None or agent is None: if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500 return jsonify({'error': 'Missing context'}), 500
# 先查出最近活跃的会话,再为每个会话回溯最近一条非空 query 作为标题。 session_rows = db.session.query(ChatSession).filter_by(
# 这样本地表单/确认等“无 query 的助手消息”不会把原始用户问题覆盖成 New Chat。 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( subquery = db.session.query(
ChatLog.conversation_id, ChatLog.conversation_id,
func.max(ChatLog.created_at).label('last_active') func.max(ChatLog.created_at).label('last_active')
).filter_by( ).filter(
user_id=user.id, ChatLog.user_id == user.id,
agent_id=agent.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() ).group_by(ChatLog.conversation_id).subquery()
results = db.session.query( legacy_rows = db.session.query(
subquery.c.conversation_id, subquery.c.conversation_id,
subquery.c.last_active, subquery.c.last_active,
).order_by(desc(subquery.c.last_active)).limit(20).all() ).order_by(desc(subquery.c.last_active)).limit(20).all()
sessions = [] for row in legacy_rows:
for row in results: if not row.conversation_id or row.conversation_id in session_ids:
if not row.conversation_id:
continue continue
latest_query_row = db.session.query(ChatLog.query).filter( latest_query_row = db.session.query(ChatLog.query).filter(
ChatLog.user_id == user.id, ChatLog.user_id == user.id,
@@ -709,13 +832,15 @@ def get_chat_sessions():
).order_by(desc(ChatLog.created_at), desc(ChatLog.id)).first() ).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() title = (latest_query_row[0] if latest_query_row and latest_query_row[0] else '').strip()
sessions.append({ sessions.append({
'id': 0, # 前端需要 id key 'id': 0,
'conversation_id': row.conversation_id, 'conversation_id': row.conversation_id,
'title': title[:30] + ('...' if len(title) > 30 else '') if title else '', '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']) @chat_bp.route('/sessions', methods=['DELETE'])
@@ -737,7 +862,8 @@ 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(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(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.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'}) return jsonify({'status': 'ok'})
@@ -754,11 +880,22 @@ def delete_chat_session(conversation_id):
if user is None or agent is None: if user is None or agent is None:
return jsonify({'error': 'Missing context'}), 500 return jsonify({'error': 'Missing context'}), 500
chat_logs = db.session.query(ChatLog).filter_by( session = _get_chat_session(user.id, agent.id, conversation_id)
user_id=user.id, if session:
agent_id=agent.id, chat_logs = db.session.query(ChatLog).filter(
conversation_id=conversation_id ChatLog.user_id == user.id,
).all() 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] chat_log_ids = [log.id for log in chat_logs]
if chat_log_ids: if chat_log_ids:
@@ -766,7 +903,9 @@ 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(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(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.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'}) return jsonify({'status': 'ok'})
@@ -781,9 +920,17 @@ def get_chat_messages():
if not conversation_id: if not conversation_id:
return jsonify([]) return jsonify([])
logs = db.session.query(ChatLog).filter_by( session = _get_chat_session(getattr(g.current_user, 'id', 0), getattr(g.current_agent, 'id', 0), conversation_id)
conversation_id=conversation_id if session:
).order_by(ChatLog.created_at.asc()).all() 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 = [] messages = []
for log in logs: for log in logs:
@@ -820,19 +967,27 @@ def save_local_message():
return jsonify({'error': 'Missing context'}), 500 return jsonify({'error': 'Missing context'}), 500
data = request.get_json() or {} data = request.get_json() or {}
conversation_id = data.get('conversation_id') conversation_id = (data.get('conversation_id') or '').strip()
message_type = data.get('type') message_type = data.get('type')
content = data.get('content', '') content = data.get('content', '')
payload = data.get('payload') payload = data.get('payload')
user_query = data.get('query', '') user_query = data.get('query', '')
if not conversation_id:
import uuid
conversation_id = str(uuid.uuid4())
if not message_type: if not message_type:
return jsonify({'error': 'type is required'}), 400 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 已经被保存过,可以直接更新该记录 # 如果 payload 里面包含 formId,且该 formId 已经被保存过,可以直接更新该记录
# 这样能保证前端表单状态(例如已确认)被持久化 # 这样能保证前端表单状态(例如已确认)被持久化
local_id = payload.get('formId') if payload and isinstance(payload, dict) else None 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( logs = db.session.query(ChatLog).filter_by(
user_id=user.id, user_id=user.id,
agent_id=agent.id, agent_id=agent.id,
conversation_id=conversation_id, session_id=conversation_id,
message_type=message_type message_type=message_type
).order_by(ChatLog.created_at.desc()).limit(20).all() ).order_by(ChatLog.created_at.desc()).limit(20).all()
@@ -863,14 +1018,17 @@ def save_local_message():
chat_log = ChatLog( chat_log = ChatLog(
user_id=user.id, user_id=user.id,
agent_id=agent.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, query=user_query,
answer=content, answer=content,
message_type=message_type, message_type=message_type,
payload=payload payload=payload
) )
db.session.add(chat_log) db.session.add(chat_log)
session.status = 'done'
session.last_active_at = datetime.utcnow()
session.updated_at = datetime.utcnow()
db.session.commit() db.session.commit()
return jsonify({'status': 'ok', 'chat_log_id': chat_log.id, 'conversation_id': conversation_id}) 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 {} data = request.get_json() or {}
# 提取用户提问内容 # 提取用户提问内容
query = data.get('query') query = data.get('query')
# 提取会话 ID(可选) # 前端传入的 conversation_id 在 B2 里代表本地 session_id
conversation_id = data.get('conversation_id') conversation_id = data.get('conversation_id')
# 知识库类型 # 知识库类型
kb_type = data.get('kb_type', '企业知识库') 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)) 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 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.dify import DifyService
from app.services.plm_oracle import PLMOracleService from app.services.plm_oracle import PLMOracleService
if PLMOracleService.supports(query, agent): external_conversation_id = None
generator = PLMOracleService.stream_chat(query, user, agent, conversation_id) 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知识库': elif kb_type == 'ERP知识库':
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from app.services.text2sql import Text2SQLService from app.services.text2sql import Text2SQLService
if HRLeaveSQLServerService.supports(query): 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: 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: else:
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
if HRLeaveSQLServerService.supports(query): 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: 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 # 返回 SSE 响应,mimetype 设为 text/event-stream
return Response( return Response(
stream_with_context( stream_with_context(
generator relay_stream()
), ),
mimetype='text/event-stream', mimetype='text/event-stream',
headers={ headers={
@@ -994,7 +1253,9 @@ def submit_feedback():
# 构造查询:限定在当前用户和 Agent 范围内 # 构造查询:限定在当前用户和 Agent 范围内
chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id) chat_logs_query = db.session.query(ChatLog).filter_by(user_id=user.id, agent_id=agent.id)
if conversation_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() chat_log = chat_logs_query.order_by(ChatLog.created_at.desc()).first()
+22
View File
@@ -178,6 +178,27 @@ class Agent(Base):
back_populates="agents" 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): class ChatLog(Base):
""" """
对话日志表 对话日志表
@@ -192,6 +213,7 @@ class ChatLog(Base):
answer: Mapped[str] = mapped_column(Text) answer: Mapped[str] = mapped_column(Text)
latency: Mapped[int] = mapped_column(default=0) latency: Mapped[int] = mapped_column(default=0)
conversation_id: Mapped[Optional[str]] = mapped_column(String(100)) 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) message_type: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True) payload: Mapped[Optional[dict]] = mapped_column(JSON, nullable=True)
tokens_used: Mapped[int] = mapped_column(default=0) tokens_used: Mapped[int] = mapped_column(default=0)
+4 -1
View File
@@ -292,7 +292,7 @@ class DifyService:
return {} return {}
@staticmethod @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 主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
Stream chat completion from Dify and relay SSE events to caller. Stream chat completion from Dify and relay SSE events to caller.
@@ -450,6 +450,7 @@ class DifyService:
chat_log_id = DifyService._log_chat( chat_log_id = DifyService._log_chat(
user_id=user_id, user_id=user_id,
agent_id=agent.id, agent_id=agent.id,
session_id=session_id,
conversation_id=data.get('conversation_id') or normalized_conversation_id, conversation_id=data.get('conversation_id') or normalized_conversation_id,
query=query, query=query,
answer=''.join(full_answer), answer=''.join(full_answer),
@@ -494,6 +495,7 @@ class DifyService:
def _log_chat( def _log_chat(
user_id, user_id,
agent_id, agent_id,
session_id,
conversation_id, conversation_id,
query, query,
answer, answer,
@@ -520,6 +522,7 @@ class DifyService:
user_id=user_id, user_id=user_id,
agent_id=agent_id, agent_id=agent_id,
conversation_id=conversation_id, conversation_id=conversation_id,
session_id=session_id,
query=query, query=query,
answer=answer, answer=answer,
tokens_used=tokens or 0, tokens_used=tokens or 0,
+2 -1
View File
@@ -263,7 +263,7 @@ WHERE c002001 = ?
return "\n".join(sections) return "\n".join(sections)
@classmethod @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() start_time = time.time()
final_conversation_id = conversation_id or f"hr_{int(time.time())}" final_conversation_id = conversation_id or f"hr_{int(time.time())}"
try: try:
@@ -319,6 +319,7 @@ WHERE c002001 = ?
user_id=user.id, user_id=user.id,
agent_id=agent.id, agent_id=agent.id,
conversation_id=final_conversation_id, conversation_id=final_conversation_id,
session_id=session_id,
query=query, query=query,
answer=result_text, answer=result_text,
tokens_used=0, tokens_used=0,
+2 -1
View File
@@ -319,7 +319,7 @@ select *
return "\n".join(lines) return "\n".join(lines)
@classmethod @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() start_time = time.time()
final_conversation_id = conversation_id or f"plm_{int(time.time())}" final_conversation_id = conversation_id or f"plm_{int(time.time())}"
material_no = cls.extract_material_no(query) material_no = cls.extract_material_no(query)
@@ -340,6 +340,7 @@ select *
user_id=user.id, user_id=user.id,
agent_id=agent.id, agent_id=agent.id,
conversation_id=final_conversation_id, conversation_id=final_conversation_id,
session_id=session_id,
query=query, query=query,
answer=answer, answer=answer,
tokens_used=0, tokens_used=0,
+2 -1
View File
@@ -495,7 +495,7 @@ class Text2SQLService:
return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}" return f"{summary_text}\n\n**查询结果如下:**\n\n{table_str}\n\n{sql_details}"
@staticmethod @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""" """Yields SSE events to frontend just like DifyService"""
start_time = time.time() start_time = time.time()
final_conversation_id = conversation_id or f"erp_{int(time.time())}" final_conversation_id = conversation_id or f"erp_{int(time.time())}"
@@ -590,6 +590,7 @@ class Text2SQLService:
user_id=user_id, user_id=user_id,
agent_id=agent.id, agent_id=agent.id,
conversation_id=final_conversation_id, conversation_id=final_conversation_id,
session_id=session_id,
query=query, query=query,
answer=result_text, answer=result_text,
tokens_used=0, tokens_used=0,
@@ -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')
+64 -2
View File
@@ -48,6 +48,7 @@ const emit = defineEmits<{
const { t } = useI18n(); const { t } = useI18n();
const isLoading = ref(false); const isLoading = ref(false);
const isDownloading = ref(false);
const error = ref(''); const error = ref('');
const markdownHtml = ref(''); const markdownHtml = ref('');
const excelPreview = ref<ExcelPreviewData | null>(null); const excelPreview = ref<ExcelPreviewData | null>(null);
@@ -298,6 +299,43 @@ const loadBinaryContent = async () => {
officeObjectUrl.value = URL.createObjectURL(blob); 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(
<div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden"> <div class="dialog-panel max-w-5xl h-[85vh] overflow-hidden">
<div class="dialog-header dialog-header--compact items-start"> <div class="dialog-header dialog-header--compact items-start">
<div class="min-w-0"> <div class="min-w-0">
<div class="label-field tracking-wide">{{ t('filePreview.title') }}</div> <div class="text-sm font-medium text-slate-500 dark:text-slate-400 tracking-wide">{{ t('filePreview.title') }}</div>
<div class="mt-1 font-semibold text-primary break-words">{{ file.name }}</div> <div class="mt-1 font-semibold text-slate-900 dark:text-slate-100 break-words">{{ file.name }}</div>
<button type="button" @click="downloadFile" :disabled="isDownloading" class="mt-2 inline-flex items-center justify-center px-3 py-1.5 text-xs font-medium rounded-lg bg-brand-50 text-brand-700 hover:bg-brand-100 border border-brand-200 dark:bg-brand-900/30 dark:text-brand-300 dark:border-brand-800 transition-colors disabled:opacity-50 disabled:cursor-not-allowed">
<svg v-if="!isDownloading" xmlns="http://www.w3.org/2000/svg" class="h-4 w-4 mr-1.5" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2">
<path stroke-linecap="round" stroke-linejoin="round" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
</svg>
<svg v-else class="animate-spin -ml-1 mr-2 h-4 w-4 text-brand-700 dark:text-brand-300" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div> </div>
<button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button> <button type="button" class="btn-secondary shrink-0" @click="close">{{ t('common.close') }}</button>
</div> </div>
@@ -532,6 +580,20 @@ watch(
<div class="mt-2 text-sm text-muted"> <div class="mt-2 text-sm text-muted">
This Office file uses a private or non-HTTPS link, so online preview cannot render it. This Office file uses a private or non-HTTPS link, so online preview cannot render it.
</div> </div>
<div class="mt-4 flex gap-3">
<button
type="button"
@click="downloadFile"
:disabled="isDownloading"
class="px-4 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700 disabled:opacity-50 disabled:cursor-not-allowed inline-flex items-center"
>
<svg v-if="isDownloading" class="animate-spin -ml-1 mr-2 h-4 w-4 text-white" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
<circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
<path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
</svg>
{{ isDownloading ? t('filePreview.downloading') : t('filePreview.download') }}
</button>
</div>
</div> </div>
<iframe <iframe
v-else v-else
+87 -18
View File
@@ -32,6 +32,18 @@ interface ChatMessage {
rated?: boolean; rated?: boolean;
} }
type RunStatus = 'running' | 'done' | 'error';
interface ChatRun {
runId: number;
viewId: number;
query: string;
messages: ChatMessage[];
conversationId: string | null;
status: RunStatus;
createdAt: string;
}
// 统一资源格式为数组,兼容 list 或 { data: list } 两种结构 // 统一资源格式为数组,兼容 list 或 { data: list } 两种结构
const normalizeResources = (resources: any): RetrieverResource[] => { const normalizeResources = (resources: any): RetrieverResource[] => {
if (!resources) return []; if (!resources) return [];
@@ -125,12 +137,35 @@ export function useChat() {
*/ */
const isThinking = ref(false); const isThinking = ref(false);
const viewId = ref(0);
const runs = ref<ChatRun[]>([]);
const activeRunId = ref<number | null>(null);
let runSeq = 0;
/** /**
* conversationId: 当前会话 ID * conversationId: 当前会话 ID
* 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog * 用于在多轮对话中关联上下文,并在反馈时找到对应 ChatLog
*/ */
const conversationId = ref<string | null>(null); const conversationId = ref<string | null>(null);
const activateRun = (runId: number) => {
const run = runs.value.find((r) => r.runId === runId);
if (!run) return;
messages.value = run.messages;
conversationId.value = run.conversationId;
isThinking.value = run.status === 'running';
activeRunId.value = runId;
};
const createNewChatView = () => {
viewId.value += 1;
messages.value = [];
conversationId.value = null;
isThinking.value = false;
activeRunId.value = null;
};
/** /**
* sendMessage * sendMessage
* 用途:发送消息并处理 SSE 流式响应 * 用途:发送消息并处理 SSE 流式响应
@@ -145,6 +180,20 @@ export function useChat() {
* agentId: 目标 Agent ID * agentId: 目标 Agent ID
*/ */
const sendMessage = async (query: string, agentId: number, kbType: string = '企业知识库') => { const sendMessage = async (query: string, agentId: number, kbType: string = '企业知识库') => {
const runViewId = viewId.value;
const runMessages = messages.value;
const run: ChatRun = {
runId: ++runSeq,
viewId: runViewId,
query,
messages: runMessages,
conversationId: conversationId.value,
status: 'running',
createdAt: new Date().toISOString(),
};
runs.value.unshift(run);
if (runs.value.length > 30) runs.value = runs.value.slice(0, 30);
activeRunId.value = run.runId;
console.info('[chat][send] start', { console.info('[chat][send] start', {
agentId, agentId,
kbType, kbType,
@@ -152,19 +201,19 @@ export function useChat() {
conversationId: conversationId.value, conversationId: conversationId.value,
}); });
// 1. 乐观 UI 更新:立即将用户消息推入列表 // 1. 乐观 UI 更新:立即将用户消息推入列表
messages.value.push({ role: 'user', content: query }); runMessages.push({ role: 'user', content: query });
// Lazily create assistant message only when answer/error arrives. // Lazily create assistant message only when answer/error arrives.
let botMsgIndex: number | null = null; let botMsgIndex: number | null = null;
const ensureBotMessage = () => { const ensureBotMessage = () => {
if (botMsgIndex === null) { if (botMsgIndex === null) {
botMsgIndex = messages.value.push({ botMsgIndex = runMessages.push({
role: 'assistant', role: 'assistant',
content: '', content: '',
retriever_resources: [], retriever_resources: [],
attribution_parts: [] attribution_parts: []
}) - 1; }) - 1;
} }
return messages.value[botMsgIndex] || null; return runMessages[botMsgIndex] || null;
}; };
isThinking.value = true; isThinking.value = true;
@@ -234,7 +283,14 @@ export function useChat() {
conversationId: data?.conversation_id || conversationId.value, conversationId: data?.conversation_id || conversationId.value,
}); });
if (data.event === 'message') { if (data?.conversation_id) {
const cid = String(data.conversation_id);
if (!run.conversationId) run.conversationId = cid;
if (messages.value === runMessages) conversationId.value = cid;
}
const eventName = String(data.event || '');
if (eventName === 'message' || eventName === 'agent_message') {
if (typeof data.answer === 'string' && data.answer.length > 0) { if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage(); const botMsg = ensureBotMessage();
if (!botMsg) continue; if (!botMsg) continue;
@@ -246,21 +302,20 @@ export function useChat() {
}); });
} }
if (botMsgIndex !== null) { if (botMsgIndex !== null) {
const currentBotMsg = messages.value[botMsgIndex]; const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) { if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data); applyEventMetadata(currentBotMsg, data);
} }
} }
} else if (data.event === 'message_end') { } else if (eventName === 'message_end' || eventName === 'workflow_finished') {
run.status = 'done';
if (messages.value === runMessages) isThinking.value = false;
if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) { if (botMsgIndex !== null && Number.isInteger(data.chat_log_id)) {
const currentBotMsg = messages.value[botMsgIndex]; const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) { if (currentBotMsg) {
currentBotMsg.chat_log_id = Number(data.chat_log_id); currentBotMsg.chat_log_id = Number(data.chat_log_id);
} }
} }
if (data.conversation_id) {
conversationId.value = data.conversation_id;
}
if (typeof data.answer === 'string' && data.answer.length > 0) { if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage(); const botMsg = ensureBotMessage();
if (!botMsg) continue; if (!botMsg) continue;
@@ -278,16 +333,22 @@ export function useChat() {
}); });
} }
if (botMsgIndex !== null) { if (botMsgIndex !== null) {
const currentBotMsg = messages.value[botMsgIndex]; const currentBotMsg = runMessages[botMsgIndex];
if (currentBotMsg) { if (currentBotMsg) {
applyEventMetadata(currentBotMsg, data); applyEventMetadata(currentBotMsg, data);
} }
} }
} else if (data.event === 'error') { } else if (eventName === 'error') {
const botMsg = ensureBotMessage(); const botMsg = ensureBotMessage();
if (!botMsg) continue; if (!botMsg) continue;
botMsg.content += `\n[Error: ${data.message}]`; botMsg.content += `\n[Error: ${data.message}]`;
console.error('[chat][sse] backend error event', data); console.error('[chat][sse] backend error event', data);
run.status = 'error';
if (messages.value === runMessages) isThinking.value = false;
} else if (typeof data.answer === 'string' && data.answer.length > 0) {
const botMsg = ensureBotMessage();
if (!botMsg) continue;
botMsg.content += normalizeStreamText(data.answer);
} }
} catch (e) { } catch (e) {
// Ignore malformed or partial payload fragments. // Ignore malformed or partial payload fragments.
@@ -297,16 +358,24 @@ export function useChat() {
} }
} catch (e: any) { } catch (e: any) {
console.error('[chat][send] failed', e); console.error('[chat][send] failed', e);
run.status = 'error';
const botMsg = ensureBotMessage(); const botMsg = ensureBotMessage();
if (botMsg) { if (botMsg) {
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`; botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
} }
} finally { } finally {
isThinking.value = false; if (messages.value === runMessages) {
console.info('[chat][send] end', { isThinking.value = false;
messages: messages.value.length, console.info('[chat][send] end', {
conversationId: conversationId.value, messages: messages.value.length,
}); conversationId: conversationId.value,
});
} else {
console.info('[chat][send] end (detached)', {
activeConversationId: conversationId.value,
runViewId,
});
}
} }
}; };
@@ -315,5 +384,5 @@ export function useChat() {
return text.replace(/\\n/g, '\n'); return text.replace(/\\n/g, '\n');
}; };
return { messages, isThinking, conversationId, sendMessage }; return { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage };
} }
+72 -14
View File
@@ -611,7 +611,7 @@ const isSidebarCollapsed = ref(false);
const copiedIndex = ref<number | null>(null); const copiedIndex = ref<number | null>(null);
// 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数 // 从 useChat 中解构出消息列表、思考状态、会话 ID 与发送函数
const { messages, isThinking, conversationId, sendMessage } = useChat(); const { messages, isThinking, conversationId, runs, activeRunId, activateRun, createNewChatView, sendMessage } = useChat();
const input = ref(''); const input = ref('');
const currentAgent = ref<any>(null); const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]); const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
@@ -1623,6 +1623,48 @@ interface ChatHistoryItem {
} }
const history = ref<ChatHistoryItem[]>([]); const history = ref<ChatHistoryItem[]>([]);
type DisplayHistoryItem = ChatHistoryItem & { __runId?: number; __status?: string };
const activeHistoryKey = computed(() => {
if (conversationId.value) return conversationId.value;
if (activeRunId.value) return `pending:${activeRunId.value}`;
return '';
});
const displayHistory = computed<DisplayHistoryItem[]>(() => {
const server = history.value || [];
const serverIds = new Set(server.map((h) => h.conversation_id));
const pending: DisplayHistoryItem[] = (runs.value || [])
.filter((r) => r.runId !== activeRunId.value)
.map((r) => ({
id: 0,
conversation_id: r.conversationId || `pending:${r.runId}`,
title: (r.query || '').trim(),
created_at: r.createdAt,
__runId: r.runId,
__status: r.status,
}))
.filter((item) => item.conversation_id.startsWith('pending:') || !serverIds.has(item.conversation_id));
const merged = [...pending, ...server] as DisplayHistoryItem[];
merged.sort((a, b) => String(b.created_at || '').localeCompare(String(a.created_at || '')));
return merged;
});
const handleHistorySelect = (item: DisplayHistoryItem) => {
if (item.__runId) {
activateRun(item.__runId);
} else {
const run = runs.value.find((r) => r.conversationId === item.conversation_id);
if (run && run.status === 'running') {
activateRun(run.runId);
} else {
loadConversation(item.conversation_id);
}
}
isSidebarOpen.value = false;
};
// 预设问题:从路由 query.preset 中读取(如果有) // 预设问题:从路由 query.preset 中读取(如果有)
const presetQuestion = computed(() => { const presetQuestion = computed(() => {
const q = route.query.preset; const q = route.query.preset;
@@ -1892,7 +1934,8 @@ const clearAllHistory = async () => {
}); });
if (res.ok) { if (res.ok) {
history.value = []; history.value = [];
if (conversationId.value) { runs.value = [];
if (conversationId.value || activeRunId.value) {
startNewChat(); startNewChat();
} }
} }
@@ -1923,9 +1966,11 @@ const deleteHistoryItem = async (id: string, event: Event) => {
}; };
const loadConversation = async (id: string) => { const loadConversation = async (id: string) => {
if (conversationId.value === id) return; if (conversationId.value === id && !activeRunId.value) return;
try { try {
activeRunId.value = null;
isThinking.value = false;
const res = await fetch(`/api/chat/messages?conversation_id=${id}&agent_id=${agentId}`, { headers: getAuthHeaders() }); const res = await fetch(`/api/chat/messages?conversation_id=${id}&agent_id=${agentId}`, { headers: getAuthHeaders() });
if (res.ok) { if (res.ok) {
messages.value = await res.json(); messages.value = await res.json();
@@ -1939,8 +1984,7 @@ const loadConversation = async (id: string) => {
}; };
const startNewChat = () => { const startNewChat = () => {
messages.value = []; createNewChatView();
conversationId.value = null;
}; };
const loadAgent = async () => { const loadAgent = async () => {
@@ -2043,6 +2087,17 @@ watch(
} }
); );
watch(
() => conversationId.value,
async (id, prev) => {
if (!id || id === prev) return;
const exists = history.value.some((item) => item.conversation_id === id);
if (!exists) {
await loadHistory();
}
}
);
onBeforeUnmount(() => { onBeforeUnmount(() => {
window.removeEventListener('pagehide', onPageHide); window.removeEventListener('pagehide', onPageHide);
window.removeEventListener('hxops:logout', onAuthLogout); window.removeEventListener('hxops:logout', onAuthLogout);
@@ -2165,29 +2220,32 @@ const showChatRating = ref(false);
</div> </div>
<div class="flex items-center justify-between px-4 py-2"> <div class="flex items-center justify-between px-4 py-2">
<span class="text-xs font-semibold text-muted">{{ $t('chat.history') }}</span> <span class="text-xs font-semibold text-slate-500 dark:text-slate-400">{{ $t('chat.history') }}</span>
<button v-if="history.length > 0" @click="clearAllHistory" class="text-xs text-muted transition-colors hover:text-secondary"> <button v-if="displayHistory.length > 0" @click="clearAllHistory" class="text-xs text-slate-400 transition-colors hover:text-slate-600 dark:hover:text-slate-200">
{{ $t('chat.clearAll') }} {{ $t('chat.clearAll') }}
</button> </button>
</div> </div>
<div class="flex-1 overflow-y-auto px-2 scrollbar-thin"> <div class="flex-1 overflow-y-auto px-2 scrollbar-thin">
<div v-if="history.length === 0" class="py-8 text-center text-sm italic text-muted">{{ $t('chat.noHistory') }}</div> <div v-if="displayHistory.length === 0" class="py-8 text-center text-sm italic text-slate-400">{{ $t('chat.noHistory') }}</div>
<div v-else class="space-y-0.5"> <div v-else class="space-y-0.5">
<div <div
v-for="item in history" v-for="item in displayHistory"
:key="item.conversation_id" :key="item.conversation_id"
class="chat-history-item" class="group relative flex w-full items-center justify-between rounded-lg transition-colors"
:class="{ 'chat-history-item--active': conversationId === item.conversation_id }" :class="activeHistoryKey === item.conversation_id ? 'bg-brand-50 dark:bg-brand-900/20' : 'hover:bg-slate-50 dark:hover:bg-slate-800/50'"
> >
<button <button
class="chat-history-link" class="flex-1 truncate px-3 py-2.5 text-left text-sm pr-8"
:class="{ 'chat-history-link--active': conversationId === item.conversation_id }" :class="activeHistoryKey === item.conversation_id
@click="loadConversation(item.conversation_id); isSidebarOpen = false;" ? 'font-medium text-brand-700 dark:text-brand-300'
: 'text-slate-600 dark:text-slate-300'"
@click="handleHistorySelect(item)"
> >
{{ item.title || $t('chat.newChat') }} {{ item.title || $t('chat.newChat') }}
</button> </button>
<button <button
v-if="!(item as any).__runId"
@click="deleteHistoryItem(item.conversation_id, $event)" @click="deleteHistoryItem(item.conversation_id, $event)"
class="absolute right-2 p-1.5 text-muted opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100" class="absolute right-2 p-1.5 text-muted opacity-0 transition-opacity hover:text-red-500 group-hover:opacity-100"
:title="$t('chat.clearOneRecord')" :title="$t('chat.clearOneRecord')"