refactor(frontend): 重构前端第三版

This commit is contained in:
sophie committed 2026-06-11 20:11:51 +08:00
1 parent bf32f8b954
commit dc141d19a2
49 files changed
+5333 -4234

No files matched your search

@@ -0,0 +1,23 @@
/**
* features/kb/composables/kb-workspace/kb-workspace.bridge.ts
* 子 composable 间的延迟绑定:先建 pathUpload,再注入 data 加载函数,打破循环依赖。
*/
import type { LoadListOptions } from '../../types/kb-workspace.types';
export interface KbWorkspaceDataBridge {
loadGroups: (options?: LoadListOptions) => Promise<void>;
loadJobs: () => Promise<void>;
loadDocuments: (groupId: number | null, options?: LoadListOptions) => Promise<void>;
refreshWorkflowStatusOnly: () => Promise<void>;
}
/** 创建可后续 Object.assign 填充的桥接对象 */
export function createKbWorkspaceDataBridge(): KbWorkspaceDataBridge {
const noop = async () => {};
return {
loadGroups: noop,
loadJobs: noop,
loadDocuments: noop,
refreshWorkflowStatusOnly: noop,
};
}
@@ -0,0 +1,211 @@
/**
* features/kb/composables/kb-workspace/kb-workspace.state.ts
* 作业面共享响应式状态:各子 composable 通过同一 state 读写,避免重复 ref。
*/
import { computed, ref } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from 'vue-i18n';
import { getStoredAuthUser } from '@/shared/utils/auth';
import type {
KbDocumentItem,
KbJob,
KbDocumentVersionItem,
KbSyncRecordItem,
KbGroup,
} from '../../api/kb.api';
import {
PATH_UPLOAD_BATCH_SIZE,
type PathUploadTaskItem,
} from '../../types/kb-workspace.types';
export interface CreateKbWorkspaceStateOptions {
embedded?: boolean;
}
/** 作业面全部 ref 与删除确认辅助逻辑 */
export function createKbWorkspaceState(options: CreateKbWorkspaceStateOptions = {}) {
const embedded = options.embedded ?? false;
const router = useRouter();
const { t } = useI18n({ useScope: 'global' });
const isKbAdmin = computed(
() => String(getStoredAuthUser()?.role || '').trim().toLowerCase() === 'admin',
);
const isLoading = ref(true);
const isDocumentsLoading = ref(false);
const isSubmitting = ref(false);
const isRecordLoading = ref(false);
const groups = ref<KbGroup[]>([]);
const documents = ref<KbDocumentItem[]>([]);
const jobs = ref<KbJob[]>([]);
const selectedGroupId = ref<number | null>(null);
const selectedDocumentId = ref<number | null>(null);
const activeUploadDocumentId = ref<number | null>(null);
const syncingDocumentId = ref<number | null>(null);
const selectedDocumentVersions = ref<KbDocumentVersionItem[]>([]);
const selectedDocumentSyncRecords = ref<KbSyncRecordItem[]>([]);
const feedback = ref('');
const feedbackType = ref<'success' | 'error' | ''>('');
const viewMode = ref<'group_overview' | 'group_detail'>(embedded ? 'group_overview' : 'group_detail');
const showMarkdownModal = ref(false);
const showRecordModal = ref(false);
const showSourceInfoModal = ref(false);
const showFailureModal = ref(false);
const showPathUploadModal = ref(false);
const showPathUploadHistoryModal = ref(false);
const showDeleteConfirmDialog = ref(false);
const deleteConfirmMessage = ref('');
let pendingDeleteAction: (() => Promise<void> | void) | null = null;
const showPathUploadDetails = ref(false);
const fileInputRef = ref<HTMLInputElement | null>(null);
const pathUploadInputRef = ref<HTMLInputElement | null>(null);
const markdownDocumentId = ref<number | null>(null);
const sourceInfoDocumentId = ref<number | null>(null);
const markdownContent = ref('');
const markdownKind = ref<'markdown' | 'preview'>('markdown');
const markdownVersionLabel = ref('');
const markdownError = ref('');
const isMarkdownLoading = ref(false);
const isMarkdownSaving = ref(false);
const isSourceInfoLoading = ref(false);
const openingSourceVersionId = ref<number | null>(null);
const failureModalType = ref<'upload' | 'clean' | 'sync' | null>(null);
const failureModalPage = ref(1);
const retryingFailureKey = ref('');
const documentStageFilter = ref<'all' | 'upload' | 'clean' | 'sync'>('all');
const documentListPage = ref(1);
const documentListPageSize = ref(20);
const documentKeyword = ref('');
const batchSubmitting = ref(false);
const selectedDocumentIds = ref<number[]>([]);
const pathUploadDraftText = ref('');
const pathUploadSelectedFiles = ref<Array<{ key: string; file: File; displayPath: string; rootLabel: string }>>([]);
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 sourceInfoVersions = ref<KbDocumentVersionItem[]>([]);
const pathUploadTask = ref<{
running: boolean;
groupId: number | null;
total: number;
success: number;
failed: number;
currentFile: string;
batchSize: number;
items: PathUploadTaskItem[];
}>({
running: false,
groupId: null,
total: 0,
success: 0,
failed: 0,
currentFile: '',
batchSize: PATH_UPLOAD_BATCH_SIZE,
items: [],
});
const openDeleteConfirmDialog = (
message: string,
onConfirm: () => Promise<void> | void,
) => {
deleteConfirmMessage.value = message;
pendingDeleteAction = onConfirm;
showDeleteConfirmDialog.value = true;
};
const closeDeleteConfirmDialog = () => {
showDeleteConfirmDialog.value = false;
deleteConfirmMessage.value = '';
pendingDeleteAction = null;
};
const handleDeleteConfirm = async () => {
if (!pendingDeleteAction) return;
try {
await pendingDeleteAction();
} catch (err) {
console.error('[deleteConfirm]', err);
feedback.value = String(err) || '操作失败';
feedbackType.value = 'error';
}
closeDeleteConfirmDialog();
};
return {
embedded,
router,
t,
isKbAdmin,
isLoading,
isDocumentsLoading,
isSubmitting,
isRecordLoading,
groups,
documents,
jobs,
selectedGroupId,
selectedDocumentId,
activeUploadDocumentId,
syncingDocumentId,
selectedDocumentVersions,
selectedDocumentSyncRecords,
feedback,
feedbackType,
viewMode,
showMarkdownModal,
showRecordModal,
showSourceInfoModal,
showFailureModal,
showPathUploadModal,
showPathUploadHistoryModal,
showDeleteConfirmDialog,
deleteConfirmMessage,
showPathUploadDetails,
fileInputRef,
pathUploadInputRef,
markdownDocumentId,
sourceInfoDocumentId,
markdownContent,
markdownKind,
markdownVersionLabel,
markdownError,
isMarkdownLoading,
isMarkdownSaving,
isSourceInfoLoading,
openingSourceVersionId,
failureModalType,
failureModalPage,
retryingFailureKey,
documentStageFilter,
documentListPage,
documentListPageSize,
documentKeyword,
batchSubmitting,
selectedDocumentIds,
pathUploadDraftText,
pathUploadSelectedFiles,
isPathUploadStaging,
pathUploadJobId,
selectedPathUploadHistoryJobId,
selectedPathUploadHistoryItemKeys,
retryingPathUploadKey,
deletingPathUploadBatch,
sourceInfoVersions,
pathUploadTask,
openDeleteConfirmDialog,
closeDeleteConfirmDialog,
handleDeleteConfirm,
};
}
export type KbWorkspaceState = ReturnType<typeof createKbWorkspaceState>;
@@ -0,0 +1,408 @@
/**
* features/kb/composables/kb-workspace/useKbWorkspaceComputed.ts
* 作业面派生状态:筛选分页、工作流徽标、失败列表、路径上传批次视图。
*/
import { computed } from 'vue';
import type { KbDocumentItem } from '../../api/kb.api';
import {
FAILURE_PAGE_SIZE,
type FailureModalItem,
type PathUploadTaskItem,
} from '../../types/kb-workspace.types';
import {
getDocumentDisplayDescription,
getDocumentDisplayTitle,
getStatusBadgeClass,
} from '../../utils/kb-display.utils';
import {
getPathUploadJobItems,
getPathUploadJobPriority,
} from '../../utils/kb-path-upload.utils';
import {
buildGetLatestJobForDocument,
getDocumentWorkflowState,
getMarkdownUnavailableMessage,
getWorkflowBadges,
} from '../../utils/kb-workflow.utils';
import type { KbWorkspaceState } from './kb-workspace.state';
export function useKbWorkspaceComputed(state: KbWorkspaceState) {
const {
documents,
jobs,
selectedGroupId,
selectedDocumentId,
sourceInfoDocumentId,
markdownDocumentId,
failureModalType,
failureModalPage,
documentStageFilter,
documentListPage,
documentListPageSize,
documentKeyword,
selectedDocumentIds,
pathUploadTask,
pathUploadSelectedFiles,
isPathUploadStaging,
selectedPathUploadHistoryJobId,
selectedPathUploadHistoryItemKeys,
groups,
} = state;
const selectedDocument = computed(() =>
documents.value.find((item) => item.id === selectedDocumentId.value) || null,
);
const sourceInfoDocument = computed(() =>
documents.value.find((item) => item.id === sourceInfoDocumentId.value) || null,
);
const selectedGroup = computed(() =>
groups.value.find((item) => item.id === selectedGroupId.value) || null,
);
const markdownModalTitle = computed(() => {
const current = documents.value.find((item) => item.id === markdownDocumentId.value);
return current ? getDocumentDisplayTitle(current) : 'Markdown 编辑器';
});
const activeGroupJobs = computed(() =>
jobs.value.filter((item) => item.group_id === selectedGroupId.value),
);
const getLatestJobForDocument = buildGetLatestJobForDocument(() => activeGroupJobs.value);
const resolveWorkflowState = (doc: KbDocumentItem) =>
getDocumentWorkflowState(doc, getLatestJobForDocument);
const getWorkflowBadgesForDoc = (doc: KbDocumentItem) =>
getWorkflowBadges(doc, getLatestJobForDocument);
const getMarkdownUnavailableMessageForDoc = (
doc: KbDocumentItem,
fallback?: string | null,
) => getMarkdownUnavailableMessage(doc, getLatestJobForDocument, fallback);
const groupSummaryItems = computed(() => {
const docItems = documents.value;
const groupName = selectedGroup.value?.name || '--';
const workflowStates = docItems.map((item) => resolveWorkflowState(item));
const pendingSyncCount = workflowStates.filter((item) => item.sync.code === 'pending').length;
const uploadFailedCount = workflowStates.filter((item) => item.upload.code === 'failed').length;
const cleanFailedCount = workflowStates.filter((item) => item.clean.code === 'failed').length;
const syncFailedCount = workflowStates.filter((item) => item.sync.code === 'failed').length;
return [
{ label: '当前知识库分组', value: groupName, wide: true, clickable: false },
{ label: '文档数量', value: String(docItems.length), wide: false, clickable: false },
{ label: '待同步数量', value: String(pendingSyncCount), wide: false, clickable: false },
{ label: '上传失败数量', value: String(uploadFailedCount), wide: false, clickable: uploadFailedCount > 0, failureType: 'upload' as const },
{ label: '清洗失败数量', value: String(cleanFailedCount), wide: false, clickable: cleanFailedCount > 0, failureType: 'clean' as const },
{ label: '同步失败数量', value: String(syncFailedCount), wide: false, clickable: syncFailedCount > 0, failureType: 'sync' as const },
];
});
const matchesDocumentStageFilter = (
doc: KbDocumentItem,
filter: 'all' | 'upload' | 'clean' | 'sync',
) => {
const workflow = resolveWorkflowState(doc);
if (filter === 'all') return true;
if (filter === 'upload') {
return workflow.upload.code !== 'success';
}
if (filter === 'clean') {
return ['pending', 'running', 'failed'].includes(workflow.clean.code);
}
return ['pending', 'running', 'failed'].includes(workflow.sync.code);
};
const matchesDocumentKeyword = (doc: KbDocumentItem, keyword: string) => {
const normalizedKeyword = keyword.trim().toLowerCase();
if (!normalizedKeyword) return true;
const candidates = [
getDocumentDisplayTitle(doc),
getDocumentDisplayDescription(doc),
doc.title,
doc.description,
doc.latest_version?.source_file_name,
];
return candidates.some((item) => String(item || '').toLowerCase().includes(normalizedKeyword));
};
const stageFilterTabs = computed(() => {
const filters: Array<{ key: 'all' | 'upload' | 'clean' | 'sync'; label: string }> = [
{ key: 'all', label: '全部' },
{ key: 'upload', label: '上传' },
{ key: 'clean', label: '清洗' },
{ key: 'sync', label: '同步' },
];
return filters.map((item) => ({
...item,
count: documents.value.filter((doc) =>
matchesDocumentStageFilter(doc, item.key) && matchesDocumentKeyword(doc, documentKeyword.value),
).length,
}));
});
const filteredDocuments = computed(() =>
documents.value.filter((doc) =>
matchesDocumentStageFilter(doc, documentStageFilter.value)
&& matchesDocumentKeyword(doc, documentKeyword.value),
),
);
const filteredDocumentTotalPages = computed(() =>
Math.max(1, Math.ceil(filteredDocuments.value.length / documentListPageSize.value)),
);
const pagedFilteredDocuments = computed(() => {
const start = (documentListPage.value - 1) * documentListPageSize.value;
return filteredDocuments.value.slice(start, start + documentListPageSize.value);
});
const pagedDocumentRange = computed(() => {
if (filteredDocuments.value.length === 0) {
return { start: 0, end: 0 };
}
const start = (documentListPage.value - 1) * documentListPageSize.value + 1;
const end = Math.min(filteredDocuments.value.length, documentListPage.value * documentListPageSize.value);
return { start, end };
});
const selectedDocuments = computed(() =>
documents.value.filter((doc) => selectedDocumentIds.value.includes(doc.id)),
);
const selectedCleanableDocuments = computed(() =>
selectedDocuments.value.filter((doc) => {
if (!doc.latest_version) return false;
const workflow = resolveWorkflowState(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)),
);
const failureModalItems = computed<FailureModalItem[]>(() => {
if (!failureModalType.value) return [];
return documents.value.flatMap<FailureModalItem>((doc) => {
const workflow = resolveWorkflowState(doc);
if (failureModalType.value === 'clean' && workflow.clean.code === 'failed') {
return [{
key: `${doc.id}-clean`,
document: doc,
stage: 'clean',
stageLabel: '清洗失败',
errorMessage: workflow.clean.errorMessage || workflow.primaryError || '清洗失败',
latestJob: getLatestJobForDocument(doc, 'clean'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
}];
}
if (failureModalType.value === 'sync' && workflow.sync.code === 'failed') {
return [{
key: `${doc.id}-sync`,
document: doc,
stage: 'sync',
stageLabel: '同步失败',
errorMessage: workflow.sync.errorMessage || workflow.primaryError || '同步失败',
latestJob: getLatestJobForDocument(doc, 'sync_dify'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
}];
}
if (failureModalType.value === 'upload' && workflow.upload.code === 'failed') {
return [{
key: `${doc.id}-upload`,
document: doc,
stage: 'upload',
stageLabel: '上传失败',
errorMessage: workflow.upload.errorMessage || workflow.primaryError || '上传失败',
latestJob: getLatestJobForDocument(doc, 'upload'),
updatedAt: doc.updated_at || doc.latest_version?.created_at || null,
}];
}
return [];
});
});
const failureModalTotalPages = computed(() =>
Math.max(1, Math.ceil(failureModalItems.value.length / FAILURE_PAGE_SIZE)),
);
const pagedFailureModalItems = computed(() => {
const start = (failureModalPage.value - 1) * FAILURE_PAGE_SIZE;
return failureModalItems.value.slice(start, start + FAILURE_PAGE_SIZE);
});
const failureModalTitle = computed(() => {
const map = {
upload: '上传失败数据',
clean: '清洗失败数据',
sync: '同步失败数据',
};
return failureModalType.value ? map[failureModalType.value] : '失败数据';
});
const documentById = computed(() =>
new Map(documents.value.map((doc) => [doc.id, doc])),
);
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();
if (aTime !== bTime) return bTime - aTime;
return Number(b.id) - Number(a.id);
})[0] ?? null;
});
const pathUploadHistoryJobs = computed(() =>
[...activeGroupJobs.value]
.filter((job) => job.job_type === 'path_upload')
.sort((a, b) => {
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;
}),
);
const selectedPathUploadHistoryJob = computed(() =>
pathUploadHistoryJobs.value.find((job) => String(job.id) === String(selectedPathUploadHistoryJobId.value))
|| 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 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 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,
failed,
queued,
uploading,
};
});
const recentPathUploadItems = computed(() =>
[...pathUploadTask.value.items]
.sort((a, b) => {
const aTime = new Date(a.finishedAt || a.startedAt || 0).getTime();
const bTime = new Date(b.finishedAt || b.startedAt || 0).getTime();
return bTime - aTime;
})
.slice(0, 30),
);
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);
});
return {
selectedDocument,
sourceInfoDocument,
selectedGroup,
markdownModalTitle,
activeGroupJobs,
resolveWorkflowState,
getWorkflowBadgesForDoc,
getMarkdownUnavailableMessageForDoc,
groupSummaryItems,
stageFilterTabs,
filteredDocuments,
filteredDocumentTotalPages,
pagedFilteredDocuments,
pagedDocumentRange,
selectedDocuments,
selectedCleanableDocuments,
isAllFilteredSelected,
failureModalItems,
failureModalTotalPages,
pagedFailureModalItems,
failureModalTitle,
documentById,
latestPathUploadJob,
pathUploadHistoryJobs,
selectedPathUploadHistoryJob,
selectedPathUploadHistoryItems,
selectedPathUploadHistorySelectedItems,
isAllPathUploadHistoryItemsSelected,
getPathUploadItemDisplayState,
pathUploadSummary,
recentPathUploadItems,
pathUploadRunning,
kbJobPollingActive,
selectedPathRoots,
};
}
export type KbWorkspaceComputed = ReturnType<typeof useKbWorkspaceComputed>;
@@ -0,0 +1,239 @@
/**
* features/kb/composables/kb-workspace/useKbWorkspaceData.ts
* 分组/文档/任务加载、静默轮询刷新与视图导航。
*/
import {
getKbDocumentSyncRecords,
getKbDocumentVersions,
getKbGroupFilesSafe,
getKbGroupsSafe,
getKbJobsSafe,
} from '../../api/kb.api';
import type { LoadListOptions } from '../../types/kb-workspace.types';
import { mergeStableItems } from '../../utils/kb-list.utils';
import { getPathUploadJobSummary } from '../../utils/kb-path-upload.utils';
import type { KbWorkspaceState } from './kb-workspace.state';
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
import type { KbWorkspacePathUpload } from './useKbWorkspacePathUpload';
let autoRefreshTimer: number | null = null;
export function useKbWorkspaceData(
state: KbWorkspaceState,
computed: KbWorkspaceComputed,
pathUpload: Pick<
KbWorkspacePathUpload,
'applyPathUploadJob' | 'startPathUploadPolling' | 'stopPathUploadPollTimer'
>,
) {
const {
isLoading,
isDocumentsLoading,
groups,
documents,
jobs,
selectedGroupId,
selectedDocumentId,
selectedDocumentVersions,
selectedDocumentSyncRecords,
feedback,
feedbackType,
viewMode,
showRecordModal,
showSourceInfoModal,
sourceInfoDocumentId,
sourceInfoVersions,
selectedDocumentIds,
showPathUploadDetails,
selectedPathUploadHistoryJobId,
} = state;
const {
kbJobPollingActive,
latestPathUploadJob,
pathUploadHistoryJobs,
} = computed;
const { applyPathUploadJob, startPathUploadPolling, stopPathUploadPollTimer } = pathUpload;
const loadGroups = async (options: LoadListOptions = {}) => {
if (!options.silent) {
isLoading.value = true;
}
try {
const result = await getKbGroupsSafe();
if (!result.ok) {
feedback.value = result.error || '加载知识库分组失败';
feedbackType.value = 'error';
return;
}
groups.value = options.silent ? mergeStableItems(groups.value, result.data) : result.data;
const firstGroup = groups.value[0];
if (!selectedGroupId.value && firstGroup && viewMode.value === 'group_detail') {
selectedGroupId.value = firstGroup.id;
}
} finally {
if (!options.silent) {
isLoading.value = false;
}
}
};
const loadDocuments = async (groupId: number | null, options: LoadListOptions = {}) => {
if (!options.silent) {
isDocumentsLoading.value = true;
}
try {
if (!groupId) {
documents.value = [];
selectedDocumentId.value = null;
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
return;
}
const result = await getKbGroupFilesSafe(groupId);
if (!result.ok) {
feedback.value = result.error || '加载文档列表失败';
feedbackType.value = 'error';
return;
}
const nextDocuments = options.silent
? mergeStableItems(documents.value, result.data)
: result.data;
documents.value = nextDocuments;
if (selectedDocumentId.value && !documents.value.some((item) => item.id === selectedDocumentId.value)) {
selectedDocumentId.value = null;
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
showRecordModal.value = false;
}
if (sourceInfoDocumentId.value && !documents.value.some((item) => item.id === sourceInfoDocumentId.value)) {
sourceInfoDocumentId.value = null;
sourceInfoVersions.value = [];
showSourceInfoModal.value = false;
}
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) =>
documents.value.some((item) => item.id === id),
);
} finally {
if (!options.silent) {
isDocumentsLoading.value = false;
}
}
};
const loadJobs = async () => {
const hadActiveKbJobs = kbJobPollingActive.value;
const result = await getKbJobsSafe();
if (!result.ok) {
feedback.value = result.error || '加载任务列表失败';
feedbackType.value = 'error';
return;
}
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;
}
if (kbJobPollingActive.value) {
startPathUploadPolling();
} else {
stopPathUploadPollTimer();
if (hadActiveKbJobs && viewMode.value === 'group_detail') {
await Promise.all([
loadDocuments(selectedGroupId.value, { silent: true }),
loadGroups({ silent: true }),
]);
}
}
};
const refreshWorkflowStatusOnly = async () => {
await Promise.all([
loadJobs(),
loadGroups({ silent: true }),
loadDocuments(selectedGroupId.value, { silent: true }),
]);
};
const refreshCurrentView = async () => {
if (viewMode.value === 'group_overview') {
await Promise.all([loadGroups(), loadJobs()]);
return;
}
await Promise.all([loadDocuments(selectedGroupId.value), loadJobs()]);
};
const startAutoRefresh = () => {
if (autoRefreshTimer !== null) {
window.clearInterval(autoRefreshTimer);
}
autoRefreshTimer = window.setInterval(() => {
void refreshCurrentView();
}, 120000);
};
const stopAutoRefresh = () => {
if (autoRefreshTimer !== null) {
window.clearInterval(autoRefreshTimer);
autoRefreshTimer = null;
}
};
const openGroupDetail = async (groupId: number) => {
selectedGroupId.value = groupId;
viewMode.value = 'group_detail';
feedback.value = '';
feedbackType.value = '';
await loadDocuments(groupId);
};
const backToGroupOverview = () => {
viewMode.value = 'group_overview';
selectedGroupId.value = null;
documents.value = [];
selectedDocumentId.value = null;
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
};
const loadDocumentVersions = async (documentId: number | null) => {
if (!documentId) {
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
return;
}
selectedDocumentVersions.value = await getKbDocumentVersions(documentId);
selectedDocumentSyncRecords.value = await getKbDocumentSyncRecords(documentId);
};
const loadSourceInfoVersions = async (documentId: number | null) => {
if (!documentId) {
sourceInfoVersions.value = [];
return;
}
sourceInfoVersions.value = await getKbDocumentVersions(documentId);
};
return {
loadGroups,
loadJobs,
loadDocuments,
refreshWorkflowStatusOnly,
refreshCurrentView,
startAutoRefresh,
stopAutoRefresh,
openGroupDetail,
backToGroupOverview,
loadDocumentVersions,
loadSourceInfoVersions,
};
}
export type KbWorkspaceData = ReturnType<typeof useKbWorkspaceData>;
@@ -0,0 +1,389 @@
/**
* features/kb/composables/kb-workspace/useKbWorkspaceDocuments.ts
* 文档列表选择、上传、清洗、同步、删除与失败重试。
*/
import type { KbDocumentItem } from '../../api/kb.api';
import {
createKbDocument,
deleteKbDocument,
submitKbDocumentClean,
syncKbDocumentToDify,
uploadKbDocumentVersion,
} from '../../api/kb.api';
import type { FailureModalItem } from '../../types/kb-workspace.types';
import {
getDocumentDisplayTitle,
normalizeDuplicateDocumentError,
} from '../../utils/kb-display.utils';
import type { KbWorkspaceState } from './kb-workspace.state';
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
import type { KbWorkspaceData } from './useKbWorkspaceData';
import type { KbWorkspacePathUpload } from './useKbWorkspacePathUpload';
export function useKbWorkspaceDocuments(
state: KbWorkspaceState,
computed: KbWorkspaceComputed,
data: Pick<
KbWorkspaceData,
'loadGroups' | 'loadJobs' | 'loadDocuments' | 'refreshWorkflowStatusOnly' | 'loadDocumentVersions'
>,
pathUpload: Pick<KbWorkspacePathUpload, 'startPathUploadPolling'>,
) {
const {
feedback,
feedbackType,
selectedGroupId,
selectedDocumentId,
selectedDocumentIds,
selectedDocumentVersions,
selectedDocumentSyncRecords,
batchSubmitting,
isSubmitting,
activeUploadDocumentId,
syncingDocumentId,
fileInputRef,
showRecordModal,
failureModalPage,
retryingFailureKey,
openDeleteConfirmDialog,
} = state;
const {
filteredDocuments,
selectedDocuments,
selectedCleanableDocuments,
isAllFilteredSelected,
failureModalTotalPages,
} = computed;
const {
loadGroups,
loadJobs,
loadDocuments,
refreshWorkflowStatusOnly,
loadDocumentVersions,
} = data;
const { startPathUploadPolling } = pathUpload;
const toggleDocumentSelection = (documentId: number) => {
if (selectedDocumentIds.value.includes(documentId)) {
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => id !== documentId);
return;
}
selectedDocumentIds.value = [...selectedDocumentIds.value, documentId];
};
const toggleSelectAllFiltered = () => {
if (isAllFilteredSelected.value) {
const filteredIds = new Set(filteredDocuments.value.map((doc) => doc.id));
selectedDocumentIds.value = selectedDocumentIds.value.filter((id) => !filteredIds.has(id));
return;
}
const merged = new Set(selectedDocumentIds.value);
filteredDocuments.value.forEach((doc) => merged.add(doc.id));
selectedDocumentIds.value = Array.from(merged);
};
const handleDeleteDocument = async (doc: KbDocumentItem) => {
openDeleteConfirmDialog(`确认删除文档「${getDocumentDisplayTitle(doc)}」吗?`, async () => {
const result = await deleteKbDocument(doc.id);
if (!result.ok) {
feedback.value = result.error || '删除文档失败';
feedbackType.value = 'error';
return;
}
if (selectedDocumentId.value === doc.id) {
selectedDocumentId.value = null;
showRecordModal.value = false;
}
feedback.value = '文档已删除';
feedbackType.value = 'success';
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
});
};
const handleBatchSync = async () => {
if (!selectedDocuments.value.length) {
feedback.value = '请先选择要批量同步的文档';
feedbackType.value = 'error';
return;
}
batchSubmitting.value = true;
try {
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} 条`;
feedbackType.value = failCount ? 'error' : 'success';
if (successCount > 0) {
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
} finally {
batchSubmitting.value = false;
}
};
const handleBatchClean = async () => {
if (!selectedDocuments.value.length) {
feedback.value = '请先选择要清洗的文档';
feedbackType.value = 'error';
return;
}
if (!selectedCleanableDocuments.value.length) {
feedback.value = '当前所选文档没有可重新清洗的项';
feedbackType.value = 'error';
return;
}
batchSubmitting.value = true;
try {
const results = await Promise.all(
selectedCleanableDocuments.value.map(async (doc) => ({
doc,
result: await submitKbDocumentClean(doc.id),
})),
);
const successCount = results.filter(({ result }) => result.ok).length;
const failResults = results.filter(({ result }) => !result.ok);
const failCount = failResults.length;
const errors = failResults.map(({ doc, result }) => `${getDocumentDisplayTitle(doc)}: ${result.error || '提交清洗失败'}`);
feedback.value = failCount
? `批量清洗任务已提交:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量清洗任务已提交:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
if (successCount > 0) {
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
} finally {
batchSubmitting.value = false;
}
};
const handleBatchDelete = async () => {
if (!selectedDocuments.value.length) {
feedback.value = '请先选择要批量删除的文档';
feedbackType.value = 'error';
return;
}
openDeleteConfirmDialog(
`确认批量删除已选中的 ${selectedDocuments.value.length} 条文档吗?会同步删除 Dify 对应文档。`,
async () => {
batchSubmitting.value = true;
let successCount = 0;
let failCount = 0;
const errors: string[] = [];
try {
for (const doc of selectedDocuments.value) {
const result = await deleteKbDocument(doc.id);
if (result.ok) {
successCount += 1;
} else {
failCount += 1;
errors.push(`${getDocumentDisplayTitle(doc)}: ${result.error || '删除失败'}`);
}
}
feedback.value = failCount
? `批量删除完成:成功 ${successCount} 条,失败 ${failCount} 条。${errors[0] || ''}`
: `批量删除完成:共成功 ${successCount} 条`;
feedbackType.value = failCount ? 'error' : 'success';
selectedDocumentIds.value = [];
await Promise.all([loadGroups(), loadDocuments(selectedGroupId.value), loadJobs()]);
} finally {
batchSubmitting.value = false;
}
},
);
};
const triggerUploadForDocument = (documentId: number) => {
activeUploadDocumentId.value = documentId;
fileInputRef.value?.click();
};
const handleRetryFailedItem = async (
item: FailureModalItem,
action: 'submit' | 'clean' | 'sync',
) => {
const actionKey = `${item.key}-${action}`;
retryingFailureKey.value = actionKey;
try {
if (action === 'submit') {
triggerUploadForDocument(item.document.id);
feedback.value = `请重新为「${getDocumentDisplayTitle(item.document)}」选择文件后提交`;
feedbackType.value = 'success';
return;
}
if (action === 'clean') {
const result = await submitKbDocumentClean(item.document.id);
if (!result.ok) {
feedback.value = result.error || '重新清洗失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.message || `已重新提交清洗:${getDocumentDisplayTitle(item.document)}`;
feedbackType.value = 'success';
startPathUploadPolling();
} else {
const result = await syncKbDocumentToDify(item.document.id);
if (!result.ok) {
feedback.value = result.error ? `重新同步失败:${result.error}` : '重新同步失败';
feedbackType.value = 'error';
return;
}
feedback.value = result.job?.message || `已重新提交同步:${getDocumentDisplayTitle(item.document)}`;
feedbackType.value = 'success';
startPathUploadPolling();
}
await refreshWorkflowStatusOnly();
if (selectedDocumentId.value) {
await loadDocumentVersions(selectedDocumentId.value);
}
if (failureModalPage.value > failureModalTotalPages.value) {
failureModalPage.value = failureModalTotalPages.value;
}
} finally {
retryingFailureKey.value = '';
}
};
const handleFileSelected = async (event: Event) => {
const input = event.target as HTMLInputElement;
const files = input.files;
if (!files || files.length === 0 || !selectedGroupId.value) {
input.value = '';
activeUploadDocumentId.value = null;
return;
}
isSubmitting.value = true;
feedback.value = '开始处理文件...';
feedbackType.value = 'success';
if (activeUploadDocumentId.value) {
const file = files[0];
if (!file) return;
const result = await uploadKbDocumentVersion(activeUploadDocumentId.value, file);
if (!result.ok) {
feedback.value = result.error || '文件上传失败';
feedbackType.value = 'error';
} else {
feedback.value = result.message || `版本文件「${file.name}」上传成功,清洗已排队`;
feedbackType.value = 'success';
startPathUploadPolling();
}
selectedDocumentId.value = activeUploadDocumentId.value;
activeUploadDocumentId.value = null;
} else {
let successCount = 0;
let failCount = 0;
const errors: string[] = [];
const fileArray = Array.from(files);
for (let i = 0; i < fileArray.length; i++) {
const file = fileArray[i];
if (!file) continue;
feedback.value = `正在上传 ${i + 1}/${fileArray.length}: ${file.name}`;
const createResult = await createKbDocument(selectedGroupId.value, {
title: file.name,
description: file.name,
});
if (!createResult.ok || !createResult.document) {
failCount++;
errors.push(`${file.name}: ${normalizeDuplicateDocumentError(createResult.error || '创建文档失败')}`);
continue;
}
const uploadResult = await uploadKbDocumentVersion(createResult.document.id, file);
if (!uploadResult.ok) {
failCount++;
const uploadError = uploadResult.error || '上传文档版本失败';
errors.push(`${file.name}: ${uploadError}`);
const cleanupResult = await deleteKbDocument(createResult.document.id);
if (!cleanupResult.ok) {
errors.push(`${file.name}: 上传失败后未能自动清理空文档(${cleanupResult.error || '删除失败'})`);
}
} else {
successCount++;
}
}
if (failCount > 0) {
feedback.value = `上传完成:成功 ${successCount} 个,失败 ${failCount} 个。${errors[0] || ''}`;
feedbackType.value = successCount > 0 ? 'success' : 'error';
} else {
feedback.value = `成功上传 ${successCount} 个文件,清洗任务已排队`;
feedbackType.value = 'success';
}
if (successCount > 0) {
startPathUploadPolling();
}
}
input.value = '';
isSubmitting.value = false;
await refreshWorkflowStatusOnly();
if (selectedDocumentId.value) {
await loadDocumentVersions(selectedDocumentId.value);
}
};
const triggerMultiUpload = () => {
activeUploadDocumentId.value = null;
fileInputRef.value?.click();
};
const handleSyncDocument = async (documentId: number) => {
syncingDocumentId.value = documentId;
const result = await syncKbDocumentToDify(documentId);
syncingDocumentId.value = null;
if (!result.ok) {
feedback.value = result.error ? `同步到 Dify 失败:${result.error}` : '同步到 Dify 失败';
feedbackType.value = 'error';
await loadDocuments(selectedGroupId.value, { silent: true });
await loadJobs();
return;
}
feedback.value = result.job?.message || '同步任务已提交,等待后台处理';
feedbackType.value = 'success';
startPathUploadPolling();
await loadDocuments(selectedGroupId.value, { silent: true });
await loadJobs();
selectedDocumentId.value = documentId;
await loadDocumentVersions(documentId);
};
return {
toggleDocumentSelection,
toggleSelectAllFiltered,
handleDeleteDocument,
handleBatchSync,
handleBatchClean,
handleBatchDelete,
handleRetryFailedItem,
triggerUploadForDocument,
handleFileSelected,
triggerMultiUpload,
handleSyncDocument,
};
}
export type KbWorkspaceDocuments = ReturnType<typeof useKbWorkspaceDocuments>;
@@ -0,0 +1,188 @@
/**
* features/kb/composables/kb-workspace/useKbWorkspaceModals.ts
* 记录/来源/Markdown/失败弹窗与原始文件预览。
*/
import type { KbDocumentItem, KbDocumentMarkdown, KbDocumentVersionItem } from '../../api/kb.api';
import {
getKbDocumentMarkdown,
getKbDocumentVersionSourceFile,
updateKbDocumentMarkdown,
} from '../../api/kb.api';
import type { KbWorkspaceState } from './kb-workspace.state';
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
import type { KbWorkspaceData } from './useKbWorkspaceData';
export function useKbWorkspaceModals(
state: KbWorkspaceState,
computed: KbWorkspaceComputed,
data: Pick<
KbWorkspaceData,
'loadDocumentVersions' | 'loadSourceInfoVersions' | 'loadDocuments' | 'loadJobs'
>,
) {
const {
selectedDocumentId,
isRecordLoading,
showRecordModal,
showSourceInfoModal,
showFailureModal,
sourceInfoDocumentId,
isSourceInfoLoading,
openingSourceVersionId,
failureModalType,
failureModalPage,
retryingFailureKey,
feedback,
feedbackType,
showMarkdownModal,
markdownDocumentId,
markdownContent,
markdownKind,
markdownVersionLabel,
markdownError,
isMarkdownLoading,
isMarkdownSaving,
documents,
selectedGroupId,
} = state;
const { getMarkdownUnavailableMessageForDoc } = computed;
const { loadDocumentVersions, loadSourceInfoVersions, loadDocuments, loadJobs } = data;
const openDocumentDetail = async (documentId: number) => {
selectedDocumentId.value = documentId;
isRecordLoading.value = true;
showRecordModal.value = true;
await loadDocumentVersions(documentId);
isRecordLoading.value = false;
};
const closeDocumentDetail = () => {
showRecordModal.value = false;
};
const openSourceInfo = async (doc: KbDocumentItem) => {
sourceInfoDocumentId.value = doc.id;
isSourceInfoLoading.value = true;
showSourceInfoModal.value = true;
await loadSourceInfoVersions(doc.id);
isSourceInfoLoading.value = false;
};
const closeSourceInfoModal = () => {
showSourceInfoModal.value = false;
};
const openOriginalSourceFile = async (version: KbDocumentVersionItem) => {
openingSourceVersionId.value = version.id;
const result = await getKbDocumentVersionSourceFile(version.id);
openingSourceVersionId.value = null;
if (!result.ok || !result.blob) {
feedback.value = result.error || '读取原始文件失败';
feedbackType.value = 'error';
return;
}
const objectUrl = window.URL.createObjectURL(result.blob);
const opened = window.open(objectUrl, '_blank', 'noopener,noreferrer');
if (!opened) {
const link = window.document.createElement('a');
link.href = objectUrl;
link.download = result.filename || version.source_file_name || `source-${version.id}`;
link.click();
}
window.setTimeout(() => window.URL.revokeObjectURL(objectUrl), 60_000);
};
const openFailureModal = (type: 'upload' | 'clean' | 'sync') => {
failureModalType.value = type;
failureModalPage.value = 1;
showFailureModal.value = true;
};
const closeFailureModal = () => {
showFailureModal.value = false;
failureModalType.value = null;
failureModalPage.value = 1;
retryingFailureKey.value = '';
};
const applyMarkdownPayload = (payload: KbDocumentMarkdown) => {
markdownContent.value = payload.content || '';
markdownKind.value = payload.kind;
markdownVersionLabel.value = payload.version
? `v${payload.version.version_no} · ${payload.version.source_file_name}`
: '暂无版本';
};
const openMarkdownEditor = async (doc: KbDocumentItem) => {
showMarkdownModal.value = true;
markdownDocumentId.value = doc.id;
markdownContent.value = '';
markdownKind.value = 'markdown';
markdownVersionLabel.value = '';
markdownError.value = '';
isMarkdownLoading.value = true;
const result = await getKbDocumentMarkdown(doc.id);
isMarkdownLoading.value = false;
if (!result.ok || !result.data) {
markdownError.value = getMarkdownUnavailableMessageForDoc(doc, result.error || '读取清洗后的 Markdown 失败');
return;
}
applyMarkdownPayload(result.data);
};
const closeMarkdownModal = () => {
if (isMarkdownSaving.value) return;
showMarkdownModal.value = false;
markdownDocumentId.value = null;
markdownContent.value = '';
markdownVersionLabel.value = '';
markdownError.value = '';
isMarkdownLoading.value = false;
};
const handleSaveMarkdown = async () => {
if (!markdownDocumentId.value) return;
isMarkdownSaving.value = true;
markdownError.value = '';
const result = await updateKbDocumentMarkdown(markdownDocumentId.value, {
content: markdownContent.value,
});
isMarkdownSaving.value = false;
if (!result.ok || !result.data) {
const currentDoc = documents.value.find((item) => item.id === markdownDocumentId.value) || null;
markdownError.value = currentDoc
? getMarkdownUnavailableMessageForDoc(currentDoc, result.error || '保存 Markdown 失败')
: (result.error || '保存 Markdown 失败');
return;
}
applyMarkdownPayload(result.data);
feedback.value = '清洗后的 Markdown 已保存';
feedbackType.value = 'success';
await loadDocuments(selectedGroupId.value);
await loadJobs();
selectedDocumentId.value = markdownDocumentId.value;
await loadDocumentVersions(markdownDocumentId.value);
closeMarkdownModal();
};
return {
openDocumentDetail,
closeDocumentDetail,
openSourceInfo,
closeSourceInfoModal,
openOriginalSourceFile,
openFailureModal,
closeFailureModal,
openMarkdownEditor,
closeMarkdownModal,
handleSaveMarkdown,
};
}
export type KbWorkspaceModals = ReturnType<typeof useKbWorkspaceModals>;
@@ -0,0 +1,454 @@
/**
* features/kb/composables/kb-workspace/useKbWorkspacePathUpload.ts
* 路径上传:选文件、分批 job、轮询进度与历史批次操作。
*/
import type { KbJob } from '../../api/kb.api';
import {
createKbPathUploadJob,
deleteKbPathJobFile,
markKbPathJobFileFailed,
retryFailedKbPathUploadJob,
uploadKbPathJobFile,
} from '../../api/kb.api';
import {
PATH_UPLOAD_BATCH_INTERVAL_MS,
PATH_UPLOAD_BATCH_SIZE,
PATH_UPLOAD_CONCURRENCY,
type PathUploadStatus,
type PathUploadTaskItem,
} from '../../types/kb-workspace.types';
import { normalizeDuplicateDocumentError } from '../../utils/kb-display.utils';
import { getPathUploadJobItems } from '../../utils/kb-path-upload.utils';
import type { KbWorkspaceDataBridge } from './kb-workspace.bridge';
import type { KbWorkspaceState } from './kb-workspace.state';
import type { KbWorkspaceComputed } from './useKbWorkspaceComputed';
let pathUploadPollTimer: number | null = null;
export function useKbWorkspacePathUpload(
state: KbWorkspaceState,
computed: KbWorkspaceComputed,
bridge: KbWorkspaceDataBridge,
) {
const {
feedback,
feedbackType,
selectedGroupId,
pathUploadInputRef,
pathUploadDraftText,
pathUploadSelectedFiles,
isPathUploadStaging,
pathUploadJobId,
pathUploadTask,
showPathUploadModal,
showPathUploadHistoryModal,
showPathUploadDetails,
selectedPathUploadHistoryJobId,
selectedPathUploadHistoryItemKeys,
retryingPathUploadKey,
deletingPathUploadBatch,
openDeleteConfirmDialog,
} = state;
const {
pathUploadRunning,
kbJobPollingActive,
pathUploadSummary,
latestPathUploadJob,
pathUploadHistoryJobs,
selectedPathUploadHistoryJob,
selectedPathUploadHistoryItems,
selectedPathUploadHistorySelectedItems,
isAllPathUploadHistoryItemsSelected,
selectedPathRoots,
} = computed;
const stopPathUploadPollTimer = () => {
if (pathUploadPollTimer !== null) {
window.clearInterval(pathUploadPollTimer);
pathUploadPollTimer = null;
}
};
const wait = (ms: number) => new Promise((resolve) => {
window.setTimeout(resolve, ms);
});
const updatePathUploadFeedback = () => {
const summary = pathUploadSummary.value;
if (!pathUploadTask.value.total) return;
feedback.value = `路径上传进度:总计 ${summary.total} 条,待上传 ${summary.pending} 条,已上传 ${summary.uploaded} 条,失败 ${summary.failed} 条`;
feedbackType.value = summary.failed > 0 ? 'error' : 'success';
};
const applyPathUploadJob = (job: KbJob | null) => {
if (!job || job.job_type !== 'path_upload') {
if (!isPathUploadStaging.value) {
pathUploadTask.value = {
running: false,
groupId: selectedGroupId.value,
total: 0,
success: 0,
failed: 0,
currentFile: '',
batchSize: PATH_UPLOAD_BATCH_SIZE,
items: [],
};
}
return;
}
const payload = job.payload_json || {};
const result = job.result_json || {};
const items = Array.isArray(payload.files)
? payload.files.map((item: Record<string, unknown>, index: number) => ({
key: String(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 as string | undefined,
documentId: item.document_id as number | undefined,
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
}))
: [];
pathUploadJobId.value = job.id;
pathUploadTask.value = {
running: ['draft', 'staging', 'queued', 'running'].includes(String(job.status || '').toLowerCase()) || isPathUploadStaging.value,
groupId: job.group_id ? Number(job.group_id) : selectedGroupId.value,
total: Number(payload.total_files || result.total || items.length || 0),
success: Number(result.success || items.filter((item) => item.status === 'success').length || 0),
failed: Number(result.failed || items.filter((item) => item.status === 'failed').length || 0),
currentFile: String(payload.current_file || ''),
batchSize: PATH_UPLOAD_BATCH_SIZE,
items,
};
updatePathUploadFeedback();
};
const startPathUploadPolling = () => {
stopPathUploadPollTimer();
pathUploadPollTimer = window.setInterval(() => {
if (!kbJobPollingActive.value) {
stopPathUploadPollTimer();
return;
}
void Promise.all([
bridge.loadJobs(),
bridge.loadDocuments(selectedGroupId.value, { silent: true }),
bridge.loadGroups({ silent: true }),
]);
}, 3000);
};
const resetPathUploadDraft = () => {
pathUploadDraftText.value = '';
pathUploadSelectedFiles.value = [];
};
const openPathUploadModal = () => {
if (pathUploadRunning.value) {
feedback.value = '有文件正在上传请稍等再试~';
feedbackType.value = 'error';
return;
}
resetPathUploadDraft();
showPathUploadModal.value = true;
};
const closePathUploadModal = () => {
if (pathUploadRunning.value) return;
showPathUploadModal.value = false;
resetPathUploadDraft();
};
const triggerPathUploadSelection = () => {
pathUploadInputRef.value?.click();
};
const handlePathFilesSelected = (event: Event) => {
const input = event.target as HTMLInputElement;
const files = Array.from(input.files || []);
if (!files.length) {
input.value = '';
return;
}
const existing = new Set(pathUploadSelectedFiles.value.map((item) => item.displayPath));
const nextItems = files.flatMap((file, index) => {
const relativePath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name;
if (existing.has(relativePath)) return [];
const rootLabel = relativePath.includes('/') ? relativePath.split('/')[0] || file.name : file.name;
return [{
key: `${Date.now()}-${index}-${relativePath}`,
file,
displayPath: relativePath,
rootLabel,
}];
});
pathUploadSelectedFiles.value = [...pathUploadSelectedFiles.value, ...nextItems];
pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n');
input.value = '';
};
const removeSelectedPathFile = (key: string) => {
pathUploadSelectedFiles.value = pathUploadSelectedFiles.value.filter((item) => item.key !== key);
pathUploadDraftText.value = pathUploadSelectedFiles.value.map((item) => item.displayPath).join('\n');
};
const openPathUploadHistoryModal = (jobId?: number | string | null) => {
selectedPathUploadHistoryJobId.value = jobId || latestPathUploadJob.value?.id || pathUploadHistoryJobs.value[0]?.id || null;
showPathUploadHistoryModal.value = true;
};
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 handleConfirmPathUpload = async () => {
if (pathUploadRunning.value) {
feedback.value = '有文件正在上传请稍等再试~';
feedbackType.value = 'error';
return;
}
if (!selectedGroupId.value) {
feedback.value = '请先选择知识库分组';
feedbackType.value = 'error';
return;
}
if (!pathUploadSelectedFiles.value.length) {
feedback.value = '请先选择至少一个本地目录或文件';
feedbackType.value = 'error';
return;
}
isPathUploadStaging.value = true;
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 || '创建上传路径任务失败';
feedbackType.value = 'error';
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 = createdJob.id;
showPathUploadDetails.value = false;
pathUploadTask.value = {
running: true,
groupId: selectedGroupId.value,
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) => {
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;
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(createdJob.id, item.file, item.displayPath);
if (!stageResult.ok) {
const errorMessage = normalizeDuplicateDocumentError(stageResult.error || '路径文件暂存失败');
const failedResult = await markKbPathJobFileFailed(createdJob.id, {
relative_path: item.displayPath,
original_name: item.file.name,
error: errorMessage,
});
if (failedResult.ok && failedResult.job) {
applyPathUploadJob(failedResult.job);
} else if (localItem) {
localItem.status = 'failed';
localItem.error = errorMessage;
updatePathUploadFeedback();
}
return;
}
if (stageResult.job) {
applyPathUploadJob(stageResult.job);
} else if (localItem) {
localItem.status = 'success';
localItem.error = undefined;
updatePathUploadFeedback();
}
await Promise.all([
bridge.loadDocuments(selectedGroupId.value, { silent: true }),
bridge.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);
}
}
isPathUploadStaging.value = false;
pathUploadTask.value.currentFile = '';
feedback.value = '路径文件已逐个上传并提交清洗';
feedbackType.value = 'success';
startPathUploadPolling();
resetPathUploadDraft();
await bridge.refreshWorkflowStatusOnly();
};
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 bridge.refreshWorkflowStatusOnly();
});
};
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([
bridge.loadJobs(),
bridge.loadDocuments(selectedGroupId.value),
bridge.loadGroups(),
]);
} finally {
deletingPathUploadBatch.value = false;
}
});
};
const handleRetryFailedPathUpload = async (
job: KbJob | null,
relativePaths?: string[],
) => {
if (!job) return;
const key = `${job.id}:${(relativePaths || []).join('|') || 'all'}`;
retryingPathUploadKey.value = key;
const result = await retryFailedKbPathUploadJob(job.id, relativePaths?.length ? { relative_paths: relativePaths } : {});
retryingPathUploadKey.value = '';
if (!result.ok || !result.job) {
feedback.value = result.error || '重试失败文件失败';
feedbackType.value = 'error';
return;
}
applyPathUploadJob(result.job);
startPathUploadPolling();
feedback.value = relativePaths?.length === 1 ? '已重新提交该失败文件' : '已重新提交失败文件';
feedbackType.value = 'success';
await bridge.refreshWorkflowStatusOnly();
};
return {
stopPathUploadPollTimer,
startPathUploadPolling,
applyPathUploadJob,
resetPathUploadDraft,
openPathUploadModal,
closePathUploadModal,
triggerPathUploadSelection,
handlePathFilesSelected,
removeSelectedPathFile,
openPathUploadHistoryModal,
closePathUploadHistoryModal,
togglePathUploadHistoryItemSelection,
toggleSelectAllPathUploadHistoryItems,
handleConfirmPathUpload,
handleDeletePathUploadItem,
handleBatchDeletePathUploadItems,
handleRetryFailedPathUpload,
};
}
export type KbWorkspacePathUpload = ReturnType<typeof useKbWorkspacePathUpload>;
@@ -0,0 +1,156 @@
/**
* features/kb/composables/useKbWorkspace.ts
* 知识库作业面编排入口:组合 state / computed / data / pathUpload / documents / modals。
*/
import { onMounted, onUnmounted, reactive, watch } from 'vue';
import {
DOCUMENT_PAGE_SIZE_OPTIONS,
FAILURE_PAGE_SIZE,
PATH_UPLOAD_BATCH_INTERVAL_MS,
PATH_UPLOAD_BATCH_SIZE,
PATH_UPLOAD_CONCURRENCY,
} from '../types/kb-workspace.types';
import {
formatDateTime,
formatFileSize,
getDocumentDisplayDescription,
getDocumentDisplayTitle,
getStatusBadgeClass,
getStatusLabel,
} from '../utils/kb-display.utils';
import {
getPathUploadJobItems,
getPathUploadJobSummary,
hasRetryablePathUploadFailure,
} from '../utils/kb-path-upload.utils';
import { createKbWorkspaceDataBridge } from './kb-workspace/kb-workspace.bridge';
import { createKbWorkspaceState } from './kb-workspace/kb-workspace.state';
import { useKbWorkspaceComputed } from './kb-workspace/useKbWorkspaceComputed';
import { useKbWorkspaceData } from './kb-workspace/useKbWorkspaceData';
import { useKbWorkspaceDocuments } from './kb-workspace/useKbWorkspaceDocuments';
import { useKbWorkspaceModals } from './kb-workspace/useKbWorkspaceModals';
import { useKbWorkspacePathUpload } from './kb-workspace/useKbWorkspacePathUpload';
export interface UseKbWorkspaceOptions {
embedded?: boolean;
}
export function useKbWorkspace(options: UseKbWorkspaceOptions = {}) {
const state = createKbWorkspaceState(options);
const computed = useKbWorkspaceComputed(state);
// pathUpload 先于 data 创建;data 加载函数通过 bridge 延迟注入,打破循环依赖
const bridge = createKbWorkspaceDataBridge();
const pathUpload = useKbWorkspacePathUpload(state, computed, bridge);
const data = useKbWorkspaceData(state, computed, pathUpload);
Object.assign(bridge, {
loadGroups: data.loadGroups,
loadJobs: data.loadJobs,
loadDocuments: data.loadDocuments,
refreshWorkflowStatusOnly: data.refreshWorkflowStatusOnly,
});
const modals = useKbWorkspaceModals(state, computed, data);
const documents = useKbWorkspaceDocuments(state, computed, data, pathUpload);
const {
selectedGroupId,
feedback,
feedbackType,
documentListPage,
selectedDocumentId,
selectedDocumentIds,
selectedDocumentVersions,
selectedDocumentSyncRecords,
documentStageFilter,
documentKeyword,
documentListPageSize,
selectedPathUploadHistoryItemKeys,
} = state;
const {
filteredDocumentTotalPages,
latestPathUploadJob,
selectedPathUploadHistoryJob,
} = computed;
const { applyPathUploadJob } = pathUpload;
// --- 筛选/分页/路径上传历史联动 ---
watch(selectedGroupId, (groupId) => {
feedback.value = '';
feedbackType.value = '';
documentListPage.value = 1;
selectedDocumentId.value = null;
selectedDocumentIds.value = [];
selectedDocumentVersions.value = [];
selectedDocumentSyncRecords.value = [];
void data.loadDocuments(groupId);
applyPathUploadJob(latestPathUploadJob.value);
});
watch(documentStageFilter, () => {
documentListPage.value = 1;
});
watch(documentKeyword, () => {
documentListPage.value = 1;
});
watch(documentListPageSize, () => {
documentListPage.value = 1;
});
watch(filteredDocumentTotalPages, (totalPages) => {
if (documentListPage.value > totalPages) {
documentListPage.value = totalPages;
}
});
watch(selectedPathUploadHistoryJob, (job) => {
const validKeys = new Set(getPathUploadJobItems(job).map((item) => item.key));
selectedPathUploadHistoryItemKeys.value = selectedPathUploadHistoryItemKeys.value.filter((key) => validKeys.has(key));
if (!job) {
selectedPathUploadHistoryItemKeys.value = [];
}
});
onMounted(async () => {
await Promise.all([data.loadGroups(), data.loadJobs()]);
if (state.viewMode.value === 'group_detail') {
await data.loadDocuments(selectedGroupId.value);
}
data.startAutoRefresh();
});
onUnmounted(() => {
data.stopAutoRefresh();
pathUpload.stopPathUploadPollTimer();
});
// reactive 便于模板以 kb.xxx 统一访问,ref/computed 在属性读取时自动解包
return reactive({
...state,
...computed,
...data,
...pathUpload,
...modals,
...documents,
getWorkflowBadges: computed.getWorkflowBadgesForDoc,
getDocumentWorkflowState: computed.resolveWorkflowState,
formatDateTime,
formatFileSize,
getDocumentDisplayTitle,
getDocumentDisplayDescription,
getStatusLabel,
getStatusBadgeClass,
getPathUploadJobItems,
hasRetryablePathUploadFailure,
getPathUploadJobSummary,
DOCUMENT_PAGE_SIZE_OPTIONS,
FAILURE_PAGE_SIZE,
PATH_UPLOAD_BATCH_SIZE,
PATH_UPLOAD_BATCH_INTERVAL_MS,
PATH_UPLOAD_CONCURRENCY,
});
}