/*
Copyright (C) 2025 QuantumNous
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
For commercial licensing, please contact support@quantumnous.com
*/
import {
RefreshCw as ActionRefreshCw,
Plus as ActionPlus,
BookOpenText as ActionBookOpenText,
UploadCloud as ActionUploadCloud,
Settings2 as ActionSettings2,
ClipboardCopy as ActionClipboardCopy,
CheckCircle2 as ActionCheckCircle2,
Building2 as ActionBuilding2,
Search as ActionSearch,
} from '@/components/common/icons/ActionIcons';
import React, {
useCallback,
useEffect,
useMemo,
useRef,
useState,
} from 'react';
import { useTranslation } from 'react-i18next';
import {
Button,
Empty,
Input,
Modal,
Popconfirm,
Progress,
Select,
Spin,
Tag,
TextArea,
Toast,
} from '@/components/ui';
import {
Boxes,
CheckCircle2,
Clock4,
Database,
FileText,
FlaskConical,
HardDrive,
Link2,
Loader2,
ShieldCheck,
XCircle,
} from 'lucide-react';
import { API } from '../../helpers/api';
import { copy, showError } from '../../helpers';
import {
usePageGuide,
PageGuideDrawer,
PageGuidePill,
PageGuideTrigger,
} from '../../components/common/PageGuide';
import './org-knowledge.css';
import OrgBreadcrumb from './components/OrgBreadcrumb';
const headersFor = (orgId) => ({ 'X-Org-Id': String(orgId) });
// Kept in sync with the backend reindex gate: pending_reconciliation is an
// in-flight state there too, so the UI must treat it as active.
const activeJobStates = new Set([
'queued',
'running',
'awaiting_embedding_budget',
'pending_reconciliation',
]);
const uploadContentType = (file) => {
if (file.type) return file.type;
const extension = file.name.split('.').pop()?.toLowerCase();
return (
{
txt: 'text/plain',
md: 'text/markdown',
docx: 'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
pdf: 'application/pdf',
}[extension] || 'application/octet-stream'
);
};
const formatBytes = (bytes, t) => {
if (!bytes) return `0 ${t('字节')}`;
const units = [t('字节'), 'KiB', 'MiB', 'GiB'];
let value = Number(bytes);
let unit = 0;
while (value >= 1024 && unit < units.length - 1) {
value /= 1024;
unit += 1;
}
return `${value.toFixed(unit === 0 ? 0 : 1)} ${units[unit]}`;
};
const statusMeta = (status, t) => {
const values = {
ready: [t('可检索'), 'green'],
uploaded: [t('等待处理'), 'blue'],
parsing: [t('正在解析'), 'blue'],
chunking: [t('正在切分'), 'blue'],
embedding: [t('正在索引'), 'blue'],
queued: [t('排队中'), 'blue'],
running: [t('处理中'), 'blue'],
awaiting_embedding_budget: [t('等待向量化额度'), 'amber'],
pending_reconciliation: [t('账务对账中'), 'amber'],
failed: [t('处理失败'), 'red'],
quarantined: [t('已隔离'), 'red'],
disabled: [t('已停用'), 'grey'],
active: [t('运行中'), 'green'],
};
return values[status] || [status || t('未知'), 'grey'];
};
// 后端把失败原因写成英文 Go 错误文本(`worker lease expired repeatedly…`、
// `cloud brain quota is insufficient`…),直显给用户既看不懂也可能带出内部细节。
// 这里按 error_code 映射中文文案,原始文本仅保留为 tooltip 供排障——与云脑任务
// 详情页 runErrorMessages 的处理方式保持一致。
const jobErrorMessages = {
processing_failed: '文档处理失败,请重试或更换文件后重新上传。',
security_rejected: '文件未通过安全扫描,已隔离,不会进入检索。',
scan_unavailable: '安全扫描服务暂时不可用,文档未入库,请稍后重试。',
parse_quality_rejected: '文档解析质量不足,请上传文字版或重新导出后再试。',
safe_retry: '处理中断,系统将自动重试。',
lease_expired: '执行节点中断,任务已重新排队。',
lease_expired_final: '多次重试仍未完成,请重试或联系管理员。',
ambiguous_embedding_result: '向量化结果未确认,账务正在安全核对。',
embedding_budget_insufficient: '向量化额度不足,补充额度后可继续处理。',
embedding_reconciled_requires_retry: '账务已核对完成,请重新发起处理。',
};
// 文档处理流水线的用户可见步骤。后端 job.stage 只细分到 parsing/chunking/
// embedding(安全扫描、哈希校验发生在 parsing 阶段内部),排队与上传由
// job.status / 上传会话表达,这里统一折算成六步,让用户一眼看出卡在哪一步。
const pipelineSteps = (t) => [
{ key: 'upload', label: t('上传') },
{ key: 'queued', label: t('排队') },
{ key: 'parsing', label: t('扫描解析') },
{ key: 'chunking', label: t('切分') },
{ key: 'embedding', label: t('向量化') },
{ key: 'ready', label: t('入库') },
];
const stageStepIndex = { parsing: 2, chunking: 3, embedding: 4, ready: 5 };
// 把 job.status + job.stage 折算成流水线位置与形态:
// active=正在推进 / waiting=等待外部条件(额度、对账)/ failed=已终止。
// 返回 null 表示已完成或没有可展示的处理过程(此时保持原有紧凑标签)。
const resolvePipeline = (job, version, t) => {
const hasJob = Boolean(job?.id);
const status = hasJob ? job.status : version?.status;
if (!status || status === 'succeeded' || status === 'ready') return null;
const stepAt = stageStepIndex[hasJob ? job.stage : version?.status] ?? 2;
switch (status) {
case 'uploaded':
return {
current: 1,
mode: 'active',
note: t('等待处理'),
since: version?.created_at,
};
case 'queued': {
const retried = Number(job.attempt || 0) > 0;
const retryScheduled =
retried &&
Number(job.available_at || 0) > Math.floor(Date.now() / 1000);
return {
current: 1,
mode: 'active',
note: retryScheduled ? t('已重新排队,等待自动重试') : t('排队中'),
// created_at 是首次提交时间:任何重试排队(手动重试 available_at=now、
// 自动重试到期待领取)用它显示"已进行"都会夸大成整个任务生命周期,
// 只要重试过就不显示。
since: retried ? undefined : job.created_at,
};
}
case 'running':
return {
current: stepAt,
mode: 'active',
note: t('处理中'),
since: job.started_at || job.created_at,
};
case 'awaiting_embedding_budget':
return {
current: 4,
mode: 'waiting',
note: t('等待向量化额度'),
since: job.started_at || job.created_at,
};
case 'pending_reconciliation':
return {
current: 4,
mode: 'waiting',
note: t('账务对账中'),
since: job.started_at || job.created_at,
};
case 'failed':
case 'quarantined': {
// version 独立保留终态而 job 行可能缺失;version.status 推不出失败
// 发生在哪一步,标错步骤(恒指向扫描解析)比不标更误导——此路径
// 交给状态标签 + 错误卡片表达,不画流水线。
if (!hasJob) return null;
if (status === 'quarantined') {
return {
current: 2,
mode: 'failed',
note: t('安全扫描未通过,已隔离'),
};
}
return { current: stepAt, mode: 'failed', note: t('在该步骤失败') };
}
// job 行缺失时 version.status 会独立处于流水线中间态(advance 同步写),
// 不归一会落进 default 把英文状态串直显给用户。
case 'parsing':
case 'chunking':
case 'embedding':
return {
current: stageStepIndex[status],
mode: 'active',
note: t('处理中'),
};
default:
return {
current: stepAt,
mode: 'active',
note: statusMeta(status, t)[0],
};
}
};
const formatElapsed = (fromSeconds, t) => {
if (!fromSeconds) return '';
const delta = Math.max(
0,
Math.floor(Date.now() / 1000) - Number(fromSeconds),
);
if (delta < 60) return `${delta} ${t('秒')}`;
if (delta < 3600) return `${Math.floor(delta / 60)} ${t('分钟')}`;
return `${Math.floor(delta / 3600)} ${t('小时')} ${Math.floor((delta % 3600) / 60)} ${t('分钟')}`;
};
const formatTimestamp = (seconds) =>
seconds ? new Date(Number(seconds) * 1000).toLocaleString() : '';
// 引导 CTA 落点:滚动到目标区块并短暂高亮,让"下一步在哪"从文字变成视觉指引。
// 延迟 350ms 等指引抽屉(SideSheet 关闭动画约 300ms)先退场,
// 避免 scrollIntoView 被遮罩滚动锁吞掉。
const flashKnowledgeSection = (selector, focusSelector) => {
window.setTimeout(() => {
const node = document.querySelector(selector);
if (!node) return;
node.scrollIntoView({
behavior: window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches
? 'auto'
: 'smooth',
block: 'center',
});
node.classList.add('knowledge-flash');
window.setTimeout(() => node.classList.remove('knowledge-flash'), 1700);
if (focusSelector) {
window.setTimeout(
() =>
document.querySelector(focusSelector)?.focus({ preventScroll: true }),
450,
);
}
}, 350);
};
const PipelineSteps = ({ pipeline, t }) => (
{pipelineSteps(t).map((step, index) => {
let state = 'pending';
if (index < pipeline.current) state = 'done';
else if (index === pipeline.current) state = pipeline.mode;
return (
{index > 0 && (
)}
{state === 'done' && }
{state === 'active' && (
)}
{state === 'waiting' && }
{state === 'failed' && }
{state === 'pending' && }
{step.label}
);
})}
);
const parseQualityMeta = (quality, t) => {
const values = {
good: [t('解析良好'), 'green'],
acceptable: [t('解析可用'), 'amber'],
poor: [t('解析质量不足'), 'red'],
};
return values[quality] || null;
};
const parseWarningsTitle = (value) => {
if (!value) return '';
try {
const warnings = JSON.parse(value);
return Array.isArray(warnings) ? warnings.join(', ') : '';
} catch {
return '';
}
};
const OrgKnowledge = ({ orgId, canAuditContent = false }) => {
const { t } = useTranslation();
const fileInputRef = useRef(null);
const pollRef = useRef(null);
const uploadProgressResetRef = useRef(null);
const basesSeqRef = useRef(0);
const documentsSeqRef = useRef(0);
// loading 所有权与数据写入权分离:3s 轮询的静默请求会 bump 数据 seq,
// 如果 loading 复位也用同一个 seq 判断,飞行中的非静默请求会被轮询"顶掉"
// 而永远跳过 setLoading(false),整页/文档面板卡死在加载态。
const basesLoadingSeqRef = useRef(0);
const documentsLoadingSeqRef = useRef(0);
const referenceSeqRef = useRef(0);
const searchSeqRef = useRef(0);
const orgIdentityRef = useRef(orgId);
orgIdentityRef.current = orgId;
// Write-callback fence: async completions must not repaint the document
// panel when the user has already selected another knowledge base.
const selectedIdRef = useRef(null);
const [loading, setLoading] = useState(true);
const [bases, setBases] = useState([]);
const [spaces, setSpaces] = useState([]);
const [experts, setExperts] = useState([]);
const [departments, setDepartments] = useState([]);
const [projects, setProjects] = useState([]);
const [members, setMembers] = useState([]);
const [selectedId, setSelectedId] = useState(null);
const [documents, setDocuments] = useState([]);
const [documentsLoading, setDocumentsLoading] = useState(false);
const [createVisible, setCreateVisible] = useState(false);
const [createValues, setCreateValues] = useState({
name: '',
description: '',
scope_type: 'organization',
scope_id: 0,
embedding_space_id: undefined,
});
const [saving, setSaving] = useState(false);
// 知识库设置弹窗:打开时从 selected.base 播种,向量空间不可改故不入表单。
const [editVisible, setEditVisible] = useState(false);
const [editValues, setEditValues] = useState({
name: '',
description: '',
scope_type: 'organization',
scope_id: 0,
status: 'active',
});
const [editSaving, setEditSaving] = useState(false);
const [uploading, setUploading] = useState(false);
const [uploadProgress, setUploadProgress] = useState(0);
const [searchQuery, setSearchQuery] = useState('');
const [searching, setSearching] = useState(false);
const [searchHits, setSearchHits] = useState([]);
// 最近一次已完成检索的元信息(null=尚未检索过)。用它区分"没搜过"与
// "搜了但零命中",并把当次的完整原文/脱敏模式固化到结果头部展示。
const [searchSummary, setSearchSummary] = useState(null);
const [searchExpert, setSearchExpert] = useState(undefined);
const [searchMember, setSearchMember] = useState(undefined);
const [searchProject, setSearchProject] = useState(undefined);
const [fullContent, setFullContent] = useState(false);
const [auditReason, setAuditReason] = useState('');
useEffect(() => {
basesSeqRef.current += 1;
documentsSeqRef.current += 1;
referenceSeqRef.current += 1;
searchSeqRef.current += 1;
setBases([]);
setSpaces([]);
setExperts([]);
setDepartments([]);
setProjects([]);
setMembers([]);
setSelectedId(null);
setDocuments([]);
setSearchHits([]);
setSearchSummary(null);
// 弹窗与创建草稿是组织私有状态:不关闭/不清空的话,切组织后弹窗会带着
// 旧组织的草稿(名称/范围 scope_id)"复活",scope_id 甚至会被提交给新组织。
setCreateVisible(false);
setEditVisible(false);
setCreateValues({
name: '',
description: '',
scope_type: 'organization',
scope_id: 0,
embedding_space_id: undefined,
});
setLoading(true);
setDocumentsLoading(false);
setSaving(false);
setUploading(false);
setUploadProgress(0);
setSearching(false);
// Simulation and audit inputs are tenant-scoped: a member/expert/project
// picked in the previous organization must not leak into the next one.
setSearchQuery('');
setSearchExpert(undefined);
setSearchMember(undefined);
setSearchProject(undefined);
setFullContent(false);
setAuditReason('');
if (uploadProgressResetRef.current) {
window.clearTimeout(uploadProgressResetRef.current);
uploadProgressResetRef.current = null;
}
}, [orgId]);
useEffect(
() => () => {
if (uploadProgressResetRef.current)
window.clearTimeout(uploadProgressResetRef.current);
},
[],
);
const selected = useMemo(
() => bases.find((item) => item.base.id === selectedId) || null,
[bases, selectedId],
);
const scopeLabel = useCallback(
(scopeType) =>
({
organization: t('全企业'),
department: t('部门及其子部门'),
project: t('指定项目'),
})[scopeType] || scopeType,
[t],
);
const notifyError = useCallback(
(error) => {
const code = error?.response?.data?.code;
const localized = {
knowledge_schema_not_ready: '企业知识服务正在升级,请稍后重试',
knowledge_job_in_progress: '当前知识库已有文档正在处理,请完成后再试',
knowledge_not_found: '知识库或文档不存在,可能已被删除',
content_audit_required: '查看完整原文需要内容审计权限',
invalid_audit_reason: '查看完整原文时,审计原因需填写 4 到 500 个字符',
member_unavailable: '模拟成员不可用或已被停用',
simulation_member_required:
'当前身份不是企业成员,请先选择要模拟的成员',
knowledge_scan_capacity:
'知识库规模已超过检索容量上限,请联系管理员扩容或缩小检索范围',
invalid_request: '请求内容无效,请检查填写内容',
knowledge_operation_failed: '知识库操作失败,请检查输入或稍后重试',
};
showError(
localized[code]
? t(localized[code])
: code
? t('操作失败')
: error?.message || t('操作失败'),
);
},
[t],
);
const fetchBases = useCallback(
async (silent = false) => {
if (!orgId) return;
const seq = ++basesSeqRef.current;
const loadingSeq = silent ? 0 : ++basesLoadingSeqRef.current;
const requestOrgId = orgId;
if (!silent) setLoading(true);
try {
const response = await API.get('/api/org/knowledge/bases', {
headers: headersFor(orgId),
skipErrorHandler: true,
});
if (!response.data.success) throw new Error(response.data.message);
const rows = response.data.data || [];
if (
seq !== basesSeqRef.current ||
requestOrgId !== orgIdentityRef.current
)
return;
setBases(rows);
setSelectedId((current) => {
if (rows.some((row) => row.base.id === current)) return current;
return rows[0]?.base?.id || null;
});
} catch (error) {
if (
seq === basesSeqRef.current &&
requestOrgId === orgIdentityRef.current
)
notifyError(error);
} finally {
// loading 复位只看"最新的非静默请求"(loadingSeq),不看数据 seq——
// 数据 seq 会被静默轮询 bump,用它判断会把 loading 永久卡死。
if (
!silent &&
loadingSeq === basesLoadingSeqRef.current &&
requestOrgId === orgIdentityRef.current
)
setLoading(false);
}
},
[notifyError, orgId],
);
const fetchDocuments = useCallback(
async (baseId, silent = false) => {
if (!baseId) {
documentsSeqRef.current += 1;
setDocuments([]);
return;
}
const seq = ++documentsSeqRef.current;
const loadingSeq = silent ? 0 : ++documentsLoadingSeqRef.current;
const requestOrgId = orgId;
if (!silent) setDocumentsLoading(true);
try {
const response = await API.get(
`/api/org/knowledge/bases/${baseId}/documents`,
{ headers: headersFor(orgId), skipErrorHandler: true },
);
if (!response.data.success) throw new Error(response.data.message);
if (
seq === documentsSeqRef.current &&
requestOrgId === orgIdentityRef.current
)
setDocuments(response.data.data || []);
} catch (error) {
if (
seq === documentsSeqRef.current &&
requestOrgId === orgIdentityRef.current
)
notifyError(error);
} finally {
if (
!silent &&
loadingSeq === documentsLoadingSeqRef.current &&
requestOrgId === orgIdentityRef.current
)
setDocumentsLoading(false);
}
},
[notifyError, orgId],
);
const fetchReferenceData = useCallback(async () => {
if (!orgId) return;
const seq = ++referenceSeqRef.current;
const requestOrgId = orgId;
const config = { headers: headersFor(orgId), skipErrorHandler: true };
const requests = [
API.get('/api/org/knowledge/spaces', config),
API.get('/api/org/knowledge/experts', config),
API.get('/api/org/dept', config),
API.get('/api/org/project', config),
API.get('/api/org/members/all', config),
];
const [
spaceResult,
expertResult,
departmentResult,
projectResult,
memberResult,
] = await Promise.allSettled(requests);
if (
seq !== referenceSeqRef.current ||
requestOrgId !== orgIdentityRef.current
)
return;
if (spaceResult.status === 'fulfilled' && spaceResult.value.data.success) {
const nextSpaces = spaceResult.value.data.data || [];
setSpaces(nextSpaces);
setCreateValues((current) => ({
...current,
embedding_space_id: current.embedding_space_id || nextSpaces[0]?.id,
}));
}
if (
expertResult.status === 'fulfilled' &&
expertResult.value.data.success
) {
setExperts(expertResult.value.data.data || []);
}
if (
departmentResult.status === 'fulfilled' &&
departmentResult.value.data.success
) {
setDepartments(departmentResult.value.data.data || []);
}
if (
projectResult.status === 'fulfilled' &&
projectResult.value.data.success
) {
setProjects(projectResult.value.data.data || []);
}
if (
memberResult.status === 'fulfilled' &&
memberResult.value.data.success
) {
setMembers(memberResult.value.data.data || []);
}
// 专家/成员加载失败若静默吞掉,「暂无可绑定专家」与空的模拟成员下拉
// 会被误读为真实业务状态(引导步骤③直接死路),必须显式提示。
const referenceFailed = [expertResult, memberResult].some(
(result) => result.status !== 'fulfilled' || !result.value.data.success,
);
if (referenceFailed) {
showError(t('专家或成员列表加载失败,页面数据可能不完整,请刷新重试'));
}
}, [orgId, t]);
useEffect(() => {
fetchBases();
fetchReferenceData().catch(notifyError);
}, [fetchBases, fetchReferenceData, notifyError]);
useEffect(() => {
selectedIdRef.current = selectedId;
fetchDocuments(selectedId);
searchSeqRef.current += 1;
setSearchHits([]);
setSearchSummary(null);
// An in-flight search for the previous base can no longer clear the
// spinner (its seq gate fails), so reset it on base switch.
setSearching(false);
}, [fetchDocuments, selectedId]);
// Depend on primitives, not the row object: the 3-second polling loop
// recreates the bases array every tick, and an object dependency cleared the
// operator's manually chosen project filter every poll.
const selectedScopeType = selected?.base?.scope_type;
const selectedScopeId = selected?.base?.scope_id;
useEffect(() => {
if (selectedScopeType === 'project') {
setSearchProject(selectedScopeId);
} else {
setSearchProject(undefined);
}
}, [selectedScopeType, selectedScopeId]);
const hasActiveJobs =
documents.some((item) => activeJobStates.has(item.job?.status)) ||
activeJobStates.has(selected?.reindex_job?.status);
// pending_reconciliation only resolves through operator action or the 72h
// conservative settlement, and awaiting_embedding_budget only through a
// human topping up quota and clicking retry — minute-scale polling on either
// would hammer the backend for hours, so only fast in-flight states keep
// the 3s cadence. Retry flips the job back to queued, restoring 3s.
const fastJobStates = ['queued', 'running'];
const hasFastActiveJobs =
documents.some((item) => fastJobStates.includes(item.job?.status)) ||
fastJobStates.includes(selected?.reindex_job?.status);
const rebuildIndex = async () => {
if (!selected || hasActiveJobs) return;
// 与 uploadFiles/retryJob 相同的 await 后护栏:请求返回时用户可能已切换
// 组织或知识库,缺护栏会把旧库的文档列表画进新库面板。
const requestOrgId = orgId;
const requestBaseId = selected.base.id;
try {
const response = await API.post(
`/api/org/knowledge/bases/${requestBaseId}/reindex`,
{ embedding_space_id: selected.base.embedding_space_id },
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
if (requestOrgId !== orgIdentityRef.current) return;
if (!response.data?.success) {
notifyError({ response });
return;
}
Toast.success(t('知识库重建任务已进入持久队列'));
// The reindex job only appears in the bases response; without this
// refresh hasActiveJobs stays false, polling never starts and the
// progress is invisible.
await Promise.all([
requestBaseId === selectedIdRef.current
? fetchDocuments(requestBaseId, true)
: Promise.resolve(),
fetchBases(true),
]);
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
}
};
useEffect(() => {
if (!hasActiveJobs || !selectedId) return undefined;
const interval = hasFastActiveJobs ? 3000 : 60000;
pollRef.current = window.setInterval(() => {
fetchDocuments(selectedId, true);
fetchBases(true);
}, interval);
return () => window.clearInterval(pollRef.current);
}, [
fetchBases,
fetchDocuments,
hasActiveJobs,
hasFastActiveJobs,
selectedId,
]);
const totals = useMemo(
() =>
bases.reduce(
(summary, item) => ({
documents: summary.documents + Number(item.base.document_count || 0),
chunks: summary.chunks + Number(item.base.chunk_count || 0),
storage: summary.storage + Number(item.base.storage_bytes || 0),
}),
{ documents: 0, chunks: 0, storage: 0 },
),
[bases],
);
// ValidateKnowledgeScope rejects disabled departments and disabled/expired
// projects, so never offer them as scope targets. 新建与编辑弹窗共用。
const scopeOptionsFor = useCallback(
(scopeType) => {
if (scopeType === 'department') {
return departments
.filter((item) => item.status === 1)
.map((item) => ({ label: item.name, value: item.id }));
}
if (scopeType === 'project') {
return projects
.filter(
(item) =>
item.status === 1 &&
(!item.expired_at || item.expired_at * 1000 > Date.now()),
)
.map((item) => ({ label: item.name, value: item.id }));
}
return [];
},
[departments, projects],
);
const scopeOptions = useMemo(
() => scopeOptionsFor(createValues.scope_type),
[scopeOptionsFor, createValues.scope_type],
);
const createBase = async () => {
if (saving) return; // Semi's loading button still fires onClick
const requestOrgId = orgId;
const payload = {
...createValues,
scope_id:
createValues.scope_type === 'organization'
? 0
: Number(createValues.scope_id || 0),
};
if (!payload.name.trim() || !payload.embedding_space_id) {
showError(t('请填写知识库名称并选择向量空间'));
return;
}
if (payload.scope_type !== 'organization' && !payload.scope_id) {
showError(t('请选择知识库的具体可见范围'));
return;
}
setSaving(true);
try {
const response = await API.post('/api/org/knowledge/bases', payload, {
headers: headersFor(requestOrgId),
skipErrorHandler: true,
});
if (!response.data.success) throw new Error(response.data.message);
if (requestOrgId !== orgIdentityRef.current) return;
setCreateVisible(false);
setCreateValues((current) => ({
...current,
name: '',
description: '',
scope_type: 'organization',
scope_id: 0,
}));
Toast.success(t('知识库已创建'));
await fetchBases();
setSelectedId(response.data.data.id);
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
} finally {
if (requestOrgId === orgIdentityRef.current) setSaving(false);
}
};
const openEditBase = () => {
if (!selected) return;
setEditValues({
name: selected.base.name || '',
description: selected.base.description || '',
scope_type: selected.base.scope_type || 'organization',
scope_id: Number(selected.base.scope_id || 0),
status: selected.base.status || 'active',
});
setEditVisible(true);
};
const updateBase = async () => {
if (editSaving || !selected) return; // Semi's loading button still fires onClick
const requestOrgId = orgId;
const requestBaseId = selected.base.id;
const payload = {
...editValues,
name: editValues.name.trim(),
scope_id:
editValues.scope_type === 'organization'
? 0
: Number(editValues.scope_id || 0),
};
if (!payload.name) {
showError(t('请填写知识库名称并选择向量空间'));
return;
}
if (payload.scope_type !== 'organization' && !payload.scope_id) {
showError(t('请选择知识库的具体可见范围'));
return;
}
setEditSaving(true);
try {
const response = await API.put(
`/api/org/knowledge/bases/${requestBaseId}`,
payload,
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
if (!response.data.success) throw new Error(response.data.message);
if (requestOrgId !== orgIdentityRef.current) return;
setEditVisible(false);
Toast.success(t('知识库已更新'));
fetchBases(true);
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
} finally {
if (requestOrgId === orgIdentityRef.current) setEditSaving(false);
}
};
const deleteBase = async () => {
if (!selected) return;
const requestOrgId = orgId;
const requestBaseId = selected.base.id;
try {
const response = await API.delete(
`/api/org/knowledge/bases/${requestBaseId}`,
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
if (!response.data.success) throw new Error(response.data.message);
if (requestOrgId !== orgIdentityRef.current) return;
setEditVisible(false);
Toast.success(t('知识库已删除'));
// fetchBases 内部会把失效的 selectedId 迁移到剩余首个知识库
fetchBases();
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
}
};
const uploadFiles = async (event) => {
const files = Array.from(event.target.files || []).slice(0, 1);
event.target.value = '';
if (!selectedId || files.length === 0 || uploading) return;
const requestOrgId = orgId;
const requestBaseId = selectedId;
if (uploadProgressResetRef.current) {
window.clearTimeout(uploadProgressResetRef.current);
uploadProgressResetRef.current = null;
}
setUploading(true);
setUploadProgress(0);
try {
for (let index = 0; index < files.length; index += 1) {
const file = files[index];
const contentType = uploadContentType(file);
const sessionResponse = await API.post(
`/api/org/knowledge/bases/${requestBaseId}/uploads`,
{
original_name: file.name,
content_type: contentType,
size_bytes: file.size,
},
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
if (!sessionResponse.data.success) {
throw new Error(sessionResponse.data.message);
}
const ticket = sessionResponse.data.data;
const putPart = async (url, body, headers = {}) => {
// Bound every direct PUT so a dead connection cannot leave the UI
// spinning until the browser tab is closed.
const abort = new AbortController();
const uploadTimeout = window.setTimeout(
() => abort.abort(),
10 * 60 * 1000,
);
try {
const response = await fetch(url, {
method: 'PUT',
headers,
body,
signal: abort.signal,
});
if (!response.ok) {
throw new Error(`${t('对象存储上传失败')} (${response.status})`);
}
return response;
} catch (error) {
// 超时主动 abort 时 DOMException 的英文原文("The user aborted
// a request")不能直显给用户。
if (error?.name === 'AbortError') {
throw new Error(t('对象存储上传超时,请检查网络后重试'));
}
throw error;
} finally {
window.clearTimeout(uploadTimeout);
}
};
const completedParts = [];
if (ticket.upload_mode === 'multipart') {
const partSize = Number(ticket.part_size || 0);
const parts = [...(ticket.parts || [])].sort(
(left, right) => left.part_number - right.part_number,
);
if (!partSize || parts.length === 0) {
throw new Error(t('分片上传会话无效'));
}
for (let partIndex = 0; partIndex < parts.length; partIndex += 1) {
const part = parts[partIndex];
const start = (part.part_number - 1) * partSize;
const response = await putPart(
part.upload_url,
file.slice(start, Math.min(start + partSize, file.size)),
);
const etag = response.headers.get('ETag');
if (!etag) {
throw new Error(t('对象存储未暴露 ETag,请检查 COS CORS 配置'));
}
completedParts.push({ part_number: part.part_number, etag });
if (requestOrgId === orgIdentityRef.current) {
setUploadProgress(
Math.round(((partIndex + 1) / parts.length) * 90),
);
}
}
} else {
await putPart(ticket.upload_url, file, {
'Content-Type': contentType,
});
if (requestOrgId === orgIdentityRef.current) setUploadProgress(90);
}
// The backend finalize is idempotent per session: if the commit went
// through but the HTTP response was lost, retrying with the same
// session returns the original ingestion job instead of forcing the
// user to re-upload the whole file (and then hit a misleading 409).
let finalizeResponse = null;
for (let attempt = 0; attempt < 3; attempt += 1) {
try {
finalizeResponse = await API.post(
`/api/org/knowledge/uploads/${ticket.session_id}/finalize`,
{ parts: completedParts },
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
break;
} catch (error) {
const isNetworkError = !error?.response;
if (!isNetworkError || attempt === 2) throw error;
await new Promise((resolve) =>
window.setTimeout(resolve, 1500 * (attempt + 1)),
);
}
}
if (!finalizeResponse.data.success) {
throw new Error(finalizeResponse.data.message);
}
// Completed-count progress: (index+1)/total, so a single file shows
// 100% on completion instead of sticking at 0%.
if (requestOrgId === orgIdentityRef.current)
setUploadProgress(Math.round(((index + 1) / files.length) * 100));
}
if (requestOrgId !== orgIdentityRef.current) return;
Toast.success(t('文档已提交处理'));
if (requestBaseId === selectedIdRef.current) {
await fetchDocuments(requestBaseId);
}
await fetchBases(true);
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
} finally {
if (requestOrgId === orgIdentityRef.current) {
setUploading(false);
uploadProgressResetRef.current = window.setTimeout(() => {
if (requestOrgId === orgIdentityRef.current) setUploadProgress(0);
uploadProgressResetRef.current = null;
}, 500);
}
}
};
const retryJob = async (jobId) => {
const requestOrgId = orgId;
const requestBaseId = selectedId;
try {
const response = await API.post(
`/api/org/knowledge/jobs/${jobId}/retry`,
{},
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
if (!response.data.success) throw new Error(response.data.message);
if (requestOrgId !== orgIdentityRef.current) return;
Toast.success(t('已重新加入处理队列'));
if (requestBaseId === selectedIdRef.current)
fetchDocuments(requestBaseId);
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
}
};
// 一键复制完整处理状态:面向"卡住了要发给管理员/技术排查"的场景。
// 中文摘要让普通用户看得懂,同时保留任务 ID、错误代码与原始英文错误,
// 排障时不丢信息。
const copyJobDiagnostics = async (documentName, job, version) => {
const stageLabels = {
uploaded: t('等待处理'),
parsing: t('扫描解析'),
chunking: t('切分'),
embedding: t('向量化'),
awaiting_embedding_budget: t('等待向量化额度'),
ready: t('入库'),
};
const [statusLabel] = statusMeta(job.status || version.status, t);
const warnings = parseWarningsTitle(version.parse_warnings);
const lines = [
// 重建索引任务没有文档版本,version 传 {},此时不渲染版本段。
`${t('文档')}: ${documentName}${version.version_no ? ` (${t('版本')} ${version.version_no})` : ''}`,
`${t('任务ID')}: ${job.id || t('无')}`,
`${t('状态')}: ${statusLabel} (${job.status || version.status || 'unknown'})`,
job.stage
? `${t('处理阶段')}: ${stageLabels[job.stage] || job.stage} (${job.stage})`
: null,
`${t('尝试次数')}: ${job.attempt ?? 0}/${job.max_attempts ?? 0}`,
job.error_code ? `${t('错误代码')}: ${job.error_code}` : null,
job.error_message ? `${t('错误信息')}: ${job.error_message}` : null,
version.parse_quality
? `${t('解析质量')}: ${version.parse_quality} (${Math.round(Number(version.parse_score || 0) * 100)})`
: null,
warnings ? `${t('解析警告')}: ${warnings}` : null,
job.created_at
? `${t('提交时间')}: ${formatTimestamp(job.created_at)}`
: null,
job.started_at
? `${t('开始处理')}: ${formatTimestamp(job.started_at)}`
: null,
job.finished_at
? `${t('结束时间')}: ${formatTimestamp(job.finished_at)}`
: null,
].filter(Boolean);
const okay = await copy(lines.join('\n'));
if (okay) Toast.success(t('处理状态已复制,可直接粘贴给管理员排查'));
else showError(t('复制失败,请手动截图页面状态'));
};
const deleteDocument = async (documentId) => {
const requestOrgId = orgId;
const requestBaseId = selectedId;
try {
const response = await API.delete(
`/api/org/knowledge/bases/${requestBaseId}/documents/${documentId}`,
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
if (!response.data.success) throw new Error(response.data.message);
if (requestOrgId !== orgIdentityRef.current) return;
Toast.success(t('文档已删除并立即退出检索'));
if (requestBaseId === selectedIdRef.current)
fetchDocuments(requestBaseId);
fetchBases(true);
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
}
};
const toggleExpert = async (expertId, bound) => {
const requestOrgId = orgId;
const requestBaseId = selectedId;
try {
const path = `/api/org/knowledge/bases/${requestBaseId}/experts${bound ? `/${expertId}` : ''}`;
const response = bound
? await API.delete(path, {
headers: headersFor(requestOrgId),
skipErrorHandler: true,
})
: await API.post(
path,
{ expert_id: expertId },
{ headers: headersFor(requestOrgId), skipErrorHandler: true },
);
if (!response.data.success) throw new Error(response.data.message);
if (requestOrgId !== orgIdentityRef.current) return;
await fetchBases(true);
} catch (error) {
if (requestOrgId === orgIdentityRef.current) notifyError(error);
}
};
const runSearch = async () => {
// Semi 的 loading 按钮仍会触发 onClick(同 createBase 的坑):完整原文
// 模式下重复提交会写重复的内容审计日志,必须防重入。
if (searching) return;
if (!searchQuery.trim()) return;
const reasonLength = auditReason.trim().length;
if (fullContent && (reasonLength < 4 || reasonLength > 500)) {
showError(t('查看完整原文时,审计原因需填写 4 到 500 个字符'));
return;
}
const seq = ++searchSeqRef.current;
const requestOrgId = orgId;
setSearching(true);
try {
const response = await API.post(
'/api/org/knowledge/search-test',
{
query: searchQuery,
base_id: selectedId,
expert_id: searchExpert,
member_id: searchMember,
project_id: searchProject,
limit: 12,
full_content: fullContent,
reason: auditReason,
},
{ headers: headersFor(orgId), skipErrorHandler: true },
);
if (!response.data.success) throw new Error(response.data.message);
if (
seq === searchSeqRef.current &&
requestOrgId === orgIdentityRef.current
) {
setSearchHits(response.data.data || []);
setSearchSummary({ full: fullContent });
// 引导卡步骤④「验证与使用」的持久完成标记。setItem 在隐私模式/配额
// 耗尽时会抛异常,必须吞掉——否则成功的检索会掉进 catch 报"操作失败"。
try {
window.localStorage.setItem(
`org-knowledge-verified-${requestOrgId}`,
'1',
);
} catch {
/* 持久化失败不影响本次检索结果 */
}
}
} catch (error) {
if (
seq === searchSeqRef.current &&
requestOrgId === orgIdentityRef.current
)
notifyError(error);
} finally {
if (
seq === searchSeqRef.current &&
requestOrgId === orgIdentityRef.current
)
setSearching(false);
}
};
// 使用指引四步定义:done 由真实数据驱动,points 是抽屉里该步骤的详细
// 操作说明,onAction 是「去完成这一步」的直达动作(关抽屉→滚动高亮落点)。
// 步骤④的完成态按组织持久化到 localStorage,与①②③的数据驱动语义一致。
const guideVerifiedKey = `org-knowledge-verified-${orgId}`;
// 直达落点:③/④的目标区块(专家面板、检索测试台)只在选中知识库后才
// 渲染;没有库时 flash 会静默落空,兜底改为引导先去建库。
const guideStepAction = (index) => {
if (index === 0) {
setCreateVisible(true);
return;
}
if (index === 1) {
if (!selected) {
setCreateVisible(true);
return;
}
if (!hasActiveJobs && !uploading) {
fileInputRef.current?.click();
} else {
flashKnowledgeSection('.knowledge-documents');
}
return;
}
if (!selected) {
setCreateVisible(true);
return;
}
if (index === 2) {
flashKnowledgeSection('.knowledge-bindings');
return;
}
flashKnowledgeSection(
'.knowledge-search-lab',
'.knowledge-search-controls textarea',
);
};
const guideSteps = [
{
title: t('新建知识库'),
detail: t('选择可见范围(全企业/部门/项目)——范围决定哪些成员能检索到它'),
done: bases.length > 0,
cta: t('去创建知识库'),
onAction: () => guideStepAction(0),
points: [
t('点右上角「新建知识库」,填写名称与用途说明'),
t('可见范围决定哪些成员能检索到:全企业 / 部门及其子部门 / 指定项目'),
t('向量空间创建后不可更换,如需更换只能通过「重建索引」迁移'),
],
},
{
title: t('上传文档'),
detail: t('支持 TXT/MD/DOCX/PDF;等流水线走完、状态变「可检索」'),
done: totals.documents > 0,
working: hasActiveJobs,
cta: t('去上传文档'),
onAction: () => guideStepAction(1),
points: [
t(
'支持 TXT / Markdown / DOCX / PDF;扫描版(图片型)PDF 会因解析质量不足被拒,请上传文字版',
),
t('文档行下方的流水线实时显示六步进度,状态变绿色「可检索」即入库完成'),
t(
'处理失败时点「复制状态」获取完整诊断发给管理员,可点「重试」重新处理',
),
t(
'同名文件再次上传会生成新版本,新版本索引完成后原子替换旧版本,期间旧版本持续可检索',
),
],
},
{
title: t('绑定专家'),
detail: t(
'在右侧「专家引用」点击专家;绑定后该专家回答任务时才会引用本库',
),
done: bases.some((row) => (row.expert_ids || []).length > 0),
cta: t('去绑定专家'),
onAction: () => guideStepAction(2),
points: [
t('在右侧「专家引用」面板点击专家卡片,变为「已允许引用」'),
t('只有绑定的专家回答任务时才会引用本库;不绑定则不会被任何专家使用'),
t('绑定不突破可见范围:成员只能通过专家检索到自己本来可见的库'),
],
},
{
title: t('验证与使用'),
detail: t(
'先用页面底部「检索测试台」验证能命中,再让成员向已绑定专家发任务,产物会带 [K#] 引用',
),
// getItem 在存储被禁的环境会抛异常,此处位于 render 路径,
// 裸调会白屏整页——与写侧(检索成功处)同款防御。
done:
Boolean(searchSummary) ||
(() => {
try {
return window.localStorage.getItem(guideVerifiedKey) === '1';
} catch {
return false;
}
})(),
cta: t('去检索验证'),
onAction: () => guideStepAction(3),
points: [
t('在页面底部「检索测试台」输入真实业务问题,验证能否命中'),
t('「模拟成员」验证权限隔离;「选择专家」模拟该专家的可检索范围'),
t('「查看完整原文」需填写 4~500 字审计原因,每次访问都会记录审计日志'),
t(
'日常使用无需成员主动检索:成员向已绑定专家发任务,产物自动带 [K#] 可信引用',
),
],
},
];
const guideFaq = [
{
q: t('检索只命中标题几个字?'),
a: t('当前为词面相似度匹配,建议用文档原文中出现过的词句提问'),
},
{
q: t('检索零命中?'),
a: t('依次检查文档是否「可检索」、专家是否已绑定、成员是否在可见范围内'),
},
{
q: t('上传按钮置灰?'),
a: t('当前知识库有任务正在处理,等流水线完成后再上传'),
},
];
const guide = usePageGuide({
guideKey: 'org-knowledge',
// 页面虽有 loading 早退兜底,仍显式声明,避免日后重构早退时胶囊闪现 0/4。
ready: !loading,
title: t('企业知识 · 使用指引'),
intro: t('四步把组织文档变成专家可引用、可追溯的知识'),
steps: guideSteps,
faq: guideFaq,
});
const closeGuide = guide.close;
// 抽屉内容是组织私有的:切组织时关闭,避免带着旧组织的进度短暂展示。
useEffect(() => {
closeGuide();
}, [orgId, closeGuide]);
if (loading) {
return (
{t('正在加载企业知识空间')}
);
}
return (
{bases.length}
{t('知识库')}
{totals.documents}
{t('有效文档')}
{totals.chunks}
{t('可检索片段')}
{formatBytes(totals.storage, t)}
{t('已用存储')}
{t('知识空间')}
{t('按可见范围隔离')}
{bases.length === 0 ? (
) : (
{bases.map((row) => {
const base = row.base;
const active = selectedId === base.id;
const [label, color] = statusMeta(base.status, t);
return (
setSelectedId(base.id)}
>
{base.name}
{base.description || t('暂无描述')}
{label}
{base.document_count} {t('篇文档')}
);
})}
)}
{!selected ? (
) : (
<>
{selected.base.name}
{t('可见范围')} · {scopeLabel(selected.base.scope_type)}
{selected.base.description || t('这个知识库还没有描述。')}
}
loading={uploading}
disabled={hasActiveJobs}
title={
hasActiveJobs
? t('有文档正在处理,完成后可继续上传')
: undefined
}
onClick={() => fileInputRef.current?.click()}
>
{t('上传文档')}
}
disabled={
hasActiveJobs || selected.base.current_generation_id <= 0
}
title={
hasActiveJobs
? t('有任务正在处理,完成后可重建索引')
: selected.base.current_generation_id <= 0
? t('尚无已入库的索引,先成功上传一篇文档')
: undefined
}
onClick={rebuildIndex}
>
{t('重建索引')}
}
title={t('编辑名称、可见范围与启用状态')}
onClick={openEditBase}
>
{t('知识库设置')}
{uploading && (
)}
{selected.reindex_job?.id &&
selected.reindex_job.status !== 'succeeded' &&
(() => {
const reindexJob = selected.reindex_job;
const reindexFailed = ['failed', 'quarantined'].includes(
reindexJob.status,
);
const [reindexLabel] = statusMeta(reindexJob.status, t);
const reindexStage =
{
// 任务创建时 stage 初始值是 uploaded(排队未领取),
// 缺了这个键会把英文原文直显给用户。
uploaded: t('等待处理'),
parsing: t('扫描解析'),
chunking: t('切分'),
embedding: t('向量化'),
awaiting_embedding_budget: t('等待向量化额度'),
ready: t('入库'),
}[reindexJob.stage] || reindexJob.stage;
// 重建任务没有 version 行,后端重试接口救不了它;卡在额度/
// 对账等待时必须告诉用户出路在哪,而不是无限转圈。
const reindexStuck = [
'awaiting_embedding_budget',
'pending_reconciliation',
].includes(reindexJob.status);
return (
{reindexFailed ? (
) : (
)}
{t('重建索引')}:{reindexLabel}
{reindexJob.stage && reindexStage !== reindexLabel
? ` · ${reindexStage}`
: ''}
{reindexJob.error_message
? ` · ${t(
jobErrorMessages[reindexJob.error_code] ||
jobErrorMessages.processing_failed,
)}`
: ''}
{reindexFailed && reindexJob.finished_at
? ` · ${formatTimestamp(reindexJob.finished_at)}`
: ''}
{reindexStuck
? ` · ${t('需补充组织额度或等待账务处理后恢复,如长时间无进展请联系平台管理员')}`
: ''}
}
onClick={() =>
copyJobDiagnostics(t('重建索引任务'), reindexJob, {})
}
>
{t('复制状态')}
);
})()}
{t('文档与版本')}
{t('新版本完成索引后才会原子替换旧版本')}
{documents.length}
{documentsLoading ? (
) : documents.length === 0 ? (
) : (
{documents.map((row) => {
const version = row.latest_version || {};
const job = row.job || {};
const status =
job.status === 'succeeded'
? version.status
: job.status || version.status;
const [label, color] = statusMeta(status, t);
const quality = parseQualityMeta(
version.parse_quality,
t,
);
const pipeline = resolvePipeline(job, version, t);
const failedNow = ['failed', 'quarantined'].includes(
job.id ? job.status : version.status,
);
// 额度不足等状态只写 version 的错误字段(job 不写),
// 只读 job 会让「补充额度后可继续」这类指引永不可达。
// 但 worker claim 只清 job 不清 version 的错误残留:
// 自动重试第 2 次运行期间 version 还挂着上次的失败原因,
// 无条件回退会让"处理中"和错误卡并排自相矛盾——
// 仅在 job 缺失或处于终态/等待态时才读 version。
const versionErrorVisible =
!job.id ||
[
'failed',
'quarantined',
'awaiting_embedding_budget',
'pending_reconciliation',
].includes(job.status);
const errorCode =
job.error_code ||
(versionErrorVisible ? version.error_code : '') ||
'';
const errorMessage =
job.error_message ||
(versionErrorVisible ? version.error_message : '') ||
'';
const hasErrorInfo = Boolean(errorCode || errorMessage);
// 后端重试接口同时接受 failed 与 awaiting_embedding_budget
// (补充额度后由用户重试恢复),按钮条件必须与之对齐,
// 否则额度等待成 UI 死局:无按钮、库被活跃任务锁死。
const retryable =
version.retryable &&
['failed', 'awaiting_embedding_budget'].includes(
job.status,
);
return (
{row.document.name}
{label}
{quality && (
{quality[0]} ·{' '}
{Math.round(
Number(version.parse_score || 0) * 100,
)}
)}
{t('版本')} {version.version_no || 1} ·{' '}
{formatBytes(version.size_bytes, t)}
{pipeline && (
<>
{t('当前步骤')}:
{pipelineSteps(t)[pipeline.current].label} ·{' '}
{pipeline.note}
{pipeline.since &&
pipeline.mode !== 'failed'
? ` · ${t('已进行')} ${formatElapsed(pipeline.since, t)}`
: ''}
>
)}
{hasErrorInfo && (
{failedNow ? (
) : (
)}
{t(
jobErrorMessages[errorCode] ||
jobErrorMessages.processing_failed,
)}
{errorMessage && (
{errorCode ? `${errorCode} · ` : ''}
{errorMessage}
)}
)}
{job.id && (pipeline || hasErrorInfo) && (
}
title={t('复制任务 ID、阶段与错误详情')}
onClick={() =>
copyJobDiagnostics(
row.document.name,
job,
version,
)
}
>
{t('复制状态')}
)}
{retryable && (
retryJob(job.id)}
>
{t('重试')}
)}
deleteDocument(row.document.id)
}
>
{t('删除')}
);
})}
)}
{t('专家引用')}
{t('绑定不突破部门或项目可见范围')}
{experts.map((expert) => {
const bound = (selected.expert_ids || []).includes(
expert.id,
);
return (
toggleExpert(expert.id, bound)}
>
{bound ? (
) : (
)}
{expert.name || expert.name_zh || expert.name_en}
{bound ? t('已允许引用') : t('点击绑定')}
);
})}
{experts.length === 0 && (
)}
{t('检索测试台')}
{t('上线前验证召回内容、来源与相关度')}
{t('仅管理员')}
{searchSummary && !searching && (
{t('命中 {{n}} 条片段', {
n: searchHits.length,
count: searchHits.length,
})}
{searchSummary.full
? t('完整原文 · 已审计')
: t('脱敏片段')}
)}
{searchHits.map((hit, index) => {
const shortHit = (hit.content || '').trim().length < 80;
return (
K{index + 1}
{hit.source_label}
{(hit.score * 100).toFixed(1)}%
{hit.base_name && {hit.base_name} }
{t('片段')} #{hit.sequence}
{hit.page_number > 0 && (
{t('页')} {hit.page_number}
)}
{shortHit && (
{t('标题类短片段')}
)}
{hit.content}
);
})}
{!searching &&
searchHits.length > 0 &&
searchHits.every(
(hit) => (hit.content || '').trim().length < 80,
) && (
{t(
'命中的都是较短的标题类片段:检索以切片为单位,标题行会独立成片且与问题词面最接近。想召回正文段落,试试直接粘贴文档正文中的原句;语义级召回需为知识库配置真实向量模型。',
)}
)}
{!searching && searchSummary && searchHits.length === 0 && (
{t('暂无命中。请调整问题或检查专家绑定和可见范围。')}
)}
>
)}
setCreateVisible(false)}
okText={t('创建知识库')}
cancelText={t('取消')}
width={620}
>
{/* Plain controlled inputs: Semi Form fields keep their own internal
value that overrides the value prop, which previously made the
dialog display empty selects while submitting hidden defaults. */}
{t('知识库名称')}
setCreateValues((current) => ({ ...current, name: value }))
}
placeholder={t('例如:产品交付标准')}
/>
{t('用途说明')}
{t('可见范围')}
setCreateValues((current) => ({
...current,
scope_type: value,
scope_id: 0,
}))
}
optionList={[
{ value: 'organization', label: t('全企业') },
{ value: 'department', label: t('部门及其子部门') },
{ value: 'project', label: t('指定项目') },
]}
style={{ width: '100%' }}
/>
{createValues.scope_type !== 'organization' && (
{t('选择具体范围')}
setCreateValues((current) => ({
...current,
scope_id: value,
}))
}
optionList={scopeOptions}
placeholder={t('请选择')}
style={{ width: '100%' }}
/>
)}
{t('向量空间')}
setCreateValues((current) => ({
...current,
embedding_space_id: value,
}))
}
optionList={spaces.map((space) => ({
value: space.id,
label: `${space.logical_model} · ${space.provider} · ${space.dimension}d · ${space.data_region}`,
}))}
style={{ width: '100%' }}
/>
{t(
'向量空间在知识库创建后保持不变;本地空间不会把文档内容发送到外部服务。',
)}
setEditVisible(false)}
okText={t('保存修改')}
cancelText={t('取消')}
width={620}
>
{t('知识库名称')}
setEditValues((current) => ({ ...current, name: value }))
}
/>
{t('用途说明')}
{t('可见范围')}
setEditValues((current) => ({
...current,
scope_type: value,
scope_id: 0,
}))
}
optionList={[
{ value: 'organization', label: t('全企业') },
{ value: 'department', label: t('部门及其子部门') },
{ value: 'project', label: t('指定项目') },
]}
style={{ width: '100%' }}
/>
{editValues.scope_type !== 'organization' && (
{t('选择具体范围')}
setEditValues((current) => ({
...current,
scope_id: value,
}))
}
optionList={scopeOptionsFor(editValues.scope_type)}
placeholder={t('请选择')}
style={{ width: '100%' }}
/>
)}
{t('启用状态')}
setEditValues((current) => ({ ...current, status: value }))
}
optionList={[
{ value: 'active', label: t('启用') },
{ value: 'disabled', label: t('停用') },
]}
style={{ width: '100%' }}
/>
{t(
'缩小可见范围立即影响成员检索与专家引用;停用后全部文档退出检索,重新启用即恢复。向量空间创建后不可更换。',
)}
{selected && (
{t('删除知识库')}
{t('删除后所有文档与索引一并移除,历史任务保留审计占位')}
{t('删除知识库')}
)}
);
};
export default OrgKnowledge;