import { useCallback, useEffect, useState } from 'react' import { BackupScheduleSection } from './BackupScheduleSection' import { LibraryStorageSection } from './LibraryStorageSection' import { QAModelSettings } from './QAModelSettings' import { MembersSection } from './MembersSection' import { DingtalkAccountStatus, SourceManagementDetails, SourceSettingsCard } from './SourceManagement' import { RoutingBindingsSection } from './RoutingBindingsSection' import { ProductionBindingsSection } from './ProductionBindingsSection' import { SourceWizard } from './SourceWizard' import { useOptionalAuth } from './auth' import { fetchMonitorOverview } from './monitor' import type { MonitorOverview } from './monitor' import { fetchReleaseCapabilities } from './reviewRelease' import { fetchCatalogRoutingCapabilities, fetchCatalogSources } from './sourceCatalog' import type { CatalogRoutingCapabilities, CatalogSource } from './sourceCatalog' import { archiveSourceConnection, fetchSourceConnectionList } from './sourceConnections' import type { SourceConnectionListItem } from './sourceConnections' import { activateUISettings, createUISettingsCandidate, fetchActiveUISettings, validKnowledgeBaseID, validProductionTenantID, validServiceEndpoint, } from './uiSettings' import type { UISettings, UISettingsCandidateInput } from './uiSettings' import './systemSettings.css' interface Props { sources: CatalogSource[] connections: SourceConnectionListItem[] monitor: MonitorOverview | null settings: UISettings | null productionEnabled: boolean productionBackupRestoreVerified?: boolean routingCapabilities: CatalogRoutingCapabilities loading: boolean saving: boolean error: string | null saveMessage: string | null onSave: (input: UISettingsCandidateInput) => void onSourcesChanged: () => void onRefresh: () => void initialSection?: SectionKey } type SectionKey = 'sources' | 'services' | 'bindings' | 'production-bindings' | 'storage' | 'refresh' | 'members' const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [ { key: 'sources', label: '数据源配置' }, { key: 'services', label: '服务配置' }, { key: 'bindings', label: '测试知识库绑定' }, { key: 'production-bindings', label: '生产知识库绑定' }, { key: 'storage', label: '存储与备份' }, { key: 'refresh', label: '刷新策略' }, { key: 'members', label: '成员与角色', adminOnly: true }, ] as { key: SectionKey; label: string; adminOnly?: boolean }[] const sourceTypeLabels: Record = { dingtalk: '钉钉知识库', pp: 'PP 资料下载中心', alist: 'AList 文件源', manual: '本地手工导入', } // 「数据源配置」只保留两个入口:**dws 导入**(按当前钉钉账号发现知识库与钉盘空间) // 与 **PP 导入**。AList 已由钉盘文件替代、钉钉知识库一律走当前账号发现、本地手工与 // PP legacy 也下架了:本页只列 PP 来源。下架用归档(archived_at)实现,不删数据 —— // 需要时用 dws 重新登记同名来源即原地复活(见 postgres.RegisterDingtalkSpace)。 export const ppSourceConnections = (connections: SourceConnectionListItem[]) => connections.filter((item) => item.source_type === 'pp') const secondsLabel = (value: number) => value < 60 ? `${value}秒` : value < 3600 ? `${value / 60}分钟` : `${value / 3600}小时` export const visibleSaveMessage = (message: string | null, dirty: boolean) => (dirty ? null : message) type ServiceHealthView = MonitorOverview['health'][number] type ServiceView = MonitorOverview['services'][number] // 服务配置只保留四项可写值(测试地址、生产地址、生产 ID、知识库 ID), // 依赖与解析队列的状态仍按真实探测呈现,不写死。 const findHealth = (monitor: MonitorOverview | null, name: string): ServiceHealthView | undefined => (monitor?.health || []).find((item) => item.name === name || item.name.startsWith(name)) export const healthStateLabel = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { if (!health) { if (!service) return '待配置' return service.state === 'healthy' ? '正常' : service.state === 'unknown' ? '未接入' : '需关注' } if (health.readiness === 'ready') return '可达 · 可接单' if (health.readiness === 'not_configured') return '状态未知 · 未配置' if (health.readiness === 'not_applicable') return '未部署' return health.liveness === 'up' ? '可达 · 不可接单' : '不可达 · 不可接单' } export const healthStateDetail = (health: ServiceHealthView | undefined, service: ServiceView | undefined): string => { if (!health) return service?.detail || '真实 Provider 未接入' const success = health.last_success_at ? `最近成功 ${new Date(health.last_success_at).toLocaleTimeString('zh-CN', { hour12: false })}` : '' if (health.readiness === 'ready') return [`延迟 ${health.latency_ms}ms`, success].filter(Boolean).join(';') const failures = health.consecutive_failures ? `连续失败${health.consecutive_failures}次` : '' return [health.reason, success, failures].filter(Boolean).join(';') } // 生产 WeKnora 卡片:端点可达性来自真实探测,写入门禁来自生产开关,两者分开呈现。 // 生产侧只做探活(/health),不做一次真实读写,所以接单能力永远是「未做接单验证」, // 不跟着别处的「可达 · 可接单」一起含糊过去。 export const productionWeKnoraProbe = (monitor: MonitorOverview | null): string => { const health = findHealth(monitor, '生产 WeKnora') if (!health) return '端点探测:暂无真实探测结果' if (!health.configured) return '端点探测:未配置' const label = health.liveness === 'up' ? health.readiness === 'ready' ? '端点可达 · 未做接单验证' : '端点可达 · 不可接单' : '端点不可达' const detail = healthStateDetail(health, undefined) return `端点探测:${label}${detail ? `(${detail})` : ''}` } export function SystemSettingsView({ sources, connections, monitor, settings, productionEnabled, productionBackupRestoreVerified = false, routingCapabilities, loading, saving, error, saveMessage, onSave, onSourcesChanged, initialSection = 'sources', }: Props) { const auth = useOptionalAuth() const identity = auth?.identity ?? null const [section, setSection] = useState(initialSection) const [documentRefresh, setDocumentRefresh] = useState<15 | 30 | 60>(settings?.document_refresh_seconds ?? 15) const [resourceRefresh, setResourceRefresh] = useState<30 | 60>(settings?.resource_refresh_seconds ?? 30) const [stalled, setStalled] = useState<1800 | 3600>(settings?.stalled_after_seconds ?? 1800) const [finalizing, setFinalizing] = useState<7200 | 14400>(settings?.finalizing_after_seconds ?? 7200) const [concurrency, setConcurrency] = useState(settings?.ingestion_concurrency ?? 2) const [endpoint, setEndpoint] = useState(settings?.production_weknora_base_url ?? '') const [testEndpoint, setTestEndpoint] = useState(settings?.test_weknora_base_url ?? '') const [productionTenantID, setProductionTenantID] = useState(settings?.production_tenant_id ?? '') const [productionKnowledgeBaseID, setProductionKnowledgeBaseID] = useState( settings?.production_knowledge_base_id ?? '' ) const [dirty, setDirty] = useState(false) // 统一入口后,清单里列全部来源(钉钉知识库 / 钉盘 / PP),不再只显示 PP。 const listedConnections = connections useEffect(() => { if (!settings) return setDocumentRefresh(settings.document_refresh_seconds) setResourceRefresh(settings.resource_refresh_seconds) setStalled(settings.stalled_after_seconds) setFinalizing(settings.finalizing_after_seconds) setConcurrency(settings.ingestion_concurrency) setEndpoint(settings.production_weknora_base_url) setTestEndpoint(settings.test_weknora_base_url) setProductionTenantID(settings.production_tenant_id) setProductionKnowledgeBaseID(settings.production_knowledge_base_id) setDirty(false) }, [settings]) const canSave = Boolean(settings && !saving) const isAdmin = identity?.role === 'admin' const endpointValid = validServiceEndpoint(endpoint) const testEndpointValid = validServiceEndpoint(testEndpoint) const productionTenantIDValid = validProductionTenantID(productionTenantID) const productionKnowledgeBaseIDValid = validKnowledgeBaseID(productionKnowledgeBaseID) const serviceSettingsValid = endpointValid && testEndpointValid && productionTenantIDValid && productionKnowledgeBaseIDValid const serviceSettingsDirty = Boolean( settings && (testEndpoint.trim() !== settings.test_weknora_base_url || endpoint.trim() !== settings.production_weknora_base_url || productionTenantID.trim() !== settings.production_tenant_id || productionKnowledgeBaseID.trim() !== settings.production_knowledge_base_id) ) const candidateInput = (overrides: Partial = {}): UISettingsCandidateInput => ({ document_refresh_seconds: documentRefresh, resource_refresh_seconds: resourceRefresh, stalled_after_seconds: stalled, finalizing_after_seconds: finalizing, ingestion_concurrency: concurrency, test_weknora_base_url: testEndpoint.trim(), production_weknora_base_url: endpoint.trim(), production_tenant_id: productionTenantID.trim(), production_knowledge_base_id: productionKnowledgeBaseID.trim(), ...overrides, }) const saveEndpoint = () => { setDirty(false) onSave(candidateInput()) } return (

系统设置

{error ? (
{error}
) : null} {monitor && settings ? (
{section === 'sources' ? (
{identity?.role === 'admin' ? ( item.name)} ppConnected={connections.some((item) => item.source_type === 'pp')} onRegistered={onSourcesChanged} /> ) : null} {identity?.role === 'admin' ? : null}
{listedConnections.length ? (
{listedConnections.map((connection) => ( ))} {sources.length ? null : ( 尚无快照数据;快照将在来源首次刷新完成后出现。 )}
) : (
还没有已接入的来源:用上面的「+ 添加数据源」加入。
)}
) : null} {section === 'services' ? (

服务配置

只配四项:测试地址、生产地址、生产 ID、知识库 ID。保存会先生成修订、验证后原子启用,旧版本保留用于审计;凭据只写不读。

{isAdmin ? : null}
测试 WeKnora {healthStateLabel(findHealth(monitor, 'WeKnora API'), undefined)} {`${healthStateDetail(findHealth(monitor, 'WeKnora API'), undefined) || '端点探测:未配置'};解析队列 对内 ${routingCapabilities.internal_enabled ? '已配置' : '未配置'} · 对外 ${routingCapabilities.external_enabled ? '已配置' : '未配置'}`}
生产 WeKnora {!productionEnabled ? '未启用' : productionBackupRestoreVerified ? '已启用 · 可提交生产请求' : '已启用 · 被阻断'} {`${productionWeKnoraProbe(monitor)};生产写入:${productionEnabled ? '开启' : '关闭'};发布目标与凭据:管理员受限配置,本页不可回读`}
{isAdmin ? ( <> ) : ( <> )}
{isAdmin ? ( <> 四项留空即表示未配置。地址只接受 http(s) 源地址(不能带用户名密码、查询串或 # 片段,凭据一律走文件引用);生产 ID 是发布契约里的租户 ID,十进制数字;知识库 ID 是生产知识库标识,粘贴 URL 不会通过。保存写入服务器活动版本(版本化 + 审计 + 原子切换);后端同时对测试地址/生产地址做真实探活,并用生产地址真查这两个 ID(WeKnora 列库接口):端点回答"没有这个知识库"或租户不符会拒绝保存,端点抖动、鉴权失败或未配置生产凭据只警告不拦,核验原话与知识库名在保存后显示。 {serviceSettingsValid ? null : (

格式不合法:地址需 http:// 或 https:// 开头的纯地址,不能带用户名密码、? 查询串或 # 片段;生产 ID 需为十进制数字;知识库 ID 不能含空格、/、?、# 或 \。

)} ) : ( 服务配置仅管理员可修改;当前值:测试地址 {settings.test_weknora_base_url || '未配置'} · 生产地址{' '} {settings.production_weknora_base_url || '未配置'} · 生产 ID{' '} {settings.production_tenant_id || '未配置'} · 知识库 ID{' '} {settings.production_knowledge_base_id || '未配置'}。 )}
) : null} {section === 'bindings' ? : null} {section === 'production-bindings' ? : null} {section === 'storage' ? ( <> ) : null} {section === 'members' && identity?.role === 'admin' ? : null} {section === 'refresh' ? (

刷新策略

这些值保存在服务器活动版本中;保存不会修改端点、凭据或生产开关。

当前活动版本
{visibleSaveMessage(saveMessage, dirty) ? (

{saveMessage}

) : null} 当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '} {secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)} 、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发{' '} {settings.ingestion_concurrency}。
) : null}
) : null}
) } export function SystemSettings() { const [sources, setSources] = useState([]) const [connections, setConnections] = useState([]) const [monitor, setMonitor] = useState(null) const [settings, setSettings] = useState(null) const [productionEnabled, setProductionEnabled] = useState(false) const [productionBackupRestoreVerified, setProductionBackupRestoreVerified] = useState(false) const [routingCapabilities, setRoutingCapabilities] = useState({ internal_enabled: false, external_enabled: false, }) const [loading, setLoading] = useState(true) const [saving, setSaving] = useState(false) const [error, setError] = useState(null) const [saveMessage, setSaveMessage] = useState(null) const [revision, setRevision] = useState(0) useEffect(() => { const controller = new AbortController() setLoading(true) void Promise.all([ fetchCatalogSources(controller.signal), fetchSourceConnectionList(controller.signal), fetchMonitorOverview(controller.signal), fetchReleaseCapabilities(controller.signal), fetchCatalogRoutingCapabilities(controller.signal), fetchActiveUISettings(controller.signal), ]) .then(([nextSources, nextConnections, overview, capabilities, routing, active]) => { if (!controller.signal.aborted) { setSources(nextSources) setConnections(nextConnections) setMonitor(overview) setProductionEnabled(capabilities.production_release_requests_enabled) setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified) setRoutingCapabilities(routing) setSettings(active) setError(null) } }) .catch((cause) => { if (!controller.signal.aborted) setError(cause instanceof Error ? cause.message : '加载系统设置失败') }) .finally(() => { if (!controller.signal.aborted) setLoading(false) }) return () => controller.abort() }, [revision]) const save = async (input: UISettingsCandidateInput) => { setSaving(true) setSaveMessage(null) setError(null) try { const candidate = await createUISettingsCandidate(input) const activated = await activateUISettings(candidate.settings.id) const active = activated.settings const verification = activated.verification ?? candidate.verification setSettings(active) setSaveMessage( `设置已验证并启用:文档${secondsLabel(active.document_refresh_seconds)}、资源${secondsLabel(active.resource_refresh_seconds)}、停滞${secondsLabel(active.stalled_after_seconds)}、finalizing ${secondsLabel(active.finalizing_after_seconds)}、入库并发 ${active.ingestion_concurrency}、测试地址 ${active.test_weknora_base_url || '未配置'}、生产地址 ${active.production_weknora_base_url || '未配置'}、生产 ID ${active.production_tenant_id || '未配置'}、知识库 ID ${active.production_knowledge_base_id || '未配置'};旧版本已保留用于审计。${verification ? `核验:${verification.message}` : ''}` ) } catch (cause) { setError(cause instanceof Error ? cause.message : '保存系统设置失败') } finally { setSaving(false) } } const reloadSources = useCallback(() => { setSaveMessage(null) setRevision((value) => value + 1) }, []) return ( void save(input)} onSourcesChanged={reloadSources} onRefresh={reloadSources} /> ) }