fix(kb知识库):知识库批量上传文件不错原因及删除报错优化

This commit is contained in:
runny committed 2026-06-05 09:52:05 +08:00
1 parent e23da3f170
commit eab7929270
3 files changed
+409 -23

No files matched your search

+190 -10
View File
@@ -3,6 +3,7 @@ backend/app/api/knowledge_base.py
文件用途:知识库/数据清洗模块第一阶段 API 文件用途:知识库/数据清洗模块第一阶段 API
""" """
import hashlib import hashlib
import shutil
from datetime import datetime from datetime import datetime
from pathlib import Path from pathlib import Path
from posixpath import normpath 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) safe_leaf = _safe_upload_filename(parts[-1] or fallback_name)
return '/'.join([*safe_parts, safe_leaf]).strip('/') or _safe_upload_filename(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']) @knowledge_base_bp.route('/groups', methods=['GET'])
def list_groups(): def list_groups():
user = _require_user() user = _require_user()
@@ -303,7 +383,24 @@ def create_path_upload_job(group_id: int):
selected_paths = data.get('selected_paths') or [] selected_paths = data.get('selected_paths') or []
if not isinstance(selected_paths, list): if not isinstance(selected_paths, list):
selected_paths = [] 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.add(job)
db.session.commit() db.session.commit()
return (jsonify(_serialize_job(job)), 201) 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) sha256, file_size = _save_upload(uploaded, target_path)
payload = dict(job.payload_json or {}) payload = dict(job.payload_json or {})
files = list(payload.get('files') 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}) entry = _find_path_upload_file_item(files, relative_path)
payload['files'] = files if entry is None:
payload['staged_count'] = len(files) entry = _build_path_upload_file_item(relative_path, fallback_name)
job.payload_json = payload files.append(entry)
job.status = 'staging' entry['original_name'] = fallback_name
job.message = f"已暂存 {len(files)}/{payload.get('total_files') or len(files)} 个文件" entry['staged_path'] = str(target_path)
result = dict(job.result_json or {}) entry['size'] = file_size
result['total'] = payload.get('total_files') or len(files) entry['sha256'] = sha256
result['staged'] = len(files) 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 job.result_json = result
db.session.commit() db.session.commit()
return (jsonify(_serialize_job(job)), 201) 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']) @knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/finalize', methods=['POST'])
def finalize_path_upload_job(job_id: int): def finalize_path_upload_job(job_id: int):
current_user = _require_user() current_user = _require_user()
@@ -354,6 +489,17 @@ def finalize_path_upload_job(job_id: int):
files = list(payload.get('files') or []) files = list(payload.get('files') or [])
if not files: if not files:
raise ValidationError('当前没有可上传的文件') 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.status = 'queued'
job.progress = 0 job.progress = 0
job.message = '等待后台批量导入文档' job.message = '等待后台批量导入文档'
@@ -365,6 +511,40 @@ def finalize_path_upload_job(job_id: int):
refreshed = db.session.get(KbJob, job.id) refreshed = db.session.get(KbJob, job.id)
return jsonify(_serialize_job(refreshed)) 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']) @knowledge_base_bp.route('/path-upload-jobs/<int:job_id>/retry-failed', methods=['POST'])
def retry_failed_path_upload_job(job_id: int): def retry_failed_path_upload_job(job_id: int):
current_user = _require_user() current_user = _require_user()
+47 -3
View File
@@ -364,7 +364,11 @@ export const uploadKbDocumentVersion = async (
export const createKbPathUploadJob = async ( export const createKbPathUploadJob = async (
groupId: number, 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 }> => { ): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try { try {
const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, { const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, {
@@ -383,7 +387,7 @@ export const uploadKbPathJobFile = async (
jobId: number | string, jobId: number | string,
file: File, file: File,
relativePath: string, relativePath: string,
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => { ): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
try { try {
const formData = new FormData(); const formData = new FormData();
formData.append('file', file); formData.append('file', file);
@@ -395,7 +399,31 @@ export const uploadKbPathJobFile = async (
}); });
return { ok: true, job }; return { ok: true, job };
} catch (e) { } 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 ( export const syncKbDocumentToDify = async (
documentId: number documentId: number
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => { ): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
+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 { computed, onMounted, onUnmounted, ref, watch } from 'vue';
import { useRouter } from 'vue-router'; import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n'; import { useI18n } from 'vue-i18n';
@@ -8,6 +8,7 @@ import {
createKbGroup, createKbGroup,
createKbDocument, createKbDocument,
createKbPathUploadJob, createKbPathUploadJob,
deleteKbPathJobFile,
deleteKbGroup, deleteKbGroup,
deleteKbDocument, deleteKbDocument,
finalizeKbPathUploadJob, finalizeKbPathUploadJob,
@@ -18,6 +19,7 @@ import {
getKbGroupFilesSafe, getKbGroupFilesSafe,
getKbGroupsSafe, getKbGroupsSafe,
getKbJobsSafe, getKbJobsSafe,
markKbPathJobFileFailed,
retryFailedKbPathUploadJob, retryFailedKbPathUploadJob,
runKbJob, runKbJob,
syncKbDocumentToDify, syncKbDocumentToDify,
@@ -92,7 +94,9 @@ const pathUploadSelectedFiles = ref<Array<{ key: string; file: File; displayPath
const isPathUploadStaging = ref(false); const isPathUploadStaging = ref(false);
const pathUploadJobId = ref<number | string | null>(null); const pathUploadJobId = ref<number | string | null>(null);
const selectedPathUploadHistoryJobId = ref<number | string | null>(null); const selectedPathUploadHistoryJobId = ref<number | string | null>(null);
const selectedPathUploadHistoryItemKeys = ref<string[]>([]);
const retryingPathUploadKey = ref(''); const retryingPathUploadKey = ref('');
const deletingPathUploadBatch = ref(false);
const groupForm = ref({ const groupForm = ref({
name: '', name: '',
description: '', description: '',
@@ -168,6 +172,7 @@ type PathUploadTaskItem = {
status: PathUploadStatus; status: PathUploadStatus;
error?: string; error?: string;
documentId?: number; documentId?: number;
retryable?: boolean;
startedAt?: string; startedAt?: string;
finishedAt?: string; finishedAt?: string;
}; };
@@ -443,6 +448,17 @@ const selectedPathUploadHistoryJob = computed(() =>
|| latestPathUploadJob.value || latestPathUploadJob.value
|| null || 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 pathUploadSummary = computed(() => {
const task = pathUploadTask.value; const task = pathUploadTask.value;
@@ -505,6 +521,9 @@ const loadJobs = async () => {
} }
jobs.value = result.data; jobs.value = result.data;
applyPathUploadJob(latestPathUploadJob.value); 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))) { if (selectedPathUploadHistoryJobId.value && !pathUploadHistoryJobs.value.some((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))) {
selectedPathUploadHistoryJobId.value = latestPathUploadJob.value?.id || null; selectedPathUploadHistoryJobId.value = latestPathUploadJob.value?.id || null;
} }
@@ -592,6 +611,7 @@ const getStatusLabel = (status?: string | null) => {
queued: '排队中', queued: '排队中',
running: '进行中', running: '进行中',
success: '成功', success: '成功',
cancelled: '已取消',
}; };
return map[normalized] || status || '未知状态'; return map[normalized] || status || '未知状态';
}; };
@@ -610,6 +630,9 @@ const getStatusBadgeClass = (status?: string | null) => {
if (normalized === 'failed') { if (normalized === 'failed') {
return 'border-rose-200 bg-rose-50 text-rose-700'; 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'; 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 []; if (!job || job.job_type !== 'path_upload') return [];
const payload = job.payload_json || {}; const payload = job.payload_json || {};
const files = Array.isArray(payload.files) ? payload.files : []; 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) => ({ return files.map((item: any, index: number) => ({
key: `${job.id}-${item.relative_path || item.original_name || index}`, key: `${job.id}-${item.relative_path || item.original_name || index}`,
title: String(item.original_name || item.relative_path || `文件${index + 1}`), title: String(item.original_name || item.relative_path || `文件${index + 1}`),
displayPath: String(item.relative_path || item.original_name || ''), displayPath: String(item.relative_path || item.original_name || ''),
rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录', rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status)) ? item.status : 'queued') as PathUploadStatus, 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, documentId: item.document_id || undefined,
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
startedAt: undefined, startedAt: undefined,
finishedAt: undefined, finishedAt: undefined,
})); }));
}; };
const hasRetryablePathUploadFailure = (job: KbJob | null) =>
getPathUploadJobItems(job).some((item) => item.retryable);
const getPathUploadJobSummary = (job: KbJob | null) => { const getPathUploadJobSummary = (job: KbJob | null) => {
const items = getPathUploadJobItems(job); const items = getPathUploadJobItems(job);
const total = Number(job?.payload_json?.total_files || job?.result_json?.total || items.length || 0); 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, status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status)) ? item.status : 'queued') as PathUploadStatus,
error: item.error || undefined, error: item.error || undefined,
documentId: item.document_id || 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 = () => { const closePathUploadHistoryModal = () => {
showPathUploadHistoryModal.value = false; showPathUploadHistoryModal.value = false;
selectedPathUploadHistoryJobId.value = null; 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 = () => { const startPathUploadPolling = () => {
@@ -1008,6 +1057,10 @@ const handleConfirmPathUpload = async () => {
const createResult = await createKbPathUploadJob(selectedGroupId.value, { const createResult = await createKbPathUploadJob(selectedGroupId.value, {
total_files: pathUploadSelectedFiles.value.length, total_files: pathUploadSelectedFiles.value.length,
selected_paths: selectedPathRoots.value, selected_paths: selectedPathRoots.value,
files: pathUploadSelectedFiles.value.map((item) => ({
relative_path: item.displayPath,
original_name: item.file.name,
})),
}); });
if (!createResult.ok || !createResult.job) { if (!createResult.ok || !createResult.job) {
feedback.value = createResult.error || '创建上传路径任务失败'; feedback.value = createResult.error || '创建上传路径任务失败';
@@ -1045,12 +1098,23 @@ const handleConfirmPathUpload = async () => {
} }
const stageResult = await uploadKbPathJobFile(createResult.job.id, item.file, item.displayPath); const stageResult = await uploadKbPathJobFile(createResult.job.id, item.file, item.displayPath);
if (!stageResult.ok) { 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) { if (localItem) {
localItem.status = 'failed'; 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; continue;
} }
if (localItem) { if (localItem) {
@@ -1076,6 +1140,59 @@ const handleConfirmPathUpload = async () => {
await Promise.all([loadJobs(), loadDocuments(selectedGroupId.value), loadGroups()]); 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 ( const handleRetryFailedPathUpload = async (
job: KbJob | null, job: KbJob | null,
relativePaths?: string[], relativePaths?: string[],
@@ -1440,6 +1557,14 @@ watch(selectedGroupId, (groupId) => {
applyPathUploadJob(latestPathUploadJob.value); 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 () => { onMounted(async () => {
await Promise.all([loadGroups(), loadJobs()]); await Promise.all([loadGroups(), loadJobs()]);
if (viewMode.value === 'group_detail') { if (viewMode.value === 'group_detail') {
@@ -1764,7 +1889,7 @@ onUnmounted(() => {
查看历史 查看历史
</button> </button>
<button <button
v-if="latestPathUploadJob && getPathUploadJobSummary(latestPathUploadJob).failed > 0 && !pathUploadRunning" v-if="latestPathUploadJob && hasRetryablePathUploadFailure(latestPathUploadJob) && !pathUploadRunning"
@click="handleRetryFailedPathUpload(latestPathUploadJob)" @click="handleRetryFailedPathUpload(latestPathUploadJob)"
:disabled="retryingPathUploadKey === `${latestPathUploadJob.id}:all`" :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" 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' ? '上传中' : '待上传' }} {{ item.status === 'success' ? '已上传' : item.status === 'failed' ? '失败' : item.status === 'uploading' ? '上传中' : '待上传' }}
</span> </span>
<button <button
v-if="item.status === 'failed' && latestPathUploadJob && !pathUploadRunning" v-if="item.retryable && latestPathUploadJob && !pathUploadRunning"
@click="handleRetryFailedPathUpload(latestPathUploadJob, [item.displayPath])" @click="handleRetryFailedPathUpload(latestPathUploadJob, [item.displayPath])"
:disabled="retryingPathUploadKey === `${latestPathUploadJob.id}:${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" 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}` ? '处理中...' : '重试' }} {{ retryingPathUploadKey === `${latestPathUploadJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
</button> </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> </div>
</div> </div>
@@ -2532,7 +2664,22 @@ onUnmounted(() => {
{{ getStatusLabel(selectedPathUploadHistoryJob.status) }} {{ getStatusLabel(selectedPathUploadHistoryJob.status) }}
</span> </span>
<button <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)" @click="handleRetryFailedPathUpload(selectedPathUploadHistoryJob)"
:disabled="retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:all`" :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" 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 class="mt-4 max-h-[50vh] space-y-2 overflow-y-auto pr-1">
<div <div
v-for="item in getPathUploadJobItems(selectedPathUploadHistoryJob)" v-for="item in selectedPathUploadHistoryItems"
:key="item.key" :key="item.key"
class="flex flex-wrap items-start justify-between gap-3 rounded-2xl border border-default px-4 py-3 " 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="min-w-0 flex-1">
<div class="truncate text-sm font-medium text-primary">{{ item.title }}</div> <div class="truncate text-sm font-medium text-primary">{{ item.title }}</div>
<div class="mt-1 truncate text-xs text-muted">{{ item.displayPath }}</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' ? '上传中' : '待上传' }} {{ item.status === 'success' ? '已上传' : item.status === 'failed' ? '失败' : item.status === 'uploading' ? '上传中' : '待上传' }}
</span> </span>
<button <button
v-if="item.status === 'failed' && !pathUploadRunning" v-if="item.retryable && !pathUploadRunning"
@click="handleRetryFailedPathUpload(selectedPathUploadHistoryJob, [item.displayPath])" @click="handleRetryFailedPathUpload(selectedPathUploadHistoryJob, [item.displayPath])"
:disabled="retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:${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" 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}` ? '处理中...' : '重试' }} {{ retryingPathUploadKey === `${selectedPathUploadHistoryJob.id}:${item.displayPath}` ? '处理中...' : '重试' }}
</button> </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> </div>
</div> </div>