Files
knowledge-governance/web/src/SystemSettings.tsx
T
姚章浩 6444814123 feat(settings): 存储与备份单页对齐真实接口
为什么:原型里的单库立备、示例容量、历史批次与目录检查在本仓接口中都不存在;
把整批 run 包装成单库按钮会误触发整批,填示例读数会把演示值当产品事实。

怎么改:按真实契约重排单页——范围/读写方向、四项告警、策略、最近批次、运行进度与
恢复验证。立即备份明确标注整批并禁用单库动作;目录/配额/预留、子库路径、历史批次、
恢复验证保留原型位置并注明未接线;归档与数据库备份分开计量。整盘色带与告警抽成
纯函数,用隔离夹具覆盖正常/不足/缺读数分支。

怎么验:tsc、vitest 618 项、vite build、prettier 通过;本地页面夹具在 1440/1024/768
无横向溢出,未接线与夹具读数两种形态均按预期渲染。
2026-11-19 23:31:16 +08:00

470 lines
21 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
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 { PPConnection } from './PPConnection'
import { KnowledgeBaseBinding } from './KnowledgeBaseBinding'
import { WeKnoraConnectionDiagnostics } from './weKnoraDiagnostics'
import { useOptionalAuth } from './auth'
import { fetchMonitorOverview } from './monitor'
import type { MonitorOverview } from './monitor'
import { fetchReleaseCapabilities } from './reviewRelease'
import { fetchWorkerCapabilities } from './systemCapabilities'
import type { WorkerCapabilities } from './systemCapabilities'
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 } from './uiSettings'
import type { UISettings, UISettingsCandidateInput } from './uiSettings'
import { refreshSettingsInput } from './settingsInputs'
import './systemSettings.css'
// 连接配置已从「服务配置」迁到「知识库绑定」。这两个纯函数仍从本模块导出,
// 既有调用与回归测试的导入路径不变。
export { refreshSettingsInput, serviceSettingsInput } from './settingsInputs'
export type { RefreshDrafts, ServiceDrafts } from './settingsInputs'
interface Props {
sources: CatalogSource[]
connections: SourceConnectionListItem[]
monitor: MonitorOverview | null
settings: UISettings | null
productionEnabled: boolean
productionBackupRestoreVerified?: boolean
routingCapabilities: CatalogRoutingCapabilities
workerCapabilities?: WorkerCapabilities | null
loading: boolean
saving: boolean
error: string | null
saveMessage: string | null
onSave: (input: UISettingsCandidateInput) => void
onSourcesChanged: () => void
onRefresh: () => void
// 兼容旧入口:'bindings'/'production-bindings'/'knowledge-map' 都落到「知识库绑定」。
initialSection?: SectionKey | 'bindings' | 'production-bindings' | 'knowledge-map'
}
type SectionKey = 'sources' | 'services' | 'knowledge-bindings' | 'storage' | 'refresh' | 'members'
const sections: { key: SectionKey; label: string; adminOnly?: boolean }[] = [
{ key: 'sources', label: '数据源配置' },
{ key: 'services', label: 'AI 模型连接' },
{ key: 'knowledge-bindings', label: '知识库绑定' },
{ key: 'storage', label: '存储与备份' },
{ key: 'refresh', label: '刷新策略' },
{ key: 'members', label: '成员与角色', adminOnly: true },
] as { key: SectionKey; label: string; adminOnly?: boolean }[]
const sourceTypeLabels: Record<string, string> = {
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)
export function SystemSettingsView({
sources,
connections,
monitor,
settings,
productionEnabled,
productionBackupRestoreVerified = false,
routingCapabilities,
workerCapabilities = null,
loading,
saving,
error,
saveMessage,
onSave,
onSourcesChanged,
initialSection = 'sources',
}: Props) {
const auth = useOptionalAuth()
const identity = auth?.identity ?? null
const [section, setSection] = useState<SectionKey>(
initialSection === 'bindings' || initialSection === 'production-bindings' || initialSection === 'knowledge-map'
? 'knowledge-bindings'
: (initialSection as SectionKey)
)
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<number>(settings?.ingestion_concurrency ?? 2)
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)
setDirty(false)
}, [settings])
const canSave = Boolean(settings && !saving)
const isAdmin = identity?.role === 'admin'
const refreshSettingsDirty = Boolean(
settings &&
(documentRefresh !== settings.document_refresh_seconds ||
resourceRefresh !== settings.resource_refresh_seconds ||
stalled !== settings.stalled_after_seconds ||
finalizing !== settings.finalizing_after_seconds ||
concurrency !== settings.ingestion_concurrency)
)
// 保存边界:刷新分区只带刷新草稿;知识库绑定的连接/选库草稿在独立组件内一次保存,
// 互不夹带(未保存的地址不会因为保存刷新策略被写进去)。
const refreshInput = (): UISettingsCandidateInput =>
settings
? refreshSettingsInput(settings, { documentRefresh, resourceRefresh, stalled, finalizing, concurrency })
: ({} as UISettingsCandidateInput)
return (
<main className="page-shell system-settings">
<header className="hero compact page-header">
<div>
<h1 className="page-title">系统设置</h1>
</div>
</header>
{error ? (
<div className="error-banner" role="alert">
{error}
</div>
) : null}
{settings || monitor ? (
<div className="settings-layout">
<nav className="settings-nav" aria-label="系统设置分区">
{sections
.filter((item) => !item.adminOnly || identity?.role === 'admin')
.map((item) => (
<button
key={item.key}
className={section === item.key ? 'active' : ''}
onClick={() => setSection(item.key)}
>
{item.label}
</button>
))}
</nav>
<div className="settings-content">
{section === 'sources' ? (
<section className="settings-panel wide source-settings-panel" id="settings-sources">
{identity?.role === 'admin' ? (
<SourceWizard
registeredNames={connections.map((item) => item.name)}
ppConnected={connections.some((item) => item.source_type === 'pp')}
onRegistered={onSourcesChanged}
/>
) : null}
{identity?.role === 'admin' ? (
<>
<DingtalkAccountStatus />
<PPConnection />
</>
) : null}
<div className="settings-source-group" id="settings-sources-pp">
{listedConnections.length ? (
<div className="settings-source-list">
{listedConnections.map((connection) => (
<SourceSettingsCard
key={connection.id}
connection={connection}
onSourcesChanged={onSourcesChanged}
/>
))}
{sources.length ? null : (
<small className="empty-inline">尚无快照数据;快照将在来源首次刷新完成后出现。</small>
)}
</div>
) : (
<div className="empty-state">还没有已接入的来源:用上面的「+ 添加数据源」加入。</div>
)}
</div>
<SourceManagementDetails connections={listedConnections} onSourcesChanged={onSourcesChanged} />
</section>
) : null}
{section === 'services' && settings ? (
<section className="settings-panel wide" id="settings-ai-model">
<div className="settings-section-heading">
<div>
<h2>AI 模型连接</h2>
<p>
问答四字段分析与中文问题翻译共用此连接;保存只更新这份连接,不会自动开启自动分析或自动翻译。
WeKnora 的知识库连接已移到「知识库绑定」。
</p>
</div>
</div>
{isAdmin ? <QAModelSettings /> : <small>仅管理员可修改模型连接;密钥不回显。</small>}
</section>
) : null}
{section === 'knowledge-bindings' ? (
<>
<KnowledgeBaseBinding />
<details className="settings-details kb-binding-diagnostics">
<summary>连接与绑定诊断(探活、封存源、整库发布目标)</summary>
{settings ? (
<WeKnoraConnectionDiagnostics
settings={settings}
monitor={monitor}
routingCapabilities={routingCapabilities}
workerCapabilities={workerCapabilities}
productionEnabled={productionEnabled}
productionBackupRestoreVerified={productionBackupRestoreVerified}
/>
) : null}
<p className="settings-hint-wide">
封存源是整库封存实际导出的库;整库发布目标由部署配置决定、只读。两者与上面的入库绑定不一致时,
发布页显示的名字与封存出来的内容会对不上。
</p>
<RoutingBindingsSection diagnosticsOnly />
<ProductionBindingsSection diagnosticsOnly />
</details>
</>
) : null}
{section === 'storage' ? (
<>
<BackupScheduleSection />
<LibraryStorageSection />
</>
) : null}
{section === 'members' && identity?.role === 'admin' ? <MembersSection /> : null}
{section === 'refresh' && settings ? (
<section className="settings-panel wide" id="settings-refresh">
<div className="settings-section-heading">
<div>
<h2>刷新策略</h2>
<p>保存只改这一组参数,不会带上「知识库绑定」里未保存的连接地址。</p>
</div>
<span className="safe-badge">当前活动版本</span>
</div>
<div className="safe-setting-grid">
<label>
文档状态刷新间隔
<select
value={documentRefresh}
onChange={(event) => {
setDocumentRefresh(Number(event.target.value) as 15 | 30 | 60)
setDirty(true)
}}
>
<option value={15}>15秒</option>
<option value={30}>30秒</option>
<option value={60}>1分钟</option>
</select>
</label>
<label>
资源刷新间隔
<select
value={resourceRefresh}
onChange={(event) => {
setResourceRefresh(Number(event.target.value) as 30 | 60)
setDirty(true)
}}
>
<option value={30}>30秒</option>
<option value={60}>1分钟</option>
</select>
</label>
<label>
解析停滞阈值
<select
value={stalled}
onChange={(event) => {
setStalled(Number(event.target.value) as 1800 | 3600)
setDirty(true)
}}
>
<option value={1800}>30分钟</option>
<option value={3600}>1小时</option>
</select>
</label>
<label>
收尾超时告警
<select
value={finalizing}
onChange={(event) => {
setFinalizing(Number(event.target.value) as 7200 | 14400)
setDirty(true)
}}
>
<option value={7200}>2小时</option>
<option value={14400}>4小时</option>
</select>
</label>
<label>
入库并发上限
<select
value={concurrency}
onChange={(event) => {
setConcurrency(Number(event.target.value))
setDirty(true)
}}
>
<option value={1}>1(谨慎,MinerU 并发 1)</option>
<option value={2}>2</option>
<option value={3}>3</option>
<option value={4}>4</option>
<option value={6}>6</option>
<option value={8}>8</option>
</select>
</label>
</div>
<button
onClick={() => {
setDirty(false)
onSave(refreshInput())
}}
disabled={!canSave || !refreshSettingsDirty}
>
{saving ? '正在验证并应用…' : '保存刷新与告警参数'}
</button>
{visibleSaveMessage(saveMessage, dirty) ? (
<p className="success-message" role="status">
{saveMessage}
</p>
) : null}
<p className="settings-warn">
解析停滞阈值保存后由 worker 在 1 分钟内生效;收尾超时告警目前只保存配置,判定尚未接入。
</p>
<small>
当前:文档 {secondsLabel(settings.document_refresh_seconds)}、资源{' '}
{secondsLabel(settings.resource_refresh_seconds)}、停滞 {secondsLabel(settings.stalled_after_seconds)}
、finalizing {secondsLabel(settings.finalizing_after_seconds)}、入库并发{' '}
{settings.ingestion_concurrency}。
</small>
</section>
) : null}
</div>
</div>
) : null}
</main>
)
}
export function SystemSettings() {
const [sources, setSources] = useState<CatalogSource[]>([])
const [connections, setConnections] = useState<SourceConnectionListItem[]>([])
const [monitor, setMonitor] = useState<MonitorOverview | null>(null)
const [settings, setSettings] = useState<UISettings | null>(null)
const [productionEnabled, setProductionEnabled] = useState(false)
const [productionBackupRestoreVerified, setProductionBackupRestoreVerified] = useState(false)
const [routingCapabilities, setRoutingCapabilities] = useState<CatalogRoutingCapabilities>({
internal_enabled: false,
external_enabled: false,
})
// 执行器能力单独加载:读不到只是这一行显示未知,不影响其它分区。
const [workerCapabilities, setWorkerCapabilities] = useState<WorkerCapabilities | null>(null)
const [loading, setLoading] = useState(true)
const [saving, setSaving] = useState(false)
const [error, setError] = useState<string | null>(null)
const [saveMessage, setSaveMessage] = useState<string | null>(null)
const [revision, setRevision] = useState(0)
// 六个请求彼此独立:任何一块失败只影响它自己,不能让成员、备份这些
// 互不相干的入口一起消失。设置本身读不到才阻断“设置”相关分区。
useEffect(() => {
const controller = new AbortController()
const failures: string[] = []
const track = <T,>(promise: Promise<T>, apply: (value: T) => void, label: string) =>
promise
.then((value) => {
if (!controller.signal.aborted) apply(value)
})
.catch((cause) => {
failures.push(`${label}:${cause instanceof Error ? cause.message : '读取失败'}`)
})
setLoading(true)
void Promise.all([
track(fetchCatalogSources(controller.signal), setSources, '数据源'),
track(fetchSourceConnectionList(controller.signal), setConnections, '来源连接'),
track(fetchMonitorOverview(controller.signal), setMonitor, '监控'),
track(
fetchReleaseCapabilities(controller.signal),
(capabilities) => {
setProductionEnabled(capabilities.production_release_requests_enabled)
setProductionBackupRestoreVerified(capabilities.production_backup_restore_verified)
},
'发布能力'
),
track(fetchCatalogRoutingCapabilities(controller.signal), setRoutingCapabilities, '路由能力'),
track(fetchWorkerCapabilities(controller.signal), setWorkerCapabilities, '执行器能力'),
track(fetchActiveUISettings(controller.signal), setSettings, '系统设置'),
]).finally(() => {
if (controller.signal.aborted) return
setError(failures.length ? failures.join(';') : null)
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)
// 保存成功后重新探测一次,卡片上的“最近检查”才不会停在旧结果。
try {
setMonitor(await fetchMonitorOverview())
} catch {
// 探测失败不影响保存结果,页面保留上一次观测。
}
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 (
<SystemSettingsView
sources={sources}
connections={connections}
monitor={monitor}
settings={settings}
productionEnabled={productionEnabled}
productionBackupRestoreVerified={productionBackupRestoreVerified}
routingCapabilities={routingCapabilities}
workerCapabilities={workerCapabilities}
loading={loading}
saving={saving}
error={error}
saveMessage={saveMessage}
onSave={(input) => void save(input)}
onSourcesChanged={reloadSources}
onRefresh={reloadSources}
/>
)
}