Merge branch 'dev' into hugo
This commit is contained in:
commit
ae6a5e7c55
49 files changed
+5333
-4234
No files matched your search
@@ -1,9 +1,9 @@
|
||||
/**
|
||||
* features/admin/modules/knowledge-base/KnowledgeBasePage.vue
|
||||
* 知识库管理独立页面。路由:/admin/knowledge-base
|
||||
* 知识库配置页(治理面)。路由:/admin/knowledge-base
|
||||
*/
|
||||
<script setup lang="ts">
|
||||
import KbAdminPanel from '@/shared/components/kb/KbAdminPanel.vue';
|
||||
import KbAdminPanel from '@/features/kb/components/KbAdminPanel.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
import { computed, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { listAdminAgents, listAdminUsers } from '@/features/admin/api/admin.api';
|
||||
import { getKbGroups, type KbGroup } from '@/api/kb';
|
||||
import { getKbGroups, type KbGroup } from '@/features/kb/api/kb.api';
|
||||
import {
|
||||
createAdminSchedule,
|
||||
deleteAdminSchedule,
|
||||
|
||||
+1
-1
@@ -1,6 +1,6 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/chat/pages/HistoryPage.vue
|
||||
* features/chat/history/HistoryPage.vue
|
||||
* 跨 Agent 聊天历史列表,点击跳转对应会话(工作台 / 移动端 Tab 入口)。
|
||||
*/
|
||||
import { inject } from 'vue';
|
||||
@@ -0,0 +1,548 @@
|
||||
/**
|
||||
* features/kb/api/kb.api.ts
|
||||
* 知识库 HTTP API。
|
||||
*/
|
||||
import { getAuthHeaders } from '@/shared/utils/auth';
|
||||
import { BusinessError, requestJson } from '@/shared/api/client';
|
||||
|
||||
export interface KbGroup {
|
||||
id: number;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
department_id?: number | null;
|
||||
document_count?: number;
|
||||
created_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentItem {
|
||||
id: number;
|
||||
group_id?: number;
|
||||
title: string;
|
||||
description?: string | null;
|
||||
status?: string;
|
||||
source_type?: string | null;
|
||||
created_at?: string | null;
|
||||
updated_at?: string;
|
||||
version_count?: number;
|
||||
latest_version?: KbDocumentVersionItem | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentVersionItem {
|
||||
id: number;
|
||||
document_id: number;
|
||||
version_no: number;
|
||||
status: string;
|
||||
is_current: boolean;
|
||||
source_file_name: string;
|
||||
source_file_ext?: string | null;
|
||||
source_file_size?: number | null;
|
||||
sha256?: string | null;
|
||||
cleaned_file_path?: string | null;
|
||||
cleaned_preview_path?: string | null;
|
||||
error_message?: string | null;
|
||||
created_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbSyncRecordItem {
|
||||
id: number;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id: number;
|
||||
dataset_id: string;
|
||||
dataset_name?: string | null;
|
||||
remote_document_id: string;
|
||||
remote_document_name?: string | null;
|
||||
status: string;
|
||||
sync_hash?: string | null;
|
||||
error_message?: string | null;
|
||||
synced_at?: string | null;
|
||||
updated_at?: string | null;
|
||||
}
|
||||
|
||||
export interface KbDocumentMarkdown {
|
||||
document_id: number;
|
||||
title: string;
|
||||
version: KbDocumentVersionItem | null;
|
||||
content: string;
|
||||
kind: 'markdown' | 'preview';
|
||||
}
|
||||
|
||||
export interface KbJob {
|
||||
id: number | string;
|
||||
job_type: string;
|
||||
status: string;
|
||||
group_id?: number | null;
|
||||
document_id?: number | null;
|
||||
document_version_id?: number | null;
|
||||
progress?: number;
|
||||
message?: string | null;
|
||||
error_message?: string | null;
|
||||
payload_json?: Record<string, any> | null;
|
||||
result_json?: Record<string, any> | null;
|
||||
created_at?: string;
|
||||
started_at?: string | null;
|
||||
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;
|
||||
KB_DIFY_PERMISSION: string;
|
||||
KB_DIFY_INDEXING_TECHNIQUE: string;
|
||||
KB_DIFY_SEARCH_METHOD: string;
|
||||
KB_DIFY_DOC_FORM: string;
|
||||
dify_api_configured?: boolean;
|
||||
}
|
||||
|
||||
export interface KbDifyHealth {
|
||||
dify_base_url: string;
|
||||
dify_api_configured: boolean;
|
||||
api: {
|
||||
configured: boolean;
|
||||
reachable: boolean;
|
||||
dataset_count?: number | null;
|
||||
error?: string | null;
|
||||
};
|
||||
local_sync_health: {
|
||||
dataset_bound_groups: number;
|
||||
sync_records: number;
|
||||
syncing_versions: number;
|
||||
synced_versions: number;
|
||||
failed_sync_records: number;
|
||||
pending_sync_jobs: number;
|
||||
};
|
||||
}
|
||||
|
||||
export interface KbListResponse<T> {
|
||||
ok: boolean;
|
||||
data: T;
|
||||
error?: string;
|
||||
status?: number;
|
||||
}
|
||||
|
||||
const auth = () => ({ headers: getAuthHeaders() });
|
||||
const jsonAuth = () => ({ headers: { 'Content-Type': 'application/json', ...getAuthHeaders() } });
|
||||
|
||||
const kbErrorMessage = (e: unknown, fallback: string) => (e as Error).message || fallback;
|
||||
|
||||
const getJson = async <T>(path: string, fallback: T): Promise<T> => {
|
||||
try {
|
||||
return await requestJson<T>(path, auth());
|
||||
} catch {
|
||||
return fallback;
|
||||
}
|
||||
};
|
||||
|
||||
const getJsonWithStatus = async <T>(path: string, fallback: T): Promise<KbListResponse<T>> => {
|
||||
try {
|
||||
const data = await requestJson<T>(path, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return {
|
||||
ok: false,
|
||||
data: fallback,
|
||||
error: kbErrorMessage(e, '知识库接口请求失败'),
|
||||
status: err.status,
|
||||
};
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbGroups = async (): Promise<KbGroup[]> => {
|
||||
return getJson<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFiles = async (groupId: number): Promise<KbDocumentItem[]> => {
|
||||
return getJson<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const getKbGroupsSafe = async (): Promise<KbListResponse<KbGroup[]>> => {
|
||||
return getJsonWithStatus<KbGroup[]>('/api/kb/groups', []);
|
||||
};
|
||||
|
||||
export const getKbGroupFilesSafe = async (groupId: number): Promise<KbListResponse<KbDocumentItem[]>> => {
|
||||
return getJsonWithStatus<KbDocumentItem[]>(`/api/kb/groups/${groupId}/files`, []);
|
||||
};
|
||||
|
||||
export const createKbGroup = async (payload: {
|
||||
name: string;
|
||||
description?: string;
|
||||
}): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const group = await requestJson<KbGroup>('/api/kb/groups', {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbJobs = async (): Promise<KbJob[]> => {
|
||||
return getJson<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbJobsSafe = async (): Promise<KbListResponse<KbJob[]>> => {
|
||||
return getJsonWithStatus<KbJob[]>('/api/kb/jobs', []);
|
||||
};
|
||||
|
||||
export const getKbDifySettings = async (): Promise<KbDifySettings | null> => {
|
||||
return getJson<KbDifySettings | null>('/api/kb/dify/settings', null);
|
||||
};
|
||||
|
||||
export const updateKbDifySettings = async (
|
||||
payload: Partial<KbDifySettings>
|
||||
): Promise<{ ok: boolean; error?: string; settings?: KbDifySettings }> => {
|
||||
try {
|
||||
const settings = await requestJson<KbDifySettings>('/api/kb/dify/settings', {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, settings };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Dify 设置失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDifyHealth = async (): Promise<KbDifyHealth | null> => {
|
||||
return getJson<KbDifyHealth | null>('/api/kb/dify/health', null);
|
||||
};
|
||||
|
||||
export const runKbJob = async (
|
||||
jobId: number | string
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; run_result?: string }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob & { run_result?: string }>(`/api/kb/jobs/${jobId}/run`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job, run_result: job.run_result };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '执行任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const createKbDocument = async (
|
||||
groupId: number,
|
||||
payload: { title: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/groups/${groupId}/files`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '创建文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocument = async (
|
||||
documentId: number,
|
||||
payload: { title: string; description?: string; status?: string }
|
||||
): Promise<{ ok: boolean; error?: string; document?: KbDocumentItem }> => {
|
||||
try {
|
||||
const document = await requestJson<KbDocumentItem>(`/api/kb/documents/${documentId}`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, document };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbDocument = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
await requestJson(`/api/kb/documents/${documentId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除文档失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentVersions = async (
|
||||
documentId: number
|
||||
): Promise<KbDocumentVersionItem[]> => {
|
||||
return getJson<KbDocumentVersionItem[]>(`/api/kb/documents/${documentId}/versions`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentVersionSourceFile = async (
|
||||
versionId: number
|
||||
): Promise<{ ok: boolean; error?: string; blob?: Blob; filename?: string; contentType?: string }> => {
|
||||
try {
|
||||
const res = await fetch(`/api/kb/document-versions/${versionId}/source-file`, {
|
||||
headers: getAuthHeaders(),
|
||||
});
|
||||
if (!res.ok) {
|
||||
let message = '读取原始文件失败';
|
||||
try {
|
||||
const data = await res.json();
|
||||
if (typeof data?.error === 'string' && data.error.trim()) message = data.error;
|
||||
else if (typeof data?.message === 'string' && data.message.trim()) message = data.message;
|
||||
} catch {
|
||||
// ignore non-json error body
|
||||
}
|
||||
return { ok: false, error: message };
|
||||
}
|
||||
const disposition = res.headers.get('content-disposition') || '';
|
||||
const filenameMatch = disposition.match(/filename\*=UTF-8''([^;]+)|filename="?([^"]+)"?/i);
|
||||
const filename = decodeURIComponent(filenameMatch?.[1] || filenameMatch?.[2] || '');
|
||||
return {
|
||||
ok: true,
|
||||
blob: await res.blob(),
|
||||
filename: filename || undefined,
|
||||
contentType: res.headers.get('content-type') || undefined,
|
||||
};
|
||||
} catch {
|
||||
return { ok: false, error: '知识库接口暂未就绪,请稍后再试' };
|
||||
}
|
||||
};
|
||||
|
||||
export const getKbDocumentSyncRecords = async (
|
||||
documentId: number
|
||||
): Promise<KbSyncRecordItem[]> => {
|
||||
return getJson<KbSyncRecordItem[]>(`/api/kb/documents/${documentId}/sync-records`, []);
|
||||
};
|
||||
|
||||
export const getKbDocumentMarkdown = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, auth());
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '读取清洗后的 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbDocumentMarkdown = async (
|
||||
documentId: number,
|
||||
payload: { content: string }
|
||||
): Promise<{ ok: boolean; error?: string; data?: KbDocumentMarkdown }> => {
|
||||
try {
|
||||
const data = await requestJson<KbDocumentMarkdown>(`/api/kb/documents/${documentId}/markdown`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, data };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '保存 Markdown 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbDocumentVersion = async (
|
||||
documentId: number,
|
||||
file: File
|
||||
): 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 payload = await requestJson<KbUploadVersionResponse>(`/api/kb/documents/${documentId}/upload`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
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) {
|
||||
return {
|
||||
ok: false,
|
||||
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||
status: 413,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: kbErrorMessage(e, '上传文档版本失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
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: {
|
||||
total_files: number;
|
||||
selected_paths: string[];
|
||||
files?: Array<{ relative_path: string; original_name: string }>;
|
||||
}
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/groups/${groupId}/path-upload-jobs`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '创建路径上传任务失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const uploadKbPathJobFile = async (
|
||||
jobId: number | string,
|
||||
file: File,
|
||||
relativePath: string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const formData = new FormData();
|
||||
formData.append('file', file);
|
||||
formData.append('relative_path', relativePath);
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
body: formData,
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
if (err.status === 413) {
|
||||
return {
|
||||
ok: false,
|
||||
error: '文件过大,超过当前上传限制,请联系管理员放宽限制后重试',
|
||||
status: 413,
|
||||
};
|
||||
}
|
||||
return { ok: false, error: kbErrorMessage(e, '上传路径文件失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const markKbPathJobFileFailed = async (
|
||||
jobId: number | string,
|
||||
payload: { relative_path: string; original_name?: string; error: string }
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/files/fail`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '记录路径文件失败状态失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const finalizeKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/path-upload-jobs/${jobId}/finalize`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '提交路径上传任务失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const retryFailedKbPathUploadJob = async (
|
||||
jobId: number | string,
|
||||
payload?: { relative_paths?: string[] },
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; status?: number }> => {
|
||||
try {
|
||||
const job = await requestJson<KbJob>(`/api/kb/path-upload-jobs/${jobId}/retry-failed`, {
|
||||
method: 'POST',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload || {}),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
const err = e as BusinessError;
|
||||
return { ok: false, error: kbErrorMessage(e, '重试失败文件失败'), status: err.status };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbPathJobFile = async (
|
||||
jobId: number | string,
|
||||
relativePath: string,
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbJob; document_deleted?: boolean }> => {
|
||||
try {
|
||||
const query = new URLSearchParams({ relative_path: relativePath });
|
||||
const result = await requestJson<{ ok: boolean; job: KbJob; document_deleted?: boolean }>(
|
||||
`/api/kb/path-upload-jobs/${jobId}/files?${query.toString()}`,
|
||||
{ method: 'DELETE', ...auth() }
|
||||
);
|
||||
return { ok: true, job: result.job, document_deleted: result.document_deleted };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除路径上传文件失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const syncKbDocumentToDify = async (
|
||||
documentId: number
|
||||
): Promise<{ ok: boolean; error?: string; job?: KbQueuedJobResponse }> => {
|
||||
try {
|
||||
const job = await requestJson<KbQueuedJobResponse>(`/api/kb/documents/${documentId}/sync`, {
|
||||
method: 'POST',
|
||||
...auth(),
|
||||
});
|
||||
return { ok: true, job };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '同步到 Dify 失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const updateKbGroup = async (
|
||||
groupId: number,
|
||||
payload: { name: string; description?: string }
|
||||
): Promise<{ ok: boolean; error?: string; group?: KbGroup }> => {
|
||||
try {
|
||||
const group = await requestJson<KbGroup>(`/api/kb/groups/${groupId}`, {
|
||||
method: 'PATCH',
|
||||
...jsonAuth(),
|
||||
body: JSON.stringify(payload),
|
||||
});
|
||||
return { ok: true, group };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '更新知识库分组失败') };
|
||||
}
|
||||
};
|
||||
|
||||
export const deleteKbGroup = async (
|
||||
groupId: number
|
||||
): Promise<{ ok: boolean; error?: string }> => {
|
||||
try {
|
||||
await requestJson(`/api/kb/groups/${groupId}`, { method: 'DELETE', ...auth() });
|
||||
return { ok: true };
|
||||
} catch (e) {
|
||||
return { ok: false, error: kbErrorMessage(e, '删除知识库分组失败') };
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,83 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/kb/components/DifyHealthDialog.vue
|
||||
* 知识库 Dify 健康检查弹窗。
|
||||
*/
|
||||
|
||||
import { ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getKbDifyHealth, type KbDifyHealth } from '../api/kb.api';
|
||||
|
||||
const props = defineProps<{ open: boolean }>();
|
||||
const emit = defineEmits<{ close: []; error: [message: string] }>();
|
||||
const { t } = useI18n();
|
||||
|
||||
const loading = ref(false);
|
||||
const payload = ref<KbDifyHealth | null>(null);
|
||||
|
||||
const close = () => emit('close');
|
||||
|
||||
const loadHealth = async () => {
|
||||
loading.value = true;
|
||||
payload.value = await getKbDifyHealth();
|
||||
loading.value = false;
|
||||
if (!payload.value) emit('error', t('kbDifyHealth.msg.loadFailed'));
|
||||
};
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) void loadHealth();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="open" class="dialog-overlay" @click="close">
|
||||
<div class="dialog-panel max-w-4xl p-6" @click.stop>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="section-title text-xl">{{ t('kbDifyHealth.title') }}</h3>
|
||||
<p class="section-desc mt-1">{{ t('kbDifyHealth.subtitle') }}</p>
|
||||
</div>
|
||||
<div class="flex items-center gap-3">
|
||||
<button type="button" class="btn-secondary btn-sm" @click="loadHealth">
|
||||
{{ t('common.refresh') }}
|
||||
</button>
|
||||
<button type="button" class="btn-secondary btn-sm" @click="close">
|
||||
{{ t('common.close') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="py-16 text-center text-sm text-muted">{{ t('kbDifyHealth.loading') }}</div>
|
||||
<div v-else-if="payload" class="mt-6 grid gap-4 md:grid-cols-2 xl:grid-cols-3">
|
||||
<div class="dialog-stat-card">
|
||||
<div class="label-field">Dify API</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.api.reachable ? t('kbDifyHealth.reachable') : t('kbDifyHealth.unreachable') }}</div>
|
||||
<div class="mt-2 break-all text-xs text-muted">{{ payload.dify_base_url || t('kbDifyHealth.notConfigured') }}</div>
|
||||
</div>
|
||||
<div class="dialog-stat-card">
|
||||
<div class="label-field">{{ t('kbDifyHealth.datasetCount') }}</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.api.dataset_count ?? '--' }}</div>
|
||||
<div class="mt-2 text-xs text-muted">{{ t('kbDifyHealth.configured') }}{{ payload.dify_api_configured ? t('common.yes') : t('common.no') }}</div>
|
||||
</div>
|
||||
<div class="dialog-stat-card">
|
||||
<div class="label-field">{{ t('kbDifyHealth.boundGroups') }}</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.dataset_bound_groups }}</div>
|
||||
<div class="mt-2 text-xs text-muted">{{ t('kbDifyHealth.localSyncRecords') }}{{ payload.local_sync_health.sync_records }}</div>
|
||||
</div>
|
||||
<div class="dialog-stat-card">
|
||||
<div class="label-field">{{ t('kbDifyHealth.syncingVersions') }}</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.syncing_versions }}</div>
|
||||
</div>
|
||||
<div class="dialog-stat-card">
|
||||
<div class="label-field">{{ t('kbDifyHealth.syncedVersions') }}</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.synced_versions }}</div>
|
||||
</div>
|
||||
<div class="dialog-stat-card">
|
||||
<div class="label-field">{{ t('kbDifyHealth.pendingSyncJobs') }}</div>
|
||||
<div class="mt-3 text-2xl font-semibold text-primary">{{ payload.local_sync_health.pending_sync_jobs }}</div>
|
||||
<div v-if="payload.api.error" class="mt-2 text-xs text-rose-500">{{ payload.api.error }}</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,119 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/kb/components/DifySettingsDialog.vue
|
||||
* 知识库 Dify 配置弹窗。
|
||||
*/
|
||||
|
||||
import { reactive, ref, watch } from 'vue';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { getKbDifySettings, updateKbDifySettings } from '../api/kb.api';
|
||||
|
||||
const props = defineProps<{ open: boolean }>();
|
||||
const emit = defineEmits<{ close: []; saved: [message: string]; error: [message: string] }>();
|
||||
const { t } = useI18n();
|
||||
|
||||
const loading = ref(false);
|
||||
const saving = ref(false);
|
||||
const form = reactive({
|
||||
DIFY_API_BASE: '',
|
||||
DIFY_API_KEY: '',
|
||||
KB_DIFY_PERMISSION: 'only_me',
|
||||
KB_DIFY_INDEXING_TECHNIQUE: 'high_quality',
|
||||
KB_DIFY_SEARCH_METHOD: 'semantic_search',
|
||||
KB_DIFY_DOC_FORM: 'text_model',
|
||||
});
|
||||
|
||||
const close = () => emit('close');
|
||||
|
||||
const loadSettings = async () => {
|
||||
loading.value = true;
|
||||
const settings = await getKbDifySettings();
|
||||
loading.value = false;
|
||||
if (!settings) {
|
||||
emit('error', t('kbDifySettings.msg.loadFailed'));
|
||||
return;
|
||||
}
|
||||
Object.assign(form, settings);
|
||||
};
|
||||
|
||||
const save = async () => {
|
||||
saving.value = true;
|
||||
const result = await updateKbDifySettings(form);
|
||||
saving.value = false;
|
||||
if (!result.ok) {
|
||||
emit('error', result.error || t('kbDifySettings.msg.saveFailed'));
|
||||
return;
|
||||
}
|
||||
emit('saved', t('kbDifySettings.msg.saved'));
|
||||
emit('close');
|
||||
};
|
||||
|
||||
watch(() => props.open, (open) => {
|
||||
if (open) void loadSettings();
|
||||
});
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div v-if="open" class="dialog-overlay" @click="close">
|
||||
<div class="dialog-panel max-w-3xl p-6" @click.stop>
|
||||
<div class="flex items-center justify-between gap-4">
|
||||
<div>
|
||||
<h3 class="section-title text-xl">{{ t('kbDifySettings.title') }}</h3>
|
||||
<p class="section-desc mt-1">{{ t('kbDifySettings.subtitle') }}</p>
|
||||
</div>
|
||||
<button type="button" class="btn-secondary btn-sm" @click="close">
|
||||
{{ t('common.close') }}
|
||||
</button>
|
||||
</div>
|
||||
|
||||
<div v-if="loading" class="py-16 text-center text-sm text-muted">{{ t('kbDifySettings.loading') }}</div>
|
||||
<div v-else class="mt-6 grid gap-4 md:grid-cols-2 form-stack">
|
||||
<label class="space-y-2 md:col-span-2">
|
||||
<span class="label-field block">Dify Base URL</span>
|
||||
<input v-model="form.DIFY_API_BASE" class="input-field" placeholder="https://api.dify.ai/v1" />
|
||||
</label>
|
||||
<label class="space-y-2 md:col-span-2">
|
||||
<span class="label-field block">Dify API Key</span>
|
||||
<input v-model="form.DIFY_API_KEY" class="input-field" placeholder="app-..." />
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Permission</span>
|
||||
<select v-model="form.KB_DIFY_PERMISSION" class="input-field">
|
||||
<option value="only_me">only_me</option>
|
||||
<option value="all_team_members">all_team_members</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Indexing Technique</span>
|
||||
<select v-model="form.KB_DIFY_INDEXING_TECHNIQUE" class="input-field">
|
||||
<option value="high_quality">high_quality</option>
|
||||
<option value="economy">economy</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Search Method</span>
|
||||
<select v-model="form.KB_DIFY_SEARCH_METHOD" class="input-field">
|
||||
<option value="semantic_search">semantic_search</option>
|
||||
<option value="hybrid_search">hybrid_search</option>
|
||||
<option value="full_text_search">full_text_search</option>
|
||||
</select>
|
||||
</label>
|
||||
<label class="space-y-2">
|
||||
<span class="label-field block">Doc Form</span>
|
||||
<select v-model="form.KB_DIFY_DOC_FORM" class="input-field">
|
||||
<option value="text_model">text_model</option>
|
||||
</select>
|
||||
</label>
|
||||
</div>
|
||||
|
||||
<div class="mt-6 flex justify-end gap-3">
|
||||
<button type="button" class="btn-secondary" @click="close">
|
||||
{{ t('common.cancel') }}
|
||||
</button>
|
||||
<button type="button" class="btn-primary" :disabled="saving" @click="save">
|
||||
{{ saving ? t('kbDifySettings.saving') : t('kbDifySettings.save') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
@@ -0,0 +1,380 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/kb/components/KbAdminPanel.vue
|
||||
* 知识库配置面板(治理面:分组、Dify、任务队列)。
|
||||
*/
|
||||
|
||||
import { computed, onMounted, ref } from 'vue';
|
||||
import { useRouter } from 'vue-router';
|
||||
import { useI18n } from 'vue-i18n';
|
||||
import { Activity, FolderPlus, Pencil, Play, Settings, Trash2, Wrench, X } from 'lucide-vue-next';
|
||||
import DifyHealthDialog from './DifyHealthDialog.vue';
|
||||
import DifySettingsDialog from './DifySettingsDialog.vue';
|
||||
import DeleteConfirmDialog from '@/shared/components/DeleteConfirmDialog.vue';
|
||||
import { WORKSPACE_PATHS } from '@/features/workspace/constants/routes';
|
||||
import {
|
||||
createKbGroup,
|
||||
deleteKbGroup,
|
||||
getKbGroupsSafe,
|
||||
getKbJobsSafe,
|
||||
runKbJob,
|
||||
updateKbGroup,
|
||||
type KbGroup,
|
||||
type KbJob,
|
||||
} from '../api/kb.api';
|
||||
|
||||
const router = useRouter();
|
||||
const { t } = useI18n();
|
||||
|
||||
const groups = ref<KbGroup[]>([]);
|
||||
const jobs = ref<KbJob[]>([]);
|
||||
const isSubmitting = ref(false);
|
||||
const isRefreshing = ref(false);
|
||||
const editingGroupId = ref<number | null>(null);
|
||||
const form = ref({
|
||||
name: '',
|
||||
description: '',
|
||||
});
|
||||
const feedback = ref('');
|
||||
const feedbackType = ref<'success' | 'error' | ''>('');
|
||||
const runningJobId = ref<number | string | null>(null);
|
||||
const settingsDialogOpen = ref(false);
|
||||
const healthDialogOpen = ref(false);
|
||||
const deleteDialogOpen = ref(false);
|
||||
const deletingGroup = ref<KbGroup | null>(null);
|
||||
|
||||
const formTitle = computed(() => editingGroupId.value ? t('kbAdmin.form.editTitle') : t('kbAdmin.form.createTitle'));
|
||||
const formDescription = computed(() => editingGroupId.value
|
||||
? t('kbAdmin.form.editDesc')
|
||||
: t('kbAdmin.form.createDesc'));
|
||||
const submitText = computed(() => {
|
||||
if (isSubmitting.value) return editingGroupId.value ? t('kbAdmin.form.saving') : t('kbAdmin.form.submitting');
|
||||
return editingGroupId.value ? t('kbAdmin.form.saveChanges') : t('kbAdmin.form.create');
|
||||
});
|
||||
|
||||
const loadData = async () => {
|
||||
isRefreshing.value = true;
|
||||
const [groupsResult, jobsResult] = await Promise.all([getKbGroupsSafe(), getKbJobsSafe()]);
|
||||
if (groupsResult.ok) {
|
||||
groups.value = groupsResult.data;
|
||||
} else {
|
||||
feedback.value = groupsResult.error || t('kbAdmin.msg.loadGroupsFailed');
|
||||
feedbackType.value = 'error';
|
||||
}
|
||||
if (jobsResult.ok) {
|
||||
jobs.value = jobsResult.data;
|
||||
} else {
|
||||
feedback.value = jobsResult.error || t('kbAdmin.msg.loadJobsFailed');
|
||||
feedbackType.value = 'error';
|
||||
}
|
||||
isRefreshing.value = false;
|
||||
};
|
||||
|
||||
const resetForm = () => {
|
||||
editingGroupId.value = null;
|
||||
form.value = { name: '', description: '' };
|
||||
};
|
||||
|
||||
const handleCreateGroup = async () => {
|
||||
if (!form.value.name.trim()) {
|
||||
feedback.value = t('kbAdmin.msg.nameRequired');
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
isSubmitting.value = true;
|
||||
const payload = {
|
||||
name: form.value.name.trim(),
|
||||
description: form.value.description.trim(),
|
||||
};
|
||||
const result = editingGroupId.value
|
||||
? await updateKbGroup(editingGroupId.value, payload)
|
||||
: await createKbGroup(payload);
|
||||
isSubmitting.value = false;
|
||||
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || t('kbAdmin.msg.createFailed');
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
feedback.value = editingGroupId.value ? t('kbAdmin.msg.updated') : t('kbAdmin.msg.created');
|
||||
feedbackType.value = 'success';
|
||||
resetForm();
|
||||
await loadData();
|
||||
};
|
||||
|
||||
const handleEditGroup = (group: KbGroup) => {
|
||||
editingGroupId.value = group.id;
|
||||
form.value = {
|
||||
name: group.name,
|
||||
description: group.description || '',
|
||||
};
|
||||
feedback.value = '';
|
||||
feedbackType.value = '';
|
||||
};
|
||||
|
||||
const handleDeleteGroup = async (group: KbGroup) => {
|
||||
deletingGroup.value = group;
|
||||
deleteDialogOpen.value = true;
|
||||
};
|
||||
|
||||
const handleDeleteGroupConfirm = async () => {
|
||||
if (!deletingGroup.value) return;
|
||||
const result = await deleteKbGroup(deletingGroup.value.id);
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || t('kbAdmin.msg.deleteFailed');
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
if (editingGroupId.value === deletingGroup.value.id) {
|
||||
resetForm();
|
||||
}
|
||||
feedback.value = t('kbAdmin.msg.deleted');
|
||||
feedbackType.value = 'success';
|
||||
deleteDialogOpen.value = false;
|
||||
deletingGroup.value = null;
|
||||
await loadData();
|
||||
};
|
||||
|
||||
const handleRunJob = async (job: KbJob) => {
|
||||
runningJobId.value = job.id;
|
||||
const result = await runKbJob(job.id);
|
||||
runningJobId.value = null;
|
||||
|
||||
if (!result.ok) {
|
||||
feedback.value = result.error || t('kbAdmin.msg.runFailed');
|
||||
feedbackType.value = 'error';
|
||||
return;
|
||||
}
|
||||
|
||||
feedback.value = result.run_result || t('kbAdmin.msg.runDone');
|
||||
feedbackType.value = 'success';
|
||||
await loadData();
|
||||
};
|
||||
|
||||
onMounted(async () => {
|
||||
await loadData();
|
||||
});
|
||||
|
||||
defineExpose({ loadData });
|
||||
</script>
|
||||
|
||||
<template>
|
||||
<div class="animate-fade-in-up">
|
||||
<div class="kb-admin-header">
|
||||
<div class="min-w-0 flex-1">
|
||||
<h2 class="text-xl font-bold text-primary">{{ t('kbAdmin.title') }}</h2>
|
||||
<p class="section-desc mt-1">
|
||||
{{ t('kbAdmin.subtitle') }}
|
||||
</p>
|
||||
</div>
|
||||
<div class="flex w-full shrink-0 flex-col gap-2 sm:w-auto sm:flex-row sm:items-center sm:justify-end">
|
||||
<div
|
||||
class="kb-admin-toolbar"
|
||||
role="toolbar"
|
||||
:aria-label="t('kbAdmin.toolbar')"
|
||||
>
|
||||
<button
|
||||
type="button"
|
||||
class="kb-admin-toolbar-btn"
|
||||
@click="settingsDialogOpen = true"
|
||||
:title="t('kbAdmin.difySettings')"
|
||||
>
|
||||
<Settings class="h-4 w-4 shrink-0" />
|
||||
<span class="whitespace-nowrap">{{ t('kbAdmin.difySettings') }}</span>
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="kb-admin-toolbar-btn"
|
||||
@click="healthDialogOpen = true"
|
||||
:title="t('kbAdmin.healthCheck')"
|
||||
>
|
||||
<Activity class="h-4 w-4 shrink-0" />
|
||||
<span class="whitespace-nowrap">{{ t('kbAdmin.healthCheck') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary inline-flex w-full items-center justify-center gap-2 px-5 py-2.5 text-sm sm:w-auto"
|
||||
@click="router.push(WORKSPACE_PATHS.knowledgeBase)"
|
||||
>
|
||||
<Wrench class="h-4 w-4 shrink-0" />
|
||||
<span class="whitespace-nowrap">{{ t('kbAdmin.goWorkspace') }}</span>
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="kb-admin-body">
|
||||
<section class="kb-admin-section">
|
||||
<div class="mb-5 flex items-center gap-3">
|
||||
<div class="flex h-10 w-10 items-center justify-center rounded-2xl bg-brand-50 text-brand-600">
|
||||
<FolderPlus class="h-5 w-5" />
|
||||
</div>
|
||||
<div>
|
||||
<h3 class="section-title">{{ formTitle }}</h3>
|
||||
<p class="section-desc">{{ formDescription }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="label-field mb-2 block">{{ t('kbAdmin.form.groupName') }}</label>
|
||||
<input v-model="form.name" class="input-field" :placeholder="t('kbAdmin.form.groupNamePlaceholder')" />
|
||||
</div>
|
||||
<div>
|
||||
<label class="label-field mb-2 block">{{ t('kbAdmin.form.groupDesc') }}</label>
|
||||
<textarea
|
||||
v-model="form.description"
|
||||
rows="4"
|
||||
class="input-field"
|
||||
:placeholder="t('kbAdmin.form.groupDescPlaceholder')"
|
||||
/>
|
||||
</div>
|
||||
<div class="flex flex-wrap items-center justify-end gap-2 border-t border-subtle pt-4">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-primary inline-flex items-center gap-1.5 px-5 py-2 text-sm disabled:cursor-not-allowed disabled:opacity-60"
|
||||
@click="handleCreateGroup"
|
||||
:disabled="isSubmitting"
|
||||
>
|
||||
<FolderPlus v-if="!isSubmitting" class="h-4 w-4 shrink-0" />
|
||||
{{ submitText }}
|
||||
</button>
|
||||
<button
|
||||
v-if="editingGroupId"
|
||||
type="button"
|
||||
class="btn-secondary inline-flex items-center gap-1.5 px-4 py-2 text-sm"
|
||||
@click="resetForm"
|
||||
>
|
||||
<X class="h-4 w-4 shrink-0" />
|
||||
{{ t('kbAdmin.form.cancelEdit') }}
|
||||
</button>
|
||||
</div>
|
||||
<p
|
||||
v-if="feedback"
|
||||
class="text-sm"
|
||||
:class="feedbackType === 'error' ? 'text-rose-500' : 'text-emerald-600'"
|
||||
>
|
||||
{{ feedback }}
|
||||
</p>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<div class="space-y-6">
|
||||
<section class="kb-admin-section">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h3 class="section-title">{{ t('kbAdmin.groupsTitle') }}</h3>
|
||||
<span class="text-xs text-muted">{{ isRefreshing ? t('common.loading') : '/api/kb/groups' }}</span>
|
||||
</div>
|
||||
<div v-if="groups.length === 0" class="kb-admin-empty">
|
||||
{{ t('kbAdmin.groupsEmpty') }}
|
||||
</div>
|
||||
<div v-else class="grid grid-cols-1 gap-3 md:grid-cols-2">
|
||||
<div
|
||||
v-for="group in groups"
|
||||
:key="group.id"
|
||||
class="kb-admin-card"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold text-primary">{{ group.name }}</div>
|
||||
<div class="mt-1 text-sm text-muted">{{ group.description || t('kbAdmin.noDescription') }}</div>
|
||||
</div>
|
||||
<div class="kb-admin-badge">
|
||||
{{ t('kbAdmin.documentCount', { count: group.document_count ?? 0 }) }}
|
||||
</div>
|
||||
</div>
|
||||
<div class="mt-4 flex flex-wrap items-center justify-between gap-3">
|
||||
<div class="text-xs text-muted">
|
||||
{{ t('kbAdmin.updatedAt') }}{{ group.updated_at || '--' }}
|
||||
</div>
|
||||
<div class="flex items-center gap-2">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary inline-flex items-center gap-1 px-3 py-2 text-xs"
|
||||
@click="handleEditGroup(group)"
|
||||
>
|
||||
<Pencil class="h-3.5 w-3.5" />
|
||||
{{ t('common.edit') }}
|
||||
</button>
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-rose-200 px-3 py-2 text-xs font-medium text-rose-600 transition-colors hover:bg-rose-50"
|
||||
@click="handleDeleteGroup(group)"
|
||||
>
|
||||
<Trash2 class="h-3.5 w-3.5" />
|
||||
{{ t('common.delete') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<section class="kb-admin-section">
|
||||
<div class="mb-4 flex items-center justify-between">
|
||||
<h3 class="section-title">{{ t('kbAdmin.jobsTitle') }}</h3>
|
||||
<span class="text-xs text-muted">/api/kb/jobs</span>
|
||||
</div>
|
||||
<div v-if="jobs.length === 0" class="kb-admin-empty">
|
||||
{{ t('kbAdmin.jobsEmpty') }}
|
||||
</div>
|
||||
<div v-else class="space-y-3">
|
||||
<div
|
||||
v-for="job in jobs"
|
||||
:key="job.id"
|
||||
class="kb-admin-card"
|
||||
>
|
||||
<div class="flex items-start justify-between gap-3">
|
||||
<div class="min-w-0">
|
||||
<div class="font-semibold text-primary">{{ job.job_type }}</div>
|
||||
<div class="mt-1 text-sm text-muted">{{ job.created_at || '--' }}</div>
|
||||
<div class="mt-2 text-sm text-muted">
|
||||
{{ job.message || t('kbAdmin.noJobMessage') }}
|
||||
</div>
|
||||
<div class="mt-2 text-xs text-muted">
|
||||
{{ t('kbAdmin.jobMeta', { docId: job.document_id ?? '--', versionId: job.document_version_id ?? '--', progress: job.progress ?? 0 }) }}
|
||||
</div>
|
||||
</div>
|
||||
<span class="kb-admin-badge">
|
||||
{{ job.status }}
|
||||
</span>
|
||||
</div>
|
||||
<div v-if="['clean', 'sync_dify'].includes(job.job_type) && job.status !== 'success'" class="mt-3 flex justify-end">
|
||||
<button
|
||||
type="button"
|
||||
class="inline-flex items-center gap-1 rounded-xl border border-brand-200 px-3 py-2 text-xs font-medium text-brand-700 transition-colors hover:bg-brand-50 disabled:cursor-not-allowed disabled:opacity-60"
|
||||
@click="handleRunJob(job)"
|
||||
:disabled="runningJobId === job.id"
|
||||
>
|
||||
<Play class="h-3.5 w-3.5" />
|
||||
{{ runningJobId === job.id ? t('kbAdmin.running') : t('kbAdmin.runJob') }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<DifySettingsDialog
|
||||
:open="settingsDialogOpen"
|
||||
@close="settingsDialogOpen = false"
|
||||
@saved="(message) => { feedback = message; feedbackType = 'success'; void loadData(); }"
|
||||
@error="(message) => { feedback = message; feedbackType = 'error'; }"
|
||||
/>
|
||||
<DifyHealthDialog
|
||||
:open="healthDialogOpen"
|
||||
@close="healthDialogOpen = false"
|
||||
@error="(message) => { feedback = message; feedbackType = 'error'; }"
|
||||
/>
|
||||
<DeleteConfirmDialog
|
||||
v-model="deleteDialogOpen"
|
||||
:title="t('kbAdmin.deleteDialog.title')"
|
||||
:message="t('kbAdmin.deleteDialog.message', { name: deletingGroup?.name || '' })"
|
||||
@confirm="handleDeleteGroupConfirm"
|
||||
@cancel="() => { deleteDialogOpen = false; deletingGroup = null; }"
|
||||
/>
|
||||
</template>
|
||||
@@ -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,
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* features/kb/types/kb-workspace.types.ts
|
||||
* 知识库作业面类型与分页/批处理常量。
|
||||
*/
|
||||
import type { KbDocumentItem, KbJob } from '../api/kb.api';
|
||||
|
||||
/** 作业面视图:分组概览(只读选择)或分组内文档维护 */
|
||||
export type KbWorkspaceViewMode = 'group_overview' | 'group_detail';
|
||||
|
||||
export type KbFeedbackType = 'success' | 'error' | '';
|
||||
|
||||
/** 上传 → 清洗 → 同步 各阶段展示状态 */
|
||||
export type WorkflowStageState = {
|
||||
code: 'pending' | 'running' | 'success' | 'failed' | 'idle';
|
||||
label: string;
|
||||
className: string;
|
||||
errorMessage?: string | null;
|
||||
};
|
||||
|
||||
/** 失败弹窗列表项 */
|
||||
export type FailureModalItem = {
|
||||
key: string;
|
||||
document: KbDocumentItem;
|
||||
stage: 'upload' | 'clean' | 'sync';
|
||||
stageLabel: string;
|
||||
errorMessage: string;
|
||||
latestJob: KbJob | null;
|
||||
updatedAt?: string | null;
|
||||
};
|
||||
|
||||
export type PathUploadStatus = 'queued' | 'uploading' | 'success' | 'failed';
|
||||
|
||||
export type PathUploadTaskItem = {
|
||||
key: string;
|
||||
title: string;
|
||||
displayPath: string;
|
||||
rootLabel: string;
|
||||
status: PathUploadStatus;
|
||||
error?: string;
|
||||
documentId?: number;
|
||||
retryable?: boolean;
|
||||
startedAt?: string;
|
||||
finishedAt?: string;
|
||||
};
|
||||
|
||||
/** 静默刷新时不切换 loading 态,避免列表闪烁 */
|
||||
export type LoadListOptions = {
|
||||
silent?: boolean;
|
||||
};
|
||||
|
||||
export const FAILURE_PAGE_SIZE = 15;
|
||||
export const PATH_UPLOAD_BATCH_SIZE = 30;
|
||||
export const PATH_UPLOAD_BATCH_INTERVAL_MS = 500;
|
||||
export const PATH_UPLOAD_CONCURRENCY = 3;
|
||||
export const DOCUMENT_PAGE_SIZE_OPTIONS = [20, 50, 100, 200] as const;
|
||||
|
||||
/** 未开始阶段的徽标样式,与 getStatusBadgeClass 默认一致 */
|
||||
export const IDLE_BADGE_CLASS = 'border-default bg-surface-soft text-muted';
|
||||
@@ -0,0 +1,84 @@
|
||||
/**
|
||||
* features/kb/utils/kb-display.utils.ts
|
||||
* 文档标题、时间、文件大小与状态徽标等纯展示工具。
|
||||
*/
|
||||
import type { KbDocumentItem } from '../api/kb.api';
|
||||
|
||||
export const formatDateTime = (value?: string | null) => {
|
||||
if (!value) return '--';
|
||||
const date = new Date(value);
|
||||
if (Number.isNaN(date.getTime())) return value;
|
||||
const pad = (n: number) => String(n).padStart(2, '0');
|
||||
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
||||
};
|
||||
|
||||
export const formatFileSize = (value?: number | null) => {
|
||||
const size = Number(value || 0);
|
||||
if (!Number.isFinite(size) || size <= 0) return '0 B';
|
||||
if (size < 1024) return `${size} B`;
|
||||
if (size < 1024 * 1024) return `${(size / 1024).toFixed(1)} KB`;
|
||||
if (size < 1024 * 1024 * 1024) return `${(size / (1024 * 1024)).toFixed(1)} MB`;
|
||||
return `${(size / (1024 * 1024 * 1024)).toFixed(1)} GB`;
|
||||
};
|
||||
|
||||
const trimPathText = (value?: string | null) => {
|
||||
const text = String(value || '').trim();
|
||||
if (!text) return '';
|
||||
return text.split(/[\\/]/).filter(Boolean).pop() || text;
|
||||
};
|
||||
|
||||
export const getDocumentDisplayTitle = (doc: KbDocumentItem) => trimPathText(doc.title) || '未命名文档';
|
||||
|
||||
export const getDocumentDisplayDescription = (doc: KbDocumentItem) => {
|
||||
const text = trimPathText(doc.description);
|
||||
return text || getDocumentDisplayTitle(doc);
|
||||
};
|
||||
|
||||
/** 将后端重复文档错误归一为前端可展示的简短文案 */
|
||||
export const normalizeDuplicateDocumentError = (message?: string | null) => {
|
||||
const text = String(message || '').trim();
|
||||
if (!text) return '知识库接口请求失败';
|
||||
if (text.includes('当前分组下已存在同名文档') || text.includes('上传失败,文件已存在')) {
|
||||
return '上传失败,文件已存在';
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
export const getStatusLabel = (status?: string | null) => {
|
||||
const normalized = String(status || '').toLowerCase();
|
||||
const map: Record<string, string> = {
|
||||
draft: '待上传',
|
||||
uploaded: '已上传',
|
||||
processing: '清洗中',
|
||||
cleaned: '已清洗',
|
||||
ready: '已就绪',
|
||||
synced: '已同步',
|
||||
syncing: '同步中',
|
||||
failed: '失败',
|
||||
queued: '排队中',
|
||||
running: '进行中',
|
||||
success: '成功',
|
||||
cancelled: '已取消',
|
||||
};
|
||||
return map[normalized] || status || '未知状态';
|
||||
};
|
||||
|
||||
export const getStatusBadgeClass = (status?: string | null) => {
|
||||
const normalized = String(status || '').toLowerCase();
|
||||
if (['cleaned', 'ready', 'synced', 'success'].includes(normalized)) {
|
||||
return 'border-emerald-200 bg-emerald-50 text-emerald-700';
|
||||
}
|
||||
if (['processing', 'running'].includes(normalized)) {
|
||||
return 'border-amber-200 bg-amber-50 text-amber-700';
|
||||
}
|
||||
if (['uploaded', 'queued', 'draft'].includes(normalized)) {
|
||||
return 'border-sky-200 bg-sky-50 text-sky-700';
|
||||
}
|
||||
if (normalized === 'failed') {
|
||||
return 'border-rose-200 bg-rose-50 text-rose-700';
|
||||
}
|
||||
if (normalized === 'cancelled') {
|
||||
return 'border-default bg-surface-soft text-secondary';
|
||||
}
|
||||
return 'border-default bg-surface-soft text-secondary';
|
||||
};
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* features/kb/utils/kb-list.utils.ts
|
||||
* 列表合并工具:轮询刷新时保持已有项顺序,减少 UI 跳动。
|
||||
*/
|
||||
|
||||
/** 按当前列表顺序合并服务端数据,新增项追加在末尾 */
|
||||
export function mergeStableItems<T extends { id: number | string }>(current: T[], incoming: T[]): T[] {
|
||||
const incomingMap = new Map(incoming.map((item) => [String(item.id), item] as const));
|
||||
const next: T[] = [];
|
||||
const seen = new Set<string>();
|
||||
|
||||
current.forEach((item) => {
|
||||
const key = String(item.id);
|
||||
const incomingItem = incomingMap.get(key);
|
||||
if (!incomingItem) return;
|
||||
next.push(incomingItem);
|
||||
seen.add(key);
|
||||
});
|
||||
|
||||
incoming.forEach((item) => {
|
||||
const key = String(item.id);
|
||||
if (seen.has(key)) return;
|
||||
next.push(item);
|
||||
});
|
||||
|
||||
return next;
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
/**
|
||||
* features/kb/utils/kb-path-upload.utils.ts
|
||||
* 路径上传任务(path_upload job)解析与排序权重。
|
||||
*/
|
||||
import type { KbJob } from '../api/kb.api';
|
||||
import type { PathUploadStatus, PathUploadTaskItem } from '../types/kb-workspace.types';
|
||||
|
||||
export 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 };
|
||||
};
|
||||
|
||||
/** 用于在历史批次列表中优先展示有进度或进行中的任务 */
|
||||
export 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;
|
||||
};
|
||||
|
||||
export const getPathUploadJobItems = (job: KbJob | null): PathUploadTaskItem[] => {
|
||||
if (!job || job.job_type !== 'path_upload') return [];
|
||||
const payload = job.payload_json || {};
|
||||
const files = Array.isArray(payload.files) ? payload.files : [];
|
||||
const failedCount = files.filter((item: { status?: string }) => String(item?.status || '').toLowerCase() === 'failed').length;
|
||||
return files.map((item: Record<string, unknown>, index: number) => ({
|
||||
key: `${job.id}-${item.relative_path || item.original_name || index}`,
|
||||
title: String(item.original_name || item.relative_path || `文件${index + 1}`),
|
||||
displayPath: String(item.relative_path || item.original_name || ''),
|
||||
rootLabel: String(item.relative_path || item.original_name || '').split('/')[0] || '本地目录',
|
||||
status: (['queued', 'uploading', 'success', 'failed'].includes(String(item.status))
|
||||
? item.status
|
||||
: 'queued') as PathUploadStatus,
|
||||
error: (item.error as string | undefined)
|
||||
|| (String(item.status || '').toLowerCase() === 'failed' && failedCount === 1
|
||||
? (job.error_message || job.message || '上传失败')
|
||||
: undefined),
|
||||
documentId: (item.document_id as number | undefined) || undefined,
|
||||
retryable: Boolean(String(item.staged_path || '').trim()) && String(item.status || '').toLowerCase() === 'failed',
|
||||
startedAt: undefined,
|
||||
finishedAt: undefined,
|
||||
}));
|
||||
};
|
||||
|
||||
export const hasRetryablePathUploadFailure = (job: KbJob | null) =>
|
||||
getPathUploadJobItems(job).some((item) => item.retryable);
|
||||
|
||||
export const getPathUploadJobSummary = (job: KbJob | null) => {
|
||||
const items = getPathUploadJobItems(job);
|
||||
const total = Number(job?.payload_json?.total_files || job?.result_json?.total || items.length || 0);
|
||||
const success = Number(job?.result_json?.success || items.filter((item) => item.status === 'success').length || 0);
|
||||
const failed = Number(job?.result_json?.failed || items.filter((item) => item.status === 'failed').length || 0);
|
||||
const pending = Math.max(total - success - failed, 0);
|
||||
return { total, success, failed, pending };
|
||||
};
|
||||
@@ -0,0 +1,193 @@
|
||||
/**
|
||||
* features/kb/utils/kb-workflow.utils.ts
|
||||
* 文档工作流(上传/清洗/同步)状态推导与错误文案归一。
|
||||
*/
|
||||
import type { KbDocumentItem, KbJob } from '../api/kb.api';
|
||||
import { IDLE_BADGE_CLASS, type WorkflowStageState } from '../types/kb-workspace.types';
|
||||
import { getStatusBadgeClass } from './kb-display.utils';
|
||||
|
||||
export 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);
|
||||
};
|
||||
|
||||
export 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('SOURCE_FILE_NOT_FOUND') || text.includes('源文件不存在')) {
|
||||
return '原始文件不存在,请重新上传后再清洗';
|
||||
}
|
||||
if (upper.includes('CLEAN_TIMEOUT') || text.includes('清洗超时')) {
|
||||
return '文件清洗超时,请稍后重试;若多次失败,请检查源文件是否损坏';
|
||||
}
|
||||
return text;
|
||||
};
|
||||
|
||||
/** 按文档与任务类型取当前分组下最新一条关联任务 */
|
||||
export function buildGetLatestJobForDocument(getActiveGroupJobs: () => KbJob[]) {
|
||||
return (doc: KbDocumentItem, jobType: string): KbJob | null => {
|
||||
const activeGroupJobs = getActiveGroupJobs();
|
||||
const currentVersionId = doc.latest_version?.id;
|
||||
const candidates = activeGroupJobs.filter((job) => {
|
||||
if (job.job_type !== jobType || job.document_id !== doc.id) return false;
|
||||
if (currentVersionId) {
|
||||
return job.document_version_id === currentVersionId;
|
||||
}
|
||||
return true;
|
||||
});
|
||||
if (!candidates.length) return null;
|
||||
return [...candidates].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();
|
||||
if (aTime !== bTime) return bTime - aTime;
|
||||
return Number(b.id) - Number(a.id);
|
||||
})[0] ?? null;
|
||||
};
|
||||
}
|
||||
|
||||
export type GetLatestJobForDocument = ReturnType<typeof buildGetLatestJobForDocument>;
|
||||
|
||||
export const getDocumentWorkflowState = (
|
||||
doc: KbDocumentItem,
|
||||
getLatestJobForDocument: GetLatestJobForDocument,
|
||||
) => {
|
||||
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
|
||||
const uploadJob = getLatestJobForDocument(doc, 'upload');
|
||||
const cleanJob = getLatestJobForDocument(doc, 'clean');
|
||||
const syncJob = getLatestJobForDocument(doc, 'sync_dify');
|
||||
|
||||
const uploadStage: WorkflowStageState = !doc.latest_version
|
||||
? { code: 'pending', label: '待上传', className: getStatusBadgeClass('draft') }
|
||||
: uploadJob?.status === 'failed'
|
||||
? {
|
||||
code: 'failed',
|
||||
label: '失败',
|
||||
className: getStatusBadgeClass('failed'),
|
||||
errorMessage: normalizeWorkflowErrorMessage(uploadJob.error_message || uploadJob.message, 'upload'),
|
||||
}
|
||||
: { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
|
||||
|
||||
let cleanStage: WorkflowStageState;
|
||||
if (!doc.latest_version) {
|
||||
cleanStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
} else if (cleanJob?.status === 'failed' || latestStatus === 'failed') {
|
||||
cleanStage = {
|
||||
code: 'failed',
|
||||
label: '失败',
|
||||
className: getStatusBadgeClass('failed'),
|
||||
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') };
|
||||
} else if (['running', 'queued'].includes(String(cleanJob?.status || '').toLowerCase()) || latestStatus === 'processing') {
|
||||
cleanStage = {
|
||||
code: 'running',
|
||||
label: latestStatus === 'processing' ? '清洗中' : '待清洗',
|
||||
className: getStatusBadgeClass(latestStatus === 'processing' ? 'processing' : 'uploaded'),
|
||||
};
|
||||
} else if (latestStatus === 'uploaded') {
|
||||
cleanStage = { code: 'pending', label: '待清洗', className: getStatusBadgeClass('uploaded') };
|
||||
} else {
|
||||
cleanStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
}
|
||||
|
||||
let syncStage: WorkflowStageState;
|
||||
if (!doc.latest_version || cleanStage.code === 'failed') {
|
||||
syncStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
} else if (syncJob?.status === 'failed') {
|
||||
syncStage = {
|
||||
code: 'failed',
|
||||
label: '失败',
|
||||
className: getStatusBadgeClass('failed'),
|
||||
errorMessage: normalizeWorkflowErrorMessage(syncJob.error_message || syncJob.message, 'sync'),
|
||||
};
|
||||
} else if (latestStatus === 'synced' || syncJob?.status === 'success') {
|
||||
syncStage = { code: 'success', label: '已完成', className: getStatusBadgeClass('success') };
|
||||
} else if (['running', 'queued'].includes(String(syncJob?.status || '').toLowerCase()) || latestStatus === 'syncing') {
|
||||
syncStage = {
|
||||
code: 'running',
|
||||
label: latestStatus === 'syncing' ? '同步中' : '待同步',
|
||||
className: getStatusBadgeClass(latestStatus === 'syncing' ? 'processing' : 'uploaded'),
|
||||
};
|
||||
} else if (['cleaned', 'ready'].includes(latestStatus)) {
|
||||
syncStage = { code: 'pending', label: '待同步', className: getStatusBadgeClass('uploaded') };
|
||||
} else {
|
||||
syncStage = { code: 'idle', label: '未开始', className: IDLE_BADGE_CLASS };
|
||||
}
|
||||
|
||||
const primaryError =
|
||||
syncStage.errorMessage ||
|
||||
cleanStage.errorMessage ||
|
||||
uploadStage.errorMessage ||
|
||||
normalizeWorkflowErrorMessage(doc.latest_version?.error_message, 'clean') ||
|
||||
null;
|
||||
|
||||
return {
|
||||
upload: uploadStage,
|
||||
clean: cleanStage,
|
||||
sync: syncStage,
|
||||
primaryError,
|
||||
};
|
||||
};
|
||||
|
||||
export const getWorkflowBadges = (
|
||||
doc: KbDocumentItem,
|
||||
getLatestJobForDocument: GetLatestJobForDocument,
|
||||
) => {
|
||||
const workflow = getDocumentWorkflowState(doc, getLatestJobForDocument);
|
||||
return [
|
||||
{ label: '上传', value: workflow.upload.label, className: workflow.upload.className },
|
||||
{ label: '清洗', value: workflow.clean.label, className: workflow.clean.className },
|
||||
{ label: '同步', value: workflow.sync.label, className: workflow.sync.className },
|
||||
];
|
||||
};
|
||||
|
||||
export const getMarkdownUnavailableMessage = (
|
||||
doc: KbDocumentItem,
|
||||
_getLatestJobForDocument: GetLatestJobForDocument,
|
||||
fallback?: string | null,
|
||||
) => {
|
||||
const latestStatus = String(doc.latest_version?.status || '').toLowerCase();
|
||||
const normalizedReason = normalizeWorkflowErrorMessage(
|
||||
doc.latest_version?.error_message,
|
||||
'clean',
|
||||
);
|
||||
|
||||
if (latestStatus === 'failed') {
|
||||
return normalizedReason
|
||||
? `当前文档清洗失败,尚未生成 Markdown。失败原因:${normalizedReason}`
|
||||
: '当前文档清洗失败,尚未生成 Markdown,请重新清洗后重试';
|
||||
}
|
||||
|
||||
if (latestStatus === 'processing') {
|
||||
return '当前文档正在清洗中,暂未生成 Markdown,请稍后再试';
|
||||
}
|
||||
|
||||
if (latestStatus === 'uploaded') {
|
||||
return '当前文档待清洗,暂未生成 Markdown,请先发起清洗';
|
||||
}
|
||||
|
||||
return fallback || '当前文档尚未生成 Markdown';
|
||||
};
|
||||
File diff suppressed because it is too large.
Load diff
@@ -19,7 +19,7 @@ export function useWorkspaceSession(deps: WorkspaceDeps, options: SessionOptions
|
||||
|
||||
const isLoggedIn = computed(() => !!currentUser.value && currentUser.value.role !== 'guest');
|
||||
const hasKnowledgeBaseAccess = computed(
|
||||
() => String(currentUser.value?.username || '').trim().toLowerCase() === 'admin',
|
||||
() => String(currentUser.value?.role || '').trim().toLowerCase() === 'admin',
|
||||
);
|
||||
|
||||
const loadAuthUser = () => {
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* @deprecated 请使用 @/features/chat/pages/HistoryPage.vue
|
||||
* @deprecated 请使用 @/features/chat/history/HistoryPage.vue
|
||||
*/
|
||||
import HistoryPage from '@/features/chat/pages/HistoryPage.vue';
|
||||
import HistoryPage from '@/features/chat/history/HistoryPage.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<script setup lang="ts">
|
||||
/**
|
||||
* features/workspace/pages/KnowledgeBasePage.vue
|
||||
* 知识库管理嵌入页,复用 KbWorkspaceView 的 embedded 模式。
|
||||
* 知识库作业面嵌入页,复用 KbWorkspaceView 的 embedded 模式。
|
||||
*/
|
||||
import KbWorkspaceView from '@/views/KbWorkspaceView.vue';
|
||||
import KbWorkspaceView from '@/features/kb/views/KbWorkspaceView.vue';
|
||||
</script>
|
||||
|
||||
<template>
|
||||
|
||||
@@ -94,6 +94,6 @@ export const SECTION_TITLE_KEY_MAP: Record<string, string> = {
|
||||
};
|
||||
|
||||
export const DEFAULT_POST_LOGIN_AGENT_ID = 16;
|
||||
export const KB_ACCESS_DENIED_MESSAGE = '暂无权限,请登录admin账号操作知识库!';
|
||||
export const KB_ACCESS_DENIED_MESSAGE = '需要管理员权限才能访问知识库。';
|
||||
export const WS_SCHEDULE_FILTER_INPUT_CLASS = 'admin-table-filter-input text-xs py-1.5 px-2';
|
||||
export const CHANGE_PASSWORD_ENABLED = true;
|
||||
Reference in new issue
Block a user