perf(kb):知识库数据清洗同步改异步优化;chat中查假期请假agent入口优化
This commit is contained in:
1 parent
61ebb46c0f
commit
c3b63df2f5
11 files changed
+839
-171
No files matched your search
+35
-7
@@ -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 失败') };
|
||||
}
|
||||
|
||||
@@ -702,6 +702,8 @@ 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()));
|
||||
|
||||
const agentGuides = ref<any[]>([]);
|
||||
const showGuideModal = ref(false);
|
||||
@@ -1825,6 +1827,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 +2147,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;
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
@@ -178,8 +177,9 @@ type PathUploadTaskItem = {
|
||||
};
|
||||
|
||||
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 pathUploadTask = ref<{
|
||||
running: boolean;
|
||||
groupId: number | null;
|
||||
@@ -221,6 +221,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 +276,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 +288,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 +315,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 +335,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 {
|
||||
@@ -356,6 +401,14 @@ 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 +476,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 +546,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,6 +645,13 @@ 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);
|
||||
@@ -527,7 +691,7 @@ 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();
|
||||
@@ -912,6 +1076,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,7 +1196,7 @@ const toggleSelectAllPathUploadHistoryItems = () => {
|
||||
const startPathUploadPolling = () => {
|
||||
stopPathUploadPollTimer();
|
||||
pathUploadPollTimer = window.setInterval(() => {
|
||||
if (!pathUploadRunning.value) {
|
||||
if (!kbJobPollingActive.value) {
|
||||
stopPathUploadPollTimer();
|
||||
return;
|
||||
}
|
||||
@@ -1068,73 +1236,96 @@ 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), 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()]);
|
||||
@@ -1262,23 +1453,60 @@ 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';
|
||||
if (successCount > 0) {
|
||||
startPathUploadPolling();
|
||||
}
|
||||
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
|
||||
} 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 Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
|
||||
} finally {
|
||||
batchSubmitting.value = false;
|
||||
@@ -1336,20 +1564,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,8 +1580,9 @@ 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()]);
|
||||
if (selectedDocumentId.value) {
|
||||
@@ -1398,8 +1622,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,9 +1668,12 @@ 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 = '';
|
||||
@@ -1477,8 +1705,9 @@ const handleSyncDocument = async (documentId: number) => {
|
||||
return;
|
||||
}
|
||||
|
||||
feedback.value = result.run_result || '已同步到 Dify';
|
||||
feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
|
||||
feedbackType.value = 'success';
|
||||
startPathUploadPolling();
|
||||
await loadDocuments(selectedGroupId.value);
|
||||
await loadJobs();
|
||||
selectedDocumentId.value = documentId;
|
||||
@@ -1803,6 +2032,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 +2150,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"
|
||||
@@ -2718,15 +2950,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"
|
||||
|
||||
Reference in new issue
Block a user