Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-06-05 15:14:06 +08:00
commit faedb625c7
14 files changed
+445 -49

No files matched your search

+3 -4
View File
@@ -48,10 +48,9 @@ GUNICORN_WORKERS=10
# MinIO(知识库文档清洗图片托管;dev 与测试机同机时用测试 MinIO)
# 本地非 Docker 跑 worker 时可改为 127.0.0.1:9000 或 192.168.100.192:9000
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD 保持一致
MINIO_ENDPOINT=127.0.0.1:9000
MINIO_BUCKET=image-hosting-service
MINIO_ENDPOINT=192.168.100.192:9000
MINIO_ACCESS_KEY=minio_testing_admin
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
MINIO_SECURE=false
MINIO_PUBLIC_BASE_URL=http://127.0.0.1:9000
#MINIO_PUBLIC_BASE_URL=http://192.168.1.100/HX工作目录/0602/hxops/backend/data
MINIO_PUBLIC_BASE_URL=http://192.168.100.192:9000
-1
View File
@@ -48,7 +48,6 @@ GUNICORN_WORKERS=20
# MinIO(知识库文档清洗图片托管,容器 minio-app)
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
MINIO_ENDPOINT=host.docker.internal:9000
MINIO_BUCKET=image-hosting-service
MINIO_ACCESS_KEY=admin
MINIO_SECRET_KEY=difyai123456
MINIO_SECURE=false
+11 -1
View File
@@ -18,6 +18,12 @@ SECRET_KEY=hxops-dify
# KB_STORAGE_ROOT=backend/data/kb
KB_TASK_EXECUTION_MODE=worker
KB_WORKER_POLL_SECONDS=2
# Linux 容器内 LibreOffice 路径(避免探测 Windows 安装路径)
EDKB_SOFFICE=/usr/bin/soffice
# LibreOffice 单次格式转换超时(秒);复杂 .doc 在容器内可能需 10 分钟左右
EDKB_SOFFICE_TIMEOUT_SEC=600
# running 任务回收阈值,须大于 EDKB_SOFFICE_TIMEOUT_SEC 及整条清洗链路耗时
KB_JOB_RUNNING_TIMEOUT_SECONDS=900
# chat回答的评分与评论
FEEDBACK_ENABLED=true
@@ -62,7 +68,11 @@ WECOM_NOTIFY_EVENTS=permission_request_approved,permission_request_rejected,perm
INTEGRATION_API_MODE=local
DIFY_API_BASE=https://api.dify.ai/v1
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod(kb-worker 容器内 endpoint 与对外 public URL 分开)
# MinIO:按环境配置见 .env.dev / .env.test / .env.prod
# MINIO_KB_IMAGE_BUCKET — 知识库文档清洗图片托管(kb-worker / export)
# MINIO_AGENT_GUIDES_BUCKET — Agent 指南文件上传(Flask minio_service)
MINIO_KB_IMAGE_BUCKET=image-hosting-service
MINIO_AGENT_GUIDES_BUCKET=agent-guides
# 硅基流动相关
GJL_API_KEY=sk-umfzicwjcvwampzblqczckkqojiscyybtaljzbsvpdwdvxlu
-1
View File
@@ -52,7 +52,6 @@ WECOM_NOTIFY_BASE_URL=http://ait.well-trust.com:8890/
# MINIO_ENDPOINT:hxops-kb-worker 容器内访问宿主机映射的 9000(勿用 127.0.0.1)
# 账号与 minio-app 的 MINIO_ROOT_USER / MINIO_ROOT_PASSWORD(及 DIFY_S3_ACCESS_KEY)保持一致
MINIO_ENDPOINT=host.docker.internal:9000
MINIO_BUCKET=image-hosting-service
MINIO_ACCESS_KEY=minio_testing_admin
MINIO_SECRET_KEY=M3CLE928P8GavJBFZPhJO3RIHVZSRYlDouOMabasojfAGBlx
MINIO_SECURE=false
+191 -11
View File
@@ -3,6 +3,7 @@ backend/app/api/knowledge_base.py
文件用途:知识库/数据清洗模块第一阶段 API
"""
import hashlib
import shutil
from datetime import datetime
from pathlib import Path
from posixpath import normpath
@@ -182,6 +183,85 @@ def _sanitize_relative_path(relative_path: str | None, fallback_name: str) -> st
safe_leaf = _safe_upload_filename(parts[-1] or fallback_name)
return '/'.join([*safe_parts, safe_leaf]).strip('/') or _safe_upload_filename(fallback_name)
def _build_path_upload_file_item(relative_path: str | None, original_name: str | None, **extra):
fallback_name = Path(str(original_name or relative_path or '')).name or 'uploaded_file'
normalized_path = _sanitize_relative_path(relative_path, fallback_name)
payload = {
'relative_path': normalized_path,
'original_name': Path(fallback_name).name or fallback_name,
'staged_path': None,
'size': None,
'sha256': None,
'status': 'queued',
'error': None,
'document_id': None,
'version_id': None,
}
payload.update(extra)
return payload
def _find_path_upload_file_item(files: list[dict], relative_path: str):
for item in files:
current = str(item.get('relative_path') or item.get('original_name') or '').strip()
if current == relative_path:
return item
return None
def _sync_path_upload_job_payload(job: KbJob, files: list[dict]):
payload = dict(job.payload_json or {})
result = dict(job.result_json or {})
selected_paths = []
for item in files:
relative_path = str(item.get('relative_path') or item.get('original_name') or '').strip()
if not relative_path:
continue
root = relative_path.split('/')[0]
if root and root not in selected_paths:
selected_paths.append(root)
payload['files'] = files
payload['total_files'] = len(files)
payload['staged_count'] = sum(1 for item in files if str(item.get('staged_path') or '').strip())
payload['selected_paths'] = selected_paths
result['total'] = len(files)
result['success'] = sum(1 for item in files if str(item.get('status') or '').lower() == 'success')
result['failed'] = sum(1 for item in files if str(item.get('status') or '').lower() == 'failed')
result['staged'] = payload['staged_count']
result['processed'] = result['success'] + result['failed']
job.payload_json = payload
job.result_json = result
return (payload, result)
def _remove_path_upload_staged_file(staged_path: str | None):
candidate = _resolve_storage_path(staged_path)
if not candidate or not candidate.exists():
return
try:
candidate.unlink()
except FileNotFoundError:
return
stop_dir = _kb_storage_root() / 'path_upload_jobs'
parent = candidate.parent
while parent.exists() and parent != stop_dir and stop_dir in parent.parents:
try:
parent.rmdir()
except OSError:
break
parent = parent.parent
def _soft_delete_document(document_id: int | None, user_id: int | None):
if not document_id:
return False
document = db.session.get(KbDocument, document_id)
if not document or document.is_deleted:
return False
try:
delete_document_from_dify(document.id)
except Exception:
pass
document.is_deleted = True
document.updated_by_id = user_id
return True
@knowledge_base_bp.route('/groups', methods=['GET'])
def list_groups():
user = _require_user()
@@ -303,7 +383,24 @@ def create_path_upload_job(group_id: int):
selected_paths = data.get('selected_paths') or []
if not isinstance(selected_paths, list):
selected_paths = []
job = KbJob(job_type='path_upload', status='draft', group_id=group_id, progress=0, message='等待上传路径文件到后台暂存区', payload_json={'total_files': total_files, 'selected_paths': selected_paths, 'staged_count': 0, 'files': []}, result_json={'total': total_files, 'success': 0, 'failed': 0, 'staged': 0}, created_by_id=getattr(current_user, 'id', None))
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:
total_files = len(files)
selected_paths = []
for item in files:
root = str(item.get('relative_path') or '').split('/')[0]
if root and root not in selected_paths:
selected_paths.append(root)
job = KbJob(job_type='path_upload', status='draft', group_id=group_id, progress=0, message='等待上传路径文件到后台暂存区', payload_json={'total_files': total_files, 'selected_paths': selected_paths, 'staged_count': 0, 'files': files}, result_json={'total': total_files, 'success': 0, 'failed': 0, 'staged': 0, 'processed': 0}, created_by_id=getattr(current_user, 'id', None))
db.session.add(job)
db.session.commit()
return (jsonify(_serialize_job(job)), 201)
@@ -329,19 +426,57 @@ def upload_path_job_file(job_id: int):
sha256, file_size = _save_upload(uploaded, target_path)
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
files.append({'relative_path': relative_path, 'original_name': fallback_name, 'staged_path': str(target_path), 'size': file_size, 'sha256': sha256, 'status': 'queued', 'error': None, 'document_id': None, 'version_id': None})
payload['files'] = files
payload['staged_count'] = len(files)
job.payload_json = payload
job.status = 'staging'
job.message = f"已暂存 {len(files)}/{payload.get('total_files') or len(files)} 个文件"
result = dict(job.result_json or {})
result['total'] = payload.get('total_files') or len(files)
result['staged'] = len(files)
entry = _find_path_upload_file_item(files, relative_path)
if entry is None:
entry = _build_path_upload_file_item(relative_path, fallback_name)
files.append(entry)
entry['original_name'] = fallback_name
entry['staged_path'] = str(target_path)
entry['size'] = file_size
entry['sha256'] = sha256
entry['status'] = 'queued'
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
db.session.commit()
return (jsonify(_serialize_job(job)), 201)
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files/fail', methods=['POST'])
def mark_path_job_file_failed(job_id: int):
current_user = _require_user()
job = db.session.get(KbJob, job_id)
if not job or job.job_type != 'path_upload':
raise NotFoundError('路径上传任务不存在')
data = request.get_json(silent=True) or {}
original_name = str(data.get('original_name') or '').strip() or None
relative_path_raw = str(data.get('relative_path') or '').strip()
try:
relative_path = _sanitize_relative_path(relative_path_raw, Path(original_name or relative_path_raw or 'uploaded_file').name or 'uploaded_file')
except ValueError as exc:
raise ValidationError(str(exc))
error_message = str(data.get('error') or '路径文件上传失败').strip() or '路径文件上传失败'
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
entry = _find_path_upload_file_item(files, relative_path)
if entry is None:
entry = _build_path_upload_file_item(relative_path, original_name)
files.append(entry)
if str(entry.get('staged_path') or '').strip() and str(entry.get('status') or '').lower() in ('queued', 'success', 'uploading'):
return jsonify(_serialize_job(job))
entry['status'] = 'failed'
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
db.session.commit()
return jsonify(_serialize_job(job))
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
def finalize_path_upload_job(job_id: int):
current_user = _require_user()
@@ -354,6 +489,17 @@ def finalize_path_upload_job(job_id: int):
files = list(payload.get('files') or [])
if not files:
raise ValidationError('当前没有可上传的文件')
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 = '当前批次没有成功暂存的文件'
db.session.commit()
return jsonify(_serialize_job(job))
job.status = 'queued'
job.progress = 0
job.message = '等待后台批量导入文档'
@@ -365,6 +511,40 @@ def finalize_path_upload_job(job_id: int):
refreshed = db.session.get(KbJob, job.id)
return jsonify(_serialize_job(refreshed))
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/files', methods=['DELETE'])
def delete_path_job_file(job_id: int):
current_user = _require_user()
job = db.session.get(KbJob, job_id)
if not job or job.job_type != 'path_upload':
raise NotFoundError('路径上传任务不存在')
relative_path_raw = str(request.args.get('relative_path') or '').strip()
if not relative_path_raw:
raise ValidationError('relative_path is required')
try:
relative_path = _sanitize_relative_path(relative_path_raw, Path(relative_path_raw).name or 'uploaded_file')
except ValueError as exc:
raise ValidationError(str(exc))
payload = dict(job.payload_json or {})
files = list(payload.get('files') or [])
entry = _find_path_upload_file_item(files, relative_path)
if entry is None:
raise NotFoundError('路径文件记录不存在')
_remove_path_upload_staged_file(entry.get('staged_path'))
document_deleted = _soft_delete_document(entry.get('document_id'), getattr(current_user, 'id', None))
files = [item for item in files if item is not entry]
_sync_path_upload_job_payload(job, files)
if not files:
job.status = 'cancelled'
job.progress = 100
job.finished_at = job.finished_at or datetime.utcnow()
job.message = '路径上传记录已清空'
job.error_message = None
staging_dir = _kb_storage_root() / 'path_upload_jobs' / f'job_{job.id:06d}'
if staging_dir.exists():
shutil.rmtree(staging_dir, ignore_errors=True)
db.session.commit()
return jsonify({'ok': True, 'job': _serialize_job(job), 'document_deleted': document_deleted, 'relative_path': relative_path})
@knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
def retry_failed_path_upload_job(job_id: int):
current_user = _require_user()
@@ -598,4 +778,4 @@ def run_job(job_id: int):
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)
return (jsonify(payload), 200 if success else 400)
+1 -1
View File
@@ -165,7 +165,7 @@ class Config:
MINIO_ACCESS_KEY = os.getenv('MINIO_ACCESS_KEY', 'minioadmin')
MINIO_SECRET_KEY = os.getenv('MINIO_SECRET_KEY', 'minioadmin')
MINIO_SECURE = os.getenv('MINIO_SECURE', 'false').lower() == 'true'
MINIO_BUCKET_NAME = os.getenv('MINIO_BUCKET_NAME', 'agent-guides')
MINIO_AGENT_GUIDES_BUCKET = os.getenv('MINIO_AGENT_GUIDES_BUCKET', 'agent-guides')
MINIO_PUBLIC_BASE_URL = os.getenv('MINIO_PUBLIC_BASE_URL', 'http://127.0.0.1:9000')
+1 -1
View File
@@ -16,7 +16,7 @@ class MinioService:
secret_key=cfg.MINIO_SECRET_KEY,
secure=cfg.MINIO_SECURE,
)
self.bucket_name = cfg.MINIO_BUCKET_NAME
self.bucket_name = cfg.MINIO_AGENT_GUIDES_BUCKET
self._ensure_bucket_exists()
def _ensure_bucket_exists(self):
+1 -1
View File
@@ -263,7 +263,7 @@ class _RemoteImageRewriter:
return None
raise RuntimeError("image-hosting disabled: MINIO_ENDPOINT is empty")
bucket_name = os.getenv("MINIO_BUCKET", "image-hosting-service")
bucket_name = os.getenv("MINIO_KB_IMAGE_BUCKET", "image-hosting-service")
access_key = os.getenv("MINIO_ACCESS_KEY", "admin")
secret_key = os.getenv("MINIO_SECRET_KEY", "difyai123456")
public_base = _normalize_public_base(
+8 -4
View File
@@ -44,9 +44,11 @@ services:
- KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker}
- KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2}
# kb-worker 自动回收长时间 running 的任务(秒)
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-300}
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900}
# LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测)
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
# LibreOffice 单次格式转换超时(秒)
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-120}
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600}
# 允许容器访问宿主机服务 (如数据库)
extra_hosts:
@@ -93,9 +95,11 @@ services:
- KB_TASK_EXECUTION_MODE=${KB_TASK_EXECUTION_MODE:-worker}
- KB_WORKER_POLL_SECONDS=${KB_WORKER_POLL_SECONDS:-2}
# kb-worker 自动回收长时间 running 的任务(秒)
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-300}
- KB_JOB_RUNNING_TIMEOUT_SECONDS=${KB_JOB_RUNNING_TIMEOUT_SECONDS:-900}
# LibreOffice 可执行文件路径(Linux 容器默认 /usr/bin/soffice,跳过 Windows 路径探测)
- EDKB_SOFFICE=${EDKB_SOFFICE:-/usr/bin/soffice}
# LibreOffice 单次格式转换超时(秒)
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-120}
- EDKB_SOFFICE_TIMEOUT_SEC=${EDKB_SOFFICE_TIMEOUT_SEC:-600}
extra_hosts:
- "host.docker.internal:host-gateway"
volumes:
+47 -3
View File
@@ -364,7 +364,11 @@ export const uploadKbDocumentVersion = async (
export const createKbPathUploadJob = async (
groupId: number,
payload: { total_files: number; selected_paths: string[] }
payload: {
total_files: number;
selected_paths: string[];
files?: Array<{ relative_path: string; original_name: string }>;
}
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try {
const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, {
@@ -383,7 +387,7 @@ export const uploadKbPathJobFile = async (
jobId: number | string,
file: File,
relativePath: string,
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try {
const formData = new FormData();
formData.append('file', file);
@@ -395,7 +399,31 @@ export const uploadKbPathJobFile = async (
});
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败') };
const err = e as BusinessError;
if (err.status === 413) {
return {
ok: false,
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
status: 413,
};
}
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败'), status: err.status };
}
};
export const markKbPathJobFileFailed = async (
jobId: number | string,
payload: { relative_path: string; original_name?: string; error: string }
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
try {
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files/fail`, {
method: 'POST',
...jsonAuth(),
body: JSON.stringify(payload),
});
return { ok: true, job };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '记录路径文件失败状态失败') };
}
};
@@ -430,6 +458,22 @@ export const retryFailedKbPathUploadJob = async (
}
};
export const deleteKbPathJobFile = async (
jobId: number | string,
relativePath: string,
): Promise<{ ok: boolean; error?: string; job?: KbJob; document_deleted?: boolean }> => {
try {
const query = new URLSearchParams({ relative_path: relativePath });
const result = await requestJson<{ ok: boolean; job: KbJob; document_deleted?: boolean }>(
`/api/kb/path-upload-jobs/${jobId}/files?${query.toString()}`,
{ method: 'DELETE', ...auth() }
);
return { ok: true, job: result.job, document_deleted: result.document_deleted };
} catch (e) {
return { ok: false, error: kbErrorMessage(e, '删除路径上传文件失败') };
}
};
export const syncKbDocumentToDify = async (
documentId: number
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
+1 -1
View File
@@ -1,5 +1,5 @@
export const config = {
appTitle: 'AI工作台',
appTitle: '和信AI智能工作台',
auth: {
// Login mode switch:
// - 'casdoor': submit username/password to backend Casdoor password-login API.
+8 -9
View File
@@ -718,13 +718,13 @@ const loadAgentGuides = async () => {
}
};
const showGuideSidebar = ref(false);
const showGuideSidebar = ref(true);
const openGuideModal = () => {
if (agentGuides.value.length > 0) {
activeGuideId.value = agentGuides.value[0].id;
showGuideModal.value = true;
showGuideSidebar.value = false; // 默认收起
showGuideSidebar.value = true; // 默认展开
}
};
const showDeleteConfirmDialog = ref(false);
@@ -2689,7 +2689,7 @@ const showChatRating = ref(false);
class="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-brand-700 bg-brand-100 border border-brand-300 rounded-lg hover:bg-brand-200 hover:border-brand-400 transition-all shadow-sm"
>
<BookOpen class="w-4 h-4" />
新手指南
学习之窗
</button>
</div>
<span v-if="currentAgent?.name === '人事规章'" class="block text-[11px] text-muted mt-1 truncate cursor-help">
@@ -2776,8 +2776,8 @@ const showChatRating = ref(false);
<!-- Bottom Icons -->
<div class="flex items-center justify-between text-muted relative" ref="userMenuRef">
<button @click="showUserDropdown = !showUserDropdown" class="flex h-8 w-8 items-center justify-center rounded-full bg-brand-600 text-sm font-bold text-white shadow-sm shadow-brand-500/20 hover:bg-brand-700 transition-colors">
{{ (currentUser?.username || 'I').charAt(0).toUpperCase() }}
<button @click="showUserDropdown = !showUserDropdown" class="flex h-10 min-w-[2.5rem] items-center justify-center rounded-full bg-brand-600 px-3 text-sm font-bold text-white shadow-sm shadow-brand-500/20 transition-colors hover:bg-brand-700">
退出
</button>
<!-- User Dropdown Menu -->
@@ -2827,7 +2827,7 @@ const showChatRating = ref(false);
class="flex items-center gap-1.5 px-3 py-1.5 text-xs font-bold text-brand-700 bg-brand-100 border border-brand-300 rounded-lg hover:bg-brand-200 hover:border-brand-400 transition-all shadow-sm ml-1"
>
<BookOpen class="w-4 h-4" />
新手指南
学习之窗
</button>
</div>
<div class="flex items-center gap-1">
@@ -3738,13 +3738,13 @@ const showChatRating = ref(false);
/>
<Teleport to="body">
<!-- 新手指南 Modal -->
<!-- 学习之窗 Modal -->
<div v-if="showGuideModal" class="fixed inset-0 z-[9999] flex items-center justify-center p-4 bg-black/50 backdrop-blur-sm">
<div class="bg-surface rounded-2xl shadow-xl w-full max-w-4xl overflow-hidden flex flex-col h-[85vh]">
<div class="px-6 py-4 border-b border-default flex justify-between items-center bg-surface shrink-0">
<h3 class="text-lg font-bold text-primary flex items-center gap-2">
<BookOpen class="w-5 h-5 text-brand-600" />
{{ currentAgent?.name }} - 新手指南
{{ currentAgent?.name }} - 学习之窗
</h3>
<div class="flex items-center gap-3">
<button @click="showGuideSidebar = !showGuideSidebar" class="flex items-center gap-1.5 px-3 py-1.5 text-sm font-medium text-brand-600 hover:text-brand-700 hover:bg-brand-50 rounded-lg transition-colors border border-transparent hover:border-brand-100">
@@ -3786,7 +3786,6 @@ const showChatRating = ref(false);
:key="'video-' + activeGuide.id"
:src="activeGuide.file_url || activeGuide.file_path"
controls
autoplay
class="w-full h-full object-contain bg-black"
></video>
<iframe
+172 -10
View File
@@ -1,4 +1,4 @@
<script setup lang="ts">
<script setup lang="ts">
import { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
@@ -8,6 +8,7 @@ import {
createKbGroup,
createKbDocument,
createKbPathUploadJob,
deleteKbPathJobFile,
deleteKbGroup,
deleteKbDocument,
finalizeKbPathUploadJob,
@@ -18,6 +19,7 @@ import {
getKbGroupFilesSafe,
getKbGroupsSafe,
getKbJobsSafe,
markKbPathJobFileFailed,
retryFailedKbPathUploadJob,
runKbJob,
syncKbDocumentToDify,
@@ -92,7 +94,9 @@ const pathUploadSelectedFiles = ref<Array<{ key: string; file: File; displayPath
const isPathUploadStaging = ref(false);
const pathUploadJobId = ref<number | string | null>(null);
const selectedPathUploadHistoryJobId = ref<number | string | null>(null);
const selectedPathUploadHistoryItemKeys = ref<string[]>([]);
const retryingPathUploadKey = ref('');
const deletingPathUploadBatch = ref(false);
const groupForm = ref({
name: '',
description: '',
@@ -168,6 +172,7 @@ type PathUploadTaskItem = {
status: PathUploadStatus;
error?: string;
documentId?: number;
retryable?: boolean;
startedAt?: string;
finishedAt?: string;
};
@@ -443,6 +448,17 @@ const selectedPathUploadHistoryJob = computed(() =>
|| latestPathUploadJob.value
|| null
);
const selectedPathUploadHistoryItems = computed(() =>
getPathUploadJobItems(selectedPathUploadHistoryJob.value)
);
const selectedPathUploadHistorySelectedItems = computed(() => {
const selectedKeySet = new Set(selectedPathUploadHistoryItemKeys.value);
return selectedPathUploadHistoryItems.value.filter((item) => selectedKeySet.has(item.key));
});
const isAllPathUploadHistoryItemsSelected = computed(() =>
selectedPathUploadHistoryItems.value.length > 0
&& selectedPathUploadHistoryItems.value.every((item) => selectedPathUploadHistoryItemKeys.value.includes(item.key))
);
const pathUploadSummary = computed(() => {
const task = pathUploadTask.value;
@@ -505,6 +521,9 @@ const loadJobs = async () => {
}
jobs.value = result.data;
applyPathUploadJob(latestPathUploadJob.value);
if (latestPathUploadJob.value && getPathUploadJobSummary(latestPathUploadJob.value).failed > 0) {
showPathUploadDetails.value = true;
}
if (selectedPathUploadHistoryJobId.value && !pathUploadHistoryJobs.value.some((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))) {
selectedPathUploadHistoryJobId.value = latestPathUploadJob.value?.id || null;
}
@@ -592,6 +611,7 @@ const getStatusLabel = (status?: string | null) => {
queued: '排队中',
running: '进行中',
success: '成功',
cancelled: '已取消',
};
return map[normalized] || status || '未知状态';
};
@@ -610,6 +630,9 @@ const getStatusBadgeClass = (status?: string | null) => {
if (normalized === 'failed') {
return 'border-rose-200 bg-rose-50 text-rose-700';
}
if (normalized === 'cancelled') {
return 'border-default bg-surface-soft text-secondary';
}
return 'border-default bg-surface-soft text-secondary';
};
@@ -900,19 +923,27 @@ const getPathUploadJobItems = (job: KbJob | null): PathUploadTaskItem[] => {
if (!job || job.job_type !== 'path_upload') return [];
const payload = job.payload_json || {};
const files = Array.isArray(payload.files) ? payload.files : [];
const failedCount = files.filter((item: any) => String(item?.status || '').toLowerCase() === 'failed').length;
return files.map((item: any, index: number) => ({
key: `${job.id}-${item.relative_path || item.original_name || index}`,
title: String(item.original_name || item.relative_path || `文件${index + 1}`),
displayPath: String(item.relative_path || item.original_name || ''),
rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status)) ? item.status : 'queued') as PathUploadStatus,
error: item.error || undefined,
error: item.error
|| (String(item.status || '').toLowerCase() === 'failed' && failedCount === 1
? (job.error_message || job.message || '上传失败')
: undefined),
documentId: item.document_id || undefined,
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
startedAt: undefined,
finishedAt: undefined,
}));
};
const hasRetryablePathUploadFailure = (job: KbJob | null) =>
getPathUploadJobItems(job).some((item) => item.retryable);
const getPathUploadJobSummary = (job: KbJob | null) => {
const items = getPathUploadJobItems(job);
const total = Number(job?.payload_json?.total_files || job?.result_json?.total || items.length || 0);
@@ -949,6 +980,7 @@ const applyPathUploadJob = (job: KbJob | null) => {
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status)) ? item.status : 'queued') as PathUploadStatus,
error: item.error || undefined,
documentId: item.document_id || undefined,
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
}))
: [];
@@ -974,6 +1006,23 @@ const openPathUploadHistoryModal = (jobId?: number | string | null) => {
const closePathUploadHistoryModal = () => {
showPathUploadHistoryModal.value = false;
selectedPathUploadHistoryJobId.value = null;
selectedPathUploadHistoryItemKeys.value = [];
};
const togglePathUploadHistoryItemSelection = (itemKey: string) => {
if (selectedPathUploadHistoryItemKeys.value.includes(itemKey)) {
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => key !== itemKey);
return;
}
selectedPathUploadHistoryItemKeys.value = [...selectedPathUploadHistoryItemKeys.value, itemKey];
};
const toggleSelectAllPathUploadHistoryItems = () => {
if (isAllPathUploadHistoryItemsSelected.value) {
selectedPathUploadHistoryItemKeys.value = [];
return;
}
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItems.value.map((item) => item.key);
};
const startPathUploadPolling = () => {
@@ -1008,6 +1057,10 @@ const handleConfirmPathUpload = async () => {
const createResult = await createKbPathUploadJob(selectedGroupId.value, {
total_files: pathUploadSelectedFiles.value.length,
selected_paths: selectedPathRoots.value,
files: pathUploadSelectedFiles.value.map((item) => ({
relative_path: item.displayPath,
original_name: item.file.name,
})),
});
if (!createResult.ok || !createResult.job) {
feedback.value = createResult.error || '创建上传路径任务失败';
@@ -1045,12 +1098,23 @@ const handleConfirmPathUpload = async () => {
}
const stageResult = await uploadKbPathJobFile(createResult.job.id, item.file, item.displayPath);
if (!stageResult.ok) {
const errorMessage = normalizeDuplicateDocumentError(stageResult.error || '路径文件暂存失败');
const failResult = await markKbPathJobFileFailed(createResult.job.id, {
relative_path: item.displayPath,
original_name: item.file.name,
error: errorMessage,
});
if (failResult.ok && failResult.job) {
applyPathUploadJob(failResult.job);
}
if (localItem) {
localItem.status = 'failed';
localItem.error = normalizeDuplicateDocumentError(stageResult.error || '路径文件暂存失败');
localItem.error = errorMessage;
}
if (!failResult.ok) {
pathUploadTask.value.failed += 1;
updatePathUploadFeedback();
}
pathUploadTask.value.failed += 1;
updatePathUploadFeedback();
continue;
}
if (localItem) {
@@ -1076,6 +1140,59 @@ const handleConfirmPathUpload = async () => {
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
};
const handleDeletePathUploadItem = async (job: KbJob | null, item: PathUploadTaskItem) => {
if (!job) return;
openDeleteConfirmDialog(`确认删除路径文件「${item.displayPath || item.title}」吗?`, async () => {
const result = await deleteKbPathJobFile(job.id, item.displayPath);
if (!result.ok) {
feedback.value = result.error || '删除路径上传文件失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.document_deleted ? '已删除路径记录,并同步删除对应文档' : '已删除路径记录';
feedbackType.value = 'success';
if (pathUploadTask.value.items.length <= 1) {
showPathUploadDetails.value = false;
}
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
});
};
const handleBatchDeletePathUploadItems = async () => {
const job = selectedPathUploadHistoryJob.value;
const items = selectedPathUploadHistorySelectedItems.value;
if (!job || !items.length) {
feedback.value = '请先选择要删除的文件';
feedbackType.value = 'error';
return;
}
openDeleteConfirmDialog(`确认批量删除已选中的 ${items.length} 条路径文件吗?`, async () => {
deletingPathUploadBatch.value = true;
let successCount = 0;
let failCount = 0;
const errors: string[] = [];
try {
for (const item of items) {
const result = await deleteKbPathJobFile(job.id, item.displayPath);
if (result.ok) {
successCount += 1;
continue;
}
failCount += 1;
errors.push(`${item.displayPath}: ${result.error || '删除失败'}`);
}
feedback.value = failCount
? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量删除完成:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
selectedPathUploadHistoryItemKeys.value = [];
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]);
} finally {
deletingPathUploadBatch.value = false;
}
});
};
const handleRetryFailedPathUpload = async (
job: KbJob | null,
relativePaths?: string[],
@@ -1440,6 +1557,14 @@ watch(selectedGroupId, (groupId) => {
applyPathUploadJob(latestPathUploadJob.value);
});
watch(selectedPathUploadHistoryJob, (job) => {
const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
if (!job) {
selectedPathUploadHistoryItemKeys.value = [];
}
});
onMounted(async () => {
await Promise.all([loadGroups(), loadJobs()]);
if (viewMode.value === 'group_detail') {
@@ -1764,7 +1889,7 @@ onUnmounted(() => {
查看历史
</button>
<button
v-if="latestPathUploadJob && getPathUploadJobSummary(latestPathUploadJob).failed > 0 && !pathUploadRunning"
v-if="latestPathUploadJob && hasRetryablePathUploadFailure(latestPathUploadJob) && !pathUploadRunning"
@click="handleRetryFailedPathUpload(latestPathUploadJob)"
:disabled="retryingPathUploadKey === `${latestPathUploadJob.id}:all`"
class="inline-flex items-center rounded-xl border border-rose-200 px-3 py-1.5 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
@@ -1798,13 +1923,20 @@ onUnmounted(() => {
{{ item.status === 'success' ? '已上传' : item.status === 'failed' ? '失败' : item.status === 'uploading' ? '上传中' : '待上传' }}
</span>
<button
v-if="item.status === 'failed' && latestPathUploadJob && !pathUploadRunning"
v-if="item.retryable && latestPathUploadJob && !pathUploadRunning"
@click="handleRetryFailedPathUpload(latestPathUploadJob, [item.displayPath])"
:disabled="retryingPathUploadKey === `${latestPathUploadJob.id}:${item.displayPath}`"
class="inline-flex items-center rounded-xl border border-rose-200 px-2.5 py-1 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
{{ retryingPathUploadKey === `${latestPathUploadJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
</button>
<button
v-if="latestPathUploadJob && !pathUploadRunning"
@click="handleDeletePathUploadItem(latestPathUploadJob, item)"
class="inline-flex items-center rounded-xl border border-default px-2.5 py-1 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
删除
</button>
</div>
</div>
</div>
@@ -2532,7 +2664,22 @@ onUnmounted(() => {
{{ getStatusLabel(selectedPathUploadHistoryJob.status) }}
</span>
<button
v-if="getPathUploadJobSummary(selectedPathUploadHistoryJob).failed > 0 && !pathUploadRunning"
v-if="selectedPathUploadHistoryItems.length && !pathUploadRunning"
@click="toggleSelectAllPathUploadHistoryItems"
class="inline-flex items-center rounded-xl border border-default px-3 py-2 text-xs font-medium text-secondary transition-colors hover:bg-surface-soft hover-surface-soft"
>
{{ isAllPathUploadHistoryItemsSelected ? '取消全选' : '全选' }}
</button>
<button
v-if="!pathUploadRunning"
@click="handleBatchDeletePathUploadItems"
:disabled="!selectedPathUploadHistorySelectedItems.length || deletingPathUploadBatch"
class="inline-flex items-center rounded-xl border border-default px-3 py-2 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft disabled:cursor-not-allowed disabled:opacity-60"
>
{{ deletingPathUploadBatch ? '删除中...' : `批量删除${selectedPathUploadHistorySelectedItems.length ? ` (${selectedPathUploadHistorySelectedItems.length})` : ''}` }}
</button>
<button
v-if="hasRetryablePathUploadFailure(selectedPathUploadHistoryJob) && !pathUploadRunning"
@click="handleRetryFailedPathUpload(selectedPathUploadHistoryJob)"
:disabled="retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:all`"
class="inline-flex items-center rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
@@ -2551,10 +2698,18 @@ onUnmounted(() => {
<div class="mt-4 max-h-[50vh] space-y-2 overflow-y-auto pr-1">
<div
v-for="item in getPathUploadJobItems(selectedPathUploadHistoryJob)"
v-for="item in selectedPathUploadHistoryItems"
:key="item.key"
class="flex flex-wrap items-start justify-between gap-3 rounded-2xl border border-default px-4 py-3 "
>
<label class="flex items-center pt-1">
<input
type="checkbox"
:checked="selectedPathUploadHistoryItemKeys.includes(item.key)"
@change="togglePathUploadHistoryItemSelection(item.key)"
class="h-4 w-4 rounded border-default text-brand-600 focus:ring-brand-500"
/>
</label>
<div class="min-w-0 flex-1">
<div class="truncate text-sm font-medium text-primary">{{ item.title }}</div>
<div class="mt-1 truncate text-xs text-muted">{{ item.displayPath }}</div>
@@ -2574,13 +2729,20 @@ onUnmounted(() => {
{{ item.status === 'success' ? '已上传' : item.status === 'failed' ? '失败' : item.status === 'uploading' ? '上传中' : '待上传' }}
</span>
<button
v-if="item.status === 'failed' && !pathUploadRunning"
v-if="item.retryable && !pathUploadRunning"
@click="handleRetryFailedPathUpload(selectedPathUploadHistoryJob, [item.displayPath])"
:disabled="retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:${item.displayPath}`"
class="inline-flex items-center rounded-xl border border-rose-200 px-2.5 py-1 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50 disabled:cursor-not-allowed disabled:opacity-60 border-rose-200 hover:bg-rose-50"
>
{{ retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
</button>
<button
v-if="!pathUploadRunning"
@click="handleDeletePathUploadItem(selectedPathUploadHistoryJob, item)"
class="inline-flex items-center rounded-xl border border-default px-2.5 py-1 text-xs font-medium text-muted transition-colors hover:bg-surface-soft hover-surface-soft"
>
删除
</button>
</div>
</div>
</div>
+1 -1
View File
@@ -1515,7 +1515,7 @@ onBeforeUnmount(() => {
<div v-else>
<header v-if="isMobile" class="sticky top-0 z-30 flex items-center justify-between border-b border-default bg-surface px-4 py-2.5">
<div class="flex items-center gap-2">
<button @click="navigateToGeneralChat" class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20" :title="$t('workspace.nav.backToChat')">AI</button>
<button @click="navigateToGeneralChat" class="flex h-7 w-7 items-center justify-center rounded-lg bg-gradient-to-br from-brand-500 via-brand-600 to-purple-600 text-xs font-bold text-white shadow-sm shadow-brand-500/20" :title="$t('workspace.nav.backToChat')">返</button>
<span class="text-sm font-semibold text-primary">{{ mobileTabTitle }}</span>
</div>
</header>