2226 lines
85 KiB
React
2226 lines
85 KiB
React
/*
|
||
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 <https://www.gnu.org/licenses/>.
|
||
|
||
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 }) => (
|
||
<div className='knowledge-pipeline' role='list'>
|
||
{pipelineSteps(t).map((step, index) => {
|
||
let state = 'pending';
|
||
if (index < pipeline.current) state = 'done';
|
||
else if (index === pipeline.current) state = pipeline.mode;
|
||
return (
|
||
<React.Fragment key={step.key}>
|
||
{index > 0 && (
|
||
<span
|
||
className={`knowledge-pipeline-arrow ${index <= pipeline.current ? 'is-passed' : ''}`}
|
||
/>
|
||
)}
|
||
<span
|
||
role='listitem'
|
||
className={`knowledge-pipeline-step is-${state}`}
|
||
>
|
||
{state === 'done' && <CheckCircle2 size={12} />}
|
||
{state === 'active' && (
|
||
<Loader2 size={12} className='knowledge-spin' />
|
||
)}
|
||
{state === 'waiting' && <Clock4 size={12} />}
|
||
{state === 'failed' && <XCircle size={12} />}
|
||
{state === 'pending' && <span className='knowledge-pipeline-dot' />}
|
||
{step.label}
|
||
</span>
|
||
</React.Fragment>
|
||
);
|
||
})}
|
||
</div>
|
||
);
|
||
|
||
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 (
|
||
<div className='knowledge-loading'>
|
||
<Spin size='large' />
|
||
<span className='knowledge-loading-text'>
|
||
{t('正在加载企业知识空间')}
|
||
</span>
|
||
</div>
|
||
);
|
||
}
|
||
|
||
return (
|
||
<main className='knowledge-page'>
|
||
<header className='knowledge-hero'>
|
||
<div className='knowledge-hero-copy'>
|
||
<OrgBreadcrumb />
|
||
<div className='knowledge-eyebrow'>
|
||
<ShieldCheck size={15} />
|
||
<span>{t('企业可信知识层')}</span>
|
||
<span className='knowledge-beta'>BETA</span>
|
||
</div>
|
||
<h1>{t('企业知识')}</h1>
|
||
<p>
|
||
{t('把组织经验转化为专家可引用、可追溯、受权限保护的知识上下文。')}
|
||
</p>
|
||
</div>
|
||
<div className='knowledge-hero-actions'>
|
||
<PageGuideTrigger guide={guide} />
|
||
<Button
|
||
icon={<ActionRefreshCw size={16} />}
|
||
onClick={() => fetchBases()}
|
||
>
|
||
{t('刷新')}
|
||
</Button>
|
||
<Button
|
||
theme='solid'
|
||
type='primary'
|
||
icon={<ActionPlus size={16} />}
|
||
onClick={() => setCreateVisible(true)}
|
||
>
|
||
{t('新建知识库')}
|
||
</Button>
|
||
</div>
|
||
</header>
|
||
|
||
<PageGuidePill guide={guide} />
|
||
|
||
<section className='knowledge-metrics' aria-label={t('知识资产概览')}>
|
||
<div className='knowledge-metric'>
|
||
<Database size={20} />
|
||
<div>
|
||
<strong>{bases.length}</strong>
|
||
<span>{t('知识库')}</span>
|
||
</div>
|
||
</div>
|
||
<div className='knowledge-metric'>
|
||
<FileText size={20} />
|
||
<div>
|
||
<strong>{totals.documents}</strong>
|
||
<span>{t('有效文档')}</span>
|
||
</div>
|
||
</div>
|
||
<div className='knowledge-metric'>
|
||
<Boxes size={20} />
|
||
<div>
|
||
<strong>{totals.chunks}</strong>
|
||
<span>{t('可检索片段')}</span>
|
||
</div>
|
||
</div>
|
||
<div className='knowledge-metric'>
|
||
<HardDrive size={20} />
|
||
<div>
|
||
<strong>{formatBytes(totals.storage, t)}</strong>
|
||
<span>{t('已用存储')}</span>
|
||
</div>
|
||
</div>
|
||
</section>
|
||
|
||
<section className='knowledge-workspace'>
|
||
<aside className='knowledge-library-rail'>
|
||
<div className='knowledge-section-heading'>
|
||
<div>
|
||
<span>{t('知识空间')}</span>
|
||
<small>{t('按可见范围隔离')}</small>
|
||
</div>
|
||
</div>
|
||
{bases.length === 0 ? (
|
||
<Empty description={t('还没有知识库')} />
|
||
) : (
|
||
<div className='knowledge-library-list'>
|
||
{bases.map((row) => {
|
||
const base = row.base;
|
||
const active = selectedId === base.id;
|
||
const [label, color] = statusMeta(base.status, t);
|
||
return (
|
||
<button
|
||
type='button'
|
||
key={base.id}
|
||
className={[
|
||
'app-action-button',
|
||
`knowledge-library-card ${active ? 'is-active' : ''}`,
|
||
]
|
||
.filter(Boolean)
|
||
.join(' ')}
|
||
onClick={() => setSelectedId(base.id)}
|
||
>
|
||
<span className='knowledge-library-icon'>
|
||
<ActionBookOpenText size={18} />
|
||
</span>
|
||
<span className='knowledge-library-copy'>
|
||
<strong>{base.name}</strong>
|
||
<small>{base.description || t('暂无描述')}</small>
|
||
<span className='knowledge-library-meta'>
|
||
<Tag color={color} size='small'>
|
||
{label}
|
||
</Tag>
|
||
<span>
|
||
{base.document_count} {t('篇文档')}
|
||
</span>
|
||
</span>
|
||
</span>
|
||
</button>
|
||
);
|
||
})}
|
||
</div>
|
||
)}
|
||
</aside>
|
||
|
||
<div className='knowledge-main-panel'>
|
||
{!selected ? (
|
||
<Empty
|
||
description={
|
||
bases.length === 0
|
||
? t(
|
||
'还没有知识库。第一步:点右上角「新建知识库」,选好可见范围后即可上传文档',
|
||
)
|
||
: t('创建或选择知识库后开始管理文档')
|
||
}
|
||
/>
|
||
) : (
|
||
<>
|
||
<div className='knowledge-base-header'>
|
||
<div>
|
||
<div className='knowledge-title-line'>
|
||
<h2>{selected.base.name}</h2>
|
||
<Tag color='cyan'>
|
||
{t('可见范围')} · {scopeLabel(selected.base.scope_type)}
|
||
</Tag>
|
||
</div>
|
||
<p>
|
||
{selected.base.description || t('这个知识库还没有描述。')}
|
||
</p>
|
||
</div>
|
||
<div className='knowledge-base-actions'>
|
||
<input
|
||
ref={fileInputRef}
|
||
type='file'
|
||
accept='.txt,.md,.docx,.pdf'
|
||
hidden
|
||
onChange={uploadFiles}
|
||
/>
|
||
<Button
|
||
theme='solid'
|
||
icon={<ActionUploadCloud size={16} />}
|
||
loading={uploading}
|
||
disabled={hasActiveJobs}
|
||
title={
|
||
hasActiveJobs
|
||
? t('有文档正在处理,完成后可继续上传')
|
||
: undefined
|
||
}
|
||
onClick={() => fileInputRef.current?.click()}
|
||
>
|
||
{t('上传文档')}
|
||
</Button>
|
||
<Button
|
||
icon={<ActionRefreshCw size={16} />}
|
||
disabled={
|
||
hasActiveJobs || selected.base.current_generation_id <= 0
|
||
}
|
||
title={
|
||
hasActiveJobs
|
||
? t('有任务正在处理,完成后可重建索引')
|
||
: selected.base.current_generation_id <= 0
|
||
? t('尚无已入库的索引,先成功上传一篇文档')
|
||
: undefined
|
||
}
|
||
onClick={rebuildIndex}
|
||
>
|
||
{t('重建索引')}
|
||
</Button>
|
||
<Button
|
||
icon={<ActionSettings2 size={16} />}
|
||
title={t('编辑名称、可见范围与启用状态')}
|
||
onClick={openEditBase}
|
||
>
|
||
{t('知识库设置')}
|
||
</Button>
|
||
</div>
|
||
</div>
|
||
{uploading && (
|
||
<div className='knowledge-upload-progress'>
|
||
<span>{t('正在安全上传并校验文档')}</span>
|
||
<Progress percent={uploadProgress} showInfo />
|
||
</div>
|
||
)}
|
||
{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 (
|
||
<div
|
||
className={`knowledge-reindex-status ${reindexFailed ? 'is-failed' : 'is-active'}`}
|
||
>
|
||
{reindexFailed ? (
|
||
<XCircle size={14} />
|
||
) : (
|
||
<Loader2 size={14} className='knowledge-spin' />
|
||
)}
|
||
<span>
|
||
{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('需补充组织额度或等待账务处理后恢复,如长时间无进展请联系平台管理员')}`
|
||
: ''}
|
||
</span>
|
||
<Button
|
||
size='small'
|
||
theme='borderless'
|
||
icon={<ActionClipboardCopy size={14} />}
|
||
onClick={() =>
|
||
copyJobDiagnostics(t('重建索引任务'), reindexJob, {})
|
||
}
|
||
>
|
||
{t('复制状态')}
|
||
</Button>
|
||
</div>
|
||
);
|
||
})()}
|
||
|
||
<div className='knowledge-subgrid'>
|
||
<section className='knowledge-card knowledge-documents'>
|
||
<div className='knowledge-card-heading'>
|
||
<div>
|
||
<h3>
|
||
<FileText size={15} /> {t('文档与版本')}
|
||
</h3>
|
||
<p>{t('新版本完成索引后才会原子替换旧版本')}</p>
|
||
</div>
|
||
<span>{documents.length}</span>
|
||
</div>
|
||
{documentsLoading ? (
|
||
<Spin />
|
||
) : documents.length === 0 ? (
|
||
<Empty
|
||
description={t('上传 TXT、Markdown、DOCX 或 PDF 文档')}
|
||
/>
|
||
) : (
|
||
<div className='knowledge-document-list'>
|
||
{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 (
|
||
<article
|
||
className='knowledge-document-row'
|
||
key={row.document.id}
|
||
>
|
||
<span className='knowledge-file-icon'>
|
||
<FileText size={18} />
|
||
</span>
|
||
<div className='knowledge-document-copy'>
|
||
<div>
|
||
<strong>{row.document.name}</strong>
|
||
<Tag color={color} size='small'>
|
||
{label}
|
||
</Tag>
|
||
{quality && (
|
||
<Tag
|
||
color={quality[1]}
|
||
size='small'
|
||
title={parseWarningsTitle(
|
||
version.parse_warnings,
|
||
)}
|
||
>
|
||
{quality[0]} ·{' '}
|
||
{Math.round(
|
||
Number(version.parse_score || 0) * 100,
|
||
)}
|
||
</Tag>
|
||
)}
|
||
</div>
|
||
<p>
|
||
{t('版本')} {version.version_no || 1} ·{' '}
|
||
{formatBytes(version.size_bytes, t)}
|
||
</p>
|
||
{pipeline && (
|
||
<>
|
||
<PipelineSteps pipeline={pipeline} t={t} />
|
||
<div
|
||
className={`knowledge-pipeline-note is-${pipeline.mode}`}
|
||
>
|
||
{t('当前步骤')}:
|
||
{pipelineSteps(t)[pipeline.current].label} ·{' '}
|
||
{pipeline.note}
|
||
{pipeline.since &&
|
||
pipeline.mode !== 'failed'
|
||
? ` · ${t('已进行')} ${formatElapsed(pipeline.since, t)}`
|
||
: ''}
|
||
</div>
|
||
</>
|
||
)}
|
||
{hasErrorInfo && (
|
||
<div
|
||
className={`knowledge-doc-error ${failedNow ? 'is-failed' : 'is-waiting'}`}
|
||
>
|
||
{failedNow ? (
|
||
<XCircle size={13} />
|
||
) : (
|
||
<Clock4 size={13} />
|
||
)}
|
||
<div>
|
||
<span>
|
||
{t(
|
||
jobErrorMessages[errorCode] ||
|
||
jobErrorMessages.processing_failed,
|
||
)}
|
||
</span>
|
||
{errorMessage && (
|
||
<code title={errorMessage}>
|
||
{errorCode ? `${errorCode} · ` : ''}
|
||
{errorMessage}
|
||
</code>
|
||
)}
|
||
</div>
|
||
</div>
|
||
)}
|
||
</div>
|
||
<div className='knowledge-row-actions'>
|
||
{job.id && (pipeline || hasErrorInfo) && (
|
||
<Button
|
||
size='small'
|
||
theme='borderless'
|
||
icon={<ActionClipboardCopy size={14} />}
|
||
title={t('复制任务 ID、阶段与错误详情')}
|
||
onClick={() =>
|
||
copyJobDiagnostics(
|
||
row.document.name,
|
||
job,
|
||
version,
|
||
)
|
||
}
|
||
>
|
||
{t('复制状态')}
|
||
</Button>
|
||
)}
|
||
{retryable && (
|
||
<Button
|
||
size='small'
|
||
onClick={() => retryJob(job.id)}
|
||
>
|
||
{t('重试')}
|
||
</Button>
|
||
)}
|
||
<Popconfirm
|
||
title={t(
|
||
'删除后文档会立即退出检索,历史任务仍保留来源占位。',
|
||
)}
|
||
onConfirm={() =>
|
||
deleteDocument(row.document.id)
|
||
}
|
||
>
|
||
<Button
|
||
size='small'
|
||
type='danger'
|
||
theme='borderless'
|
||
>
|
||
{t('删除')}
|
||
</Button>
|
||
</Popconfirm>
|
||
</div>
|
||
</article>
|
||
);
|
||
})}
|
||
</div>
|
||
)}
|
||
</section>
|
||
|
||
<section className='knowledge-card knowledge-bindings'>
|
||
<div className='knowledge-card-heading'>
|
||
<div>
|
||
<h3>
|
||
<Link2 size={15} /> {t('专家引用')}
|
||
</h3>
|
||
<p>{t('绑定不突破部门或项目可见范围')}</p>
|
||
</div>
|
||
</div>
|
||
<div className='knowledge-expert-list'>
|
||
{experts.map((expert) => {
|
||
const bound = (selected.expert_ids || []).includes(
|
||
expert.id,
|
||
);
|
||
return (
|
||
<button
|
||
type='button'
|
||
className={[
|
||
'app-action-button',
|
||
`knowledge-expert ${bound ? 'is-bound' : ''}`,
|
||
]
|
||
.filter(Boolean)
|
||
.join(' ')}
|
||
key={expert.id}
|
||
onClick={() => toggleExpert(expert.id, bound)}
|
||
>
|
||
<span>
|
||
{bound ? (
|
||
<ActionCheckCircle2 size={17} />
|
||
) : (
|
||
<ActionBuilding2 size={17} />
|
||
)}
|
||
</span>
|
||
<span>
|
||
<strong>
|
||
{expert.name || expert.name_zh || expert.name_en}
|
||
</strong>
|
||
<small>
|
||
{bound ? t('已允许引用') : t('点击绑定')}
|
||
</small>
|
||
</span>
|
||
</button>
|
||
);
|
||
})}
|
||
{experts.length === 0 && (
|
||
<Empty description={t('暂无可绑定专家')} />
|
||
)}
|
||
</div>
|
||
</section>
|
||
</div>
|
||
|
||
<section className='knowledge-card knowledge-search-lab'>
|
||
<div className='knowledge-card-heading'>
|
||
<div>
|
||
<h3>
|
||
<FlaskConical size={18} /> {t('检索测试台')}
|
||
</h3>
|
||
<p>{t('上线前验证召回内容、来源与相关度')}</p>
|
||
</div>
|
||
<Tag color='blue'>{t('仅管理员')}</Tag>
|
||
</div>
|
||
<div className='knowledge-search-controls'>
|
||
<textarea
|
||
value={searchQuery}
|
||
onChange={(event) => setSearchQuery(event.target.value)}
|
||
placeholder={t(
|
||
'输入一个真实业务问题,例如:项目上线前必须完成哪些安全检查?',
|
||
)}
|
||
rows={3}
|
||
/>
|
||
<div className='knowledge-search-options'>
|
||
<Select
|
||
value={searchExpert}
|
||
onChange={setSearchExpert}
|
||
placeholder={t('选择专家(可选)')}
|
||
allowClear
|
||
optionList={experts.map((expert) => ({
|
||
value: expert.id,
|
||
label: expert.name || expert.name_zh || expert.name_en,
|
||
}))}
|
||
/>
|
||
<Select
|
||
value={searchMember}
|
||
onChange={setSearchMember}
|
||
placeholder={t('模拟成员(默认当前用户)')}
|
||
allowClear
|
||
filter
|
||
optionList={members.map((member) => ({
|
||
value: member.id,
|
||
label:
|
||
member.display_name ||
|
||
member.username ||
|
||
`#${member.id}`,
|
||
}))}
|
||
/>
|
||
<Select
|
||
value={searchProject}
|
||
onChange={setSearchProject}
|
||
placeholder={t('关联项目(可选)')}
|
||
allowClear
|
||
optionList={projects.map((project) => ({
|
||
value: project.id,
|
||
label: project.name,
|
||
}))}
|
||
/>
|
||
{canAuditContent && (
|
||
<label className='knowledge-audit-toggle'>
|
||
<input
|
||
type='checkbox'
|
||
checked={fullContent}
|
||
onChange={(event) =>
|
||
setFullContent(event.target.checked)
|
||
}
|
||
/>
|
||
{t('查看完整原文')}
|
||
</label>
|
||
)}
|
||
<Button
|
||
theme='solid'
|
||
icon={<ActionSearch size={16} />}
|
||
loading={searching}
|
||
disabled={!searchQuery.trim()}
|
||
onClick={runSearch}
|
||
>
|
||
{t('开始检索')}
|
||
</Button>
|
||
</div>
|
||
{fullContent && (
|
||
<input
|
||
className='knowledge-audit-reason'
|
||
value={auditReason}
|
||
onChange={(event) => setAuditReason(event.target.value)}
|
||
maxLength={500}
|
||
placeholder={t('请输入查看完整原文的审计原因')}
|
||
/>
|
||
)}
|
||
</div>
|
||
<div className='knowledge-hit-list'>
|
||
{searchSummary && !searching && (
|
||
<div className='knowledge-hit-summary'>
|
||
<span>
|
||
{t('命中 {{n}} 条片段', {
|
||
n: searchHits.length,
|
||
count: searchHits.length,
|
||
})}
|
||
</span>
|
||
<Tag
|
||
color={searchSummary.full ? 'amber' : 'grey'}
|
||
size='small'
|
||
>
|
||
{searchSummary.full
|
||
? t('完整原文 · 已审计')
|
||
: t('脱敏片段')}
|
||
</Tag>
|
||
</div>
|
||
)}
|
||
{searchHits.map((hit, index) => {
|
||
const shortHit = (hit.content || '').trim().length < 80;
|
||
return (
|
||
<article key={hit.chunk_id} className='knowledge-hit'>
|
||
<div className='knowledge-hit-rank'>K{index + 1}</div>
|
||
<div className='knowledge-hit-body'>
|
||
<div className='knowledge-hit-title'>
|
||
<strong>{hit.source_label}</strong>
|
||
<span>{(hit.score * 100).toFixed(1)}%</span>
|
||
</div>
|
||
<div className='knowledge-hit-meta'>
|
||
{hit.base_name && <span>{hit.base_name}</span>}
|
||
<span>
|
||
{t('片段')} #{hit.sequence}
|
||
</span>
|
||
{hit.page_number > 0 && (
|
||
<span>
|
||
{t('页')} {hit.page_number}
|
||
</span>
|
||
)}
|
||
{shortHit && (
|
||
<span className='knowledge-hit-flag'>
|
||
{t('标题类短片段')}
|
||
</span>
|
||
)}
|
||
</div>
|
||
<p>{hit.content}</p>
|
||
</div>
|
||
</article>
|
||
);
|
||
})}
|
||
{!searching &&
|
||
searchHits.length > 0 &&
|
||
searchHits.every(
|
||
(hit) => (hit.content || '').trim().length < 80,
|
||
) && (
|
||
<div className='knowledge-hit-tip'>
|
||
{t(
|
||
'命中的都是较短的标题类片段:检索以切片为单位,标题行会独立成片且与问题词面最接近。想召回正文段落,试试直接粘贴文档正文中的原句;语义级召回需为知识库配置真实向量模型。',
|
||
)}
|
||
</div>
|
||
)}
|
||
{!searching && searchSummary && searchHits.length === 0 && (
|
||
<div className='knowledge-no-hit'>
|
||
{t('暂无命中。请调整问题或检查专家绑定和可见范围。')}
|
||
</div>
|
||
)}
|
||
</div>
|
||
</section>
|
||
</>
|
||
)}
|
||
</div>
|
||
</section>
|
||
|
||
<Modal
|
||
title={t('新建知识库')}
|
||
visible={createVisible}
|
||
confirmLoading={saving}
|
||
onOk={createBase}
|
||
onCancel={() => 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. */}
|
||
<div className='knowledge-create-form'>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('知识库名称')}</span>
|
||
<Input
|
||
value={createValues.name}
|
||
onChange={(value) =>
|
||
setCreateValues((current) => ({ ...current, name: value }))
|
||
}
|
||
placeholder={t('例如:产品交付标准')}
|
||
/>
|
||
</label>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('用途说明')}</span>
|
||
<TextArea
|
||
value={createValues.description}
|
||
onChange={(value) =>
|
||
setCreateValues((current) => ({
|
||
...current,
|
||
description: value,
|
||
}))
|
||
}
|
||
placeholder={t('说明知识来源、维护责任和适用场景')}
|
||
/>
|
||
</label>
|
||
<div className='knowledge-form-grid'>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('可见范围')}</span>
|
||
<Select
|
||
value={createValues.scope_type}
|
||
onChange={(value) =>
|
||
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%' }}
|
||
/>
|
||
</label>
|
||
{createValues.scope_type !== 'organization' && (
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('选择具体范围')}</span>
|
||
<Select
|
||
value={createValues.scope_id || undefined}
|
||
onChange={(value) =>
|
||
setCreateValues((current) => ({
|
||
...current,
|
||
scope_id: value,
|
||
}))
|
||
}
|
||
optionList={scopeOptions}
|
||
placeholder={t('请选择')}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
</label>
|
||
)}
|
||
</div>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('向量空间')}</span>
|
||
<Select
|
||
value={createValues.embedding_space_id}
|
||
onChange={(value) =>
|
||
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%' }}
|
||
/>
|
||
</label>
|
||
<div className='knowledge-space-note'>
|
||
<ShieldCheck size={16} />
|
||
<span>
|
||
{t(
|
||
'向量空间在知识库创建后保持不变;本地空间不会把文档内容发送到外部服务。',
|
||
)}
|
||
</span>
|
||
</div>
|
||
</div>
|
||
</Modal>
|
||
|
||
<Modal
|
||
title={t('知识库设置')}
|
||
visible={editVisible}
|
||
confirmLoading={editSaving}
|
||
onOk={updateBase}
|
||
onCancel={() => setEditVisible(false)}
|
||
okText={t('保存修改')}
|
||
cancelText={t('取消')}
|
||
width={620}
|
||
>
|
||
<div className='knowledge-create-form'>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('知识库名称')}</span>
|
||
<Input
|
||
value={editValues.name}
|
||
onChange={(value) =>
|
||
setEditValues((current) => ({ ...current, name: value }))
|
||
}
|
||
/>
|
||
</label>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('用途说明')}</span>
|
||
<TextArea
|
||
value={editValues.description}
|
||
onChange={(value) =>
|
||
setEditValues((current) => ({
|
||
...current,
|
||
description: value,
|
||
}))
|
||
}
|
||
/>
|
||
</label>
|
||
<div className='knowledge-form-grid'>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('可见范围')}</span>
|
||
<Select
|
||
value={editValues.scope_type}
|
||
onChange={(value) =>
|
||
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%' }}
|
||
/>
|
||
</label>
|
||
{editValues.scope_type !== 'organization' && (
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('选择具体范围')}</span>
|
||
<Select
|
||
value={editValues.scope_id || undefined}
|
||
onChange={(value) =>
|
||
setEditValues((current) => ({
|
||
...current,
|
||
scope_id: value,
|
||
}))
|
||
}
|
||
optionList={scopeOptionsFor(editValues.scope_type)}
|
||
placeholder={t('请选择')}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
</label>
|
||
)}
|
||
</div>
|
||
<label className='knowledge-form-field'>
|
||
<span>{t('启用状态')}</span>
|
||
<Select
|
||
value={editValues.status}
|
||
onChange={(value) =>
|
||
setEditValues((current) => ({ ...current, status: value }))
|
||
}
|
||
optionList={[
|
||
{ value: 'active', label: t('启用') },
|
||
{ value: 'disabled', label: t('停用') },
|
||
]}
|
||
style={{ width: '100%' }}
|
||
/>
|
||
</label>
|
||
<div className='knowledge-space-note'>
|
||
<ShieldCheck size={16} />
|
||
<span>
|
||
{t(
|
||
'缩小可见范围立即影响成员检索与专家引用;停用后全部文档退出检索,重新启用即恢复。向量空间创建后不可更换。',
|
||
)}
|
||
</span>
|
||
</div>
|
||
{selected && (
|
||
<div className='knowledge-danger-zone'>
|
||
<div>
|
||
<strong>{t('删除知识库')}</strong>
|
||
<small>
|
||
{t('删除后所有文档与索引一并移除,历史任务保留审计占位')}
|
||
</small>
|
||
</div>
|
||
<Popconfirm
|
||
title={t('确定删除该知识库?此操作不可恢复。')}
|
||
onConfirm={deleteBase}
|
||
>
|
||
<Button type='danger'>{t('删除知识库')}</Button>
|
||
</Popconfirm>
|
||
</div>
|
||
)}
|
||
</div>
|
||
</Modal>
|
||
|
||
<PageGuideDrawer guide={guide} />
|
||
</main>
|
||
);
|
||
};
|
||
|
||
export default OrgKnowledge;
|