fix: 支持原文件下载,同时将postgres地址由localhost变更为8.152.207.171
This commit is contained in:
1 parent
70f95e9f5c
commit
c380248502
12 files changed
+1273
-273
No files matched your search
+50
-1
@@ -8,6 +8,7 @@ backend/app/api/chat.py
|
||||
from flask import Blueprint, request, Response, stream_with_context, jsonify, g, current_app
|
||||
from sqlalchemy import func, desc
|
||||
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 import db
|
||||
@@ -85,7 +86,12 @@ def get_chat_messages():
|
||||
messages = []
|
||||
for log in logs:
|
||||
messages.append({'role': 'user', 'content': log.query})
|
||||
messages.append({'role': 'assistant', 'content': log.answer})
|
||||
messages.append({
|
||||
'role': 'assistant',
|
||||
'content': log.answer,
|
||||
'retriever_resources': log.retriever_resources or [],
|
||||
'attribution_parts': log.attribution_parts or []
|
||||
})
|
||||
|
||||
return jsonify(messages)
|
||||
|
||||
@@ -116,8 +122,17 @@ def chat_completions():
|
||||
user = getattr(g, 'current_user', None)
|
||||
agent = getattr(g, 'current_agent', None)
|
||||
|
||||
current_app.logger.info(
|
||||
"[chat-api] /completions request user_id=%s agent_id=%s query_len=%s conversation_id=%s",
|
||||
getattr(user, 'id', None),
|
||||
getattr(agent, 'id', None),
|
||||
len(query or ''),
|
||||
conversation_id,
|
||||
)
|
||||
|
||||
# 安全兜底:如果装饰器未正确注入,返回错误
|
||||
if user is None or agent is None:
|
||||
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
|
||||
|
||||
# 返回 SSE 响应,mimetype 设为 text/event-stream
|
||||
@@ -128,6 +143,8 @@ def chat_completions():
|
||||
mimetype='text/event-stream',
|
||||
headers={
|
||||
'Cache-Control': 'no-cache',
|
||||
'Content-Type': 'text/event-stream; charset=utf-8',
|
||||
'Connection': 'keep-alive',
|
||||
# 对于 Nginx 反向代理,需要关闭缓冲以支持实时流式传输
|
||||
'X-Accel-Buffering': 'no'
|
||||
}
|
||||
@@ -193,3 +210,35 @@ def submit_feedback():
|
||||
|
||||
db.session.commit()
|
||||
return jsonify({'status': 'ok'})
|
||||
|
||||
|
||||
@chat_bp.route('/source-file', methods=['GET'])
|
||||
@require_agent_permission
|
||||
def resolve_source_file():
|
||||
"""
|
||||
Resolve original source download URL by Dify dataset/document IDs.
|
||||
"""
|
||||
dataset_id = (request.args.get('dataset_id') or '').strip()
|
||||
remote_document_id = (request.args.get('remote_document_id') or '').strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
current_app.logger.warning(
|
||||
"[source-file] missing required params: dataset_id=%r remote_document_id_present=%s remote_document_id_preview=%r query_args=%s",
|
||||
dataset_id,
|
||||
bool(remote_document_id),
|
||||
(remote_document_id[:8] + "...") if remote_document_id else "",
|
||||
dict(request.args),
|
||||
)
|
||||
return jsonify({'error': 'dataset_id and remote_document_id are required'}), 400
|
||||
|
||||
payload = IntegrationApiService.lookup_file_by_dify(dataset_id, remote_document_id)
|
||||
if not payload:
|
||||
return jsonify({'error': 'source file mapping not found'}), 404
|
||||
|
||||
return jsonify({
|
||||
'dataset_id': dataset_id,
|
||||
'remote_document_id': remote_document_id,
|
||||
'source_filename': payload.get('source_filename'),
|
||||
'source_ext': payload.get('source_ext'),
|
||||
'source_download_url': payload.get('source_download_url'),
|
||||
'download_url_expires_at': payload.get('download_url_expires_at'),
|
||||
})
|
||||
+27
-10
@@ -1,9 +1,17 @@
|
||||
|
||||
"""
|
||||
"""
|
||||
backend/app/config.py
|
||||
配置类,区分开发/生产环境
|
||||
"""
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
from dotenv import load_dotenv
|
||||
|
||||
|
||||
# Auto-load backend/.env so new shell windows also pick up local settings.
|
||||
_BACKEND_DIR = Path(__file__).resolve().parents[1]
|
||||
load_dotenv(_BACKEND_DIR / '.env')
|
||||
|
||||
|
||||
class Config:
|
||||
SQLALCHEMY_TRACK_MODIFICATIONS = False
|
||||
@@ -13,7 +21,7 @@ class Config:
|
||||
'pool_size': 20,
|
||||
'max_overflow': 10,
|
||||
'pool_recycle': 3600,
|
||||
'pool_pre_ping': True
|
||||
'pool_pre_ping': True,
|
||||
}
|
||||
# Dify 网关配置
|
||||
DIFY_API_BASE = os.getenv('DIFY_API_BASE', 'https://api.dify.ai/v1')
|
||||
@@ -23,10 +31,15 @@ class Config:
|
||||
FEEDBACK_ENABLED = os.getenv('FEEDBACK_ENABLED', 'true').lower() == 'true'
|
||||
HR_WORKFLOW_IFRAME_URL = os.getenv(
|
||||
'HR_WORKFLOW_IFRAME_URL',
|
||||
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg'
|
||||
'http://192.168.100.230:8882/chatbot/imrmbYyasJUHjXQg',
|
||||
)
|
||||
HR_WORKFLOW_API_BASE = os.getenv('HR_WORKFLOW_API_BASE', 'http://127.0.0.1:5001/v1')
|
||||
HR_WORKFLOW_API_KEY = os.getenv('HR_WORKFLOW_API_KEY')
|
||||
|
||||
# External integration API (resolve original source file links by Dify IDs)
|
||||
INTEGRATION_API_BASE = os.getenv('INTEGRATION_API_BASE', 'http://192.168.100.230:8891')
|
||||
INTEGRATION_API_KEY = os.getenv('INTEGRATION_API_KEY')
|
||||
|
||||
# WeCom (企业微信) 登录配置
|
||||
WECOM_ENABLED = os.getenv('WECOM_ENABLED', 'false').lower() == 'true'
|
||||
WECOM_CORP_ID = os.getenv('WECOM_CORP_ID')
|
||||
@@ -35,19 +48,22 @@ class Config:
|
||||
WECOM_REDIRECT_URI = os.getenv('WECOM_REDIRECT_URI')
|
||||
WECOM_AUTO_CREATE_USER = os.getenv('WECOM_AUTO_CREATE_USER', 'true').lower() == 'true'
|
||||
|
||||
|
||||
class DevelopmentConfig(Config):
|
||||
DEBUG = True
|
||||
# 本地 MacBook PostgreSQL 配置(数据库: hxops_db,用户: postgres, 密码: difyai123456)
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
'postgresql://postgres:difyai123456@localhost:5432/hxops_db'
|
||||
'postgresql://postgres:123456@8.152.207.171:5432/hxops_db',
|
||||
)
|
||||
|
||||
|
||||
class ProductionConfig(Config):
|
||||
DEBUG = False
|
||||
# 服务器 Ubuntu PostgreSQL 配置
|
||||
# 注意:在服务器上通过环境变量覆盖,但此处保留默认模板
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv('DATABASE_URL', 'postgresql://postgres:difyai123456@localhost:5432/hxops_prod')
|
||||
SQLALCHEMY_DATABASE_URI = os.getenv(
|
||||
'DATABASE_URL',
|
||||
'postgresql://postgres:123456@8.152.207.171:5432/hxops_prod',
|
||||
)
|
||||
|
||||
|
||||
class TestingConfig(Config):
|
||||
TESTING = True
|
||||
@@ -55,9 +71,10 @@ class TestingConfig(Config):
|
||||
WTF_CSRF_ENABLED = False
|
||||
SQLALCHEMY_ENGINE_OPTIONS = {}
|
||||
|
||||
|
||||
config = {
|
||||
'development': DevelopmentConfig,
|
||||
'testing': TestingConfig,
|
||||
'production': ProductionConfig,
|
||||
'default': DevelopmentConfig
|
||||
'default': DevelopmentConfig,
|
||||
}
|
||||
@@ -194,6 +194,9 @@ class ChatLog(Base):
|
||||
latency: Mapped[int] = mapped_column(default=0)
|
||||
conversation_id: Mapped[Optional[str]] = mapped_column(String(100))
|
||||
tokens_used: Mapped[int] = mapped_column(default=0)
|
||||
# Persist citation/source metadata so history messages can still show sources.
|
||||
retriever_resources: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
attribution_parts: Mapped[Optional[list]] = mapped_column(JSON)
|
||||
created_at: Mapped[datetime] = mapped_column(default=datetime.utcnow)
|
||||
|
||||
# 关联 Feedback
|
||||
|
||||
+459
-90
@@ -1,125 +1,213 @@
|
||||
|
||||
"""
|
||||
backend/app/services/dify.py
|
||||
文件用途:Dify API 集成服务
|
||||
引用文件:requests, json, models, config
|
||||
逻辑关系:负责与 Dify 平台进行 HTTP 通信,处理 SSE 流式响应,并记录审计日志
|
||||
|
||||
File-Level Overview
|
||||
-------------------
|
||||
This module provides the backend service wrapper for Dify streaming chat APIs.
|
||||
It is responsible for:
|
||||
1) Forwarding chat requests from this system to Dify in streaming mode.
|
||||
2) Relaying Dify SSE events to the frontend.
|
||||
3) Aggregating answer text and metadata (retriever resources / attribution).
|
||||
4) Enriching retriever resources with original source-file download URLs via
|
||||
the integration API mapping (dataset_id + remote_document_id).
|
||||
5) Persisting chat logs to the local database.
|
||||
|
||||
Main Data Flow
|
||||
--------------
|
||||
chat.py (/api/chat/completions)
|
||||
-> DifyService.stream_chat(...)
|
||||
-> requests.post(... stream=True) to Dify
|
||||
-> parse SSE events from Dify
|
||||
-> optional enrichment of source links on message_end
|
||||
-> write chat log
|
||||
-> yield SSE events to frontend
|
||||
"""
|
||||
import requests
|
||||
import json
|
||||
import time
|
||||
from typing import Any, List
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
from app.models import ChatLog, db
|
||||
|
||||
from app.config import Config
|
||||
from app.models import ChatLog, db
|
||||
from app.services.integration_api import IntegrationApiService
|
||||
|
||||
|
||||
class DifyService:
|
||||
"""
|
||||
Dify 服务类
|
||||
用途:封装与 Dify API 的交互逻辑
|
||||
"""
|
||||
|
||||
"""Dify service wrapper."""
|
||||
|
||||
@staticmethod
|
||||
def stream_chat(query: str, user_id: int, agent, conversation_id: str = None):
|
||||
"""
|
||||
生成器函数:向 Dify 发起请求并流式返回
|
||||
用途:处理 /v1/chat-messages 接口的流式响应
|
||||
核心逻辑:
|
||||
1. 构造请求头与 Payload
|
||||
2. 使用 requests.post(stream=True) 发起请求
|
||||
3. 逐行读取 SSE 数据
|
||||
4. 解析 'data: ' 开头的行,透传给前端
|
||||
5. 在 'message_end' 事件中记录完整日志到数据库
|
||||
参数:
|
||||
query: 用户提问内容
|
||||
user_id: 当前用户 ID
|
||||
agent: Agent 模型对象,包含 API Key
|
||||
conversation_id: 会话 ID (可选)
|
||||
输出:
|
||||
Yields SSE 格式字符串 "data: {...}\n\n"
|
||||
主流程,调用 Dify、解析 SSE、记录日志、写库、向上游继续产出 SSE
|
||||
Stream chat completion from Dify and relay SSE events to caller.
|
||||
|
||||
Args:
|
||||
query: User prompt text.
|
||||
user_id: Local user ID (sent to Dify as user string).
|
||||
agent: Agent model instance, must contain dify_api_key and optional api_base_url.
|
||||
conversation_id: Existing conversation ID for multi-turn context (optional).
|
||||
|
||||
Yields:
|
||||
SSE event lines in format: `data: {...}\\n\\n`.
|
||||
|
||||
Side Effects:
|
||||
- Collects/merges metadata from Dify events.
|
||||
- Enriches retriever resources with source URLs on message_end.
|
||||
- Persists chat log to DB when message_end arrives.
|
||||
- Writes diagnostic logs.
|
||||
"""
|
||||
# 使用 Agent 自定义的 API Base URL,若未配置则使用全局配置
|
||||
# Prefer agent-specific base URL; fallback to global config.
|
||||
base_url = agent.api_base_url if agent.api_base_url else Config.DIFY_API_BASE
|
||||
# 移除末尾斜杠以避免双斜杠问题
|
||||
base_url = base_url.rstrip('/')
|
||||
url = f"{base_url}/chat-messages"
|
||||
|
||||
headers = {
|
||||
'Authorization': f'Bearer {agent.dify_api_key}',
|
||||
'Content-Type': 'application/json'
|
||||
'Content-Type': 'application/json',
|
||||
}
|
||||
payload = {
|
||||
"inputs": {},
|
||||
"query": query,
|
||||
"response_mode": "streaming",
|
||||
"conversation_id": conversation_id,
|
||||
"user": str(user_id)
|
||||
'inputs': {},
|
||||
'query': query,
|
||||
'response_mode': 'streaming',
|
||||
'conversation_id': conversation_id,
|
||||
'user': str(user_id),
|
||||
}
|
||||
|
||||
# 记录开始时间,用于计算耗时
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] start user_id=%s agent_id=%s base_url=%s query_len=%s conversation_id=%s",
|
||||
user_id,
|
||||
getattr(agent, 'id', None),
|
||||
base_url,
|
||||
len(query or ''),
|
||||
conversation_id,
|
||||
)
|
||||
|
||||
start_time = time.time()
|
||||
# 用于收集流式片段拼接完整回答
|
||||
full_answer = []
|
||||
|
||||
full_answer: List[str] = []
|
||||
retriever_resources: List[Any] = []
|
||||
attribution_parts: List[str] = []
|
||||
|
||||
try:
|
||||
# stream=True 关键参数,建立长连接
|
||||
# 设置连接超时为 5 秒,读取超时为 60 秒
|
||||
with requests.post(url, headers=headers, json=payload, stream=True, timeout=(5, 60)) as response:
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] dify response status=%s reason=%s",
|
||||
response.status_code,
|
||||
response.reason,
|
||||
)
|
||||
response.raise_for_status()
|
||||
|
||||
# 逐行迭代响应内容
|
||||
|
||||
for line in response.iter_lines():
|
||||
if line:
|
||||
decoded_line = line.decode('utf-8')
|
||||
# 识别 SSE 数据行
|
||||
if decoded_line.startswith('data: '):
|
||||
json_str = decoded_line[6:]
|
||||
try:
|
||||
data = json.loads(json_str)
|
||||
event = data.get('event')
|
||||
|
||||
# 核心:将 Dify 的原始数据透传给前端
|
||||
yield f"data: {json_str}\n\n"
|
||||
|
||||
# 收集完整回答用于日志
|
||||
if event == 'message':
|
||||
full_answer.append(data.get('answer', ''))
|
||||
elif event == 'message_end':
|
||||
# 对话结束,记录日志
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
metadata = data.get('metadata', {})
|
||||
usage = metadata.get('usage', {})
|
||||
|
||||
# 显式使用应用上下文
|
||||
with current_app.app_context():
|
||||
DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or conversation_id,
|
||||
query=query,
|
||||
answer="".join(full_answer),
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency
|
||||
)
|
||||
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
else:
|
||||
# 处理 keep-alive 等其他行
|
||||
pass
|
||||
|
||||
if not line:
|
||||
continue
|
||||
|
||||
decoded_line = line.decode('utf-8')
|
||||
if not decoded_line.startswith('data: '):
|
||||
continue
|
||||
|
||||
raw_json = decoded_line[6:]
|
||||
try:
|
||||
data = json.loads(raw_json)
|
||||
except json.JSONDecodeError:
|
||||
continue
|
||||
|
||||
event = data.get('event')
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] event=%s answer_len=%s has_metadata=%s conversation_id=%s",
|
||||
event,
|
||||
len(data.get('answer', '') or ''),
|
||||
bool(data.get('metadata')),
|
||||
data.get('conversation_id') or conversation_id,
|
||||
)
|
||||
|
||||
if event == 'message':
|
||||
full_answer.append(data.get('answer', ''))
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
elif event in ('message_end', 'agent_message', 'workflow_finished'):
|
||||
if data.get('answer'):
|
||||
full_answer.append(data.get('answer', ''))
|
||||
DifyService._collect_metadata(retriever_resources, attribution_parts, data)
|
||||
|
||||
if event == 'message_end':
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] message_end: collected retriever resources=%s",
|
||||
len(retriever_resources),
|
||||
)
|
||||
# Resolve original source file URLs from external integration API.
|
||||
DifyService._enrich_retriever_resources_with_source_urls(retriever_resources)
|
||||
|
||||
metadata = data.get('metadata') or {}
|
||||
metadata['retriever_resources'] = retriever_resources
|
||||
data['metadata'] = metadata
|
||||
data['retriever_resources'] = retriever_resources
|
||||
|
||||
latency = int((time.time() - start_time) * 1000)
|
||||
usage = metadata.get('usage', {}) or {}
|
||||
|
||||
with current_app.app_context():
|
||||
DifyService._log_chat(
|
||||
user_id=user_id,
|
||||
agent_id=agent.id,
|
||||
conversation_id=data.get('conversation_id') or conversation_id,
|
||||
query=query,
|
||||
answer=''.join(full_answer),
|
||||
tokens=usage.get('total_tokens', 0),
|
||||
latency=latency,
|
||||
retriever_resources=retriever_resources,
|
||||
attribution_parts=attribution_parts,
|
||||
)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[chat-stream] message_end logged conversation_id=%s answer_len=%s resources=%s attribution=%s latency_ms=%s",
|
||||
data.get('conversation_id') or conversation_id,
|
||||
len(''.join(full_answer)),
|
||||
len(retriever_resources),
|
||||
len(attribution_parts),
|
||||
latency,
|
||||
)
|
||||
|
||||
# Pass-through SSE event (after optional enrichment).
|
||||
# SSE frame delimiter must be real newlines, not literal "\n".
|
||||
yield f"data: {json.dumps(data, ensure_ascii=False)}\n\n"
|
||||
|
||||
except requests.exceptions.RequestException as e:
|
||||
# 异常处理:返回标准错误格式给前端
|
||||
error_msg = json.dumps({"event": "error", "message": str(e)})
|
||||
if current_app:
|
||||
current_app.logger.exception("[chat-stream] request exception: %s", e)
|
||||
error_msg = json.dumps({'event': 'error', 'message': str(e)})
|
||||
yield f"data: {error_msg}\n\n"
|
||||
|
||||
@staticmethod
|
||||
def _log_chat(user_id, agent_id, conversation_id, query, answer, tokens, latency):
|
||||
def _log_chat(
|
||||
user_id,
|
||||
agent_id,
|
||||
conversation_id,
|
||||
query,
|
||||
answer,
|
||||
tokens,
|
||||
latency,
|
||||
retriever_resources=None,
|
||||
attribution_parts=None,
|
||||
):
|
||||
"""
|
||||
内部方法:写入数据库日志
|
||||
用途:将对话详情持久化到 ChatLog 表
|
||||
把最终问答和元数据写入 ChatLog
|
||||
Persist one chat record into ChatLog table.
|
||||
|
||||
Args:
|
||||
user_id, agent_id, conversation_id: Chat identity fields.
|
||||
query: User input.
|
||||
answer: Aggregated assistant answer.
|
||||
tokens: Total token usage (best effort).
|
||||
latency: End-to-end latency in milliseconds.
|
||||
retriever_resources: Source retrieval metadata list.
|
||||
attribution_parts: Attribution/annotation list.
|
||||
"""
|
||||
try:
|
||||
# 确保在应用上下文中
|
||||
chat_log = ChatLog(
|
||||
user_id=user_id,
|
||||
agent_id=agent_id,
|
||||
@@ -127,12 +215,293 @@ class DifyService:
|
||||
query=query,
|
||||
answer=answer,
|
||||
tokens_used=tokens or 0,
|
||||
latency=latency or 0
|
||||
latency=latency or 0,
|
||||
retriever_resources=retriever_resources or [],
|
||||
attribution_parts=attribution_parts or [],
|
||||
)
|
||||
db.session.add(chat_log)
|
||||
db.session.commit()
|
||||
except Exception as e:
|
||||
# Re-acquire logger from current_app as it might be detached
|
||||
if current_app:
|
||||
current_app.logger.error(f"Failed to log chat: {e}")
|
||||
current_app.logger.error(f'Failed to log chat: {e}')
|
||||
db.session.rollback()
|
||||
|
||||
@staticmethod
|
||||
def _normalize_resources(resources):
|
||||
"""
|
||||
把资源结构统一为 list
|
||||
Normalize retriever resource payload into a list.
|
||||
|
||||
Dify events may return resources as:
|
||||
- list
|
||||
- dict with `data: []`
|
||||
- empty / None
|
||||
"""
|
||||
if not resources:
|
||||
return []
|
||||
if isinstance(resources, list):
|
||||
return resources
|
||||
if isinstance(resources, dict) and isinstance(resources.get('data'), list):
|
||||
return resources.get('data')
|
||||
return []
|
||||
|
||||
@staticmethod
|
||||
def _merge_retriever_resources(target: List[Any], resources):
|
||||
"""
|
||||
合并去重检索来源
|
||||
Merge retriever resources into target list with de-duplication.
|
||||
|
||||
De-dup strategy: serialize each item as sorted JSON string.
|
||||
"""
|
||||
for item in DifyService._normalize_resources(resources):
|
||||
item_key = json.dumps(item, ensure_ascii=False, sort_keys=True, default=str)
|
||||
exists = any(
|
||||
json.dumps(existing, ensure_ascii=False, sort_keys=True, default=str) == item_key
|
||||
for existing in target
|
||||
)
|
||||
if not exists:
|
||||
target.append(item)
|
||||
|
||||
@staticmethod
|
||||
def _merge_attribution_parts(target: List[str], value):
|
||||
"""
|
||||
合并去重归属片段
|
||||
Merge attribution values into target list with de-duplication.
|
||||
|
||||
Supports string / list / dict / arbitrary values and converts them to
|
||||
stable text snippets.
|
||||
"""
|
||||
if value is None:
|
||||
return
|
||||
|
||||
def push_unique(v):
|
||||
text = (v or '').strip()
|
||||
if text and text not in target:
|
||||
target.append(text)
|
||||
|
||||
if isinstance(value, str):
|
||||
push_unique(value)
|
||||
return
|
||||
|
||||
if isinstance(value, list):
|
||||
for item in value:
|
||||
if isinstance(item, str):
|
||||
push_unique(item)
|
||||
elif isinstance(item, dict):
|
||||
push_unique(item.get('content') or item.get('text') or item.get('title') or json.dumps(item, ensure_ascii=False))
|
||||
else:
|
||||
push_unique(str(item))
|
||||
return
|
||||
|
||||
if isinstance(value, dict):
|
||||
push_unique(value.get('content') or value.get('text') or value.get('title') or json.dumps(value, ensure_ascii=False))
|
||||
return
|
||||
|
||||
push_unique(str(value))
|
||||
|
||||
@staticmethod
|
||||
def _collect_metadata(retriever_resources: List[Any], attribution_parts: List[str], event_data: dict):
|
||||
"""
|
||||
从 event 和 metadata 中收集来源与归属
|
||||
Collect metadata from one Dify SSE event and merge into accumulators.
|
||||
|
||||
Reads both top-level and nested metadata keys to improve compatibility
|
||||
with different Dify event payload shapes.
|
||||
"""
|
||||
metadata = event_data.get('metadata', {}) or {}
|
||||
|
||||
DifyService._merge_retriever_resources(retriever_resources, event_data.get('retriever_resources'))
|
||||
DifyService._merge_retriever_resources(retriever_resources, metadata.get('retriever_resources'))
|
||||
DifyService._merge_retriever_resources(retriever_resources, metadata.get('retrieverResources'))
|
||||
|
||||
DifyService._merge_attribution_parts(attribution_parts, event_data.get('annotations'))
|
||||
DifyService._merge_attribution_parts(attribution_parts, event_data.get('annotation_reply'))
|
||||
DifyService._merge_attribution_parts(attribution_parts, metadata.get('annotations'))
|
||||
DifyService._merge_attribution_parts(attribution_parts, metadata.get('annotation_reply'))
|
||||
DifyService._merge_attribution_parts(attribution_parts, event_data.get('citation'))
|
||||
DifyService._merge_attribution_parts(attribution_parts, metadata.get('citation'))
|
||||
|
||||
@staticmethod
|
||||
def _extract_dify_ids(resource: dict):
|
||||
"""
|
||||
从 resource(含嵌套 metadata)提取 dataset_id 和 remote_document_id
|
||||
Extract dataset_id and remote_document_id from a retriever resource.
|
||||
|
||||
Tries multiple key aliases from both top-level and metadata, then
|
||||
falls back to recursive deep search for robustness.
|
||||
"""
|
||||
metadata = resource.get('metadata') if isinstance(resource, dict) else None
|
||||
metadata = metadata if isinstance(metadata, dict) else {}
|
||||
|
||||
dataset_id = (
|
||||
resource.get('dataset_id')
|
||||
or resource.get('dify_dataset_id')
|
||||
or resource.get('knowledge_base_id')
|
||||
or metadata.get('dataset_id')
|
||||
or metadata.get('dify_dataset_id')
|
||||
or metadata.get('knowledge_base_id')
|
||||
or DifyService._find_first_by_keys(
|
||||
resource,
|
||||
['dataset_id', 'dify_dataset_id', 'knowledge_base_id', 'kb_id'],
|
||||
)
|
||||
)
|
||||
|
||||
remote_document_id = (
|
||||
resource.get('remote_document_id')
|
||||
or resource.get('dify_document_id')
|
||||
or resource.get('document_id')
|
||||
or resource.get('doc_id')
|
||||
or metadata.get('remote_document_id')
|
||||
or metadata.get('dify_document_id')
|
||||
or metadata.get('document_id')
|
||||
or metadata.get('doc_id')
|
||||
or DifyService._find_first_by_keys(
|
||||
resource,
|
||||
[
|
||||
'remote_document_id',
|
||||
'dify_document_id',
|
||||
'document_id',
|
||||
'doc_id',
|
||||
'source_document_id',
|
||||
],
|
||||
)
|
||||
)
|
||||
|
||||
return dataset_id, remote_document_id
|
||||
|
||||
@staticmethod
|
||||
def _find_first_by_keys(payload: Any, key_candidates: List[str]):
|
||||
"""
|
||||
递归在任意嵌套结构里按候选 key 找第一个非空值
|
||||
Recursively find the first non-empty value for any key in key_candidates.
|
||||
"""
|
||||
if isinstance(payload, dict):
|
||||
for k, v in payload.items():
|
||||
if k in key_candidates and v not in (None, ''):
|
||||
return v
|
||||
for v in payload.values():
|
||||
found = DifyService._find_first_by_keys(v, key_candidates)
|
||||
if found not in (None, ''):
|
||||
return found
|
||||
elif isinstance(payload, list):
|
||||
for item in payload:
|
||||
found = DifyService._find_first_by_keys(item, key_candidates)
|
||||
if found not in (None, ''):
|
||||
return found
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def _enrich_retriever_resources_with_source_urls(resources: List[Any]):
|
||||
"""
|
||||
批量调用集成 API,把 source_download_url 回填到每个 resource
|
||||
Batch enrich retriever resources with source_download_url and file meta.
|
||||
|
||||
Process:
|
||||
1) Extract (dataset_id, remote_document_id) pairs from resources.
|
||||
2) Batch query integration mapping service.
|
||||
3) Write resolved source URL / filename / ext / expiry back to each item.
|
||||
|
||||
Notes:
|
||||
- Resources without required IDs are skipped with warning logs.
|
||||
- Existing source_download_url is preserved.
|
||||
"""
|
||||
candidates = []
|
||||
index_to_key = {}
|
||||
|
||||
for idx, item in enumerate(resources):
|
||||
if not isinstance(item, dict):
|
||||
if current_app:
|
||||
current_app.logger.debug(
|
||||
"[source-link] resource[%s] skipped: not a dict (type=%s)",
|
||||
idx,
|
||||
type(item).__name__,
|
||||
)
|
||||
continue
|
||||
if item.get('source_download_url'):
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] resource[%s] already has source_download_url",
|
||||
idx,
|
||||
)
|
||||
continue
|
||||
|
||||
dataset_id, remote_document_id = DifyService._extract_dify_ids(item)
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] resource[%s] extracted ids: dataset_id=%r remote_document_id=%r",
|
||||
idx,
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
)
|
||||
if not dataset_id or not remote_document_id:
|
||||
if current_app:
|
||||
metadata = item.get('metadata') if isinstance(item.get('metadata'), dict) else {}
|
||||
current_app.logger.warning(
|
||||
"[source-link] resource[%s] missing ids. top-level keys=%s metadata keys=%s",
|
||||
idx,
|
||||
sorted(list(item.keys())),
|
||||
sorted(list(metadata.keys())),
|
||||
)
|
||||
continue
|
||||
|
||||
key = (str(dataset_id), str(remote_document_id))
|
||||
index_to_key[idx] = key
|
||||
candidates.append({
|
||||
"dataset_id": key[0],
|
||||
"remote_document_id": key[1],
|
||||
})
|
||||
|
||||
if not candidates:
|
||||
return
|
||||
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] batch resolving source urls: candidates=%s",
|
||||
len(candidates),
|
||||
)
|
||||
|
||||
resolved_map = IntegrationApiService.lookup_files_by_dify(candidates)
|
||||
|
||||
for idx, item in enumerate(resources):
|
||||
if idx not in index_to_key:
|
||||
continue
|
||||
dataset_id, remote_document_id = index_to_key[idx]
|
||||
payload = resolved_map.get((dataset_id, remote_document_id))
|
||||
if not payload:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[source-link] resource[%s] integration lookup empty for dataset_id=%s remote_document_id=%s",
|
||||
idx,
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
)
|
||||
continue
|
||||
|
||||
source_url = payload.get('source_download_url')
|
||||
if not source_url:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"[source-link] resource[%s] integration payload has no source_download_url "
|
||||
"(dataset_id=%s remote_document_id=%s, payload keys=%s)",
|
||||
idx,
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
sorted(list(payload.keys())) if isinstance(payload, dict) else [],
|
||||
)
|
||||
continue
|
||||
|
||||
item['source_download_url'] = source_url
|
||||
if payload.get('source_filename'):
|
||||
item['source_filename'] = payload.get('source_filename')
|
||||
if payload.get('source_ext'):
|
||||
item['source_ext'] = payload.get('source_ext')
|
||||
if payload.get('download_url_expires_at'):
|
||||
item['source_download_url_expires_at'] = payload.get('download_url_expires_at')
|
||||
if current_app:
|
||||
current_app.logger.info(
|
||||
"[source-link] resource[%s] resolved source_download_url ok "
|
||||
"(dataset_id=%s remote_document_id=%s)",
|
||||
idx,
|
||||
dataset_id,
|
||||
remote_document_id,
|
||||
)
|
||||
@@ -0,0 +1,179 @@
|
||||
"""
|
||||
Integration API client for resolving original source-file download links.
|
||||
"""
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
from flask import current_app
|
||||
|
||||
from app.config import Config
|
||||
|
||||
|
||||
class IntegrationApiService:
|
||||
_cache: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
|
||||
@staticmethod
|
||||
def _cache_key(dataset_id: str, remote_document_id: str) -> Tuple[str, str]:
|
||||
return (str(dataset_id), str(remote_document_id))
|
||||
|
||||
@staticmethod
|
||||
def _is_cache_valid(payload: Dict[str, Any]) -> bool:
|
||||
exp = payload.get("download_url_expires_at")
|
||||
if not exp:
|
||||
return True
|
||||
try:
|
||||
return datetime.fromisoformat(exp) > datetime.now().astimezone()
|
||||
except Exception:
|
||||
return True
|
||||
|
||||
@staticmethod
|
||||
def lookup_file_by_dify(dataset_id: str, remote_document_id: str) -> Optional[Dict[str, Any]]:
|
||||
if not dataset_id or not remote_document_id:
|
||||
return None
|
||||
|
||||
cache_key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
cached = IntegrationApiService._cache.get(cache_key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
return cached
|
||||
|
||||
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
|
||||
api_key = Config.INTEGRATION_API_KEY
|
||||
if not base_url or not api_key:
|
||||
return None
|
||||
|
||||
url = f"{base_url}/api/integration/dify-file"
|
||||
headers = {"X-Integration-Key": api_key}
|
||||
params = {
|
||||
"dataset_id": str(dataset_id),
|
||||
"remote_document_id": str(remote_document_id),
|
||||
}
|
||||
|
||||
try:
|
||||
resp = requests.get(url, headers=headers, params=params, timeout=(4, 8))
|
||||
if resp.status_code != 200:
|
||||
return None
|
||||
payload = resp.json()
|
||||
if not isinstance(payload, dict):
|
||||
return None
|
||||
IntegrationApiService._cache[cache_key] = payload
|
||||
return payload
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Integration API lookup failed: {e}")
|
||||
return None
|
||||
|
||||
@staticmethod
|
||||
def lookup_files_by_dify(items: List[Dict[str, str]]) -> Dict[Tuple[str, str], Dict[str, Any]]:
|
||||
"""
|
||||
Batch resolve source files by (dataset_id, remote_document_id).
|
||||
Returns a mapping keyed by (dataset_id, remote_document_id).
|
||||
"""
|
||||
results: Dict[Tuple[str, str], Dict[str, Any]] = {}
|
||||
if not items:
|
||||
return results
|
||||
|
||||
unresolved: List[Dict[str, str]] = []
|
||||
seen = set()
|
||||
|
||||
for item in items:
|
||||
dataset_id = str(item.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(item.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
|
||||
cached = IntegrationApiService._cache.get(key)
|
||||
if cached and IntegrationApiService._is_cache_valid(cached):
|
||||
results[key] = cached
|
||||
else:
|
||||
unresolved.append({
|
||||
"dataset_id": dataset_id,
|
||||
"remote_document_id": remote_document_id,
|
||||
})
|
||||
|
||||
if not unresolved:
|
||||
return results
|
||||
|
||||
base_url = (Config.INTEGRATION_API_BASE or "").rstrip("/")
|
||||
api_key = Config.INTEGRATION_API_KEY
|
||||
if not base_url or not api_key:
|
||||
return results
|
||||
|
||||
url = f"{base_url}/api/integration/dify-files/resolve"
|
||||
headers = {
|
||||
"X-Integration-Key": api_key,
|
||||
"Content-Type": "application/json",
|
||||
}
|
||||
body = {"items": unresolved}
|
||||
|
||||
try:
|
||||
resp = requests.post(url, headers=headers, json=body, timeout=(5, 12))
|
||||
if resp.status_code != 200:
|
||||
if current_app:
|
||||
current_app.logger.warning(
|
||||
"Integration API batch lookup failed: status=%s", resp.status_code
|
||||
)
|
||||
# Fallback to single lookup for reliability.
|
||||
for item in unresolved:
|
||||
payload = IntegrationApiService.lookup_file_by_dify(
|
||||
item["dataset_id"], item["remote_document_id"]
|
||||
)
|
||||
if payload:
|
||||
key = IntegrationApiService._cache_key(
|
||||
item["dataset_id"], item["remote_document_id"]
|
||||
)
|
||||
results[key] = payload
|
||||
return results
|
||||
|
||||
payload = resp.json()
|
||||
data = payload.get("data") if isinstance(payload, dict) else None
|
||||
if not isinstance(data, list):
|
||||
return results
|
||||
|
||||
for row in data:
|
||||
if not isinstance(row, dict):
|
||||
continue
|
||||
req = row.get("request") if isinstance(row.get("request"), dict) else {}
|
||||
dataset_id = str(req.get("dataset_id") or "").strip()
|
||||
remote_document_id = str(req.get("remote_document_id") or "").strip()
|
||||
if not dataset_id or not remote_document_id:
|
||||
continue
|
||||
if not row.get("found"):
|
||||
continue
|
||||
|
||||
doc = row.get("document") if isinstance(row.get("document"), dict) else {}
|
||||
source_url = doc.get("source_download_url")
|
||||
if not source_url:
|
||||
continue
|
||||
|
||||
normalized = {
|
||||
"source_download_url": source_url,
|
||||
"source_filename": doc.get("source_filename"),
|
||||
"source_ext": doc.get("source_ext"),
|
||||
"download_url_expires_at": doc.get("download_url_expires_at"),
|
||||
"version_id": doc.get("version_id"),
|
||||
"document_id": doc.get("document_id"),
|
||||
}
|
||||
key = IntegrationApiService._cache_key(dataset_id, remote_document_id)
|
||||
IntegrationApiService._cache[key] = normalized
|
||||
results[key] = normalized
|
||||
|
||||
return results
|
||||
except Exception as e:
|
||||
if current_app:
|
||||
current_app.logger.warning(f"Integration API batch lookup exception: {e}")
|
||||
# Fallback to single lookup when batch call errors.
|
||||
for item in unresolved:
|
||||
payload = IntegrationApiService.lookup_file_by_dify(
|
||||
item["dataset_id"], item["remote_document_id"]
|
||||
)
|
||||
if payload:
|
||||
key = IntegrationApiService._cache_key(
|
||||
item["dataset_id"], item["remote_document_id"]
|
||||
)
|
||||
results[key] = payload
|
||||
return results
|
||||
@@ -0,0 +1,27 @@
|
||||
"""add source metadata fields to chat_logs
|
||||
|
||||
Revision ID: d1e8a7f4c2b9
|
||||
Revises: c4e2d9f1a6bc
|
||||
Create Date: 2026-03-31 12:00:00.000000
|
||||
|
||||
"""
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
|
||||
# revision identifiers, used by Alembic.
|
||||
revision = 'd1e8a7f4c2b9'
|
||||
down_revision = 'c4e2d9f1a6bc'
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade():
|
||||
op.add_column('chat_logs', sa.Column('retriever_resources', sa.JSON(), nullable=True))
|
||||
op.add_column('chat_logs', sa.Column('attribution_parts', sa.JSON(), nullable=True))
|
||||
|
||||
|
||||
def downgrade():
|
||||
op.drop_column('chat_logs', 'attribution_parts')
|
||||
op.drop_column('chat_logs', 'retriever_resources')
|
||||
|
||||
@@ -1,4 +1,13 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* FilePreviewModal.vue
|
||||
* 文件用途:文件预览弹窗,用于在聊天页预览来源文件内容
|
||||
* 引用文件:vue, marked
|
||||
* 逻辑关系:
|
||||
* - 接收 ChatView 传入的 file(name/url)与弹窗显隐状态
|
||||
* - 根据扩展名选择预览模式(markdown/image/iframe)
|
||||
* - 对 Office 文档在可公网 HTTPS 访问时走 Office 在线预览,否则降级为打开/下载
|
||||
*/
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { marked } from 'marked';
|
||||
|
||||
@@ -20,6 +29,11 @@ const isLoading = ref(false);
|
||||
const error = ref('');
|
||||
const markdownHtml = ref('');
|
||||
|
||||
/**
|
||||
* Extract extension from URL or filename.
|
||||
* - Drops query string first (for signed URLs).
|
||||
* - Returns lowercase extension without dot.
|
||||
*/
|
||||
const getExt = (raw: string) => {
|
||||
const clean = (raw.split('?')[0] ?? '').toLowerCase();
|
||||
const i = clean.lastIndexOf('.');
|
||||
@@ -40,9 +54,50 @@ const preferredMode = computed<'markdown' | 'image' | 'iframe'>(() => {
|
||||
});
|
||||
const resolvedMode = ref<'markdown' | 'image' | 'iframe'>('iframe');
|
||||
|
||||
const isOfficeDoc = computed(() => ['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value));
|
||||
|
||||
/**
|
||||
* Decide whether Office Online Viewer can be used safely.
|
||||
* Requirements (practical):
|
||||
* - Office-like file type.
|
||||
* - HTTPS URL.
|
||||
* - Publicly reachable host (not localhost/private subnet).
|
||||
*/
|
||||
const canUseOfficeOnlineViewer = computed(() => {
|
||||
const raw = props.file?.url || '';
|
||||
if (!raw || !isOfficeDoc.value) return false;
|
||||
try {
|
||||
const u = new URL(raw, window.location.origin);
|
||||
// Office online viewer usually requires a publicly reachable HTTPS URL.
|
||||
// Private-network or local addresses typically render as blank pages.
|
||||
if (u.protocol !== 'https:') return false;
|
||||
const host = u.hostname;
|
||||
if (
|
||||
host === 'localhost' ||
|
||||
host === '127.0.0.1' ||
|
||||
host === '::1' ||
|
||||
/^10\./.test(host) ||
|
||||
/^192\.168\./.test(host) ||
|
||||
/^172\.(1[6-9]|2\d|3[0-1])\./.test(host)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
});
|
||||
|
||||
const needsOfficeFallback = computed(() => isOfficeDoc.value && !canUseOfficeOnlineViewer.value);
|
||||
|
||||
/**
|
||||
* Compute iframe source.
|
||||
* - Office docs with public HTTPS: use Office Online embed endpoint.
|
||||
* - Otherwise: fallback to raw file URL (browser/native handling).
|
||||
*/
|
||||
const iframeSrc = computed(() => {
|
||||
if (!props.file?.url) return '';
|
||||
if (['doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx'].includes(ext.value)) {
|
||||
if (isOfficeDoc.value && canUseOfficeOnlineViewer.value) {
|
||||
return `https://view.officeapps.live.com/op/embed.aspx?src=${encodeURIComponent(props.file.url)}`;
|
||||
}
|
||||
return props.file.url;
|
||||
@@ -50,6 +105,14 @@ const iframeSrc = computed(() => {
|
||||
|
||||
const close = () => emit('update:modelValue', false);
|
||||
|
||||
/**
|
||||
* Load preview content when modal/file changes.
|
||||
* Strategy:
|
||||
* 1) Reset state and choose preferred mode by extension.
|
||||
* 2) Only actively fetch for markdown/text mode.
|
||||
* 3) Auto-switch mode by response content-type (image/binary/text).
|
||||
* 4) Parse markdown to HTML on success; set error on failure.
|
||||
*/
|
||||
const loadContent = async () => {
|
||||
error.value = '';
|
||||
markdownHtml.value = '';
|
||||
@@ -87,6 +150,12 @@ const loadContent = async () => {
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Reactively reload preview when:
|
||||
* - modal visibility changes
|
||||
* - file URL changes
|
||||
* - file name changes
|
||||
*/
|
||||
watch(
|
||||
() => [props.modelValue, props.file?.url, props.file?.name],
|
||||
() => {
|
||||
@@ -121,6 +190,33 @@ watch(
|
||||
<div v-else-if="resolvedMode === 'image'" class="h-full flex items-center justify-center bg-white dark:bg-slate-900 border border-slate-200 dark:border-slate-700 rounded-lg p-2">
|
||||
<img :src="file.url" :alt="file.name" class="max-w-full max-h-full object-contain" />
|
||||
</div>
|
||||
<div
|
||||
v-else-if="needsOfficeFallback"
|
||||
class="h-full rounded-lg border border-slate-200 dark:border-slate-700 bg-white dark:bg-slate-900 p-6"
|
||||
>
|
||||
<!-- Graceful fallback for private/non-HTTPS Office links:
|
||||
show actions instead of an empty iframe. -->
|
||||
<div class="text-sm text-slate-700 dark:text-slate-200 font-semibold">Preview not available for this file URL</div>
|
||||
<div class="mt-2 text-sm text-slate-500 dark:text-slate-400">
|
||||
This Office file uses a private or non-HTTPS link, so online preview cannot render it.
|
||||
</div>
|
||||
<div class="mt-4 flex gap-3">
|
||||
<a
|
||||
:href="file.url"
|
||||
target="_blank"
|
||||
class="px-3 py-2 rounded-lg bg-brand-600 text-white text-sm hover:bg-brand-700"
|
||||
>
|
||||
Open in new tab
|
||||
</a>
|
||||
<a
|
||||
:href="file.url"
|
||||
download
|
||||
class="px-3 py-2 rounded-lg border border-slate-300 dark:border-slate-600 text-sm text-slate-700 dark:text-slate-200 hover:bg-slate-50 dark:hover:bg-slate-800"
|
||||
>
|
||||
Download file
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
<iframe
|
||||
v-else
|
||||
:src="iframeSrc"
|
||||
|
||||
+148
-105
@@ -23,6 +23,75 @@ interface ChatMessage {
|
||||
attribution_parts?: string[];
|
||||
}
|
||||
|
||||
const normalizeResources = (resources: any): RetrieverResource[] => {
|
||||
if (!resources) return [];
|
||||
if (Array.isArray(resources)) return resources;
|
||||
if (Array.isArray(resources.data)) return resources.data;
|
||||
return [];
|
||||
};
|
||||
|
||||
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
const list = normalizeResources(resources);
|
||||
if (list.length === 0) return;
|
||||
if (!msg.retriever_resources) msg.retriever_resources = [];
|
||||
for (const item of list) {
|
||||
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
|
||||
const exists = msg.retriever_resources.some(
|
||||
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
|
||||
);
|
||||
if (!exists) {
|
||||
msg.retriever_resources.push(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const addAttributionParts = (msg: ChatMessage, value: any) => {
|
||||
if (!value) return;
|
||||
if (!msg.attribution_parts) msg.attribution_parts = [];
|
||||
|
||||
const pushUnique = (text: string) => {
|
||||
const v = text.trim();
|
||||
if (!v) return;
|
||||
if (!msg.attribution_parts!.includes(v)) {
|
||||
msg.attribution_parts!.push(v);
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof value === 'string') {
|
||||
pushUnique(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
if (typeof item === 'string') {
|
||||
pushUnique(item);
|
||||
} else if (item && typeof item === 'object') {
|
||||
pushUnique(item.content || item.text || item.title || JSON.stringify(item));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
pushUnique(value.content || value.text || value.title || JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
const applyEventMetadata = (msg: ChatMessage, data: any) => {
|
||||
const metadata = data?.metadata || {};
|
||||
addRetrieverResources(msg, data?.retriever_resources);
|
||||
addRetrieverResources(msg, metadata?.retriever_resources);
|
||||
addRetrieverResources(msg, metadata?.retrieverResources);
|
||||
|
||||
addAttributionParts(msg, data?.annotations);
|
||||
addAttributionParts(msg, data?.annotation_reply);
|
||||
addAttributionParts(msg, metadata?.annotations);
|
||||
addAttributionParts(msg, metadata?.annotation_reply);
|
||||
addAttributionParts(msg, data?.citation);
|
||||
addAttributionParts(msg, metadata?.citation);
|
||||
};
|
||||
|
||||
export function useChat() {
|
||||
/**
|
||||
* messages: 响应式消息列表,用于 UI 渲染
|
||||
@@ -81,6 +150,11 @@ export function useChat() {
|
||||
* agentId: 目标 Agent ID
|
||||
*/
|
||||
const sendMessage = async (query: string, agentId: number) => {
|
||||
console.info('[chat][send] start', {
|
||||
agentId,
|
||||
queryLength: query.length,
|
||||
conversationId: conversationId.value,
|
||||
});
|
||||
// 1. 乐观 UI 更新:立即将用户消息推入列表
|
||||
messages.value.push({ role: 'user', content: query });
|
||||
// 创建一个空的 Assistant 消息用于流式追加,并记录其索引
|
||||
@@ -105,8 +179,15 @@ export function useChat() {
|
||||
})
|
||||
});
|
||||
|
||||
console.info('[chat][send] response', {
|
||||
ok: response.ok,
|
||||
status: response.status,
|
||||
contentType: response.headers.get('content-type'),
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const err = await response.json().catch(() => ({}));
|
||||
console.error('[chat][send] non-ok response', err);
|
||||
throw new Error(err.error || `Request failed with status ${response.status}`);
|
||||
}
|
||||
|
||||
@@ -116,128 +197,90 @@ export function useChat() {
|
||||
|
||||
if (!reader) throw new Error('No reader');
|
||||
|
||||
// 循环读取流数据
|
||||
// Loop read SSE stream; use a buffer to avoid dropping partial chunks.
|
||||
let buffer = '';
|
||||
while (true) {
|
||||
const { done, value } = await reader.read();
|
||||
if (done) break;
|
||||
|
||||
// 解码二进制块为文本
|
||||
const chunk = decoder.decode(value);
|
||||
// SSE 数据可能包含多行,按双换行符分割
|
||||
const lines = chunk.split('\n\n');
|
||||
|
||||
for (const line of lines) {
|
||||
if (line.startsWith('data: ')) {
|
||||
try {
|
||||
// 解析 JSON 数据
|
||||
const data = JSON.parse(line.slice(6));
|
||||
// 仅处理 message 事件,追加 answer 到当前消息
|
||||
if (data.event === 'message') {
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
if (!botMsg) continue;
|
||||
botMsg.content += data.answer;
|
||||
applyEventMetadata(botMsg, data);
|
||||
} else if (data.event === 'message_end') {
|
||||
// 记录会话 ID,便于后续发送反馈
|
||||
if (data.conversation_id) {
|
||||
conversationId.value = data.conversation_id;
|
||||
}
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
if (!botMsg) continue;
|
||||
applyEventMetadata(botMsg, data);
|
||||
} else if (data.event === 'agent_message' || data.event === 'workflow_finished') {
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
if (!botMsg) continue;
|
||||
applyEventMetadata(botMsg, data);
|
||||
} else if (data.event === 'error') {
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
if (!botMsg) continue;
|
||||
botMsg.content += `\n[Error: ${data.message}]`;
|
||||
}
|
||||
} catch (e) {
|
||||
// 忽略 JSON 解析错误 (可能是 keep-alive 或非完整 JSON)
|
||||
// Decode as stream and normalize CRLF so Windows-style SSE frames are parsed correctly.
|
||||
buffer += decoder.decode(value, { stream: true });
|
||||
buffer = buffer.replace(/\r\n/g, '\n');
|
||||
const frames = buffer.split('\n\n');
|
||||
buffer = frames.pop() || '';
|
||||
|
||||
for (const frame of frames) {
|
||||
const dataLines = frame
|
||||
.split('\n')
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l.startsWith('data:'));
|
||||
if (dataLines.length === 0) continue;
|
||||
|
||||
// SSE allows multiple data lines in one event.
|
||||
const payload = dataLines
|
||||
.map((l) => l.replace(/^data:\s?/, ''))
|
||||
.join('\n');
|
||||
if (!payload) continue;
|
||||
|
||||
try {
|
||||
const data = JSON.parse(payload);
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
if (!botMsg) continue;
|
||||
console.debug('[chat][sse] event', {
|
||||
event: data?.event,
|
||||
answerLength: typeof data?.answer === 'string' ? data.answer.length : 0,
|
||||
hasRetrieverResources: Boolean(data?.retriever_resources || data?.metadata?.retriever_resources),
|
||||
conversationId: data?.conversation_id || conversationId.value,
|
||||
});
|
||||
|
||||
if (data.event === 'message' || data.event === 'agent_message') {
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
botMsg.content += data.answer;
|
||||
console.debug('[chat][sse] append answer chunk', {
|
||||
event: data.event,
|
||||
appended: data.answer.length,
|
||||
total: botMsg.content.length,
|
||||
});
|
||||
}
|
||||
applyEventMetadata(botMsg, data);
|
||||
} else if (data.event === 'message_end' || data.event === 'workflow_finished') {
|
||||
if (data.conversation_id) {
|
||||
conversationId.value = data.conversation_id;
|
||||
}
|
||||
// Some providers may put final answer on message_end/workflow events.
|
||||
if (typeof data.answer === 'string' && data.answer.length > 0) {
|
||||
botMsg.content += data.answer;
|
||||
console.debug('[chat][sse] append final answer', {
|
||||
event: data.event,
|
||||
appended: data.answer.length,
|
||||
total: botMsg.content.length,
|
||||
});
|
||||
}
|
||||
applyEventMetadata(botMsg, data);
|
||||
} else if (data.event === 'error') {
|
||||
botMsg.content += `\n[Error: ${data.message}]`;
|
||||
console.error('[chat][sse] backend error event', data);
|
||||
}
|
||||
} catch (e) {
|
||||
// Ignore malformed or partial payload fragments.
|
||||
console.warn('[chat][sse] parse failed', { payloadPreview: payload.slice(0, 200), error: e });
|
||||
}
|
||||
}
|
||||
}
|
||||
} catch (e: any) {
|
||||
console.error(e);
|
||||
console.error('[chat][send] failed', e);
|
||||
const botMsg = messages.value[botMsgIndex];
|
||||
if (botMsg) {
|
||||
botMsg.content += `\n[Error: ${e.message || 'Network Issue'}]`;
|
||||
}
|
||||
} finally {
|
||||
isThinking.value = false;
|
||||
console.info('[chat][send] end', {
|
||||
messages: messages.value.length,
|
||||
conversationId: conversationId.value,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return { messages, isThinking, conversationId, sendMessage };
|
||||
}
|
||||
const normalizeResources = (resources: any): RetrieverResource[] => {
|
||||
if (!resources) return [];
|
||||
if (Array.isArray(resources)) return resources;
|
||||
if (Array.isArray(resources.data)) return resources.data;
|
||||
return [];
|
||||
};
|
||||
|
||||
const addRetrieverResources = (msg: ChatMessage, resources: any) => {
|
||||
const list = normalizeResources(resources);
|
||||
if (list.length === 0) return;
|
||||
if (!msg.retriever_resources) msg.retriever_resources = [];
|
||||
for (const item of list) {
|
||||
const key = `${item.document_name || ''}|${item.segment_id || ''}|${item.content || ''}`;
|
||||
const exists = msg.retriever_resources.some(
|
||||
(r) => `${r.document_name || ''}|${r.segment_id || ''}|${r.content || ''}` === key
|
||||
);
|
||||
if (!exists) {
|
||||
msg.retriever_resources.push(item);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const addAttributionParts = (msg: ChatMessage, value: any) => {
|
||||
if (!value) return;
|
||||
if (!msg.attribution_parts) msg.attribution_parts = [];
|
||||
|
||||
const pushUnique = (text: string) => {
|
||||
const v = text.trim();
|
||||
if (!v) return;
|
||||
if (!msg.attribution_parts!.includes(v)) {
|
||||
msg.attribution_parts!.push(v);
|
||||
}
|
||||
};
|
||||
|
||||
if (typeof value === 'string') {
|
||||
pushUnique(value);
|
||||
return;
|
||||
}
|
||||
|
||||
if (Array.isArray(value)) {
|
||||
for (const item of value) {
|
||||
if (typeof item === 'string') {
|
||||
pushUnique(item);
|
||||
} else if (item && typeof item === 'object') {
|
||||
pushUnique(item.content || item.text || item.title || JSON.stringify(item));
|
||||
}
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (typeof value === 'object') {
|
||||
pushUnique(value.content || value.text || value.title || JSON.stringify(value));
|
||||
}
|
||||
};
|
||||
|
||||
const applyEventMetadata = (msg: ChatMessage, data: any) => {
|
||||
const metadata = data?.metadata || {};
|
||||
addRetrieverResources(msg, data?.retriever_resources);
|
||||
addRetrieverResources(msg, metadata?.retriever_resources);
|
||||
addRetrieverResources(msg, metadata?.retrieverResources);
|
||||
|
||||
addAttributionParts(msg, data?.annotations);
|
||||
addAttributionParts(msg, data?.annotation_reply);
|
||||
addAttributionParts(msg, metadata?.annotations);
|
||||
addAttributionParts(msg, metadata?.annotation_reply);
|
||||
addAttributionParts(msg, data?.citation);
|
||||
addAttributionParts(msg, metadata?.citation);
|
||||
};
|
||||
+16
-3
@@ -33,8 +33,17 @@ const messages = {
|
||||
rememberMe: 'Remember me for 30 days',
|
||||
forgotPasswordDesc: 'Enter your email to reset your password',
|
||||
findPassword: 'Find Password',
|
||||
announcements: 'Announcements',
|
||||
passwordResetEmailSent: 'If the account exists, a reset link has been sent to your email.',
|
||||
passwordResetRequestFailed: 'Failed to request password reset',
|
||||
wecomLogin: 'Login with WeCom',
|
||||
wecomConnecting: 'Connecting to WeCom...'
|
||||
wecomConnecting: 'Connecting to WeCom...',
|
||||
wecomStartFailed: 'Failed to start WeCom login',
|
||||
wecomInvalidState: 'Invalid WeCom login state',
|
||||
wecomStateExpired: 'WeCom login session expired, please try again.',
|
||||
wecomBindRequired: 'Current WeCom account is not bound to a local user, please contact admin.',
|
||||
wecomAccountDisabled: 'Account is disabled, please contact admin.',
|
||||
wecomLoginFailed: 'WeCom login failed'
|
||||
},
|
||||
landing: {
|
||||
hero: {
|
||||
@@ -57,12 +66,16 @@ const messages = {
|
||||
failed: 'Registration failed',
|
||||
inputError: 'Please enter username and password',
|
||||
requestFailed: 'Request failed',
|
||||
emailRequired: 'Email is required',
|
||||
fields: {
|
||||
realName: 'Real Name',
|
||||
employeeId: 'Employee ID',
|
||||
phone: 'Phone Number'
|
||||
}
|
||||
},
|
||||
common: {
|
||||
errorOccurred: 'An error occurred'
|
||||
},
|
||||
workspace: {
|
||||
title: 'AI Workspace',
|
||||
userTitle: '{username}\'s AI Workspace',
|
||||
@@ -586,8 +599,8 @@ const messages = {
|
||||
landing: {
|
||||
hero: {
|
||||
prefix: '释放',
|
||||
highlight: '生成式 AI 的力量',
|
||||
subtitle: '访问为您企业量身定制的强大 AI 助手套件。安全、可扩展、智能。'
|
||||
highlight: '生成式 AI 的强大力量',
|
||||
subtitle: '获取一套专为企业需求打造的强大 AI 智能体,安全、可扩展且智能。'
|
||||
},
|
||||
agent: {
|
||||
role: 'AI 助手'
|
||||
|
||||
@@ -63,6 +63,12 @@ interface SourceFileLink {
|
||||
url: string;
|
||||
}
|
||||
|
||||
const PREFERRED_SOURCE_EXTS = new Set([
|
||||
'pdf', 'doc', 'docx', 'ppt', 'pptx', 'xls', 'xlsx', 'csv',
|
||||
'jpg', 'jpeg', 'png', 'gif', 'webp', 'svg', 'bmp',
|
||||
'txt', 'rtf', 'md', 'markdown',
|
||||
]);
|
||||
|
||||
const safeDecode = (value: string) => {
|
||||
try {
|
||||
return decodeURIComponent(value);
|
||||
@@ -92,6 +98,43 @@ const normalizeUrl = (url: string) => {
|
||||
return '';
|
||||
};
|
||||
|
||||
const getUrlExt = (url: string) => {
|
||||
const clean = (url.split('?')[0] || '').toLowerCase();
|
||||
const idx = clean.lastIndexOf('.');
|
||||
if (idx < 0) return '';
|
||||
return clean.slice(idx + 1);
|
||||
};
|
||||
|
||||
const isChunkLikeLink = (url: string) => {
|
||||
// Keep original Markdown files; only filter explicit chunk/segment-style links.
|
||||
return /segment|chunk|fragments?|split/i.test(url);
|
||||
};
|
||||
|
||||
const isPreferredSourceLink = (url: string) => {
|
||||
const ext = getUrlExt(url);
|
||||
return PREFERRED_SOURCE_EXTS.has(ext);
|
||||
};
|
||||
|
||||
const isNoisySourceUrl = (url: string) => {
|
||||
// Raw signed download links are noisy in UI (e.g. download?version_id=...&token=...).
|
||||
return /(?:^|\/)download\?/i.test(url) || /[?&](token|version_id|kind)=/i.test(url);
|
||||
};
|
||||
|
||||
const isNoisySourceName = (name: string) => {
|
||||
// Guard against names that are actually query strings instead of human-readable filenames.
|
||||
const n = (name || '').trim().toLowerCase();
|
||||
return n.startsWith('download?') || n.includes('token=') || n.includes('version_id=');
|
||||
};
|
||||
|
||||
const looksLikeFileName = (name: string) => {
|
||||
const n = (name || '').trim();
|
||||
if (!n) return false;
|
||||
// Keep Chinese/English file labels such as 员工手册.doc
|
||||
return /\.[A-Za-z0-9]{2,8}$/.test(n);
|
||||
};
|
||||
|
||||
const isMarkdownFileName = (name: string) => /\.(md|markdown)$/i.test((name || '').trim());
|
||||
|
||||
const extractUrlsFromText = (text: string) => {
|
||||
if (!text) return [];
|
||||
const urls: string[] = [];
|
||||
@@ -139,11 +182,13 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
const map = new Map<string, SourceFileLink>();
|
||||
for (const item of resources) {
|
||||
const directCandidates = [
|
||||
item?.source_download_url,
|
||||
item?.url,
|
||||
item?.file_url,
|
||||
item?.document_url,
|
||||
item?.source_url,
|
||||
item?.download_url,
|
||||
item?.metadata?.source_download_url,
|
||||
item?.metadata?.url,
|
||||
item?.metadata?.file_url,
|
||||
item?.metadata?.document_url,
|
||||
@@ -167,14 +212,21 @@ const getSourceLinks = (resources: any[] = []): SourceFileLink[] => {
|
||||
}
|
||||
|
||||
for (const url of discovered) {
|
||||
const name = item?.document_name || item?.title || decodeURIComponent(url.split('/').pop() || 'source-file');
|
||||
if (isChunkLikeLink(url)) continue;
|
||||
// If URL is noisy and we don't have an explicit filename from metadata, skip it.
|
||||
if (isNoisySourceUrl(url) && !item?.source_filename && !item?.document_name) continue;
|
||||
const name = item?.source_filename || item?.document_name || item?.title || safeDecode(url.split('/').pop() || 'source-file');
|
||||
// Skip links whose display name itself is noisy.
|
||||
if (isNoisySourceName(name)) continue;
|
||||
const key = `${name}|${url}`;
|
||||
if (!map.has(key)) {
|
||||
map.set(key, { name, url });
|
||||
}
|
||||
}
|
||||
}
|
||||
return Array.from(map.values());
|
||||
const links = Array.from(map.values());
|
||||
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
};
|
||||
|
||||
const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
@@ -182,41 +234,29 @@ const getMessageLinks = (msg: any): SourceFileLink[] => {
|
||||
|
||||
const merge = (links: SourceFileLink[]) => {
|
||||
for (const link of links) {
|
||||
if (isChunkLikeLink(link.url)) continue;
|
||||
// Keep file buttons if name is valid, even when URL is signed/temporary.
|
||||
if (isNoisySourceName(link.name)) continue;
|
||||
if (isMarkdownFileName(link.name)) {
|
||||
const key = `${link.name}|${link.url}`;
|
||||
if (!map.has(key)) map.set(key, link);
|
||||
continue;
|
||||
}
|
||||
if (isNoisySourceUrl(link.url) && !looksLikeFileName(link.name)) continue;
|
||||
const key = `${link.name}|${link.url}`;
|
||||
if (!map.has(key)) map.set(key, link);
|
||||
}
|
||||
};
|
||||
|
||||
if (msg?.retriever_resources) {
|
||||
// Only use structured retriever resources for source buttons,
|
||||
// so we don't accidentally show random URLs from answer text.
|
||||
merge(getSourceLinks(msg.retriever_resources));
|
||||
}
|
||||
|
||||
const contentLinks = extractUrlsFromText(msg?.content || '');
|
||||
for (const url of contentLinks) {
|
||||
const name = safeDecode(url.split('/').pop() || 'source-file');
|
||||
merge([{ name, url }]);
|
||||
}
|
||||
|
||||
if (Array.isArray(msg?.attribution_parts)) {
|
||||
for (const part of msg.attribution_parts) {
|
||||
const urls = extractUrlsFromText(typeof part === 'string' ? part : JSON.stringify(part));
|
||||
for (const url of urls) {
|
||||
const name = safeDecode(url.split('/').pop() || 'source-file');
|
||||
merge([{ name, url }]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// 5) 最后兜底:扫描整条 assistant 消息的 JSON 字符串。
|
||||
// 用途:覆盖 Dify 在未知嵌套字段里返回链接但未被上面路径命中的情况。
|
||||
const fullMessageText = JSON.stringify(msg || {});
|
||||
const allUrls = extractUrlsFromText(fullMessageText);
|
||||
for (const url of allUrls) {
|
||||
const name = safeDecode(url.split('/').pop() || 'source-file');
|
||||
merge([{ name, url }]);
|
||||
}
|
||||
|
||||
return Array.from(map.values());
|
||||
const links = Array.from(map.values());
|
||||
const preferred = links.filter((l) => isPreferredSourceLink(l.url));
|
||||
return preferred.length > 0 ? preferred : links;
|
||||
};
|
||||
|
||||
const filePreviewVisible = ref(false);
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* WorkspaceView.vue
|
||||
* 文件用途:用户工作台,支持自定义布局、收藏、嵌入 Agent
|
||||
* 引用文件:vue, vue-router, lucide-vue-next, 后端 /api/user 接口
|
||||
* 鏂囦欢鐢ㄩ€旓細鐢ㄦ埛宸ヤ綔鍙帮紝鏀寔鑷畾涔夊竷灞€銆佹敹钘忋€佸祵鍏?Agent
|
||||
* 寮曠敤鏂囦欢锛歷ue, vue-router, lucide-vue-next, 鍚庣 /api/user 鎺ュ彛
|
||||
*/
|
||||
import { ref, onMounted, computed, watch } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
@@ -19,6 +19,7 @@ import {
|
||||
Edit,
|
||||
ExternalLink,
|
||||
Bot,
|
||||
Lock,
|
||||
User,
|
||||
LogOut,
|
||||
Megaphone,
|
||||
@@ -120,7 +121,7 @@ const isWecomLoggingIn = ref(false);
|
||||
|
||||
const handleForgotPassword = async () => {
|
||||
if (!forgotPasswordForm.value.email) {
|
||||
alert(t('register.email') + ' is required');
|
||||
alert(t('register.emailRequired'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -133,21 +134,21 @@ const handleForgotPassword = async () => {
|
||||
|
||||
const data = await res.json();
|
||||
if (res.ok) {
|
||||
alert(t('login.passwordResetEmailSent') || 'If the account exists, a reset link has been sent to your email.');
|
||||
alert(t('login.passwordResetEmailSent'));
|
||||
showForgotPasswordModal.value = false;
|
||||
forgotPasswordForm.value = { email: '' };
|
||||
} else {
|
||||
alert(data.error || 'Failed to request password reset');
|
||||
alert(data.error || t('login.passwordResetRequestFailed'));
|
||||
}
|
||||
} catch (e) {
|
||||
console.error('Password reset error', e);
|
||||
alert('An error occurred');
|
||||
alert(t('common.errorOccurred'));
|
||||
}
|
||||
};
|
||||
|
||||
/*
|
||||
const showLoginTip = () => {
|
||||
alert(t('login.pleaseLoginFirst') || 'Please login to access this agent.');
|
||||
alert(t('login.pleaseLoginFirst'));
|
||||
};
|
||||
*/
|
||||
const userReport = ref<any>(null);
|
||||
@@ -399,11 +400,11 @@ const handleLogin = async () => {
|
||||
const err = await res.json();
|
||||
// Handle specific error messages if needed, or just alert
|
||||
let msg = err.error || t('login.failed');
|
||||
if (err.error === 'User not found') msg = t('login.userNotFound') || 'User not found';
|
||||
if (err.error === 'Incorrect password') msg = t('login.incorrectPassword') || 'Incorrect password';
|
||||
if (err.error === 'Account is disabled') msg = t('login.accountDisabled') || 'Account is disabled';
|
||||
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed') || 'Database connection failed';
|
||||
if (err.error === 'Internal server error') msg = t('login.internalError') || 'Internal server error';
|
||||
if (err.error === 'User not found') msg = t('login.userNotFound');
|
||||
if (err.error === 'Incorrect password') msg = t('login.incorrectPassword');
|
||||
if (err.error === 'Account is disabled') msg = t('login.accountDisabled');
|
||||
if (err.error === 'Database connection failed') msg = t('login.dbConnectionFailed');
|
||||
if (err.error === 'Internal server error') msg = t('login.internalError');
|
||||
|
||||
alert(msg);
|
||||
return;
|
||||
@@ -426,7 +427,7 @@ const handleLogin = async () => {
|
||||
}
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert(t('login.requestFailed') || 'Login request failed. Please check your network or server status.');
|
||||
alert(t('login.requestFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -438,7 +439,7 @@ const handleWecomLogin = async () => {
|
||||
const res = await fetch(`${api}?redirect_uri=${encodeURIComponent(redirectUri)}`);
|
||||
const data = await res.json();
|
||||
if (!res.ok || !data.url) {
|
||||
alert(data.error || 'Failed to start WeCom login');
|
||||
alert(data.error || t('login.wecomStartFailed'));
|
||||
return;
|
||||
}
|
||||
if (data.state) {
|
||||
@@ -447,7 +448,7 @@ const handleWecomLogin = async () => {
|
||||
window.location.href = data.url;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert('Failed to start WeCom login');
|
||||
alert(t('login.wecomStartFailed'));
|
||||
}
|
||||
};
|
||||
|
||||
@@ -461,7 +462,7 @@ const tryWecomCallbackLogin = async () => {
|
||||
|
||||
const expectedState = sessionStorage.getItem('hxops_wecom_state');
|
||||
if (expectedState && state && state !== expectedState) {
|
||||
alert('Invalid WeCom login state');
|
||||
alert(t('login.wecomInvalidState'));
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -476,13 +477,13 @@ const tryWecomCallbackLogin = async () => {
|
||||
const data = await res.json();
|
||||
if (!res.ok) {
|
||||
const rawError = String(data.error || '');
|
||||
let friendly = rawError || 'WeCom login failed';
|
||||
let friendly = rawError || t('login.wecomLoginFailed');
|
||||
if (rawError.includes('Invalid or expired WeCom state')) {
|
||||
friendly = '企业微信登录会话已过期,请重新点击企业微信登录';
|
||||
friendly = t('login.wecomStateExpired');
|
||||
} else if (rawError.includes('bind WeCom account') || rawError.includes('No linked account found')) {
|
||||
friendly = '当前企业微信账号未绑定本系统用户,请联系管理员在后台完成绑定';
|
||||
friendly = t('login.wecomBindRequired');
|
||||
} else if (rawError.includes('Account is disabled')) {
|
||||
friendly = '账号已被禁用,请联系管理员';
|
||||
friendly = t('login.wecomAccountDisabled');
|
||||
}
|
||||
alert(friendly);
|
||||
return true;
|
||||
@@ -495,7 +496,7 @@ const tryWecomCallbackLogin = async () => {
|
||||
return true;
|
||||
} catch (e) {
|
||||
console.error(e);
|
||||
alert('WeCom login failed');
|
||||
alert(t('login.wecomLoginFailed'));
|
||||
return true;
|
||||
} finally {
|
||||
isWecomLoggingIn.value = false;
|
||||
@@ -587,7 +588,7 @@ const toggleFavorite = async (agentId: number) => {
|
||||
// Quick Questions
|
||||
const getAgentName = (agentId: number) => {
|
||||
const agent = agents.value.find(a => a.id === agentId);
|
||||
return agent ? agent.name : t('workspace.unknownAgent', 'Unknown Agent');
|
||||
return agent ? agent.name : t('workspace.unknownAgent');
|
||||
};
|
||||
|
||||
const openAddQuestionForm = () => {
|
||||
@@ -614,7 +615,7 @@ const cancelAddQuestion = () => {
|
||||
|
||||
const saveQuickQuestion = async () => {
|
||||
if (!newQuestion.value.title || !newQuestion.value.question || !newQuestion.value.agent_id) {
|
||||
alert(t('workspace.quickQuestions.addTitle') + ' (Please fill all fields)');
|
||||
alert(t('workspace.quickQuestions.msg.fillAll'));
|
||||
return;
|
||||
}
|
||||
|
||||
@@ -737,7 +738,7 @@ onMounted(async () => {
|
||||
<button @click="showUserDropdown = !showUserDropdown" class="flex items-center gap-3 pl-3 pr-2 py-1.5 rounded-full hover:bg-slate-50 dark:hover:bg-slate-800 transition-colors border border-transparent hover:border-slate-200 dark:hover:border-slate-700">
|
||||
<div class="text-right hidden sm:block">
|
||||
<div class="text-sm font-bold text-slate-900 dark:text-slate-100 leading-tight">{{ currentUser?.username }}</div>
|
||||
<div class="text-[10px] font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{{ currentUser?.role === 'admin' ? 'Admin' : 'User' }}</div>
|
||||
<div class="text-[10px] font-medium text-slate-500 dark:text-slate-400 uppercase tracking-wide">{{ currentUser?.role }}</div>
|
||||
</div>
|
||||
<div class="w-9 h-9 bg-brand-100 rounded-full flex items-center justify-center text-brand-600 font-bold border-2 border-white shadow-sm">
|
||||
{{ (currentUser?.username || 'U').charAt(0).toUpperCase() }}
|
||||
@@ -755,7 +756,7 @@ onMounted(async () => {
|
||||
|
||||
<button @click="navigateToProfile" class="w-full text-left px-4 py-2 text-sm text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 hover:text-brand-600 flex items-center gap-2">
|
||||
<User class="w-4 h-4" />
|
||||
{{ $t('profile.title') || 'My Profile' }}
|
||||
{{ $t('profile.title') }}
|
||||
</button>
|
||||
|
||||
<button v-if="currentUser?.role === 'admin'" @click="router.push('/admin')" class="w-full text-left px-4 py-2 text-sm text-slate-700 dark:text-slate-300 hover:bg-slate-50 dark:hover:bg-slate-800 hover:text-brand-600 flex items-center gap-2">
|
||||
@@ -795,21 +796,21 @@ onMounted(async () => {
|
||||
<span class="animate-ping absolute inline-flex h-full w-full rounded-full bg-brand-400 opacity-75"></span>
|
||||
<span class="relative inline-flex rounded-full h-2 w-2 bg-brand-500"></span>
|
||||
</span>
|
||||
Enterprise AI Gateway
|
||||
{{ $t('title') }}
|
||||
</div>
|
||||
<h1 class="text-5xl font-bold text-slate-900 leading-tight">
|
||||
Unleash the Power of <br/>
|
||||
<span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-purple-600">Generative AI</span>
|
||||
{{ $t('landing.hero.prefix') }} <br/>
|
||||
<span class="text-transparent bg-clip-text bg-gradient-to-r from-brand-600 to-purple-600">{{ $t('landing.hero.highlight') }}</span>
|
||||
</h1>
|
||||
<p class="text-lg text-slate-600 max-w-md leading-relaxed">
|
||||
Access a suite of powerful AI agents tailored for your enterprise needs. Secure, scalable, and intelligent.
|
||||
{{ $t('landing.hero.subtitle') }}
|
||||
</p>
|
||||
|
||||
<!-- Announcements List -->
|
||||
<div v-if="announcements.length > 0" class="bg-white/60 dark:bg-slate-900/70 backdrop-blur-sm rounded-2xl border border-slate-100 dark:border-slate-700 p-6 shadow-sm">
|
||||
<h3 class="text-sm font-bold text-slate-900 mb-4 flex items-center gap-2">
|
||||
<Megaphone class="w-4 h-4 text-brand-600" />
|
||||
{{ $t('login.announcements') || 'Announcements' }}
|
||||
{{ $t('login.announcements') }}
|
||||
</h3>
|
||||
<div class="space-y-3">
|
||||
<div v-for="ann in announcements.slice(0, 3)" :key="ann.id"
|
||||
@@ -832,7 +833,7 @@ onMounted(async () => {
|
||||
</div>
|
||||
<div class="truncate">
|
||||
<div class="font-semibold text-slate-900 text-sm truncate">{{ agent.name }}</div>
|
||||
<div class="text-xs text-slate-500 truncate">AI Assistant</div>
|
||||
<div class="text-xs text-slate-500 truncate">{{ $t('landing.agent.role') }}</div>
|
||||
</div>
|
||||
|
||||
</div>
|
||||
@@ -864,7 +865,7 @@ onMounted(async () => {
|
||||
|
||||
<div class="flex items-center gap-2 mt-2">
|
||||
<input type="checkbox" id="rememberMe" v-model="rememberMe" class="rounded border-slate-300 text-brand-600 focus:ring-brand-500 w-4 h-4" />
|
||||
<label for="rememberMe" class="text-sm text-slate-600 cursor-pointer select-none">{{ $t('login.rememberMe') || 'Remember me for 30 days' }}</label>
|
||||
<label for="rememberMe" class="text-sm text-slate-600 cursor-pointer select-none">{{ $t('login.rememberMe') }}</label>
|
||||
</div>
|
||||
|
||||
<button @click="handleLogin" class="btn-primary w-full py-3 text-base shadow-brand-500/40 hover:shadow-brand-500/50 transform hover:-translate-y-0.5 transition-all mt-4">
|
||||
@@ -877,7 +878,7 @@ onMounted(async () => {
|
||||
:disabled="isWecomLoggingIn"
|
||||
class="btn-secondary w-full py-3 text-base mt-3 disabled:opacity-60 disabled:cursor-not-allowed"
|
||||
>
|
||||
{{ isWecomLoggingIn ? ($t('login.wecomConnecting') || 'Connecting to WeCom...') : ($t('login.wecomLogin') || 'Login with WeCom') }}
|
||||
{{ isWecomLoggingIn ? $t('login.wecomConnecting') : $t('login.wecomLogin') }}
|
||||
</button>
|
||||
|
||||
<div class="flex justify-between items-center pt-4 mt-2 border-t border-slate-100/50">
|
||||
@@ -1097,7 +1098,7 @@ onMounted(async () => {
|
||||
<Lock class="w-6 h-6" />
|
||||
</div>
|
||||
<h3 class="text-xl font-bold text-slate-900 dark:text-slate-100">{{ $t('login.forgotPassword') }}</h3>
|
||||
<p class="text-slate-500 dark:text-slate-400 text-sm mt-2">{{ $t('login.forgotPasswordDesc') || 'Enter your email to reset your password' }}</p>
|
||||
<p class="text-slate-500 dark:text-slate-400 text-sm mt-2">{{ $t('login.forgotPasswordDesc') }}</p>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
@@ -1107,7 +1108,7 @@ onMounted(async () => {
|
||||
|
||||
<div class="flex justify-end gap-3 mt-8">
|
||||
<button @click="showForgotPasswordModal = false" class="btn-secondary flex-1">{{ $t('register.cancel') }}</button>
|
||||
<button @click="handleForgotPassword" class="btn-primary flex-1">{{ $t('login.findPassword') || 'Find Password' }}</button>
|
||||
<button @click="handleForgotPassword" class="btn-primary flex-1">{{ $t('login.findPassword') }}</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
param(
|
||||
[ValidateSet("sqlite", "postgres")]
|
||||
[string]$DbMode = "sqlite",
|
||||
[string]$DatabaseUrl = "",
|
||||
[switch]$SkipInstall
|
||||
)
|
||||
|
||||
$ErrorActionPreference = "Stop"
|
||||
|
||||
function Test-CommandExists {
|
||||
param([string]$Name)
|
||||
return $null -ne (Get-Command $Name -ErrorAction SilentlyContinue)
|
||||
}
|
||||
|
||||
function Get-PythonCommand {
|
||||
$candidates = @(
|
||||
"py -3.12",
|
||||
"py -3.11",
|
||||
"py -3",
|
||||
"python"
|
||||
)
|
||||
|
||||
foreach ($candidate in $candidates) {
|
||||
try {
|
||||
$parts = $candidate.Split(" ", 2)
|
||||
$exe = $parts[0]
|
||||
$args = if ($parts.Count -gt 1) { $parts[1] } else { "" }
|
||||
|
||||
if (-not (Test-CommandExists $exe)) {
|
||||
continue
|
||||
}
|
||||
|
||||
if ([string]::IsNullOrWhiteSpace($args)) {
|
||||
& $exe --version | Out-Null
|
||||
}
|
||||
else {
|
||||
& $exe $args --version | Out-Null
|
||||
}
|
||||
return $candidate
|
||||
}
|
||||
catch {
|
||||
continue
|
||||
}
|
||||
}
|
||||
|
||||
throw "Python was not found. Please install Python 3.11+."
|
||||
}
|
||||
|
||||
function Ensure-Backend {
|
||||
param(
|
||||
[string]$BackendPath,
|
||||
[string]$PyCmd,
|
||||
[string]$Mode,
|
||||
[string]$DbUrl,
|
||||
[bool]$DoInstall
|
||||
)
|
||||
|
||||
Write-Host "[backend] preparing..." -ForegroundColor Cyan
|
||||
Set-Location $BackendPath
|
||||
|
||||
if (-not (Test-Path ".\venv\Scripts\python.exe")) {
|
||||
Write-Host "[backend] creating virtualenv..." -ForegroundColor Yellow
|
||||
if ($PyCmd -like "py *") {
|
||||
$parts = $PyCmd.Split(" ", 2)
|
||||
& $parts[0] $parts[1] -m venv venv
|
||||
}
|
||||
else {
|
||||
& $PyCmd -m venv venv
|
||||
}
|
||||
}
|
||||
|
||||
$venvPy = Join-Path $BackendPath "venv\Scripts\python.exe"
|
||||
|
||||
if ($DoInstall) {
|
||||
Write-Host "[backend] installing python dependencies..." -ForegroundColor Yellow
|
||||
& $venvPy -m pip install --upgrade pip
|
||||
& $venvPy -m pip install -r requirements.txt
|
||||
}
|
||||
|
||||
if ($Mode -eq "sqlite") {
|
||||
Write-Host "[backend] initializing sqlite data..." -ForegroundColor Yellow
|
||||
& $venvPy .\init_local_db.py
|
||||
}
|
||||
else {
|
||||
if (-not [string]::IsNullOrWhiteSpace($DbUrl)) {
|
||||
$env:DATABASE_URL = $DbUrl
|
||||
Write-Host "[backend] DATABASE_URL set from parameter." -ForegroundColor Yellow
|
||||
}
|
||||
elseif (-not $env:DATABASE_URL) {
|
||||
Write-Warning "DbMode=postgres but DATABASE_URL is not set. Using app default from backend/app/config.py."
|
||||
}
|
||||
|
||||
Write-Host "[backend] initializing postgres data..." -ForegroundColor Yellow
|
||||
& $venvPy .\init_db.py
|
||||
& $venvPy .\fix_admin.py
|
||||
}
|
||||
}
|
||||
|
||||
function Ensure-Frontend {
|
||||
param(
|
||||
[string]$FrontendPath,
|
||||
[bool]$DoInstall
|
||||
)
|
||||
|
||||
if (-not (Test-CommandExists "npm")) {
|
||||
throw "npm was not found. Please install Node.js (with npm)."
|
||||
}
|
||||
|
||||
Write-Host "[frontend] preparing..." -ForegroundColor Cyan
|
||||
Set-Location $FrontendPath
|
||||
|
||||
if ($DoInstall) {
|
||||
Write-Host "[frontend] installing npm dependencies..." -ForegroundColor Yellow
|
||||
npm install
|
||||
}
|
||||
}
|
||||
|
||||
function Start-BackendWindow {
|
||||
param(
|
||||
[string]$BackendPath,
|
||||
[string]$Mode,
|
||||
[string]$DbUrl
|
||||
)
|
||||
|
||||
$dbExport = ""
|
||||
if ($Mode -eq "postgres" -and -not [string]::IsNullOrWhiteSpace($DbUrl)) {
|
||||
$escaped = $DbUrl.Replace("'", "''")
|
||||
$dbExport = "`$env:DATABASE_URL='$escaped'; "
|
||||
}
|
||||
|
||||
$cmd = "$dbExport Set-Location '$BackendPath'; .\venv\Scripts\python.exe .\run.py"
|
||||
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
|
||||
}
|
||||
|
||||
function Start-FrontendWindow {
|
||||
param([string]$FrontendPath)
|
||||
$cmd = "Set-Location '$FrontendPath'; npm run dev"
|
||||
Start-Process powershell -ArgumentList @("-NoExit", "-ExecutionPolicy", "Bypass", "-Command", $cmd) | Out-Null
|
||||
}
|
||||
|
||||
$repoRoot = Split-Path -Parent $PSScriptRoot
|
||||
$backendDir = Join-Path $repoRoot "backend"
|
||||
$frontendDir = Join-Path $repoRoot "frontend"
|
||||
|
||||
if (-not (Test-Path $backendDir)) { throw "backend directory not found: $backendDir" }
|
||||
if (-not (Test-Path $frontendDir)) { throw "frontend directory not found: $frontendDir" }
|
||||
|
||||
$pythonCmd = Get-PythonCommand
|
||||
$doInstall = -not $SkipInstall.IsPresent
|
||||
|
||||
Write-Host "== HXOPS local startup ==" -ForegroundColor Green
|
||||
Write-Host "mode: $DbMode" -ForegroundColor Green
|
||||
|
||||
Ensure-Backend -BackendPath $backendDir -PyCmd $pythonCmd -Mode $DbMode -DbUrl $DatabaseUrl -DoInstall $doInstall
|
||||
Ensure-Frontend -FrontendPath $frontendDir -DoInstall $doInstall
|
||||
|
||||
Start-BackendWindow -BackendPath $backendDir -Mode $DbMode -DbUrl $DatabaseUrl
|
||||
Start-FrontendWindow -FrontendPath $frontendDir
|
||||
|
||||
Write-Host ""
|
||||
Write-Host "Started in two new PowerShell windows." -ForegroundColor Green
|
||||
Write-Host "Frontend URL: http://127.0.0.1:8881" -ForegroundColor Green
|
||||
Write-Host "Default local admin (sqlite/init scripts): admin / Hxit@54321" -ForegroundColor Green
|
||||
Reference in new issue
Block a user