Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-06-06 19:41:12 +08:00
commit 7eaff3c8bf
24 files changed
+1893 -341

No files matched your search

+1 -1
View File
@@ -52,4 +52,4 @@ MINIO_ACCESS_KEY=admin
MINIO_SECRET_KEY=difyai123456
MINIO_SECURE=false
# MINIO_PUBLIC_BASE_URL:导出 Markdown 中图片链接,浏览器/外部系统可访问
MINIO_PUBLIC_BASE_URL=http://192.168.100.230:9000
MINIO_PUBLIC_BASE_URL=http://ai.well-trust.com:9000
+8 -1
View File
@@ -18,10 +18,17 @@ SECRET_KEY=hxops-dify
# KB_STORAGE_ROOT=backend/data/kb
KB_TASK_EXECUTION_MODE=worker
KB_WORKER_POLL_SECONDS=2
KB_WORKER_CONCURRENCY=3
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
EDKB_SOFFICE=/usr/bin/soffice
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
EDKB_SOFFICE_TIMEOUT_SEC=600
# Windows Word COM / word_bridge 单次转换超时(秒);复杂 .doc 可适当放宽
EDKB_WORD_TIMEOUT_SEC=300
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免单条任务长期卡住整个 worker
EDKB_FILE_TIMEOUT_SEC=180
# Word 文档(.doc/.docx)单文件清洗总超时(秒);优先于 EDKB_FILE_TIMEOUT_SEC
EDKB_WORD_FILE_TIMEOUT_SEC=420
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
@@ -112,4 +119,4 @@ SRM_SQLSERVER_TIMEOUT=10
# ERP
ERP_DB_DSN=192.168.8.24:1521/topprod
TEXT2SQL_SCHEMA_PATH=
TEXT2SQL_SCHEMA_PATH=
+20 -16
View File
@@ -25,6 +25,13 @@ from app.models import Agent, ChatLog, ChatSession, Feedback
from app import db
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
chat_bp = Blueprint('chat', __name__)
LEAVE_FEATURE_AGENT_NAMES = {'通用入口', '人事规章'}
def _can_use_leave_feature(agent_proxy) -> bool:
agent_name = str(getattr(agent_proxy, 'name', None) or '').strip()
return agent_name in LEAVE_FEATURE_AGENT_NAMES
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:
@@ -1056,27 +1063,24 @@ def chat_completions():
if normalized_files and PLMOracleService.supports(query, agent_proxy):
raise ValidationError('This route does not support attachments')
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
leave_supported = HRLeaveSQLServerService.supports(query)
leave_feature_enabled = _can_use_leave_feature(agent_proxy)
if PLMOracleService.supports(query, agent_proxy):
generator = PLMOracleService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif leave_supported and leave_feature_enabled:
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
elif leave_supported:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
elif kb_type == 'ERP知识库':
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
from app.services.text2sql import Text2SQLService
if HRLeaveSQLServerService.supports(query):
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = Text2SQLService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
from app.services.hr_leave_sqlserver import HRLeaveSQLServerService
if HRLeaveSQLServerService.supports(query):
if normalized_files:
raise ValidationError('This route does not support attachments')
generator = HRLeaveSQLServerService.stream_chat(query, user_proxy, agent_proxy, external_conversation_id, session_id=session.session_id)
else:
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
generator = DifyService.stream_chat(query, user_proxy.id, agent_proxy, external_conversation_id, request_id=request_id, session_id=session.session_id, files=normalized_files)
def relay_stream():
created_event = {
+315 -45
View File
@@ -19,7 +19,6 @@ from app.models import KbDifySyncRecord, KbDocument, KbDocumentVersion, KbGroup,
from app.services.knowledge_cleaning.dify_sync_service import delete_document_from_dify
from app.services.knowledge_cleaning.queue_service import enqueue_clean_job, enqueue_kb_job
from app.services.knowledge_cleaning.settings_service import get_kb_dify_health_payload, get_kb_dify_settings, save_kb_dify_settings
from app.services.knowledge_cleaning.tasks import run_clean_job, run_sync_job
from app.errors import AppError, ValidationError, UnauthorizedError, ForbiddenError, NotFoundError, ConflictError, ServiceUnavailableError, raise_for_status
knowledge_base_bp = Blueprint('knowledge_base', __name__)
@@ -74,6 +73,18 @@ def _current_version(document: KbDocument | None) -> KbDocumentVersion | None:
return None
return next((item for item in versions if item.is_current), versions[0])
def _latest_job_for_version(version_id: int, job_type: str) -> KbJob | None:
return (
db.session.query(KbJob)
.filter(
KbJob.document_version_id == version_id,
KbJob.job_type == job_type,
)
.order_by(KbJob.created_at.desc(), KbJob.id.desc())
.first()
)
def _resolve_storage_path(path_value: str | None) -> Path | None:
if not path_value:
return None
@@ -85,14 +96,46 @@ def _resolve_storage_path(path_value: str | None) -> Path | None:
return None
return candidate
def _resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]:
def _ensure_preview_markdown(version: KbDocumentVersion) -> tuple[Path | None, str]:
primary = _resolve_storage_path(version.cleaned_file_path)
if primary and primary.exists():
return (primary, 'markdown')
preview = _resolve_storage_path(version.cleaned_preview_path)
if preview and preview.exists():
return (preview, 'preview')
return (None, 'markdown')
preview_exists = bool(preview and preview.exists())
primary_exists = bool(primary and primary.exists())
if preview_exists:
preview_content = preview.read_text(encoding='utf-8', errors='ignore')
# Some legacy versions incorrectly store cleaned_preview_path as document.md.
if preview != primary and 'data:image/' not in preview_content:
return (preview, 'preview')
source = primary if primary_exists else preview if preview_exists else None
if not source:
return (None, 'markdown')
content = source.read_text(encoding='utf-8', errors='ignore')
if 'data:image/' not in content:
if source == preview:
return (preview, 'preview')
if not version.cleaned_preview_path:
version.cleaned_preview_path = str(primary)
db.session.commit()
return (primary, 'markdown')
from edkb_system.skills.export import _LocalPreviewImageRewriter
preview = primary.parent / 'document_preview.md'
images_dir = primary.parent / 'images_view'
if images_dir.exists():
shutil.rmtree(images_dir, ignore_errors=True)
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
preview.write_text(rewriter.replace_text(content), encoding='utf-8')
version.cleaned_preview_path = str(preview)
db.session.commit()
return (preview, 'preview')
def _resolve_markdown_read_path(version: KbDocumentVersion) -> tuple[Path | None, str]:
return _ensure_preview_markdown(version)
def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
primary = _resolve_storage_path(version.cleaned_file_path)
@@ -109,6 +152,20 @@ def _resolve_markdown_write_path(version: KbDocumentVersion) -> Path | None:
def _serialize_markdown_payload(document: KbDocument, version: KbDocumentVersion, content: str, kind: str):
return {'document_id': document.id, 'title': document.title, 'version': _serialize_version(version), 'content': content, 'kind': kind}
def _markdown_unavailable_message(version: KbDocumentVersion) -> str:
status = str(getattr(version, 'status', '') or '').strip().lower()
error_message = str(getattr(version, 'error_message', '') or '').strip()
if status == 'failed':
if error_message:
return f'当前文档清洗失败,尚未生成 Markdown。失败原因:{error_message}'
return '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试'
if status == 'processing':
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试'
if status == 'uploaded':
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗'
return '当前文档尚未生成可编辑 Markdown'
@knowledge_base_bp.route('/dify/settings', methods=['GET'])
@require_admin
def get_dify_settings():
@@ -166,6 +223,26 @@ def _save_upload(file_storage, target_path: Path):
def _get_active_path_upload_job(group_id: int) -> KbJob | None:
return db.session.query(KbJob).filter(KbJob.group_id == group_id, KbJob.job_type == 'path_upload', KbJob.status.in_(('draft', 'staging', 'queued', 'running'))).order_by(KbJob.created_at.desc(), KbJob.id.desc()).first()
def _upsert_path_upload_job_files(job: KbJob, requested_files: list[dict]) -> None:
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
for requested_item in requested_files:
relative_path = str(requested_item.get('relative_path') or '').strip()
if not relative_path:
continue
existing_item = _find_path_upload_file_item(files, relative_path)
if existing_item is None:
files.append(requested_item)
continue
if not str(existing_item.get('original_name') or '').strip():
existing_item['original_name'] = requested_item.get('original_name')
_sync_path_upload_job_payload(job, files)
if job.status in ('draft', 'staging', 'queued', 'running'):
_refresh_path_upload_job_state(job)
def _sanitize_relative_path(relative_path: str | None, fallback_name: str) -> str:
raw = str(relative_path or '').replace('\\', '/').strip().lstrip('/')
normalized = normpath(raw) if raw else fallback_name
@@ -231,6 +308,51 @@ def _sync_path_upload_job_payload(job: KbJob, files: list[dict]):
job.result_json = result
return (payload, result)
def _refresh_path_upload_job_state(job: KbJob) -> None:
payload = dict(job.payload_json or {})
result = dict(job.result_json or {})
total = max(int(result.get('total') or payload.get('total_files') or 0), 0)
success = int(result.get('success') or 0)
failed = int(result.get('failed') or 0)
processed = int(result.get('processed') or (success + failed) or 0)
files = list(payload.get('files') or [])
has_pending = any(
str(item.get('status') or '').lower() in ('queued', 'uploading')
for item in files
)
payload['current_file'] = ''
job.payload_json = payload
job.progress = min(int(processed * 100 / total), 100) if total else 100
if total == 0:
job.status = 'cancelled'
job.finished_at = datetime.utcnow()
job.progress = 100
job.message = '路径上传记录为空'
job.error_message = None
return
if has_pending or processed < total:
job.status = 'staging'
job.finished_at = None
job.message = f'已上传并提交清洗 {processed}/{total} 个文件'
job.error_message = None
return
job.finished_at = datetime.utcnow()
job.progress = 100
if failed > 0:
job.status = 'failed'
job.message = f'路径上传完成,成功 {success} 条,失败 {failed} 条'
job.error_message = f'部分文件上传失败:{failed} 条'
return
job.status = 'success'
job.message = f'路径上传完成,成功 {success} 条'
job.error_message = None
def _remove_path_upload_staged_file(staged_path: str | None):
candidate = _resolve_storage_path(staged_path)
if not candidate or not candidate.exists():
@@ -377,7 +499,24 @@ def create_path_upload_job(group_id: int):
raise NotFoundError('Knowledge base group not found')
existing_job = _get_active_path_upload_job(group_id)
if existing_job:
raise ConflictError('有文件正在上传请稍等再试~', details={'job': _serialize_job(existing_job)})
data = request.get_json(silent=True) or {}
raw_files = data.get('files') or []
files = []
if isinstance(raw_files, list):
for item in raw_files:
if not isinstance(item, dict):
continue
try:
files.append(_build_path_upload_file_item(item.get('relative_path'), item.get('original_name')))
except ValueError:
continue
if files:
_upsert_path_upload_job_files(existing_job, files)
db.session.commit()
payload = _serialize_job(existing_job)
payload['reused_existing'] = True
payload['message'] = payload.get('message') or '检测到未完成的路径上传任务,已自动续传'
return jsonify(payload)
data = request.get_json(silent=True) or {}
total_files = max(int(data.get('total_files') or 0), 0)
selected_paths = data.get('selected_paths') or []
@@ -427,6 +566,11 @@ def upload_path_job_file(job_id: int):
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
entry = _find_path_upload_file_item(files, relative_path)
if entry is not None and str(entry.get('status') or '').lower() == 'success' and entry.get('document_id') and entry.get('version_id'):
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
db.session.commit()
return jsonify(_serialize_job(job))
if entry is None:
entry = _build_path_upload_file_item(relative_path, fallback_name)
files.append(entry)
@@ -434,11 +578,37 @@ def upload_path_job_file(job_id: int):
entry['staged_path'] = str(target_path)
entry['size'] = file_size
entry['sha256'] = sha256
entry['status'] = 'queued'
entry['status'] = 'uploading'
entry['error'] = None
payload, result = _sync_path_upload_job_payload(job, files)
job.message = f"已暂存 {job.payload_json.get('staged_count')}/{job.payload_json.get('total_files') or len(files)} 个文件"
job.result_json = result
entry['document_id'] = None
entry['version_id'] = None
payload['current_file'] = relative_path
job.status = 'staging'
job.started_at = job.started_at or datetime.utcnow()
payload, _result = _sync_path_upload_job_payload(job, files)
job.payload_json = payload
job.message = f'正在上传并提交清洗:{relative_path}'
try:
from app.services.knowledge_cleaning.tasks import _register_document_version_from_staged_file
document, version, _clean_job = _register_document_version_from_staged_file(
group_id=job.group_id,
relative_path=relative_path,
staged_path=target_path,
original_name=fallback_name,
user_id=getattr(current_user, 'id', None),
)
entry['status'] = 'success'
entry['document_id'] = document.id
entry['version_id'] = version.id
entry['error'] = None
except Exception as exc:
entry['status'] = 'failed'
entry['error'] = str(exc)
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
db.session.commit()
return (jsonify(_serialize_job(job)), 201)
@@ -468,12 +638,7 @@ def mark_path_job_file_failed(job_id: int):
entry['error'] = error_message
entry['original_name'] = entry.get('original_name') or original_name or Path(relative_path).name
_sync_path_upload_job_payload(job, files)
if str(job.status or '').lower() in ('draft', 'staging') and not any(str(item.get('staged_path') or '').strip() for item in files):
job.status = 'failed'
job.progress = 100
job.finished_at = datetime.utcnow()
job.message = f'路径上传完成,成功 0 条,失败 {job.result_json.get("failed", 0)} 条'
job.error_message = error_message
_refresh_path_upload_job_state(job)
db.session.commit()
return jsonify(_serialize_job(job))
@@ -483,6 +648,8 @@ def finalize_path_upload_job(job_id: int):
job = db.session.get(KbJob, job_id)
if not job or job.job_type != 'path_upload':
raise NotFoundError('路径上传任务不存在')
if job.status in ('success', 'failed', 'cancelled'):
return jsonify(_serialize_job(job))
if job.status not in ('draft', 'staging'):
raise ConflictError('当前任务不允许提交执行')
payload = dict(job.payload_json or {})
@@ -492,24 +659,24 @@ def finalize_path_upload_job(job_id: int):
staged_files = [item for item in files if str(item.get('staged_path') or '').strip()]
if not staged_files:
_sync_path_upload_job_payload(job, files)
job.status = 'failed'
job.progress = 100
job.finished_at = datetime.utcnow()
failed_count = int(job.result_json.get('failed') or 0)
job.message = f'路径上传完成,成功 0 条,失败 {failed_count} 条'
job.error_message = '当前批次没有成功暂存的文件'
_refresh_path_upload_job_state(job)
if job.status != 'failed':
job.status = 'failed'
job.message = '当前批次没有成功暂存的文件'
job.error_message = '当前批次没有成功暂存的文件'
db.session.commit()
return jsonify(_serialize_job(job))
job.status = 'queued'
job.progress = 0
job.message = '等待后台批量导入文档'
payload['finalized_at'] = datetime.utcnow().isoformat()
job.payload_json = payload
job.created_by_id = getattr(current_user, 'id', None)
_sync_path_upload_job_payload(job, files)
_refresh_path_upload_job_state(job)
db.session.commit()
enqueue_kb_job(job.id)
refreshed = db.session.get(KbJob, job.id)
return jsonify(_serialize_job(refreshed))
response_payload = _serialize_job(refreshed)
response_payload['queue_result'] = 'inline_per_file'
response_payload['accepted'] = True
return (jsonify(response_payload), 202)
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
def delete_path_job_file(job_id: int):
@@ -631,7 +798,7 @@ def get_document_markdown(document_id: int):
raise NotFoundError('当前文档暂无版本记录')
markdown_path, kind = _resolve_markdown_read_path(version)
if not markdown_path:
raise ConflictError('当前文档尚未生成可编辑 Markdown')
raise ConflictError(_markdown_unavailable_message(version))
content = markdown_path.read_text(encoding='utf-8', errors='ignore')
return jsonify(_serialize_markdown_payload(document, version, content, kind))
@@ -650,7 +817,7 @@ def update_document_markdown(document_id: int):
raise ValidationError('content is required')
markdown_path = _resolve_markdown_write_path(version)
if not markdown_path:
raise ConflictError('当前文档尚未生成可编辑 Markdown')
raise ConflictError(_markdown_unavailable_message(version))
markdown_path.parent.mkdir(parents=True, exist_ok=True)
markdown_path.write_text(content, encoding='utf-8')
version.cleaned_file_path = str(markdown_path)
@@ -692,10 +859,75 @@ def upload_document_version(document_id: int):
db.session.add(upload_job)
db.session.add(clean_job)
db.session.commit()
enqueue_clean_job(clean_job.id)
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
db.session.expire_all()
version = db.session.get(KbDocumentVersion, version.id)
return (jsonify(_serialize_version(version)), 201)
clean_job = db.session.get(KbJob, clean_job.id)
return (jsonify({
'accepted': True,
'message': '文件上传成功,清洗已排队',
'queue_result': queue_result,
'version': _serialize_version(version),
'clean_job': _serialize_job(clean_job) if clean_job else None,
}), 201)
@knowledge_base_bp.route('/documents/<int:document_id>/clean', methods=['POST'])
@require_admin
def submit_document_clean(document_id: int):
current_user = get_current_user()
document = (
db.session.query(KbDocument)
.options(joinedload(KbDocument.versions))
.filter(KbDocument.id == document_id, KbDocument.is_deleted.is_(False))
.first()
)
if not document:
raise NotFoundError('Knowledge base document not found')
version = _current_version(document)
if not version:
raise ValidationError('当前文档暂无可清洗版本')
latest_clean_job = _latest_job_for_version(version.id, 'clean')
if latest_clean_job and latest_clean_job.status in ('queued', 'running'):
payload = _serialize_job(latest_clean_job)
payload['accepted'] = True
payload['queue_result'] = 'already_queued'
payload['message'] = latest_clean_job.message or '清洗任务已在处理中'
return jsonify(payload), 202
version.status = 'uploaded'
version.error_message = None
if document.status == 'failed':
document.status = 'uploaded'
document.updated_by_id = getattr(current_user, 'id', None)
clean_job = KbJob(
job_type='clean',
status='queued',
group_id=document.group_id,
document_id=document.id,
document_version_id=version.id,
progress=0,
message='等待清洗任务执行',
payload_json={
'document_version_id': version.id,
'document_id': document.id,
'source_file_name': version.source_file_name,
'retry_mode': 'manual',
},
created_by_id=getattr(current_user, 'id', None),
)
db.session.add(clean_job)
db.session.commit()
_enqueued, queue_result = enqueue_clean_job(clean_job.id)
refreshed = db.session.get(KbJob, clean_job.id)
payload = _serialize_job(refreshed) if refreshed else {'id': clean_job.id}
payload['accepted'] = True
payload['queue_result'] = queue_result
payload['message'] = refreshed.message if refreshed else '清洗任务已提交,等待后台处理'
return jsonify(payload), 202
@knowledge_base_bp.route('/documents/<int:document_id>/sync', methods=['POST'])
@require_admin
@@ -710,13 +942,13 @@ def sync_document(document_id: int):
sync_job = KbJob(job_type='sync_dify', status='queued', group_id=document.group_id, document_id=document.id, document_version_id=version.id, progress=0, message='等待同步到 Dify', payload_json={'document_version_id': version.id, 'document_id': document.id}, created_by_id=getattr(current_user, 'id', None))
db.session.add(sync_job)
db.session.commit()
success, message = run_sync_job(sync_job.id)
_enqueued, queue_result = enqueue_kb_job(sync_job.id)
refreshed = db.session.get(KbJob, sync_job.id)
payload = _serialize_job(refreshed) if refreshed else {'id': sync_job.id}
payload['run_result'] = message
if not success:
payload['error'] = (refreshed.error_message if refreshed else None) or message
return (jsonify(payload), 200 if success else 400)
payload['accepted'] = True
payload['queue_result'] = queue_result
payload['message'] = refreshed.message if refreshed else '同步任务已提交,等待后台处理'
return (jsonify(payload), 202)
@knowledge_base_bp.route('/documents/<int:document_id>', methods=['PATCH'])
def update_document(document_id: int):
@@ -769,13 +1001,51 @@ def run_job(job_id: int):
job = db.session.get(KbJob, job_id)
if not job:
raise NotFoundError('任务不存在')
if job.job_type == 'clean':
success, message = run_clean_job(job_id)
elif job.job_type == 'sync_dify':
success, message = run_sync_job(job_id)
else:
if job.job_type not in ('clean', 'sync_dify'):
raise ValidationError('当前仅支持手动执行 clean 或 sync_dify 任务')
if job.status in ('queued', 'running'):
refreshed = db.session.get(KbJob, job_id)
payload = _serialize_job(refreshed) if refreshed else {'id': job_id}
payload['accepted'] = True
payload['queue_result'] = 'already_queued'
payload['run_result'] = '任务已在后台处理中'
return jsonify(payload), 202
version = db.session.get(KbDocumentVersion, job.document_version_id) if job.document_version_id else None
if job.job_type == 'clean':
if not version:
raise NotFoundError('关联文档版本不存在')
job.status = 'queued'
job.progress = 0
job.started_at = None
job.finished_at = None
job.error_message = None
job.message = '等待清洗任务执行'
version.status = 'uploaded'
version.error_message = None
if version.document:
version.document.status = 'uploaded'
else:
if not version:
raise NotFoundError('关联文档版本不存在')
job.status = 'queued'
job.progress = 0
job.started_at = None
job.finished_at = None
job.error_message = None
job.message = '等待同步到 Dify'
if version.status in ('failed', 'ready', 'synced'):
version.error_message = None
db.session.commit()
_enqueued, queue_result = enqueue_kb_job(job.id)
refreshed = db.session.get(KbJob, job_id)
payload = _serialize_job(refreshed) if refreshed else {'id': job_id}
payload['run_result'] = message
return (jsonify(payload), 200 if success else 400)
payload['accepted'] = True
payload['queue_result'] = queue_result
payload['run_result'] = '任务已提交后台异步执行'
return jsonify(payload), 202
+5 -2
View File
@@ -55,10 +55,13 @@ class Config:
SQLALCHEMY_TRACK_MODIFICATIONS = False
SECRET_KEY = os.getenv('SECRET_KEY')
KB_STORAGE_ROOT = os.getenv('KB_STORAGE_ROOT', str(_BACKEND_DIR / 'data' / 'kb'))
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'sync').strip().lower()
KB_TASK_EXECUTION_MODE = os.getenv('KB_TASK_EXECUTION_MODE', 'worker').strip().lower()
KB_WORKER_POLL_SECONDS = float(os.getenv('KB_WORKER_POLL_SECONDS', '2'))
KB_WORKER_CONCURRENCY = int(os.getenv('KB_WORKER_CONCURRENCY', '3') or '3')
# kb-worker 自动回收长时间 running 的任务(秒),默认 300,应大于单次清洗预期耗时
KB_JOB_RUNNING_TIMEOUT_SECONDS = float(os.getenv('KB_JOB_RUNNING_TIMEOUT_SECONDS', '300'))
# 单文件清洗总超时(秒);超时后终止当前文件处理,避免卡住整个 worker 队列
EDKB_FILE_TIMEOUT_SEC = int(os.getenv('EDKB_FILE_TIMEOUT_SEC', '0') or '0')
# 数据库连接池配置
SQLALCHEMY_ENGINE_OPTIONS = {
'pool_size': 20,
@@ -69,7 +72,7 @@ class Config:
PUBLIC_BASE_URL = os.getenv('PUBLIC_BASE_URL')
DEFAULT_ADMIN_USERNAME = os.getenv('DEFAULT_ADMIN_USERNAME')
DEFAULT_ADMIN_PASSWORD = os.getenv('DEFAULT_ADMIN_PASSWORD')
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', 'sync').strip().lower()
TASK_EXECUTION_MODE = os.getenv('TASK_EXECUTION_MODE', '').strip().lower()
# Dify 网关配置
DIFY_API_BASE = os.getenv('DIFY_API_BASE')
DIFY_API_KEY = os.getenv('DIFY_API_KEY')
+4 -1
View File
@@ -34,6 +34,9 @@ _BACKEND_DIR = Path(__file__).resolve().parents[1]
_ROOT_DIR = _BACKEND_DIR.parent
ROOT_ENV_LOCAL_PATH = _ROOT_DIR / '.env.local'
LEGACY_BACKEND_ENV_PATH = _BACKEND_DIR / '.env'
# Backward-compatible alias for tests and older callers that still patch/read
# the historical backend/.env location directly.
BACKEND_ENV_PATH = LEGACY_BACKEND_ENV_PATH
WECOM_BOOL_KEYS = {
'WECOM_ENABLED',
'WECOM_AUTO_CREATE_USER',
@@ -180,7 +183,7 @@ def _persist_to_env_file(values: dict[str, str]) -> bool:
def _load_from_env_file(prefixes: tuple[str, ...]) -> dict[str, str]:
merged: dict[str, str] = {}
for env_path in (LEGACY_BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
for env_path in (BACKEND_ENV_PATH, ROOT_ENV_LOCAL_PATH):
if not env_path.exists():
continue
try:
@@ -152,6 +152,16 @@ def _is_remote_document_missing(error_text: str) -> bool:
)
def _resolve_upload_name(version: KbDocumentVersion) -> str:
document_title = str(getattr(version.document, 'title', '') or '').strip()
if document_title:
return document_title
source_file_name = str(version.source_file_name or '').strip()
if source_file_name:
return source_file_name
return f'文档-{version.document_id}'
def sync_document_version_to_dify(document_version_id: int, synced_by_id: int | None = None) -> dict:
version = db.session.get(KbDocumentVersion, document_version_id)
if not version or not version.document or not version.document.group:
@@ -177,7 +187,7 @@ def sync_document_version_to_dify(document_version_id: int, synced_by_id: int |
remote_document_id = None
remote_document_name = None
upload_name = version.source_file_name or document.title
upload_name = _resolve_upload_name(version)
if existing_record and existing_record.dataset_id == dataset_id and existing_record.sync_hash == sync_hash:
try:
payload = service.get_document(
@@ -4,6 +4,7 @@ backend/app/services/knowledge_cleaning/edkb_adapter.py
"""
from __future__ import annotations
import os
import shutil
import tempfile
from pathlib import Path
@@ -12,6 +13,27 @@ from pathlib import Path
TEXT_EXTS = {'.txt', '.md'}
def _temporary_env(**overrides: str):
saved: dict[str, str | None] = {}
class _EnvGuard:
def __enter__(self):
for key, value in overrides.items():
saved[key] = os.environ.get(key)
os.environ[key] = value
return self
def __exit__(self, exc_type, exc, tb):
for key, old_value in saved.items():
if old_value is None:
os.environ.pop(key, None)
else:
os.environ[key] = old_value
return False
return _EnvGuard()
def _find_generated_markdown(output_root: Path) -> Path:
# Look for md files directly inside output_root or inside any of its subdirectories
# Note that edkb_system puts output inside a directory matching the parent dir name, which might be tmp_dir
@@ -22,6 +44,28 @@ def _find_generated_markdown(output_root: Path) -> Path:
return candidates[0]
def _find_generated_preview_markdown(output_root: Path) -> Path | None:
candidates = [path for path in output_root.rglob('03_clean_view.md') if path.is_file()]
if not candidates:
return None
candidates.sort(key=lambda item: len(item.parts))
return candidates[0]
def _rewrite_preview_markdown_if_needed(preview_path: Path, target_dir: Path) -> None:
content = preview_path.read_text(encoding='utf-8', errors='ignore')
if 'data:image/' not in content:
return
from edkb_system.skills.export import _LocalPreviewImageRewriter
images_dir = target_dir / 'images_view'
if images_dir.exists():
shutil.rmtree(images_dir)
rewriter = _LocalPreviewImageRewriter(images_dir=images_dir)
preview_path.write_text(rewriter.replace_text(content), encoding='utf-8')
def _write_text_result(source_path: Path, target_dir: Path) -> dict:
target_dir.mkdir(parents=True, exist_ok=True)
cleaned_path = target_dir / 'document.md'
@@ -70,19 +114,37 @@ def build_clean_result(source_path: Path, target_dir: Path) -> dict:
shutil.copy2(source_path, tmp_source_path)
config = SystemConfig.load(None)
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
# Align with the xx system: do not spend clean-time uploading images to MinIO.
# Keep embedded-image fallback so Markdown can still be produced locally.
with _temporary_env(
MINIO_UPLOAD_ENABLED='false',
MINIO_ALLOW_EMBED_FALLBACK='true',
):
result = build_knowledge(tmp_source_path, output_dir, config, cache_dir)
failures = [item for item in result if item.get('status') == 'failed']
if failures:
raise RuntimeError(failures[0].get('error') or 'edkb_system failed.')
markdown_source = _find_generated_markdown(output_dir)
preview_source = _find_generated_preview_markdown(output_dir)
cleaned_path = target_dir / 'document.md'
shutil.copy2(markdown_source, cleaned_path)
preview_path = cleaned_path
if preview_source and preview_source.exists():
preview_path = target_dir / 'document_preview.md'
shutil.copy2(preview_source, preview_path)
preview_images_dir = preview_source.parent / 'images_view'
target_preview_images_dir = target_dir / 'images_view'
if target_preview_images_dir.exists():
shutil.rmtree(target_preview_images_dir)
if preview_images_dir.exists():
shutil.copytree(preview_images_dir, target_preview_images_dir)
_rewrite_preview_markdown_if_needed(preview_path, target_dir)
content = cleaned_path.read_text(encoding='utf-8', errors='ignore')
return {
'mode': 'edkb_system',
'cleaned_file_path': str(cleaned_path),
'cleaned_preview_path': str(cleaned_path),
'cleaned_preview_path': str(preview_path),
'word_count': len(content.split()),
}
@@ -12,11 +12,38 @@ import logging
from datetime import datetime, timedelta
from flask import current_app
from sqlalchemy.exc import OperationalError
from app import db
from app.models import KbDocumentVersion, KbJob
logger = logging.getLogger('kb-worker')
_WORD_EXTENSIONS = {'doc', 'docx'}
def _normalize_source_ext(value: str | None) -> str:
return str(value or '').strip().lower().lstrip('.')
def _is_word_clean_job(job: KbJob | None) -> bool:
if not job or job.job_type != 'clean' or not job.document_version:
return False
return _normalize_source_ext(job.document_version.source_file_ext) in _WORD_EXTENSIONS
def _has_running_word_clean_job() -> bool:
running_jobs = (
db.session.query(KbJob)
.join(KbDocumentVersion, KbDocumentVersion.id == KbJob.document_version_id)
.filter(
KbJob.job_type == 'clean',
KbJob.status == 'running',
KbDocumentVersion.source_file_ext.isnot(None),
)
.order_by(KbJob.started_at.asc(), KbJob.id.asc())
.all()
)
return any(_is_word_clean_job(job) for job in running_jobs)
def recover_stale_running_jobs() -> tuple[int, str]:
@@ -79,8 +106,8 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
- manual: 保留 queued,等待管理台手动执行。
"""
mode = str(
current_app.config.get('TASK_EXECUTION_MODE')
or current_app.config.get('KB_TASK_EXECUTION_MODE', 'sync')
current_app.config.get('KB_TASK_EXECUTION_MODE')
or current_app.config.get('TASK_EXECUTION_MODE', 'worker')
).strip().lower()
job = db.session.get(KbJob, job_id)
@@ -88,12 +115,14 @@ def enqueue_kb_job(job_id: int) -> tuple[bool, str]:
return False, 'job_not_found'
if mode == 'sync':
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_job
if job.job_type == 'clean':
return run_clean_job(job_id)
if job.job_type == 'path_upload':
return run_path_upload_job(job_id)
if job.job_type == 'sync_dify':
return run_sync_job(job_id)
return False, f'unsupported_sync_job:{job.job_type}'
if mode in ('worker', 'rq'):
@@ -106,23 +135,67 @@ def enqueue_clean_job(job_id: int) -> tuple[bool, str]:
return enqueue_kb_job(job_id)
def claim_next_kb_job() -> KbJob | None:
"""
原子领取下一条 queued 任务,避免并发 worker 重复消费同一条记录。
当前运行在 PostgreSQL,可安全使用 FOR UPDATE SKIP LOCKED。
"""
now = datetime.utcnow()
try:
has_running_word_job = _has_running_word_clean_job()
candidates = (
db.session.query(KbJob)
.filter(KbJob.job_type.in_(('path_upload', 'clean', 'sync_dify')), KbJob.status == 'queued')
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.with_for_update(skip_locked=True)
.limit(20)
.all()
)
except OperationalError:
db.session.rollback()
logger.exception('failed to claim next kb job')
return None
job = next(
(
item for item in candidates
if not (has_running_word_job and _is_word_clean_job(item))
),
None,
)
if not job:
db.session.rollback()
return None
job.status = 'running'
job.started_at = job.started_at or now
job.progress = max(int(job.progress or 0), 1)
if job.job_type == 'clean':
job.message = 'worker 已领取 Word 串行清洗任务' if _is_word_clean_job(job) else 'worker 已领取清洗任务'
elif job.job_type == 'sync_dify':
job.message = 'worker 已领取同步任务'
else:
job.message = 'worker 已领取路径上传任务'
db.session.commit()
return job
def process_next_kb_job() -> tuple[bool, str]:
# 先回收历史卡死的 running 任务,再领取下一条 queued 任务
recover_stale_running_jobs()
job = (
db.session.query(KbJob)
.filter(KbJob.job_type.in_(('path_upload', 'clean')), KbJob.status == 'queued')
.order_by(KbJob.created_at.asc(), KbJob.id.asc())
.first()
)
job = claim_next_kb_job()
if not job:
return False, 'no_job'
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job
from app.services.knowledge_cleaning.tasks import run_clean_job, run_path_upload_job, run_sync_job
if job.job_type == 'path_upload':
return run_path_upload_job(job.id)
if job.job_type == 'sync_dify':
return run_sync_job(job.id)
return run_clean_job(job.id)
@@ -85,12 +85,91 @@ def _safe_storage_filename(filename: str) -> str:
return f'{safe_stem}{suffix}'
def _safe_display_filename(filename: str) -> str:
candidate = Path(filename or '').name.strip()
if not candidate:
return 'uploaded_file'
invalid_chars = '\\/:*?"<>|'
sanitized = ''.join('_' if ch in invalid_chars else ch for ch in candidate).strip()
return sanitized or 'uploaded_file'
def _kb_storage_root() -> Path:
root = Path(current_app.config.get('KB_STORAGE_ROOT')).resolve()
root.mkdir(parents=True, exist_ok=True)
return root
def _resolve_path_upload_display_name(relative_path: str, original_name: str) -> str:
relative_name = Path(str(relative_path or '').replace('\\', '/')).name.strip()
if relative_name:
return relative_name
original_leaf = Path(original_name or '').name.strip()
if original_leaf:
return original_leaf
return 'uploaded_file'
def _resolve_clean_display_filename(version: KbDocumentVersion, source_path: Path) -> str:
document_title = _safe_display_filename(str(getattr(version.document, 'title', '') or ''))
if document_title:
title_path = Path(document_title)
if title_path.suffix:
return document_title
normalized_source_name = _normalized_source_filename(version, source_path)
source_suffix = Path(normalized_source_name).suffix
return f'{document_title}{source_suffix}' if source_suffix else document_title
return _safe_display_filename(_normalized_source_filename(version, source_path))
def _normalize_markdown_title_candidate(value: str) -> str:
text = str(value or '').strip()
if not text:
return ''
if text.startswith('#'):
text = text.lstrip('#').strip()
return text
def _rewrite_markdown_title(cleaned_file_path: str | None, *, preferred_title: str, fallback_source_name: str) -> None:
if not cleaned_file_path:
return
cleaned_path = Path(cleaned_file_path)
if cleaned_path.suffix.lower() != '.md' or not cleaned_path.exists():
return
preferred_stem = Path(preferred_title or '').stem.strip()
if not preferred_stem:
return
fallback_candidates = {
Path(fallback_source_name or '').stem.strip(),
Path(cleaned_path.stem or '').stem.strip(),
}
fallback_candidates = {item for item in fallback_candidates if item}
if not fallback_candidates:
return
lines = cleaned_path.read_text(encoding='utf-8', errors='ignore').splitlines()
for index, raw_line in enumerate(lines):
stripped_line = raw_line.strip()
if not stripped_line:
continue
normalized_line = _normalize_markdown_title_candidate(stripped_line)
if normalized_line not in fallback_candidates or normalized_line == preferred_stem:
return
if stripped_line.startswith('#'):
prefix = raw_line[: len(raw_line) - len(raw_line.lstrip())]
heading_prefix = raw_line[len(prefix):].split(normalized_line, 1)[0]
lines[index] = f'{prefix}{heading_prefix}{preferred_stem}'
else:
prefix = raw_line[: len(raw_line) - len(raw_line.lstrip())]
lines[index] = f'{prefix}{preferred_stem}'
cleaned_path.write_text('\n'.join(lines) + ('\n' if lines else ''), encoding='utf-8')
return
return
def _get_or_create_document(*, group_id: int, title: str, description: str | None, user_id: int | None) -> KbDocument:
document = (
db.session.query(KbDocument)
@@ -145,7 +224,7 @@ def _register_document_version_from_staged_file(
original_name: str,
user_id: int | None,
) -> tuple[KbDocument, KbDocumentVersion, KbJob]:
display_name = Path(original_name or relative_path).name or Path(relative_path).name or 'uploaded_file'
display_name = _resolve_path_upload_display_name(relative_path, original_name)
if _find_existing_active_document(group_id=group_id, title=display_name):
raise FileExistsError('上传失败,文件已存在')
document = _get_or_create_document(
@@ -155,11 +234,12 @@ def _register_document_version_from_staged_file(
user_id=user_id,
)
version_no = _next_version_no(document)
source_file_name = _safe_storage_filename(original_name)
source_file_name = display_name
stored_file_name = _safe_display_filename(display_name)
ext = Path(source_file_name).suffix.lower().lstrip('.') or None
version_dir = _kb_storage_root() / f'group_{group_id:04d}' / f'document_{document.id:06d}' / f'v{version_no:03d}'
version_dir.mkdir(parents=True, exist_ok=True)
target_path = version_dir / source_file_name
target_path = version_dir / stored_file_name
shutil.copy2(staged_path, target_path)
sha256, file_size = _hash_file(target_path)
@@ -375,13 +455,18 @@ def run_clean_job(job_id: int) -> tuple[bool, str]:
warnings = []
try:
normalized_name = _normalized_source_filename(version, source_path)
normalized_name = _resolve_clean_display_filename(version, source_path)
staged_source = target_dir / normalized_name
if staged_source != source_path:
shutil.copy2(source_path, staged_source)
source_path = staged_source
result = build_clean_result(source_path, target_dir)
_rewrite_markdown_title(
result.get('cleaned_file_path'),
preferred_title=str(getattr(version.document, 'title', '') or ''),
fallback_source_name=str(version.source_file_name or source_path.name),
)
job_message = '真实清洗结果已生成'
except Exception as exc:
# soffice 超时等不可恢复错误:直接失败,避免回退占位结果掩盖问题
+57 -9
View File
@@ -212,12 +212,33 @@ def _derive_output_rel_md(file_path: Path, input_path: Path) -> Path:
return rel.with_suffix(".md")
def _strip_in_memory_images(blocks: list) -> list:
out = []
for b in blocks:
meta = dict(getattr(b, "meta", {}) or {})
if "image" in meta:
meta.pop("image", None)
b = type(b)(
id=b.id,
page=b.page,
type=b.type,
text=b.text,
bbox=b.bbox,
meta=meta,
)
out.append(b)
return out
def _normalize_path_for_match(p: Path | str) -> str:
return str(p).replace("\\", "/")
def _file_timeout_sec() -> int | None:
raw = str(os.environ.get("EDKB_FILE_TIMEOUT_SEC", "0")).strip()
_WORD_TIMEOUT_EXTS = {".doc", ".docx"}
def _parse_timeout_env(name: str, default: str = "0") -> int | None:
raw = str(os.environ.get(name, default)).strip()
try:
value = int(raw)
except ValueError:
@@ -225,6 +246,15 @@ def _file_timeout_sec() -> int | None:
return value if value > 0 else None
def _file_timeout_sec(file_path: Path | None = None) -> int | None:
suffix = str(getattr(file_path, "suffix", "") or "").lower()
if suffix in _WORD_TIMEOUT_EXTS:
specific = _parse_timeout_env("EDKB_WORD_FILE_TIMEOUT_SEC")
if specific:
return specific
return _parse_timeout_env("EDKB_FILE_TIMEOUT_SEC")
def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
if input_path.is_file():
candidates = [input_path]
@@ -246,6 +276,28 @@ def _cleanup_input_temp_files(input_path: Path) -> list[Path]:
return removed
def _should_run_ocr(profile, cfg, blocks: list, context: Context | None = None) -> bool:
if not blocks or not cfg.ocr.enable:
return False
if profile.file_type in {"ppt", "pptx"}:
return False
pipeline_requests_ocr = "edkb-ocr" in profile.recommended_pipeline
has_image_blocks = any(b.type == "image" for b in blocks)
# Word documents often contain decorative or embedded images. If intake
# did not explicitly request OCR, do not force a slow OCR pass just because
# image blocks exist.
if profile.file_type in {"doc", "docx"} and not pipeline_requests_ocr:
return False
if profile.file_type == "pdf" and not pipeline_requests_ocr:
extras = getattr(context, "extras", {}) or {}
return bool(extras.get("scan_likely") or extras.get("pdf_page_image_mode_pages"))
return pipeline_requests_ocr or has_image_blocks
def _matches_pattern(candidates: list[str], patterns: list[str]) -> str | None:
if not patterns:
return None
@@ -311,7 +363,7 @@ def _run_one_with_timeout(
final_md_path: Path | None = None,
progress_label: str | None = None,
) -> dict:
timeout = _file_timeout_sec()
timeout = _file_timeout_sec(file_path)
if not timeout:
return _run_one(
file_path,
@@ -536,18 +588,14 @@ def _run_one(
if blocks:
ctx.images = sum(1 for b in blocks if b.type == "image")
should_ocr = cfg.ocr.enable and (
"edkb-ocr" in profile.recommended_pipeline
or any(b.type == "image" for b in blocks)
)
if profile.file_type in {"ppt", "pptx"}:
should_ocr = False
should_ocr = _should_run_ocr(profile, cfg, blocks, ctx)
if should_ocr:
_announce("ocr")
t0 = time.perf_counter()
blocks = ocr.run(blocks, ctx, min_confidence=cfg.ocr.min_confidence)
_mark("edkb-ocr", t0)
trace_steps.append("edkb-ocr")
blocks = _strip_in_memory_images(blocks)
doc_kind = (ctx.extras.get("intake") or {}).get("doc_kind")
policy_text = doc_kind == "policy_text"
+12 -6
View File
@@ -206,7 +206,17 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
lines.append(f"## {txt}")
elif b.type == "image":
data_uri = b.meta.get("data_uri") if b.meta else None
if data_uri:
is_pdf_page_image = bool(
b.meta
and b.meta.get("page_image")
and b.meta.get("page_image_source") == "pdf"
)
if is_pdf_page_image:
lines.append(f"![page-image-{b.page}]")
ocr_text = ocr_by_image.get(b.id)
if ocr_text:
lines.append(f"图中文字:{ocr_text}")
elif data_uri:
image_idx += 1
if b.meta and b.meta.get("page_image"):
lines.append(f"![page-image-{b.page}]({data_uri})")
@@ -220,11 +230,7 @@ def blocks_to_plain_markdown(blocks: list[Block]) -> str:
page_body_chars.get(b.page, 0) >= 15
or page_text_chars.get(b.page, 0) >= 40
)
if (
b.meta
and b.meta.get("page_image")
and b.meta.get("page_image_source") != "pptx"
):
if b.meta and b.meta.get("page_image"):
lines.extend(_page_image_structured_lines(ocr_text))
if not suppress_pptx_ocr:
lines.append(f"图中文字:{ocr_text}")
+65
View File
@@ -472,6 +472,67 @@ class _RemoteImageRewriter:
)
class _LocalPreviewImageRewriter:
def __init__(self, *, images_dir: Path) -> None:
self.images_dir = images_dir
self.uri_cache: dict[str, str] = {}
self.sha_cache: dict[str, str] = {}
self._next_image_index = 1
def _store_embedded_uri(self, uri: str, fmt: str, b64_raw: str) -> str:
cached = self.uri_cache.get(uri)
if cached is not None:
return cached
b64_clean = re.sub(r"\s+", "", b64_raw or "")
try:
blob = base64.b64decode(b64_clean, validate=False)
except Exception:
self.uri_cache[uri] = ""
return ""
if not _is_valid_image_blob(blob):
self.uri_cache[uri] = ""
return ""
sha = hashlib.sha256(blob).hexdigest()
cached_sha = self.sha_cache.get(sha)
if cached_sha is not None:
self.uri_cache[uri] = cached_sha
return cached_sha
ext = _normalize_ext(fmt, blob)
file_name = f"img_{self._next_image_index:03d}_{sha[:8]}.{ext}"
self._next_image_index += 1
self.images_dir.mkdir(parents=True, exist_ok=True)
image_path = self.images_dir / file_name
image_path.write_bytes(blob)
rel_path = f"{self.images_dir.name}/{file_name}"
self.sha_cache[sha] = rel_path
self.uri_cache[uri] = rel_path
return rel_path
def replace_text(self, text: str) -> str:
if not text or "data:image/" not in text:
return text
def repl(m: re.Match[str]) -> str:
alt = m.group("alt") or "image"
rel_path = self._store_embedded_uri(
m.group("uri"),
m.group("fmt") or "png",
m.group("b64") or "",
)
if not rel_path:
return f"![{alt}]"
return f"![{alt}]({rel_path})"
out = _EMBEDDED_IMG_RE.sub(repl, text)
if "data:image/" in out:
out = _EMBEDDED_IMG_ANY_RE.sub("![image]", out)
return out
def run(input_data: dict, context: Context) -> dict:
out_dir = Path(input_data["out_dir"])
out_dir.mkdir(parents=True, exist_ok=True)
@@ -518,8 +579,12 @@ def run(input_data: dict, context: Context) -> dict:
exported_chunks = [replace(c, text=rewriter.replace_text(c.text)) for c in chunks]
rewriter.finalize()
preview_rewriter = _LocalPreviewImageRewriter(images_dir=view_images_dir)
preview_md = preview_rewriter.replace_text(clean_md)
_write(out_dir / "03_clean.md", clean_md)
_write(flat_clean_path, clean_md)
_write(view_clean_path, preview_md)
lines = [json.dumps(asdict(c), ensure_ascii=False) for c in exported_chunks]
_write(out_dir / "04_chunks.jsonl", "\n".join(lines) + ("\n" if lines else ""))
+95 -37
View File
@@ -17,6 +17,9 @@ from edkb_system.contracts import Block, Context
from edkb_system.skills.soffice_util import convert_with_soffice, soffice_candidates
from edkb_system.skills.word_bridge import convert_with_word
_IMAGE_URI_CACHE: dict[tuple[str, str], str] = {}
_IMAGE_URI_CACHE_MAX = 512
def _to_data_uri(blob: bytes, content_type: str | None = None) -> str:
ct = content_type or "image/png"
@@ -25,18 +28,64 @@ def _to_data_uri(blob: bytes, content_type: str | None = None) -> str:
def _to_preferred_image_data_uri(blob: bytes, content_type: str | None = None) -> str:
ct = str(content_type or "image/png").strip().lower() or "image/png"
cache_key = (hashlib.sha1(blob).hexdigest(), ct)
cached = _IMAGE_URI_CACHE.get(cache_key)
if cached:
return cached
if ct in {"image/jpeg", "image/jpg"}:
uri = _to_data_uri(blob, "image/jpeg")
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
_IMAGE_URI_CACHE.clear()
_IMAGE_URI_CACHE[cache_key] = uri
return uri
try:
from PIL import Image
with Image.open(io.BytesIO(blob)) as im:
rgb = Image.new("RGB", im.size, (255, 255, 255))
rgba = im.convert("RGBA")
rgb.paste(rgba, mask=rgba.split()[3])
out = io.BytesIO()
rgb.save(out, format="JPEG", quality=90)
return _to_data_uri(out.getvalue(), "image/jpeg")
if im.mode in {"RGB", "L"} and ct in {"image/png", "image/bmp"}:
uri = _to_data_uri(blob, ct)
else:
rgb = Image.new("RGB", im.size, (255, 255, 255))
rgba = im.convert("RGBA")
rgb.paste(rgba, mask=rgba.split()[3])
out = io.BytesIO()
rgb.save(out, format="JPEG", quality=90)
uri = _to_data_uri(out.getvalue(), "image/jpeg")
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
_IMAGE_URI_CACHE.clear()
_IMAGE_URI_CACHE[cache_key] = uri
return uri
except Exception:
return _to_data_uri(blob, content_type)
uri = _to_data_uri(blob, content_type)
if len(_IMAGE_URI_CACHE) >= _IMAGE_URI_CACHE_MAX:
_IMAGE_URI_CACHE.clear()
_IMAGE_URI_CACHE[cache_key] = uri
return uri
def _build_image_uri_map(doc) -> dict[str, str]:
image_uri_by_rid: dict[str, str] = {}
rel_items = list(doc.part.rels.items())
rel_items.sort(
key=lambda kv: int((kv[0] or "rId0").replace("rId", "") or 0)
if (kv[0] or "").startswith("rId")
else 0
)
for rid, rel in rel_items:
reltype = getattr(rel, "reltype", "") or ""
if "image" not in reltype:
continue
try:
part = rel.target_part
blob = part.blob
content_type = getattr(part, "content_type", None)
image_uri_by_rid[str(rid)] = _to_preferred_image_data_uri(blob, content_type)
except Exception:
continue
return image_uri_by_rid
def _image_dimensions(blob: bytes, ext: str) -> tuple[int, int]:
@@ -209,14 +258,24 @@ def _split_tall_image(blob: bytes, ext: str) -> list[bytes]:
return [blob]
def _extract_image_uris_from_paragraph(para, doc) -> list[str]:
def _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid: dict[str, str] | None = None
) -> list[str]:
uris: list[str] = []
seen_rids: set[str] = set()
try:
rids = para._element.xpath(".//a:blip/@r:embed")
except Exception:
return uris
for rid in rids:
rid = str(rid)
if rid in seen_rids:
continue
seen_rids.add(rid)
try:
if image_uri_by_rid and rid in image_uri_by_rid:
uris.append(image_uri_by_rid[rid])
continue
part = doc.part.related_parts[rid]
blob = part.blob
content_type = getattr(part, "content_type", None)
@@ -226,42 +285,34 @@ def _extract_image_uris_from_paragraph(para, doc) -> list[str]:
return uris
def _extract_all_image_uris_from_doc(doc) -> list[str]:
def _extract_all_image_uris_from_doc(
doc, image_uri_by_rid: dict[str, str] | None = None
) -> list[str]:
if image_uri_by_rid:
return list(dict.fromkeys(image_uri_by_rid.values()))
uris: list[str] = []
seen: set[str] = set()
rel_items = list(doc.part.rels.items())
rel_items.sort(
key=lambda kv: int((kv[0] or "rId0").replace("rId", "") or 0)
if (kv[0] or "").startswith("rId")
else 0
)
for _, rel in rel_items:
reltype = getattr(rel, "reltype", "") or ""
if "image" not in reltype:
continue
try:
part = rel.target_part
blob = part.blob
content_type = getattr(part, "content_type", None)
uri = _to_preferred_image_data_uri(blob, content_type)
key = hashlib.sha1(blob).hexdigest()
if key in seen:
continue
seen.add(key)
uris.append(uri)
except Exception:
for uri in _build_image_uri_map(doc).values():
if uri in seen:
continue
seen.add(uri)
uris.append(uri)
return uris
def _extract_image_uris_from_table(table, doc) -> list[str]:
def _extract_image_uris_from_table(
table, doc, image_uri_by_rid: dict[str, str] | None = None
) -> list[str]:
uris: list[str] = []
seen: set[str] = set()
try:
for row in table.rows:
for cell in row.cells:
for para in cell.paragraphs:
for uri in _extract_image_uris_from_paragraph(para, doc):
for uri in _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid
):
if uri in seen:
continue
seen.add(uri)
@@ -1298,7 +1349,9 @@ def _extract_missing_634_badge_table_from_word_html(
]
def _table_to_markdown(table, doc) -> str:
def _table_to_markdown(
table, doc, image_uri_by_rid: dict[str, str] | None = None
) -> str:
rows: list[list[str]] = []
seen_img_uri: set[str] = set()
for r in table.rows:
@@ -1308,7 +1361,9 @@ def _table_to_markdown(table, doc) -> str:
img_uris: list[str] = []
try:
for para in c.paragraphs:
for uri in _extract_image_uris_from_paragraph(para, doc):
for uri in _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid
):
if uri in seen_img_uri:
continue
seen_img_uri.add(uri)
@@ -1664,6 +1719,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
parsed: list[Block] = []
doc = Document(str(docx_path))
image_uri_by_rid = _build_image_uri_map(doc)
num_to_abs, levels = _load_numbering_schema(docx_path)
list_states: dict[str, dict[int, int]] = {}
context.pages = 1
@@ -1706,7 +1762,9 @@ def run(input_data: dict, context: Context) -> list[Block]:
if marker and text and not text.startswith(marker):
text = f"{marker} {text}"
image_uris = _extract_image_uris_from_paragraph(para, doc)
image_uris = _extract_image_uris_from_paragraph(
para, doc, image_uri_by_rid
)
if text:
idx += 1
typ = (
@@ -1738,7 +1796,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
)
elif isinstance(child, CT_Tbl):
table = Table(child, doc)
md = _table_to_markdown(table, doc)
md = _table_to_markdown(table, doc, image_uri_by_rid)
if md:
if _looks_like_form_metadata_table(md):
blocks = _form_table_to_blocks(table, idx)
@@ -1760,7 +1818,7 @@ def run(input_data: dict, context: Context) -> list[Block]:
# 表格内图片已并入表格 markdown 单元格,避免脱离原始位置。
if not any(b.type == "image" for b in parsed):
for uri in _extract_all_image_uris_from_doc(doc):
for uri in _extract_all_image_uris_from_doc(doc, image_uri_by_rid):
idx += 1
context.images += 1
parsed.append(
+88 -29
View File
@@ -6,6 +6,9 @@ from pathlib import Path
from edkb_system.contracts import Block, Context
_PAGE_IMAGE_RENDER_SCALE = 0.75
_PAGE_IMAGE_JPEG_QUALITY = 82
def _is_scanned(text_chars: int, pages: int) -> bool:
return text_chars < int(300 * max(pages, 1) / 10)
@@ -76,32 +79,58 @@ def _should_use_page_image_mode(
return False
def _collect_image_boxes(
file_path: Path, page_count: int
def _analysis_candidate_pages(
page_payloads: list[dict], scan_likely: bool
) -> list[int]:
if scan_likely:
return [int(payload["page"]) for payload in page_payloads]
return [
int(payload["page"])
for payload in page_payloads
if len(str(payload.get("text") or "")) <= 120
]
def _collect_image_boxes_from_doc(
doc, page_numbers: list[int]
) -> dict[int, list[tuple[float, float, float, float]]]:
try:
import pypdfium2 as pdfium
import pypdfium2.raw as pdfium_c
except Exception:
return {}
out: dict[int, list[tuple[float, float, float, float]]] = {}
for page_number in page_numbers:
try:
page = doc[page_number - 1]
except Exception:
continue
boxes: list[tuple[float, float, float, float]] = []
try:
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
try:
bounds = obj.get_bounds()
except Exception:
bounds = obj.get_pos()
boxes.append(tuple(float(v) for v in bounds))
except Exception:
boxes = []
out[page_number] = boxes
return out
def _collect_image_boxes(
file_path: Path, page_numbers: list[int]
) -> dict[int, list[tuple[float, float, float, float]]]:
try:
import pypdfium2 as pdfium
except Exception:
return {}
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
for page_idx in range(page_count):
page = doc[page_idx]
boxes: list[tuple[float, float, float, float]] = []
try:
for obj in page.get_objects(filter=[pdfium_c.FPDF_PAGEOBJ_IMAGE]):
try:
bounds = obj.get_bounds()
except Exception:
bounds = obj.get_pos()
boxes.append(tuple(float(v) for v in bounds))
except Exception:
boxes = []
out[page_idx + 1] = boxes
return _collect_image_boxes_from_doc(doc, page_numbers)
except Exception:
return {}
finally:
@@ -110,12 +139,25 @@ def _collect_image_boxes(
doc.close()
except Exception:
pass
return out
def _render_page_image_from_doc(
doc, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
) -> object | None:
try:
import numpy as np
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil().convert("RGB")
return np.asarray(pil_image)
except Exception:
return None
def _render_page_png(
file_path: Path, page_number: int, scale: float = 2.0
) -> bytes | None:
file_path: Path, page_number: int, scale: float = _PAGE_IMAGE_RENDER_SCALE
) -> object | None:
try:
import pypdfium2 as pdfium
except Exception:
@@ -124,12 +166,7 @@ def _render_page_png(
doc = None
try:
doc = pdfium.PdfDocument(str(file_path))
page = doc[page_number - 1]
bitmap = page.render(scale=scale)
pil_image = bitmap.to_pil()
buf = io.BytesIO()
pil_image.save(buf, format="PNG")
return buf.getvalue()
return _render_page_image_from_doc(doc, page_number, scale=scale)
except Exception:
return None
finally:
@@ -170,7 +207,19 @@ def run(input_data: dict, context: Context) -> list[Block]:
page_payloads.append({"page": page_idx, "text": text, "images": images})
scan_likely = _is_scanned(text_chars, context.pages)
image_boxes_by_page = _collect_image_boxes(file_path, context.pages)
candidate_pages = _analysis_candidate_pages(page_payloads, scan_likely)
image_boxes_by_page: dict[int, list[tuple[float, float, float, float]]] = {}
pdfium_doc = None
if candidate_pages:
try:
import pypdfium2 as pdfium
pdfium_doc = pdfium.PdfDocument(str(file_path))
image_boxes_by_page = _collect_image_boxes_from_doc(
pdfium_doc, candidate_pages
)
except Exception:
image_boxes_by_page = _collect_image_boxes(file_path, candidate_pages)
page_image_mode_pages: list[int] = []
for payload in page_payloads:
@@ -199,8 +248,12 @@ def run(input_data: dict, context: Context) -> list[Block]:
)
if use_page_image_mode:
rendered = _render_page_png(file_path, page_idx)
if rendered:
rendered = (
_render_page_image_from_doc(pdfium_doc, page_idx)
if pdfium_doc is not None
else _render_page_png(file_path, page_idx)
)
if rendered is not None:
blocks.append(
Block(
id=f"pdf-page-{page_idx}",
@@ -209,8 +262,9 @@ def run(input_data: dict, context: Context) -> list[Block]:
text="",
bbox=(0.0, 0.0, 1000.0, 1000.0),
meta={
"data_uri": _to_data_uri(rendered, "image/png"),
"page_image": True,
"page_image_source": "pdf",
"image": rendered,
},
)
)
@@ -244,6 +298,11 @@ def run(input_data: dict, context: Context) -> list[Block]:
"pdf page-image mode pages: "
+ ", ".join(str(x) for x in page_image_mode_pages)
)
try:
if pdfium_doc is not None:
pdfium_doc.close()
except Exception:
pass
except Exception as exc:
context.warnings.append(f"PDF parse failed: {exc}")
+57 -3
View File
@@ -6,6 +6,9 @@ import re
from edkb_system.contracts import Block, Context
_RAPID_OCR_ENGINE = None
_PDF_PAGE_IMAGE_MAX_EDGE = 1800
def _decode_data_uri_image(data_uri: str):
m = re.match(r"^data:image/[^;]+;base64,(.+)$", data_uri or "", re.DOTALL)
@@ -26,17 +29,66 @@ def _decode_data_uri_image(data_uri: str):
return None
def _get_ocr_engine():
global _RAPID_OCR_ENGINE
if _RAPID_OCR_ENGINE is not None:
return _RAPID_OCR_ENGINE
from rapidocr_onnxruntime import RapidOCR # type: ignore
_RAPID_OCR_ENGINE = RapidOCR()
return _RAPID_OCR_ENGINE
def _prepare_image_for_ocr(image_obj, block: Block):
meta = getattr(block, "meta", {}) or {}
if not (
meta.get("page_image")
and str(meta.get("page_image_source") or "").lower() == "pdf"
):
return image_obj
try:
import numpy as np
from PIL import Image
if not hasattr(image_obj, "shape") or len(image_obj.shape) < 2:
return image_obj
height = int(image_obj.shape[0])
width = int(image_obj.shape[1])
max_edge = max(width, height)
if max_edge <= _PDF_PAGE_IMAGE_MAX_EDGE:
return image_obj
scale = _PDF_PAGE_IMAGE_MAX_EDGE / float(max_edge)
target_size = (
max(1, int(round(width * scale))),
max(1, int(round(height * scale))),
)
pil_image = Image.fromarray(np.asarray(image_obj, dtype=np.uint8))
resized = pil_image.resize(target_size, Image.Resampling.LANCZOS)
return np.asarray(resized)
except Exception:
return image_obj
def _ocr_call_kwargs(block: Block) -> dict:
meta = getattr(block, "meta", {}) or {}
if meta.get("page_image") and str(meta.get("page_image_source") or "").lower() == "pdf":
return {"use_det": True, "use_cls": False, "use_rec": True}
return {}
def run(
input_data: list[Block], context: Context, min_confidence: float = 0.3
) -> list[Block]:
blocks = input_data
try:
from rapidocr_onnxruntime import RapidOCR # type: ignore
engine = _get_ocr_engine()
except Exception:
context.warnings.append("RapidOCR unavailable; skip OCR")
return blocks
engine = RapidOCR()
out: list[Block] = []
for b in blocks:
out.append(b)
@@ -46,6 +98,8 @@ def run(
image_obj = b.meta.get("image")
if image_obj is None and b.meta and b.meta.get("data_uri"):
image_obj = _decode_data_uri_image(str(b.meta.get("data_uri")))
if image_obj is not None:
image_obj = _prepare_image_for_ocr(image_obj, b)
if image_obj is None:
out.append(
Block(
@@ -59,7 +113,7 @@ def run(
continue
try:
result, _ = engine(image_obj)
result, _ = engine(image_obj, **_ocr_call_kwargs(b))
lines = []
for it in result or []:
if len(it) < 3:
+36 -5
View File
@@ -5,6 +5,7 @@ backend/worker_kb.py
from __future__ import annotations
import logging
import multiprocessing as mp
import os
import sys
import time
@@ -16,12 +17,12 @@ _LOG_FORMAT = '%(asctime)s %(levelname)s [kb-worker] %(message)s'
_LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
def _configure_logging() -> logging.Logger:
logger = logging.getLogger('kb-worker')
def _configure_logging(worker_label: str = 'main') -> logging.Logger:
logger = logging.getLogger(f'kb-worker.{worker_label}')
if logger.handlers:
return logger
handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(logging.Formatter(_LOG_FORMAT, datefmt=_LOG_DATEFMT))
handler.setFormatter(logging.Formatter(f'{_LOG_FORMAT} [worker={worker_label}]', datefmt=_LOG_DATEFMT))
logger.addHandler(handler)
logger.setLevel(logging.INFO)
logger.propagate = False
@@ -58,8 +59,9 @@ def _resolve_config_name() -> str:
return mapping.get(env_name, 'production')
def main():
log = _configure_logging()
def _worker_loop(worker_index: int):
worker_label = str(worker_index)
log = _configure_logging(worker_label)
app = create_app(_resolve_config_name())
poll_seconds = float(app.config.get('KB_WORKER_POLL_SECONDS', 2))
@@ -73,5 +75,34 @@ def main():
log.info('processed job: %s', message)
def main():
bootstrap_app = create_app(_resolve_config_name())
concurrency = max(int(bootstrap_app.config.get('KB_WORKER_CONCURRENCY', 1) or 1), 1)
if concurrency == 1:
_worker_loop(1)
return
log = _configure_logging('master')
log.info('starting %s worker processes', concurrency)
workers: list[mp.Process] = []
for index in range(concurrency):
proc = mp.Process(target=_worker_loop, args=(index + 1,), name=f'kb-worker-{index + 1}')
proc.start()
workers.append(proc)
try:
for proc in workers:
proc.join()
except KeyboardInterrupt:
log.info('stopping worker pool')
for proc in workers:
if proc.is_alive():
proc.terminate()
for proc in workers:
proc.join(timeout=5)
if __name__ == '__main__':
mp.freeze_support()
main()
+103
View File
@@ -775,3 +775,106 @@ const update = () => { isMobile.value = window.innerHeight > window.innerWidth;
### 17.4 关键设计决策
- **大文件处理**:文件存储至独立的 MinIO 服务,配置 Public Read 策略或预签名 URL,前端直接访问,减轻 FastAPI 服务带宽压力。
- **预览方案**:复用现有依赖 `@vue-office/pdf` 进行 PDF 渲染,保持项目轻量化。
---
## 18. 知识库异步化改造技术方案
### 18.1 背景
当前知识库上传链路虽然已经具备 `KbJob` 任务模型,但运行模式默认仍偏向 `sync`,导致路径上传提交、单文件清洗、Dify 同步等重操作仍可能在 Web 请求内直接执行。文件数量较多或外部依赖较慢时,容易出现接口阻塞、页面卡顿、批量上传超时等问题。
### 18.2 当前问题
- 路径上传 `finalize` 阶段可能在一次请求中串行执行整批导入与清洗
- 单文件上传完成后会立即触发清洗,容易拉长上传接口耗时
- 同步 Dify 直接在接口中调用外部 API,网络波动会直接影响页面响应
- Web 进程承担了过多 CPU / IO 密集型任务,不利于稳定性和扩展性
### 18.3 改造目标
- 重操作统一改为后台 worker 异步执行
- 前端接口改为“提交任务后立即返回”,通过 job 状态轮询展示进度
- Web 进程职责收敛为“接收请求、创建任务、返回状态”
- 尽量复用现有 `KbJob`、轮询、失败重试等能力,采用增量改造方式落地
### 18.4 优先改造接口
#### P0
- `POST /api/kb/path-upload-jobs/<id>/finalize`
- 当前最重的阻塞点
- 建议改为仅校验并提交 `path_upload` 任务,返回 `202 Accepted`
- `POST /api/kb/documents/<id>/sync`
- 当前会同步调用 Dify 接口
- 建议改为仅创建 `sync_dify` 任务,返回 `202 Accepted`
#### P1
- `POST /api/kb/documents/<id>/upload`
- 文件接收保持同步
- 上传完成后只排队 `clean` 任务,不等待清洗完成
#### 暂不优先
- `POST /api/kb/path-upload-jobs/<id>/files`
- 该接口核心是接收文件字节并落盘
- 后续更适合做并发上传、分片上传或对象存储直传,不作为本轮异步化重点
### 18.5 关键实现方案
#### 运行模式
- 生产环境将 `KB_TASK_EXECUTION_MODE` 从 `sync` 切换为 `worker`
- 确保 `worker_kb.py` 常驻运行
- 保留 `manual` 模式用于排障和运维
#### Worker 能力补齐
- 现有 worker 已支持 `path_upload` / `clean`
- 需要补充 `sync_dify` 类型任务消费能力
- 统一任务状态流转:`queued -> running -> succeeded / failed`
#### 接口语义调整
- `upload`:表示“文件上传成功,清洗已排队”
- `finalize`:表示“批量上传任务已提交,后台处理中”
- `sync`:表示“同步任务已提交,后台处理中”
#### 前端交互调整
- 前端不再等待重任务执行完成
- 提交成功后展示“处理中”或“已排队”
- 统一通过 jobs / document 状态轮询刷新页面
- 批量同步改为并发提交 job,再统一刷新状态
### 18.6 推荐实施顺序
#### 第一步
- 将 `KB_TASK_EXECUTION_MODE` 切换为 `worker`
- 确认 `hxops-kb-worker` 常驻运行正常
#### 第二步
- 扩展 worker 对 `sync_dify` 的消费能力
- 将 `POST /api/kb/documents/<id>/sync` 改为真正异步
#### 第三步
- 将 `POST /api/kb/path-upload-jobs/<id>/finalize` 改为真正异步
- 保证批量导入只排队、不在请求内执行
#### 第四步
- 调整 `POST /api/kb/documents/<id>/upload` 返回语义
- 前端统一收口为基于 job 的状态展示
### 18.7 预期收益
- 批量上传提交耗时从“整批处理耗时”降低为“任务提交耗时”
- Dify 波动不再直接阻塞页面操作
- Web 进程压力下降,系统稳定性提升
- 失败任务可重试,进度展示更清晰
- 整体知识库链路更适合后续扩展为高并发、多批次处理模式
+35 -7
View File
@@ -81,6 +81,19 @@ export interface KbJob {
finished_at?: string | null;
}
export interface KbQueuedJobResponse extends KbJob {
accepted?: boolean;
queue_result?: string;
}
export interface KbUploadVersionResponse {
accepted?: boolean;
message?: string;
queue_result?: string;
version: KbDocumentVersionItem;
clean_job?: KbJob | null;
}
export interface KbDifySettings {
DIFY_API_BASE: string;
DIFY_API_KEY: string;
@@ -339,16 +352,16 @@ export const updateKbDocumentMarkdown = async (
export const uploadKbDocumentVersion = async (
documentId: number,
file: File
): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; status?: number }> => {
): Promise<{ ok: boolean; error?: string; version?: KbDocumentVersionItem; clean_job?: KbJob | null; message?: string; status?: number }> => {
try {
const formData = new FormData();
formData.append('file', file);
const version = await requestJson<KbDocumentVersionItem>(`/api/kb/documents/${documentId}/upload`, {
const payload = await requestJson<KbUploadVersionResponse>(`/api/kb/documents/${documentId}/upload`, {
method: 'POST',
...auth(),
body: formData,
});
return { ok: true, version };
return { ok: true, version: payload.version, clean_job: payload.clean_job, message: payload.message };
} catch (e) {
const err = e as BusinessError;
if (err.status === 413) {
@@ -362,6 +375,21 @@ export const uploadKbDocumentVersion = async (
}
};
export const submitKbDocumentClean = async (
documentId: number
): Promise<{ ok: boolean; error?: string; job?: KbJob | null; message?: string; status?: number }> => {
try {
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/documents/${documentId}/clean`, {
method: 'POST',
...auth(),
});
return { ok: true, job, message: job.message || undefined };
} catch (e) {
const err = e as BusinessError;
return { ok: false, error: kbErrorMessage(e, '提交清洗任务失败'), status: err.status };
}
};
export const createKbPathUploadJob = async (
groupId: number,
payload: {
@@ -431,7 +459,7 @@ export const finalizeKbPathUploadJob = async (
jobId: number | string,
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
try {
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
method: 'POST',
...auth(),
});
@@ -476,13 +504,13 @@ export const deleteKbPathJobFile = async (
export const syncKbDocumentToDify = async (
documentId: number
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
): Promise<{ ok: boolean; error?: string; job?: KbQueuedJobResponse }> => {
try {
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/documents/${documentId}/sync`, {
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/documents/${documentId}/sync`, {
method: 'POST',
...auth(),
});
return { ok: true, job, run_result: job.run_result };
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
}
@@ -37,6 +37,8 @@ const {
resetForm,
selectAgent,
submitAgent,
addSuggestedQuestion,
removeSuggestedQuestion,
deleteAgent,
openTestModal,
runAgentTest,
@@ -133,6 +135,66 @@ onMounted(() => {
:placeholder="t('admin.agent.fields.descPlaceholder')"
/>
</div>
<div class="col-span-1 md:col-span-2 space-y-3">
<div class="flex items-center justify-between gap-3">
<label class="text-xs font-bold text-muted uppercase tracking-wider">常见问题</label>
<button
type="button"
class="inline-flex items-center gap-1 rounded-lg border border-default px-3 py-1.5 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft"
@click="addSuggestedQuestion"
>
<Plus class="h-4 w-4" />
添加问题
</button>
</div>
<div class="flex items-center gap-3 text-sm">
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="plain" class="accent-brand-600" />
<span>无样式</span>
</label>
<label class="inline-flex items-center gap-2 text-secondary">
<input v-model="form.suggested_questions_style" type="radio" value="styled" class="accent-brand-600" />
<span>有样式</span>
</label>
</div>
<div v-if="form.suggested_questions.length === 0" class="rounded-xl border border-dashed border-default px-4 py-5 text-sm text-muted">
暂未配置常见问题,点击“添加问题”后会同步到对应 Agent 的 Chat 欢迎页。
</div>
<div v-else class="space-y-3">
<div
v-for="(item, index) in form.suggested_questions"
:key="index"
class="rounded-2xl border border-default bg-surface-soft/50 p-4"
>
<div class="grid grid-cols-1 gap-3 md:grid-cols-[1fr_220px_auto]">
<input
v-model="item.question"
type="text"
class="w-full input-field"
placeholder="请输入常见问题,例如:查询我有多少假期?"
/>
<input
v-model="item.group"
type="text"
class="w-full input-field"
:disabled="form.suggested_questions_style !== 'styled'"
:placeholder="form.suggested_questions_style === 'styled' ? '可选:分组标题,例如:考勤与休假' : '无样式下无需分组'"
/>
<button
type="button"
class="inline-flex items-center justify-center rounded-xl border border-red-200 bg-red-50 px-3 py-2 text-red-600 transition-colors hover:bg-red-100"
@click="removeSuggestedQuestion(index)"
>
<Trash2 class="h-4 w-4" />
</button>
</div>
</div>
</div>
</div>
</div>
<div class="flex justify-end">
<button type="button" class="btn-primary btn-lg" @click="submitAgent">
@@ -18,9 +18,25 @@ import {
} from '@/api/admin';
import { useMessage } from '@/composables/useMessage';
import type { AdminUserRow } from '@/features/admin/types/admin.types';
import type { AgentFormState, AgentRow, AgentTestResult } from '@/features/admin/types/agent.types';
import type { AgentFormState, AgentRow, AgentSuggestedQuestionItem, AgentTestResult } from '@/features/admin/types/agent.types';
import { createEmptyAgentForm } from '@/features/admin/types/agent.types';
const normalizeSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (typeof item === 'string') {
return { question: item.trim(), group: '' };
}
if (!item || typeof item !== 'object') return null;
const question = String((item as Record<string, unknown>).question || (item as Record<string, unknown>).text || '').trim();
const group = String((item as Record<string, unknown>).group || '').trim();
if (!question) return null;
return { question, group };
})
.filter((item): item is AgentSuggestedQuestionItem => !!item);
};
export function useAgentsAdmin() {
const { t } = useI18n();
const msg = useMessage();
@@ -90,6 +106,8 @@ export function useAgentsAdmin() {
dify_app_type: agent.extra_config?.dify_app_type === 'workflow' ? 'workflow' : 'chatflow',
api_base_url: agent.api_base_url || '',
iframe_url: String(agent.extra_config?.iframe_url || ''),
suggested_questions_style: agent.extra_config?.suggested_questions_style === 'styled' ? 'styled' : 'plain',
suggested_questions: normalizeSuggestedQuestions(agent.extra_config?.suggested_questions),
is_active: agent.is_active,
};
isEditing.value = true;
@@ -132,6 +150,13 @@ export function useAgentsAdmin() {
if (form.value.type === 'api') {
extra_config.dify_app_type = form.value.dify_app_type === 'workflow' ? 'workflow' : 'chatflow';
}
extra_config.suggested_questions_style = form.value.suggested_questions_style === 'styled' ? 'styled' : 'plain';
extra_config.suggested_questions = form.value.suggested_questions
.map((item) => ({
question: String(item.question || '').trim(),
group: String(item.group || '').trim(),
}))
.filter((item) => item.question);
try {
const editingId = isEditing.value ? Number(form.value.id) : null;
@@ -149,6 +174,7 @@ export function useAgentsAdmin() {
payload.dify_api_key = form.value.dify_api_key;
}
await updateAdminAgent(form.value.id, payload);
msg.success('应用更新成功');
} else {
await createAdminAgent({
name: form.value.name,
@@ -159,6 +185,7 @@ export function useAgentsAdmin() {
api_base_url: form.value.api_base_url,
extra_config,
});
msg.success('应用创建成功');
}
await loadAgents();
@@ -176,6 +203,14 @@ export function useAgentsAdmin() {
}
};
const addSuggestedQuestion = (): void => {
form.value.suggested_questions.push({ question: '', group: '' });
};
const removeSuggestedQuestion = (index: number): void => {
form.value.suggested_questions.splice(index, 1);
};
const deleteAgent = async (id: number): Promise<void> => {
openDeleteConfirm(t('admin.agent.confirmDelete'), async () => {
try {
@@ -293,6 +328,8 @@ export function useAgentsAdmin() {
resetForm,
selectAgent,
submitAgent,
addSuggestedQuestion,
removeSuggestedQuestion,
deleteAgent,
openTestModal,
runAgentTest,
@@ -19,6 +19,11 @@ export interface AgentRow {
iframe_url?: string;
}
export interface AgentSuggestedQuestionItem {
question: string;
group: string;
}
export interface AgentTestResult {
success: boolean;
request_url: string;
@@ -38,6 +43,8 @@ export interface AgentFormState {
dify_app_type: 'chatflow' | 'workflow';
api_base_url: string;
iframe_url: string;
suggested_questions_style: 'plain' | 'styled';
suggested_questions: AgentSuggestedQuestionItem[];
is_active: boolean;
}
@@ -50,5 +57,7 @@ export const createEmptyAgentForm = (): AgentFormState => ({
dify_app_type: 'chatflow',
api_base_url: '',
iframe_url: '',
suggested_questions_style: 'plain',
suggested_questions: [],
is_active: true,
});
+139 -47
View File
@@ -702,6 +702,94 @@ watch(isThinking, (thinking) => {
const currentAgent = ref<any>(null);
const userAgents = ref<Array<{ id: number; name: string; description: string; icon_url?: string; dify_app_type?: 'chatflow' | 'workflow' }>>([]);
const showGeneralFeedbackDialog = ref(false);
const LEAVE_FEATURE_AGENT_NAMES = new Set(['通用入口', '人事规章']);
const canUseLeaveFeature = computed(() => LEAVE_FEATURE_AGENT_NAMES.has(String(currentAgent.value?.name || '').trim()));
type AgentSuggestedQuestionItem = {
question: string;
group: string;
};
const DEFAULT_AGENT_DESCRIPTIONS: Record<string, string> = {
人事规章: '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。',
通用入口: '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。',
};
const DEFAULT_AGENT_SUGGESTED_QUESTIONS: Record<string, { style: 'plain' | 'styled'; questions: AgentSuggestedQuestionItem[] }> = {
人事规章: {
style: 'styled',
questions: [
{ question: '查询我有多少假期?', group: '考勤与休假' },
{ question: '如何进行请假?', group: '考勤与休假' },
{ question: '查公司法定节假日?', group: '考勤与休假' },
{ question: '新员工入职须知', group: '规章与日常' },
{ question: '怎么开具在职证明?', group: '规章与日常' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '规章与日常' },
],
},
通用入口: {
style: 'plain',
questions: [
{ question: '新员工入职须知', group: '' },
{ question: '查询我有多少假期?', group: '' },
{ question: '如何进行请假?', group: '' },
{ question: '查公司法定节假日?', group: '' },
{ question: '查公司薪酬及福利待遇怎么样?', group: '' },
],
},
};
const normalizeAgentSuggestedQuestions = (value: unknown): AgentSuggestedQuestionItem[] => {
if (!Array.isArray(value)) return [];
return value
.map((item) => {
if (typeof item === 'string') {
const question = item.trim();
return question ? { question, group: '' } : null;
}
if (!item || typeof item !== 'object') return null;
const record = item as Record<string, unknown>;
const question = String(record.question || record.text || '').trim();
const group = String(record.group || '').trim();
return question ? { question, group } : null;
})
.filter((item): item is AgentSuggestedQuestionItem => !!item);
};
const currentAgentName = computed(() => String(currentAgent.value?.name || '').trim());
const agentDescription = computed(() => {
const text = String(currentAgent.value?.description || '').trim();
return text || DEFAULT_AGENT_DESCRIPTIONS[currentAgentName.value] || '';
});
const suggestedQuestionsStyle = computed<'plain' | 'styled'>(() => {
const style = String(currentAgent.value?.extra_config?.suggested_questions_style || '').trim().toLowerCase();
if (style === 'styled') return 'styled';
if (style === 'plain') return 'plain';
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.style || 'plain';
});
const agentSuggestedQuestions = computed<AgentSuggestedQuestionItem[]>(() => {
const configured = normalizeAgentSuggestedQuestions(
currentAgent.value?.suggested_questions ?? currentAgent.value?.extra_config?.suggested_questions,
);
if (configured.length > 0) return configured;
return DEFAULT_AGENT_SUGGESTED_QUESTIONS[currentAgentName.value]?.questions || [];
});
const styledSuggestedQuestionSections = computed(() => {
const groups = new Map<string, AgentSuggestedQuestionItem[]>();
for (const item of agentSuggestedQuestions.value) {
const groupName = String(item.group || '').trim() || '常见问题';
if (!groups.has(groupName)) {
groups.set(groupName, []);
}
groups.get(groupName)?.push(item);
}
const iconTypes: Array<'calendar' | 'building'> = ['calendar', 'building'];
return Array.from(groups.entries()).map(([title, questions], index) => ({
title,
questions,
iconType: iconTypes[index % iconTypes.length],
}));
});
const agentGuides = ref<any[]>([]);
const showGuideModal = ref(false);
@@ -1825,6 +1913,10 @@ const handleChatMarkdownClick = (event: MouseEvent) => {
const action = actionElement.getAttribute('data-leave-action');
if (action !== 'start-leave-flow' || isThinking.value) return;
event.preventDefault();
if (!canUseLeaveFeature.value) {
msg.warning('请在“通用入口”或“人事规章”入口使用请假功能');
return;
}
startLocalLeaveFlow('我要请假');
};
@@ -2141,7 +2233,7 @@ const handleSend = async (textOrEvent?: string | Event) => {
const content = (typeof textOrEvent === 'string' ? textOrEvent : null) || input.value;
if (!content.trim() || isThinking.value || isUploadingAttachments.value) return;
if (isStrongLeaveIntent(content)) {
if (canUseLeaveFeature.value && isStrongLeaveIntent(content)) {
startLocalLeaveFlow(content);
return;
}
@@ -2692,17 +2784,14 @@ const showChatRating = ref(false);
学习之窗
</button>
</div>
<span v-if="currentAgent?.name === '人事规章'" class="block text-[11px] text-muted mt-1 truncate cursor-help">
我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。
</span>
<span v-else-if="currentAgent?.name === '通用入口'" class="block text-[11px] text-muted mt-1 truncate cursor-help">
我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。
<span v-if="agentDescription" class="block text-[11px] text-muted mt-1 truncate cursor-help">
{{ agentDescription }}
</span>
<!-- 气泡提示 -->
<div v-if="currentAgent?.name === '人事规章' || currentAgent?.name === '通用入口'" class="absolute left-0 top-[calc(100%+0.25rem)] w-[20rem] p-3 bg-surface border border-default rounded-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-[100] shadow-xl pointer-events-none">
<div v-if="agentDescription" class="absolute left-0 top-[calc(100%+0.25rem)] w-[20rem] p-3 bg-surface border border-default rounded-xl opacity-0 invisible group-hover:opacity-100 group-hover:visible transition-all duration-200 z-[100] shadow-xl pointer-events-none">
<div class="leading-relaxed text-[11px] text-secondary">
{{ currentAgent?.name === '人事规章' ? '我是你的7x24小时专属HR政策助手。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的规章制度中,为你精准提取并总结答案。' : '我是你的7x24小时专属AI数字人。无需手动检索文档,只需用日常说话的方式提问,我能从公司最新、最全的人事规章制度中,为你精准提取并总结答案。' }}
{{ agentDescription }}
</div>
</div>
</div>
@@ -2881,61 +2970,64 @@ const showChatRating = ref(false);
<div
:class="messages.length === 0 ? 'h-full' : 'flex min-h-full flex-col justify-end'"
>
<div v-if="messages.length === 0" class="flex h-full flex-col items-center justify-center py-2 md:pb-16 w-full px-4">
<template v-if="currentAgent?.name === '人事规章'">
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
HR
<div v-if="messages.length === 0" class="flex h-full min-h-0 w-full flex-col items-center px-4 pt-2 pb-2 md:pb-3">
<template v-if="suggestedQuestionsStyle === 'styled' && styledSuggestedQuestionSections.length > 0">
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
{{ currentAgent?.name === '人事规章' ? 'HR' : 'AI' }}
</div>
<h2 class="text-center text-xl font-bold text-primary md:text-2xl mb-8">你好,我是人事规章 AI 助手</h2>
<div class="grid grid-cols-1 md:grid-cols-2 gap-4 w-full max-w-4xl mx-auto">
<!-- 考勤与休假 -->
<div class="bg-surface border border-default rounded-2xl p-5 hover:border-brand-300 transition-colors shadow-sm">
<div class="flex items-center gap-2 mb-3">
<div class="p-1.5 bg-brand-50 rounded-lg text-brand-600">
<CalendarDays class="h-4 w-4" />
</div>
<h3 class="font-semibold text-secondary">考勤与休假</h3>
</div>
<div class="space-y-2">
<button @click="handleSend('查询我有多少假期?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"查询我有多少假期?"</button>
<button @click="handleSend('如何进行请假?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"如何进行请假?"</button>
<button @click="handleSend('查公司法定节假日?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"查公司法定节假日?"</button>
</div>
</div>
<h2 class="mb-6 shrink-0 text-center text-xl font-bold text-primary md:text-2xl">
{{ currentAgent?.name === '人事规章' ? '你好,我是人事规章 AI 助手' : t('chat.welcomeTitle') }}
</h2>
<!-- 规章与日常 -->
<div class="bg-surface border border-default rounded-2xl p-5 hover:border-brand-300 transition-colors shadow-sm">
<div class="w-full flex-1 min-h-0 overflow-y-auto pb-2">
<div class="mx-auto grid w-full max-w-4xl grid-cols-1 gap-4 md:grid-cols-2">
<div
v-for="(section, sectionIndex) in styledSuggestedQuestionSections"
:key="`${section.title}-${sectionIndex}`"
class="w-full bg-surface border border-default rounded-2xl p-5 hover:border-brand-300 transition-colors shadow-sm"
>
<div class="flex items-center gap-2 mb-3">
<div class="p-1.5 bg-brand-50 rounded-lg text-brand-600">
<Building class="h-4 w-4" />
<CalendarDays v-if="section.iconType === 'calendar'" class="h-4 w-4" />
<Building v-else class="h-4 w-4" />
</div>
<h3 class="font-semibold text-secondary">规章与日常</h3>
<h3 class="font-semibold text-secondary">{{ section.title }}</h3>
</div>
<div class="space-y-2">
<button @click="handleSend('新员工入职须知')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"新员工入职须知"</button>
<button @click="handleSend('怎么开具在职证明?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"怎么开具在职证明?"</button>
<button @click="handleSend('查公司薪酬及福利待遇怎么样?')" class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate">"查公司薪酬及福利待遇怎么样?"</button>
<button
v-for="(item, questionIndex) in section.questions"
:key="`${section.title}-${questionIndex}`"
@click="handleSend(item.question)"
class="w-full text-left text-xs md:text-sm text-secondary hover:text-brand-600 bg-surface-soft hover:bg-brand-50 px-3 py-2 rounded-lg transition-colors truncate"
>
"{{ item.question }}"
</button>
</div>
</div>
</div>
</div>
</template>
<template v-else-if="currentAgent?.name === '通用入口'">
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
<template v-else-if="agentSuggestedQuestions.length > 0">
<div class="mb-6 mt-2 flex h-16 w-16 shrink-0 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
</div>
<h2 class="text-center text-xl font-medium text-primary md:text-2xl mb-8">{{ $t('chat.welcomeTitle') }}</h2>
<div class="flex flex-wrap justify-center gap-3 w-full max-w-3xl mx-auto mt-2">
<button @click="handleSend('新员工入职须知')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"新员工入职须知"</button>
<button @click="handleSend('查询我有多少假期?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"查询我有多少假期?"</button>
<button @click="handleSend('如何进行请假?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"如何进行请假?"</button>
<button @click="handleSend('查公司法定节假日?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"查公司法定节假日?"</button>
<button @click="handleSend('查公司薪酬及福利待遇怎么样?')" class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm">"查公司薪酬及福利待遇怎么样?"</button>
<h2 class="mb-6 shrink-0 text-center text-xl font-medium text-primary md:text-2xl">{{ $t('chat.welcomeTitle') }}</h2>
<div class="w-full flex-1 min-h-0 overflow-y-auto pb-2">
<div class="flex flex-wrap justify-center gap-3 w-full max-w-3xl mx-auto mt-2">
<button
v-for="(item, index) in agentSuggestedQuestions"
:key="`${item.question}-${index}`"
@click="handleSend(item.question)"
class="px-4 py-2 text-sm text-secondary bg-surface border border-default rounded-full hover:border-brand-300 hover:text-brand-600 hover:bg-brand-50 transition-all shadow-sm"
>
"{{ item.question }}"
</button>
</div>
</div>
</template>
<template v-else>
<div class="mb-6 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
<div class="mb-6 mt-2 flex h-16 w-16 items-center justify-center rounded-2xl bg-gradient-to-br from-brand-500 via-brand-600 to-sky-600 text-2xl font-bold text-white shadow-lg shadow-brand-500/20">
AI
</div>
<h2 class="text-center text-xl font-medium text-primary md:text-2xl">{{ $t('chat.welcomeTitle') }}</h2>
+497 -114
View File
@@ -11,7 +11,6 @@ import {
deleteKbPathJobFile,
deleteKbGroup,
deleteKbDocument,
finalizeKbPathUploadJob,
getKbDocumentMarkdown,
getKbDocumentSyncRecords,
getKbDocumentVersionSourceFile,
@@ -21,7 +20,7 @@ import {
getKbJobsSafe,
markKbPathJobFileFailed,
retryFailedKbPathUploadJob,
runKbJob,
submitKbDocumentClean,
syncKbDocumentToDify,
uploadKbPathJobFile,
uploadKbDocumentVersion,
@@ -87,6 +86,8 @@ const failureModalType = ref<'upload' | 'clean' | 'sync' | null>(null);
const failureModalPage = ref(1);
const retryingFailureKey = ref('');
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
const documentListPage = ref(1);
const documentListPageSize = ref(50);
const batchSubmitting = ref(false);
const selectedDocumentIds = ref<number[]>([]);
const pathUploadDraftText = ref('');
@@ -177,9 +178,15 @@ type PathUploadTaskItem = {
finishedAt?: string;
};
type LoadListOptions = {
silent?: boolean;
};
const FAILURE_PAGE_SIZE = 15;
const PATH_UPLOAD_BATCH_SIZE = 20;
const PATH_UPLOAD_BATCH_INTERVAL_MS = 1500;
const PATH_UPLOAD_BATCH_SIZE = 30;
const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
const PATH_UPLOAD_CONCURRENCY = 3;
const DOCUMENT_PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const;
const pathUploadTask = ref<{
running: boolean;
groupId: number | null;
@@ -221,6 +228,48 @@ const getLatestJobForDocument = (doc: KbDocumentItem, jobType: string): KbJob |
})[0] ?? null;
};
const isUnreadableErrorMessage = (value: string | null | undefined) => {
const text = String(value || '').trim();
if (!text) return true;
const compact = text.replace(/[\s::,,。.!!;;\-_/\\()[\]【】]/g, '');
if (!compact) return true;
return /^[??]+$/.test(compact);
};
const normalizeWorkflowErrorMessage = (
value: string | null | undefined,
stage: 'upload' | 'clean' | 'sync',
) => {
const text = String(value || '').trim();
if (!text) return null;
const upper = text.toUpperCase();
if (isUnreadableErrorMessage(text)) {
if (stage === 'clean') {
return '历史失败任务原因不可读,请重新点击“清洗数据”发起清洗';
}
if (stage === 'sync') {
return '历史同步失败原因不可读,请重新发起同步';
}
return '历史上传失败原因不可读,请重新上传文件';
}
if (upper.includes('LEGACY_CLEAN_TASK_RECOVERED_MANUALLY')) {
return '历史遗留清洗任务已人工回收,请重新点击“清洗数据”发起清洗';
}
if (upper.includes('JOB_TIMEOUT_RECOVERED')) {
return '后台任务执行超时,系统已自动回收,请重新发起';
}
if (upper.includes('CLEAN_SOURCE_MISSING')) {
return '原始文件不存在,请重新上传后再清洗';
}
if (upper.includes('CLEAN_VERSION_MISSING')) {
return '关联版本不存在,请重新上传后再试';
}
if (upper.includes('CLEAN_TIMEOUT') || /file processing timed out|timed out after/i.test(text)) {
return '文件清洗超时,请稍后重试;若多次失败,请检查源文件是否损坏';
}
return text;
};
const getDocumentWorkflowState = (doc: KbDocumentItem) => {
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
const uploadJob = getLatestJobForDocument(doc, 'upload');
@@ -234,7 +283,7 @@ const getDocumentWorkflowState = (doc: KbDocumentItem) => {
code: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
errorMessage: uploadJob.error_message || uploadJob.message,
errorMessage: normalizeWorkflowErrorMessage(uploadJob.error_message || uploadJob.message, 'upload'),
}
: { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
@@ -246,7 +295,10 @@ const getDocumentWorkflowState = (doc: KbDocumentItem) => {
code: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
errorMessage: cleanJob?.error_message || doc.latest_version?.error_message || cleanJob?.message || null,
errorMessage: normalizeWorkflowErrorMessage(
cleanJob?.error_message || doc.latest_version?.error_message || cleanJob?.message || null,
'clean',
),
};
} else if (['cleaned', 'ready', 'syncing', 'synced'].includes(latestStatus)) {
cleanStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
@@ -270,7 +322,7 @@ const getDocumentWorkflowState = (doc: KbDocumentItem) => {
code: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
errorMessage: syncJob.error_message || syncJob.message,
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync'),
};
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
syncStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
@@ -290,7 +342,7 @@ const getDocumentWorkflowState = (doc: KbDocumentItem) => {
syncStage.errorMessage ||
cleanStage.errorMessage ||
uploadStage.errorMessage ||
doc.latest_version?.error_message ||
normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean') ||
null;
return {
@@ -352,10 +404,36 @@ const filteredDocuments = computed(() =>
documents.value.filter((doc) => matchesDocumentStageFilter(doc, documentStageFilter.value))
);
const filteredDocumentTotalPages = computed(() =>
Math.max(1, Math.ceil(filteredDocuments.value.length / documentListPageSize.value))
);
const pagedFilteredDocuments = computed(() => {
const start = (documentListPage.value - 1) * documentListPageSize.value;
return filteredDocuments.value.slice(start, start + documentListPageSize.value);
});
const pagedDocumentRange = computed(() => {
if (filteredDocuments.value.length === 0) {
return { start: 0, end: 0 };
}
const start = (documentListPage.value - 1) * documentListPageSize.value + 1;
const end = Math.min(filteredDocuments.value.length, documentListPage.value * documentListPageSize.value);
return { start, end };
});
const selectedDocuments = computed(() =>
documents.value.filter((doc) => selectedDocumentIds.value.includes(doc.id))
);
const selectedCleanableDocuments = computed(() =>
selectedDocuments.value.filter((doc) => {
if (!doc.latest_version) return false;
const workflow = getDocumentWorkflowState(doc);
return ['failed', 'pending', 'idle'].includes(workflow.clean.code);
})
);
const isAllFilteredSelected = computed(() =>
filteredDocuments.value.length > 0
&& filteredDocuments.value.every((doc) => selectedDocumentIds.value.includes(doc.id))
@@ -423,13 +501,46 @@ const failureModalTitle = computed(() => {
return failureModalType.value ? map[failureModalType.value] : '失败数据';
});
const documentById = computed(() =>
new Map(documents.value.map((doc) => [doc.id, doc]))
);
const getPathUploadJobProgress = (job: KbJob | null) => {
const payload = job?.payload_json || {};
const result = job?.result_json || {};
const success = Number(result.success || 0);
const failed = Number(result.failed || 0);
const processed = Number(result.processed || success + failed || 0);
const total = Number(result.total || payload.total_files || 0);
return { total, success, failed, processed };
};
const getPathUploadJobPriority = (job: KbJob) => {
const normalizedStatus = String(job.status || '').toLowerCase();
const { processed, success, failed } = getPathUploadJobProgress(job);
const hasProgress = processed > 0 || success > 0 || failed > 0 || Boolean(job.started_at) || Boolean(job.finished_at);
const statusScore = normalizedStatus === 'running'
? 50
: normalizedStatus === 'success'
? 40
: normalizedStatus === 'failed'
? 35
: ['queued', 'staging', 'draft'].includes(normalizedStatus)
? 20
: 0;
return (hasProgress ? 1000 : 0) + statusScore;
};
const latestPathUploadJob = computed(() => {
const pathJobs = activeGroupJobs.value.filter((job) => job.job_type === 'path_upload');
if (!pathJobs.length) return null;
return [...pathJobs].sort((a, b) => {
const priorityDiff = getPathUploadJobPriority(b) - getPathUploadJobPriority(a);
if (priorityDiff !== 0) return priorityDiff;
const aTime = new Date(a.created_at || a.finished_at || a.started_at || 0).getTime();
const bTime = new Date(b.created_at || b.finished_at || b.started_at || 0).getTime();
return bTime - aTime;
if (aTime !== bTime) return bTime - aTime;
return Number(b.id) - Number(a.id);
})[0] ?? null;
});
@@ -460,15 +571,86 @@ const isAllPathUploadHistoryItemsSelected = computed(() =>
&& selectedPathUploadHistoryItems.value.every((item) => selectedPathUploadHistoryItemKeys.value.includes(item.key))
);
const getPathUploadItemDisplayState = (item: PathUploadTaskItem) => {
if (item.status === 'failed') {
return {
normalized: 'failed',
label: '失败',
className: getStatusBadgeClass('failed'),
};
}
const doc = item.documentId ? documentById.value.get(item.documentId) || null : null;
const latestStatus = String(doc?.latest_version?.status || doc?.status || '').toLowerCase();
if (latestStatus === 'processing') {
return {
normalized: 'processing',
label: '清洗中',
className: getStatusBadgeClass('processing'),
};
}
if (['cleaned', 'ready'].includes(latestStatus)) {
return {
normalized: latestStatus,
label: '已清洗',
className: getStatusBadgeClass(latestStatus),
};
}
if (latestStatus === 'syncing') {
return {
normalized: 'syncing',
label: '同步中',
className: getStatusBadgeClass('processing'),
};
}
if (latestStatus === 'synced') {
return {
normalized: 'synced',
label: '已同步',
className: getStatusBadgeClass('synced'),
};
}
if (latestStatus === 'uploaded') {
return {
normalized: 'uploaded',
label: '待清洗',
className: getStatusBadgeClass('uploaded'),
};
}
if (item.status === 'success' || item.documentId) {
return {
normalized: 'success',
label: '已上传',
className: getStatusBadgeClass('success'),
};
}
if (item.status === 'uploading') {
return {
normalized: 'uploading',
label: '上传中',
className: getStatusBadgeClass('processing'),
};
}
return {
normalized: 'queued',
label: '待上传',
className: getStatusBadgeClass('queued'),
};
};
const pathUploadSummary = computed(() => {
const task = pathUploadTask.value;
const queued = task.items.filter((item) => item.status === 'queued').length;
const uploading = task.items.filter((item) => item.status === 'uploading').length;
const displayedStates = task.items.map((item) => getPathUploadItemDisplayState(item).normalized);
const queued = displayedStates.filter((status) => status === 'queued').length;
const uploading = displayedStates.filter((status) => status === 'uploading').length;
const failed = displayedStates.filter((status) => status === 'failed').length;
const uploaded = Math.max(task.total - queued - uploading - failed, 0);
return {
total: task.total,
pending: queued + uploading,
uploaded: task.success,
failed: task.failed,
uploaded,
failed,
queued,
uploading,
};
@@ -488,13 +670,44 @@ const pathUploadRunning = computed(() =>
isPathUploadStaging.value
|| ['draft', 'staging', 'queued', 'running'].includes(String(latestPathUploadJob.value?.status || '').toLowerCase())
);
const kbJobPollingActive = computed(() =>
pathUploadRunning.value
|| activeGroupJobs.value.some((job) =>
['clean', 'sync_dify'].includes(String(job.job_type || '').toLowerCase())
&& ['queued', 'running'].includes(String(job.status || '').toLowerCase())
)
);
const selectedPathRoots = computed(() => {
const roots = new Set(pathUploadSelectedFiles.value.map((item) => item.rootLabel));
return Array.from(roots);
});
const loadGroups = async () => {
isLoading.value = true;
const mergeStableItems = <T extends { id: number | string }>(current: T[], incoming: T[]) => {
const incomingMap = new Map(incoming.map((item) => [String(item.id), item] as const));
const next: T[] = [];
const seen = new Set<string>();
current.forEach((item) => {
const key = String(item.id);
const incomingItem = incomingMap.get(key);
if (!incomingItem) return;
next.push(incomingItem);
seen.add(key);
});
incoming.forEach((item) => {
const key = String(item.id);
if (seen.has(key)) return;
next.push(item);
});
return next;
};
const loadGroups = async (options: LoadListOptions = {}) => {
if (!options.silent) {
isLoading.value = true;
}
try {
const result = await getKbGroupsSafe();
if (!result.ok) {
@@ -502,17 +715,20 @@ const loadGroups = async () => {
feedbackType.value = 'error';
return;
}
groups.value = result.data;
groups.value = options.silent ? mergeStableItems(groups.value, result.data) : result.data;
const firstGroup = groups.value[0];
if (!selectedGroupId.value && firstGroup && viewMode.value === 'group_detail') {
selectedGroupId.value = firstGroup.id;
}
} finally {
isLoading.value = false;
if (!options.silent) {
isLoading.value = false;
}
}
};
const loadJobs = async () => {
const hadActiveKbJobs = kbJobPollingActive.value;
const result = await getKbJobsSafe();
if (!result.ok) {
feedback.value = result.error || '加载任务列表失败';
@@ -527,13 +743,27 @@ const loadJobs = async () => {
if (selectedPathUploadHistoryJobId.value && !pathUploadHistoryJobs.value.some((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))) {
selectedPathUploadHistoryJobId.value = latestPathUploadJob.value?.id || null;
}
if (pathUploadRunning.value) {
if (kbJobPollingActive.value) {
startPathUploadPolling();
} else {
stopPathUploadPollTimer();
if (hadActiveKbJobs && viewMode.value === 'group_detail') {
await Promise.all([
loadDocuments(selectedGroupId.value, { silent: true }),
loadGroups({ silent: true }),
]);
}
}
};
const refreshWorkflowStatusOnly = async () => {
await Promise.all([
loadJobs(),
loadGroups({ silent: true }),
loadDocuments(selectedGroupId.value, { silent: true }),
]);
};
const refreshCurrentView = async () => {
if (viewMode.value === 'group_overview') {
await Promise.all([loadGroups(), loadJobs()]);
@@ -645,6 +875,33 @@ const getWorkflowBadges = (doc: KbDocumentItem) => {
];
};
const getMarkdownUnavailableMessage = (
doc: KbDocumentItem,
fallback?: string | null,
) => {
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
const normalizedReason = normalizeWorkflowErrorMessage(
doc.latest_version?.error_message,
'clean',
);
if (latestStatus === 'failed') {
return normalizedReason
? `当前文档清洗失败,尚未生成 Markdown。失败原因:${normalizedReason}`
: '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试';
}
if (latestStatus === 'processing') {
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试';
}
if (latestStatus === 'uploaded') {
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗';
}
return fallback || '当前文档尚未生成 Markdown';
};
const resetGroupForm = () => {
editingGroupId.value = null;
groupForm.value = {
@@ -741,8 +998,10 @@ const handleDeleteGroup = async (group: KbGroup) => {
});
};
const loadDocuments = async (groupId: number | null) => {
isDocumentsLoading.value = true;
const loadDocuments = async (groupId: number | null, options: LoadListOptions = {}) => {
if (!options.silent) {
isDocumentsLoading.value = true;
}
try {
if (!groupId) {
documents.value = [];
@@ -757,7 +1016,10 @@ const loadDocuments = async (groupId: number | null) => {
feedbackType.value = 'error';
return;
}
documents.value = result.data;
const nextDocuments = options.silent
? mergeStableItems(documents.value, result.data)
: result.data;
documents.value = nextDocuments;
if (selectedDocumentId.value && !documents.value.some((item) => item.id === selectedDocumentId.value)) {
selectedDocumentId.value = null;
selectedDocumentVersions.value = [];
@@ -771,7 +1033,9 @@ const loadDocuments = async (groupId: number | null) => {
}
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => documents.value.some((item) => item.id === id));
} finally {
isDocumentsLoading.value = false;
if (!options.silent) {
isDocumentsLoading.value = false;
}
}
};
@@ -912,6 +1176,10 @@ const stopPathUploadPollTimer = () => {
}
};
const wait = (ms: number) => new Promise((resolve) => {
window.setTimeout(resolve, ms);
});
const updatePathUploadFeedback = () => {
const summary = pathUploadSummary.value;
if (!pathUploadTask.value.total) return;
@@ -1028,11 +1296,15 @@ const toggleSelectAllPathUploadHistoryItems = () => {
const startPathUploadPolling = () => {
stopPathUploadPollTimer();
pathUploadPollTimer = window.setInterval(() => {
if (!pathUploadRunning.value) {
if (!kbJobPollingActive.value) {
stopPathUploadPollTimer();
return;
}
void Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
void Promise.all([
loadJobs(),
loadDocuments(selectedGroupId.value, { silent: true }),
loadGroups({ silent: true }),
]);
}, 3000);
};
@@ -1068,76 +1340,99 @@ const handleConfirmPathUpload = async () => {
isPathUploadStaging.value = false;
return;
}
const createdJob = createResult.job;
const existingJobItems = getPathUploadJobItems(createdJob);
const existingItemMap = new Map(existingJobItems.map((item) => [item.displayPath, item]));
const selectedPathSet = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath));
const pendingFiles = pathUploadSelectedFiles.value.filter((item) => {
const existingItem = existingItemMap.get(item.displayPath);
return !existingItem || existingItem.status !== 'success';
});
pathUploadJobId.value = createResult.job.id;
pathUploadJobId.value = createdJob.id;
showPathUploadDetails.value = false;
pathUploadTask.value = {
running: true,
groupId: selectedGroupId.value,
total: pathUploadSelectedFiles.value.length,
success: 0,
failed: 0,
currentFile: '',
total: Number(createdJob.payload_json?.total_files || existingJobItems.length || pathUploadSelectedFiles.value.length),
success: Number(createdJob.result_json?.success || existingJobItems.filter((item) => item.status === 'success').length || 0),
failed: Number(createdJob.result_json?.failed || existingJobItems.filter((item) => item.status === 'failed').length || 0),
currentFile: String(createdJob.payload_json?.current_file || ''),
batchSize: PATH_UPLOAD_BATCH_SIZE,
items: pathUploadSelectedFiles.value.map((item) => ({
key: item.key,
title: item.file.name,
displayPath: item.displayPath,
rootLabel: item.rootLabel,
status: 'queued',
})),
items: [
...pathUploadSelectedFiles.value.map((item) => {
const existingItem = existingItemMap.get(item.displayPath);
return {
key: item.key,
title: item.file.name,
displayPath: item.displayPath,
rootLabel: item.rootLabel,
status: existingItem?.status || 'queued',
error: existingItem?.error,
documentId: existingItem?.documentId,
retryable: existingItem?.retryable,
} satisfies PathUploadTaskItem;
}),
...existingJobItems.filter((item) => !selectedPathSet.has(item.displayPath)),
],
};
updatePathUploadFeedback();
showPathUploadModal.value = false;
for (const item of pathUploadSelectedFiles.value) {
const stageSinglePathUploadFile = async (item: { key: string; file: File; displayPath: string; rootLabel: string }) => {
pathUploadTask.value.currentFile = item.displayPath;
const localItem = pathUploadTask.value.items.find((candidate) => candidate.key === item.key);
if (localItem) {
localItem.status = 'uploading';
}
const stageResult = await uploadKbPathJobFile(createResult.job.id, item.file, item.displayPath);
const stageResult = await uploadKbPathJobFile(createdJob.id, item.file, item.displayPath);
if (!stageResult.ok) {
const errorMessage = normalizeDuplicateDocumentError(stageResult.error || '路径文件暂存失败');
const failResult = await markKbPathJobFileFailed(createResult.job.id, {
const failedResult = await markKbPathJobFileFailed(createdJob.id, {
relative_path: item.displayPath,
original_name: item.file.name,
error: errorMessage,
});
if (failResult.ok && failResult.job) {
applyPathUploadJob(failResult.job);
}
if (localItem) {
if (failedResult.ok && failedResult.job) {
applyPathUploadJob(failedResult.job);
} else if (localItem) {
localItem.status = 'failed';
localItem.error = errorMessage;
}
if (!failResult.ok) {
pathUploadTask.value.failed += 1;
updatePathUploadFeedback();
}
continue;
}
if (localItem) {
localItem.status = 'queued';
localItem.error = undefined;
return;
}
if (stageResult.job) {
applyPathUploadJob(stageResult.job);
} else if (localItem) {
localItem.status = 'success';
localItem.error = undefined;
updatePathUploadFeedback();
}
await Promise.all([loadDocuments(selectedGroupId.value, { silent: true }), loadJobs()]);
};
const files = [...pendingFiles];
for (let batchStart = 0; batchStart < files.length; batchStart += PATH_UPLOAD_BATCH_SIZE) {
const batch = files.slice(batchStart, batchStart + PATH_UPLOAD_BATCH_SIZE);
for (let i = 0; i < batch.length; i += PATH_UPLOAD_CONCURRENCY) {
const chunk = batch.slice(i, i + PATH_UPLOAD_CONCURRENCY);
await Promise.all(chunk.map((item) => stageSinglePathUploadFile(item)));
}
if (batchStart + PATH_UPLOAD_BATCH_SIZE < files.length) {
await wait(PATH_UPLOAD_BATCH_INTERVAL_MS);
}
}
const finalizeResult = await finalizeKbPathUploadJob(createResult.job.id);
isPathUploadStaging.value = false;
pathUploadTask.value.currentFile = '';
if (!finalizeResult.ok || !finalizeResult.job) {
feedback.value = finalizeResult.error || '提交路径上传任务失败';
feedbackType.value = 'error';
return;
}
applyPathUploadJob(finalizeResult.job);
feedback.value = '路径文件已逐个上传并提交清洗';
feedbackType.value = 'success';
startPathUploadPolling();
resetPathUploadDraft();
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
await refreshWorkflowStatusOnly();
};
const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTaskItem) => {
@@ -1154,7 +1449,7 @@ const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTas
if (pathUploadTask.value.items.length <= 1) {
showPathUploadDetails.value = false;
}
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
await refreshWorkflowStatusOnly();
});
};
@@ -1211,7 +1506,7 @@ const handleRetryFailedPathUpload = async (
startPathUploadPolling();
feedback.value = relativePaths?.length === 1 ? '已重新提交该失败文件' : '已重新提交失败文件';
feedbackType.value = 'success';
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
await refreshWorkflowStatusOnly();
};
const toggleDocumentSelection = (documentId: number) => {
@@ -1262,24 +1557,61 @@ const handleBatchSync = async () => {
return;
}
batchSubmitting.value = true;
let successCount = 0;
let failCount = 0;
const errors: string[] = [];
try {
for (const doc of selectedDocuments.value) {
const result = await syncKbDocumentToDify(doc.id);
if (result.ok) {
successCount += 1;
} else {
failCount += 1;
errors.push(`${getDocumentDisplayTitle(doc)}: ${result.error || '同步失败'}`);
}
}
const results = await Promise.all(
selectedDocuments.value.map(async (doc) => ({
doc,
result: await syncKbDocumentToDify(doc.id),
}))
);
const successCount = results.filter(({ result }) => result.ok).length;
const failResults = results.filter(({ result }) => !result.ok);
const failCount = failResults.length;
const errors = failResults.map(({ doc, result }) => `${getDocumentDisplayTitle(doc)}: ${result.error || '同步失败'}`);
feedback.value = failCount
? `批量同步完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量同步完成:共成功 ${successCount} 条`;
? `批量同步任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量同步任务已提交:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
if (successCount > 0) {
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
} finally {
batchSubmitting.value = false;
}
};
const handleBatchClean = async () => {
if (!selectedDocuments.value.length) {
feedback.value = '请先选择要清洗的文档';
feedbackType.value = 'error';
return;
}
if (!selectedCleanableDocuments.value.length) {
feedback.value = '当前所选文档没有可重新清洗的项';
feedbackType.value = 'error';
return;
}
batchSubmitting.value = true;
try {
const results = await Promise.all(
selectedCleanableDocuments.value.map(async (doc) => ({
doc,
result: await submitKbDocumentClean(doc.id),
}))
);
const successCount = results.filter(({ result }) => result.ok).length;
const failResults = results.filter(({ result }) => !result.ok);
const failCount = failResults.length;
const errors = failResults.map(({ doc, result }) => `${getDocumentDisplayTitle(doc)}: ${result.error || '提交清洗失败'}`);
feedback.value = failCount
? `批量清洗任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量清洗任务已提交:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
if (successCount > 0) {
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
} finally {
batchSubmitting.value = false;
}
@@ -1336,20 +1668,15 @@ const handleRetryFailedItem = async (
return;
}
if (action === 'clean') {
const cleanJob = item.latestJob || getLatestJobForDocument(item.document, 'clean');
if (!cleanJob) {
feedback.value = '未找到可重试的清洗任务';
feedbackType.value = 'error';
return;
}
const result = await runKbJob(cleanJob.id);
const result = await submitKbDocumentClean(item.document.id);
if (!result.ok) {
feedback.value = result.error || '重新清洗失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.run_result || `已重新提交清洗:${getDocumentDisplayTitle(item.document)}`;
feedback.value = result.message || `已重新提交清洗:${getDocumentDisplayTitle(item.document)}`;
feedbackType.value = 'success';
startPathUploadPolling();
} else {
const result = await syncKbDocumentToDify(item.document.id);
if (!result.ok) {
@@ -1357,10 +1684,11 @@ const handleRetryFailedItem = async (
feedbackType.value = 'error';
return;
}
feedback.value = result.run_result || `已重新提交同步:${getDocumentDisplayTitle(item.document)}`;
feedback.value = result.job?.message || `已重新提交同步:${getDocumentDisplayTitle(item.document)}`;
feedbackType.value = 'success';
startPathUploadPolling();
}
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
await refreshWorkflowStatusOnly();
if (selectedDocumentId.value) {
await loadDocumentVersions(selectedDocumentId.value);
}
@@ -1398,8 +1726,9 @@ const handleFileSelected = async (event: Event) => {
feedback.value = result.error || '文件上传失败';
feedbackType.value = 'error';
} else {
feedback.value = `版本文件「${file.name}」上传成功`;
feedback.value = result.message || `版本文件「${file.name}」上传成功,清洗已排队`;
feedbackType.value = 'success';
startPathUploadPolling();
}
selectedDocumentId.value = activeUploadDocumentId.value;
activeUploadDocumentId.value = null;
@@ -1443,17 +1772,18 @@ const handleFileSelected = async (event: Event) => {
feedback.value = `上传完成:成功 ${successCount} 个,失败 ${failCount} 个。${errors[0] || ''}`;
feedbackType.value = successCount > 0 ? 'success' : 'error';
} else {
feedback.value = `成功上传 ${successCount} 个文件`;
feedback.value = `成功上传 ${successCount} 个文件,清洗任务已排队`;
feedbackType.value = 'success';
}
if (successCount > 0) {
startPathUploadPolling();
}
}
input.value = '';
isSubmitting.value = false;
await loadGroups();
await loadDocuments(selectedGroupId.value);
await loadJobs();
await refreshWorkflowStatusOnly();
if (selectedDocumentId.value) {
await loadDocumentVersions(selectedDocumentId.value);
}
@@ -1472,14 +1802,15 @@ const handleSyncDocument = async (documentId: number) => {
if (!result.ok) {
feedback.value = result.error ? `同步到 Dify 失败:${result.error}` : '同步到 Dify 失败';
feedbackType.value = 'error';
await loadDocuments(selectedGroupId.value);
await loadDocuments(selectedGroupId.value, { silent: true });
await loadJobs();
return;
}
feedback.value = result.run_result || '已同步到 Dify';
feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
feedbackType.value = 'success';
await loadDocuments(selectedGroupId.value);
startPathUploadPolling();
await loadDocuments(selectedGroupId.value, { silent: true });
await loadJobs();
selectedDocumentId.value = documentId;
await loadDocumentVersions(documentId);
@@ -1505,7 +1836,7 @@ const openMarkdownEditor = async (doc: KbDocumentItem) => {
const result = await getKbDocumentMarkdown(doc.id);
isMarkdownLoading.value = false;
if (!result.ok || !result.data) {
markdownError.value = result.error || '读取清洗后的 Markdown 失败';
markdownError.value = getMarkdownUnavailableMessage(doc, result.error || '读取清洗后的 Markdown 失败');
return;
}
applyMarkdownPayload(result.data);
@@ -1532,7 +1863,10 @@ const handleSaveMarkdown = async () => {
isMarkdownSaving.value = false;
if (!result.ok || !result.data) {
markdownError.value = result.error || '保存 Markdown 失败';
const currentDoc = documents.value.find((item) => item.id === markdownDocumentId.value) || null;
markdownError.value = currentDoc
? getMarkdownUnavailableMessage(currentDoc, result.error || '保存 Markdown 失败')
: (result.error || '保存 Markdown 失败');
return;
}
@@ -1549,6 +1883,7 @@ const handleSaveMarkdown = async () => {
watch(selectedGroupId, (groupId) => {
feedback.value = '';
feedbackType.value = '';
documentListPage.value = 1;
selectedDocumentId.value = null;
selectedDocumentIds.value = [];
selectedDocumentVersions.value = [];
@@ -1557,6 +1892,20 @@ watch(selectedGroupId, (groupId) => {
applyPathUploadJob(latestPathUploadJob.value);
});
watch(documentStageFilter, () => {
documentListPage.value = 1;
});
watch(documentListPageSize, () => {
documentListPage.value = 1;
});
watch(filteredDocumentTotalPages, (totalPages) => {
if (documentListPage.value > totalPages) {
documentListPage.value = totalPages;
}
});
watch(selectedPathUploadHistoryJob, (job) => {
const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
@@ -1803,6 +2152,15 @@ onUnmounted(() => {
</div>
</div>
<div class="flex flex-wrap items-center gap-3">
<button
v-if="selectedGroupId"
@click="handleBatchClean"
:disabled="batchSubmitting || selectedDocuments.length === 0"
class="inline-flex items-center gap-2 rounded-2xl border border-amber-200 px-4 py-2.5 text-sm font-medium text-amber-700 transition-colors hover:bg-amber-50 disabled:cursor-not-allowed disabled:opacity-60"
>
<RefreshCw class="h-4 w-4" />
{{ batchSubmitting ? '处理中...' : `清洗数据${selectedDocuments.length ? `(${selectedDocuments.length})` : ''}` }}
</button>
<button
v-if="selectedGroupId"
@click="handleBatchSync"
@@ -1912,15 +2270,9 @@ onUnmounted(() => {
<div class="flex items-center gap-2">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="item.status === 'success'
? getStatusBadgeClass('success')
: item.status === 'failed'
? getStatusBadgeClass('failed')
: item.status === 'uploading'
? getStatusBadgeClass('processing')
: getStatusBadgeClass('queued')"
:class="getPathUploadItemDisplayState(item).className"
>
{{ item.status === 'success' ? '已上传' : item.status === 'failed' ? '失败' : item.status === 'uploading' ? '上传中' : '待上传' }}
{{ getPathUploadItemDisplayState(item).label }}
</span>
<button
v-if="item.retryable && latestPathUploadJob && !pathUploadRunning"
@@ -1966,7 +2318,20 @@ onUnmounted(() => {
<span class="rounded-full bg-surface-soft px-2 py-0.5 text-xs ">{{ tab.count }}</span>
</button>
</div>
<div class="text-sm text-muted">已选 {{ selectedDocuments.length }} 条 · 共 {{ filteredDocuments.length }} 条</div>
<div class="flex flex-wrap items-center gap-3 text-sm text-muted">
<label class="inline-flex items-center gap-2">
<span>每页</span>
<select
v-model.number="documentListPageSize"
class="rounded-xl border border-default bg-surface px-3 py-1.5 text-sm text-secondary outline-none transition-colors focus:border-brand-300"
>
<option v-for="size in DOCUMENT_PAGE_SIZE_OPTIONS" :key="size" :value="size">{{ size }}</option>
</select>
<span>条</span>
</label>
<span>已选 {{ selectedDocuments.length }} 条 · 共 {{ filteredDocuments.length }} 条</span>
<span v-if="filteredDocuments.length > 0">当前显示 {{ pagedDocumentRange.start }}-{{ pagedDocumentRange.end }} 条</span>
</div>
</div>
<div v-if="!selectedGroupId" class="rounded-2xl border border-dashed border-default px-4 py-12 text-center text-sm text-muted ">
@@ -1980,7 +2345,7 @@ onUnmounted(() => {
</div>
<div v-else class="space-y-3">
<div
v-for="doc in filteredDocuments"
v-for="doc in pagedFilteredDocuments"
:key="doc.id"
class="rounded-2xl border px-4 py-4 transition-colors"
:class="selectedDocumentId === doc.id
@@ -2082,6 +2447,30 @@ onUnmounted(() => {
</div>
</div>
</div>
<div
v-if="filteredDocuments.length > documentListPageSize"
class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
>
<div class="text-sm text-muted">
第 {{ documentListPage }} / {{ filteredDocumentTotalPages }} 页 · 共 {{ filteredDocuments.length }} 条
</div>
<div class="flex items-center gap-2">
<button
@click="documentListPage = Math.max(1, documentListPage - 1)"
:disabled="documentListPage === 1"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
>
上一页
</button>
<button
@click="documentListPage = Math.min(filteredDocumentTotalPages, documentListPage + 1)"
:disabled="documentListPage === filteredDocumentTotalPages"
class="inline-flex items-center justify-center rounded-xl border border-default px-4 py-2 text-sm font-medium text-secondary transition-colors hover:bg-surface-soft disabled:cursor-not-allowed disabled:opacity-60 hover-surface-soft"
>
下一页
</button>
</div>
</div>
</div>
</div>
</section>
@@ -2718,15 +3107,9 @@ onUnmounted(() => {
<div class="flex items-center gap-2">
<span
class="inline-flex items-center rounded-full border px-2.5 py-1 text-xs font-semibold"
:class="item.status === 'success'
? getStatusBadgeClass('success')
: item.status === 'failed'
? getStatusBadgeClass('failed')
: item.status === 'uploading'
? getStatusBadgeClass('processing')
: getStatusBadgeClass('queued')"
:class="getPathUploadItemDisplayState(item).className"
>
{{ item.status === 'success' ? '已上传' : item.status === 'failed' ? '失败' : item.status === 'uploading' ? '上传中' : '待上传' }}
{{ getPathUploadItemDisplayState(item).label }}
</span>
<button
v-if="item.retryable && !pathUploadRunning"