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
+410 -24

No files matched your search

+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>